@engini/cli 0.34.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,408 +1,60 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ CLIENT_ID,
4
+ CliError,
5
+ DEFAULT_API_URL,
6
+ Exit,
7
+ OAUTH_FIELDS,
8
+ PromptCancelled,
9
+ PromptStreamEnded,
10
+ addUniversalOptions,
11
+ assertNoLegacyKeyEnv,
12
+ checkedPair,
13
+ configPath,
14
+ confirm,
15
+ confirmOrFail,
16
+ dryRun,
17
+ ensureFreshSession,
18
+ fail,
19
+ findScope,
20
+ flattenScopes,
21
+ getProfile,
22
+ isInteractive,
23
+ isTty,
24
+ loadConfig,
25
+ mapCommanderExitCode,
26
+ maskSecret,
27
+ note,
28
+ openBrowser,
29
+ outputFlags,
30
+ printOutput,
31
+ profileDefaults,
32
+ profileResumeFlag,
33
+ progress,
34
+ promptHidden,
35
+ promptText,
36
+ readStdin,
37
+ resolveActive,
38
+ resolvePair,
39
+ revokeSession,
40
+ runCommand,
41
+ sandboxKey,
42
+ selectedProfile,
43
+ updateConfig,
44
+ validateProfileName,
45
+ withRefreshLock
46
+ } from "./chunk-XNKWQPRX.js";
2
47
 
3
48
  // src/index.ts
4
49
  import { realpathSync } from "fs";
5
50
  import { pathToFileURL } from "url";
6
51
 
7
- // src/prompt.ts
8
- import { spawn } from "child_process";
9
- import { createInterface } from "readline";
10
- function openBrowser(url) {
11
- const command = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
12
- const args = process.platform === "win32" ? ["", url] : [url];
13
- try {
14
- const child = spawn(command, args, { stdio: "ignore", detached: true, shell: process.platform === "win32" });
15
- child.on("error", () => {
16
- });
17
- child.unref();
18
- } catch {
19
- }
20
- }
21
- var PromptCancelled = class extends Error {
22
- constructor() {
23
- super("cancelled");
24
- this.name = "PromptCancelled";
25
- }
26
- };
27
- var PromptStreamEnded = class extends Error {
28
- constructor() {
29
- super("stdin ended before an answer was given");
30
- this.name = "PromptStreamEnded";
31
- }
32
- };
33
- async function readStdin(stream = process.stdin) {
34
- const chunks = [];
35
- for await (const chunk of stream) {
36
- chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
37
- }
38
- return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
39
- }
40
- function ask(rl, question) {
41
- return new Promise((resolve, reject) => {
42
- let answered = false;
43
- rl.question(question, (value) => {
44
- answered = true;
45
- resolve(value);
46
- });
47
- rl.once("close", () => {
48
- if (!answered) reject(new PromptStreamEnded());
49
- });
50
- });
51
- }
52
- async function confirm(question) {
53
- const rl = createInterface({ input: process.stdin, output: process.stdout });
54
- try {
55
- const answer = (await ask(rl, `${question} [y/N] `)).trim().toLowerCase();
56
- return answer === "y" || answer === "yes";
57
- } finally {
58
- rl.close();
59
- }
60
- }
61
- async function promptText(label, fallback = "") {
62
- const suffix = fallback ? ` [${fallback}]` : "";
63
- const rl = createInterface({ input: process.stdin, output: process.stdout });
64
- try {
65
- const answer = (await ask(rl, `${label}${suffix}: `)).trim();
66
- return answer || fallback;
67
- } finally {
68
- rl.close();
69
- }
70
- }
71
- var ESC = "\x1B";
72
- var CTRL_C = "";
73
- var CTRL_D = "";
74
- var CTRL_U = "";
75
- var DEL = "\x7F";
76
- var BACKSPACE = "\b";
77
- var MAX_ESCAPE_LENGTH = 256;
78
- function escapeKind(pending) {
79
- if (pending.length < 2) return "incomplete";
80
- const second = pending[1];
81
- if (second !== "[" && second !== "O") return "two-char";
82
- if (pending.length < 3) return "incomplete";
83
- const last = pending[pending.length - 1];
84
- return last >= "@" && last <= "~" ? "csi" : "incomplete";
85
- }
86
- function promptHidden(label, opts = {}) {
87
- const streams = opts.streams ?? { input: process.stdin, output: process.stdout };
88
- const { input, output } = streams;
89
- const wasRaw = Boolean(input.isRaw);
90
- let raw = false;
91
- if (input.isTTY && typeof input.setRawMode === "function") {
92
- try {
93
- input.setRawMode(true);
94
- raw = true;
95
- } catch {
96
- raw = false;
97
- }
98
- }
99
- const mask = (opts.mask ?? true) && raw;
100
- return new Promise((resolve, reject) => {
101
- let settled = false;
102
- const write = (s) => {
103
- try {
104
- output.write(s);
105
- } catch {
106
- }
107
- };
108
- let restored = false;
109
- const restore = () => {
110
- if (restored) return;
111
- restored = true;
112
- try {
113
- if (raw) input.setRawMode?.(wasRaw);
114
- } catch {
115
- }
116
- try {
117
- input.pause();
118
- } catch {
119
- }
120
- };
121
- const usingRealStdin = input === process.stdin;
122
- if (usingRealStdin) process.once("exit", restore);
123
- const detach = () => {
124
- input.removeListener("data", onData);
125
- input.removeListener("end", onEnd);
126
- input.removeListener("error", onEnd);
127
- if (usingRealStdin) process.removeListener("exit", restore);
128
- };
129
- const finish = (err, result) => {
130
- if (settled) return;
131
- settled = true;
132
- detach();
133
- restore();
134
- write("\n");
135
- if (err) reject(err);
136
- else resolve(result);
137
- };
138
- function onEnd() {
139
- finish(new PromptStreamEnded());
140
- }
141
- let buf = "";
142
- let pending = "";
143
- const eraseOne = () => {
144
- const cps = Array.from(buf);
145
- cps.pop();
146
- buf = cps.join("");
147
- };
148
- const clearLine = () => {
149
- if (mask) write("\b \b".repeat(Array.from(buf).length));
150
- buf = "";
151
- };
152
- const onData = (chunk) => {
153
- const chars = Array.from(chunk);
154
- let discarding = false;
155
- for (let i = 0; i < chars.length; i++) {
156
- const ch = chars[i];
157
- if (ch === CTRL_C || ch === CTRL_D) return finish(new PromptCancelled());
158
- if (ch === "\r" || ch === "\n") {
159
- const rest = chars.slice(i + 1).join("");
160
- return finish(null, { value: buf.trim(), truncated: rest.trim().length > 0 });
161
- }
162
- if (discarding) continue;
163
- if (pending) {
164
- pending += ch;
165
- if (pending.length > MAX_ESCAPE_LENGTH) {
166
- clearLine();
167
- pending = "";
168
- discarding = true;
169
- continue;
170
- }
171
- const kind = escapeKind(pending);
172
- if (kind === "csi") {
173
- pending = "";
174
- } else if (kind === "two-char") {
175
- if (pending[1] === ESC) {
176
- pending = ESC;
177
- continue;
178
- }
179
- clearLine();
180
- pending = "";
181
- }
182
- continue;
183
- }
184
- if (ch === ESC) {
185
- pending = ch;
186
- continue;
187
- }
188
- if (ch === DEL || ch === BACKSPACE) {
189
- if (buf.length > 0) {
190
- eraseOne();
191
- if (mask) write("\b \b");
192
- }
193
- continue;
194
- }
195
- if (ch === CTRL_U) {
196
- clearLine();
197
- continue;
198
- }
199
- if (ch < " ") continue;
200
- buf += ch;
201
- if (mask) write("*");
202
- }
203
- };
204
- try {
205
- input.resume();
206
- input.setEncoding("utf8");
207
- write(`${label}: `);
208
- input.on("data", onData);
209
- input.on("end", onEnd);
210
- input.on("error", onEnd);
211
- } catch (err) {
212
- finish(err instanceof Error ? err : new Error(String(err)));
213
- }
214
- });
215
- }
216
-
217
- // src/conventions.ts
218
- var Exit = /* @__PURE__ */ ((Exit2) => {
219
- Exit2[Exit2["OK"] = 0] = "OK";
220
- Exit2[Exit2["GENERIC"] = 1] = "GENERIC";
221
- Exit2[Exit2["USAGE"] = 2] = "USAGE";
222
- Exit2[Exit2["AUTH"] = 3] = "AUTH";
223
- Exit2[Exit2["NOT_FOUND"] = 4] = "NOT_FOUND";
224
- Exit2[Exit2["VALIDATION"] = 5] = "VALIDATION";
225
- Exit2[Exit2["TIMEOUT"] = 124] = "TIMEOUT";
226
- return Exit2;
227
- })(Exit || {});
228
- var ERROR_NAMES = {
229
- [1 /* GENERIC */]: "Error",
230
- [2 /* USAGE */]: "UsageError",
231
- [3 /* AUTH */]: "AuthError",
232
- [4 /* NOT_FOUND */]: "ResourceNotFound",
233
- [5 /* VALIDATION */]: "ValidationError",
234
- [124 /* TIMEOUT */]: "Timeout"
235
- };
236
- var CliError = class extends Error {
237
- constructor(code) {
238
- super(`CliExit(${code})`);
239
- this.code = code;
240
- this.name = "CliError";
241
- }
242
- code;
243
- };
244
- function isTty() {
245
- return Boolean(process.stdout.isTTY);
246
- }
247
- function isInteractive() {
248
- return Boolean(process.stdout.isTTY && process.stdin.isTTY);
249
- }
250
- var context = { forceJson: false, quiet: false, dryRun: false };
251
- function setOutputContext(ctx) {
252
- context = ctx;
253
- }
254
- function dryRun() {
255
- return context.dryRun;
256
- }
257
- function outputFlags() {
258
- return { forceJson: context.forceJson, quiet: context.quiet };
259
- }
260
- function formatValue(value) {
261
- return typeof value === "string" ? value : JSON.stringify(value);
262
- }
263
- function pretty(obj) {
264
- if (obj !== null && typeof obj === "object" && !Array.isArray(obj)) {
265
- for (const [key, value] of Object.entries(obj)) {
266
- console.log(`${key}: ${formatValue(value)}`);
267
- }
268
- } else if (Array.isArray(obj)) {
269
- for (const item of obj) {
270
- console.log(formatValue(item));
271
- }
272
- } else {
273
- console.log(formatValue(obj));
274
- }
275
- }
276
- function printOutput(obj) {
277
- if (context.forceJson) {
278
- console.log(JSON.stringify(obj, null, 2));
279
- } else if (!isTty()) {
280
- console.log(JSON.stringify(obj));
281
- } else {
282
- pretty(obj);
283
- }
284
- }
285
- function progress(message) {
286
- if (isTty() && !context.quiet) console.error(message);
287
- }
288
- function fail(code, message, hint2, extra) {
289
- if (isTty()) {
290
- console.error(`Error: ${message}`);
291
- if (hint2) console.error(`Hint: ${hint2}`);
292
- if (extra?.diagnostics?.length) {
293
- for (const line of diagnosticTable(extra.diagnostics)) console.error(line);
294
- }
295
- } else {
296
- const payload = {
297
- error: ERROR_NAMES[code] ?? "Error",
298
- message,
299
- exit_code: code
300
- };
301
- if (hint2) payload.hint = hint2;
302
- if (extra?.code !== void 0) payload.code = extra.code;
303
- if (extra?.path) payload.path = extra.path;
304
- if (extra?.currentRevisionId != null) payload.current_revision_id = extra.currentRevisionId;
305
- if (extra?.diagnostics?.length) payload.diagnostics = extra.diagnostics;
306
- console.error(JSON.stringify(payload));
307
- }
308
- throw new CliError(code);
309
- }
310
- function diagnosticTable(rows) {
311
- const header = ["SEVERITY", "CODE", "STEP", "FIELD", "MESSAGE"];
312
- const body = rows.map((d) => [d.severity, d.code, d.stepKey ?? "-", d.field ?? "-", d.message]);
313
- const widths = header.map((h, i) => Math.max(h.length, ...body.map((r) => r[i].length)));
314
- const line = (cells) => cells.map((c, i) => i === cells.length - 1 ? c : c.padEnd(widths[i])).join(" ");
315
- return [line(header), ...body.map(line)];
316
- }
317
- function mapCommanderExitCode(exitCode) {
318
- const code = exitCode ?? 1;
319
- return code === 0 ? 0 /* OK */ : 2 /* USAGE */;
320
- }
321
- function maskSecret(value) {
322
- return value.length > 8 ? `${value.slice(0, 4)}\u2026${value.slice(-4)}` : "****";
323
- }
324
- async function confirmOrFail(prompt, opts) {
325
- if (opts.force) return;
326
- if (isInteractive()) {
327
- if (!await confirm(prompt)) {
328
- throw new CliError(0 /* OK */);
329
- }
330
- return;
331
- }
332
- fail(2 /* USAGE */, `${prompt} Pass --force to proceed non-interactively.`);
333
- }
334
- var SCHEMA_VERSION = "1";
335
- var UNIVERSAL_FLAGS = /* @__PURE__ */ new Set(["--json", "--quiet", "--schema", "--dry-run"]);
336
- function schemaKey(name) {
337
- return name.replace(/^--?/, "").replace(/-/g, "_");
338
- }
339
- function optionTakesValue(option) {
340
- return option.required || option.optional;
341
- }
342
- function buildSchema(command, mutating) {
343
- const args = {};
344
- for (const arg of command.registeredArguments) {
345
- args[schemaKey(arg.name())] = { type: "string", required: arg.required };
346
- }
347
- for (const option of command.options) {
348
- if (UNIVERSAL_FLAGS.has(option.long ?? "")) continue;
349
- const key = schemaKey(option.long ?? option.short ?? "");
350
- args[key] = {
351
- type: optionTakesValue(option) ? "string" : "boolean",
352
- required: option.mandatory
353
- };
354
- }
355
- return {
356
- $schema: "https://json-schema.org/draft/2020-12/schema",
357
- version: SCHEMA_VERSION,
358
- mutating,
359
- args,
360
- output: null
361
- };
362
- }
363
- function addUniversalOptions(command, opts = {}) {
364
- command.option("--json", "Pretty JSON output").option("--quiet", "Suppress non-essential output").option("--schema", "Print this command's args/output schema as JSON");
365
- if (opts.mutating) {
366
- command.option("--dry-run", "Preview without executing");
367
- }
368
- return command;
369
- }
370
- async function runCommand(command, opts, mutating, body) {
371
- if (opts.schema) {
372
- console.log(JSON.stringify(buildSchema(command, mutating), null, 2));
373
- throw new CliError(0 /* OK */);
374
- }
375
- setOutputContext({
376
- forceJson: Boolean(opts.json),
377
- quiet: Boolean(opts.quiet),
378
- dryRun: Boolean(opts.dryRun)
379
- });
380
- try {
381
- await body();
382
- } catch (err) {
383
- if (err instanceof PromptCancelled) {
384
- fail(2 /* USAGE */, "Cancelled.");
385
- }
386
- if (err instanceof PromptStreamEnded) {
387
- fail(
388
- 2 /* USAGE */,
389
- "Input ended before the prompt was answered.",
390
- "Pass the required values as flags when running non-interactively."
391
- );
392
- }
393
- throw err;
394
- }
395
- }
396
-
397
52
  // src/main.ts
398
53
  import { Command } from "commander";
399
54
 
400
55
  // src/http.ts
401
56
  import {
402
57
  Engini,
403
- ENV_API_KEY_VAR,
404
- ENV_COMPANY_TOKEN_VAR,
405
- ENV_TOKEN_VAR,
406
58
  EnginiAuthError,
407
59
  EnginiBuilderError,
408
60
  EnginiConflictError,
@@ -417,75 +69,59 @@ import {
417
69
  EnginiValidationError
418
70
  } from "@engini/sdk";
419
71
 
420
- // src/config.ts
421
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
422
- import { homedir } from "os";
423
- import { dirname, join } from "path";
424
- import { parse, stringify } from "smol-toml";
425
- var CONFIG_SCHEMA_VERSION = 1;
426
- function defaultConfig() {
427
- return {
428
- config_schema_version: CONFIG_SCHEMA_VERSION,
429
- api_url: "https://api.engini.io",
430
- identity_url: "https://app.engini.io"
431
- };
432
- }
433
- function configPath() {
434
- const base = process.platform === "win32" ? process.env.APPDATA ?? homedir() : process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
435
- return join(base, "engini", "config.toml");
436
- }
437
- function asString(value) {
438
- return typeof value === "string" ? value : void 0;
439
- }
440
- function loadConfig(path = configPath()) {
441
- if (!existsSync(path)) return defaultConfig();
442
- const data = parse(readFileSync(path, "utf8"));
443
- const config = defaultConfig();
444
- if (typeof data.config_schema_version === "number") {
445
- config.config_schema_version = data.config_schema_version;
446
- }
447
- config.api_url = asString(data.api_url) ?? config.api_url;
448
- config.identity_url = asString(data.identity_url) ?? config.identity_url;
449
- config.api_key = asString(data.api_key);
450
- config.api_token = asString(data.api_token);
451
- config.company_token = asString(data.company_token);
452
- if (data.auth_kind === "api-key" || data.auth_kind === "jwt") {
453
- config.auth_kind = data.auth_kind;
454
- }
455
- return config;
456
- }
457
- function saveConfig(config, path = configPath()) {
458
- mkdirSync(dirname(path), { recursive: true });
459
- const data = {};
460
- for (const [key, value] of Object.entries(config)) {
461
- if (value !== void 0) data[key] = value;
462
- }
463
- writeFileSync(path, stringify(data), { mode: 384 });
464
- if (process.platform !== "win32") chmodSync(path, 384);
465
- }
466
-
467
72
  // src/version.ts
468
- var VERSION = true ? "0.34.0" : "0.0.0";
73
+ var VERSION = true ? "0.36.0" : "0.0.0";
469
74
 
470
75
  // src/http.ts
471
76
  var USER_AGENT_PREFIX = `engini-cli/${VERSION}`;
472
- function buildClient(overrides = {}) {
473
- const config = loadConfig();
474
- const key = overrides.apiKey ?? process.env[ENV_API_KEY_VAR] ?? config.api_key;
475
- if (key) {
476
- return new Engini({ apiKey: key, baseUrl: config.api_url, userAgentPrefix: USER_AGENT_PREFIX });
77
+ function clientFor(creds, apiUrl, pair) {
78
+ return new Engini({
79
+ ...creds,
80
+ baseUrl: apiUrl,
81
+ userAgentPrefix: USER_AGENT_PREFIX,
82
+ ...pair && { workspaceId: pair.workspaceId, environmentId: pair.environmentId }
83
+ });
84
+ }
85
+ function buildClient() {
86
+ assertNoLegacyKeyEnv();
87
+ const active = resolveActive();
88
+ const { profile } = active;
89
+ const { pair } = resolvePair(active);
90
+ if (active.source === "env-credential") {
91
+ const token = process.env.ENGINI_API_TOKEN;
92
+ if (profile.api_url !== DEFAULT_API_URL) {
93
+ note(`Using ${profile.api_url} (from the default profile) for ENGINI_API_TOKEN.`);
94
+ }
95
+ return clientFor({ token, companyToken: process.env.ENGINI_COMPANY_TOKEN }, profile.api_url);
477
96
  }
478
- const token = overrides.apiToken ?? process.env[ENV_TOKEN_VAR] ?? config.api_token;
479
- const company = overrides.companyToken ?? process.env[ENV_COMPANY_TOKEN_VAR] ?? config.company_token;
480
- if (!token) {
481
- fail(3 /* AUTH */, "No credentials found. Run `engini login`.");
97
+ if (profile.auth_kind === "oauth") {
98
+ if (process.env.ENGINI_COMPANY_TOKEN) {
99
+ fail(
100
+ 2 /* USAGE */,
101
+ `Profile "${active.name}" is a browser login, and ENGINI_COMPANY_TOKEN is set.`,
102
+ "Unset ENGINI_COMPANY_TOKEN: a browser login already names its account."
103
+ );
104
+ }
105
+ if (!profile.access_token) {
106
+ fail(3 /* AUTH */, `Profile "${active.name}" has no session.`, `Run \`engini login --profile ${active.name}\`.`);
107
+ }
108
+ return clientFor({ token: profile.access_token }, profile.api_url, pair);
482
109
  }
483
- return new Engini({
484
- token,
485
- companyToken: company,
486
- baseUrl: config.api_url,
487
- userAgentPrefix: USER_AGENT_PREFIX
488
- });
110
+ if (profile.api_key) return clientFor({ apiKey: profile.api_key }, profile.api_url);
111
+ if (profile.api_token) {
112
+ if (!profile.company_token && process.env.ENGINI_COMPANY_TOKEN) {
113
+ fail(
114
+ 2 /* USAGE */,
115
+ `Profile "${active.name}" has a token but no company token, and ENGINI_COMPANY_TOKEN is set.`,
116
+ "Unset ENGINI_COMPANY_TOKEN, or log in again with the profile's own company token."
117
+ );
118
+ }
119
+ return clientFor({ token: profile.api_token, companyToken: profile.company_token }, profile.api_url);
120
+ }
121
+ if (active.name !== void 0) {
122
+ fail(3 /* AUTH */, `Profile "${active.name}" has no credentials.`, `Run \`engini login --profile ${active.name}\`.`);
123
+ }
124
+ fail(3 /* AUTH */, "No credentials found. Run `engini login`.");
489
125
  }
490
126
  var AUTH_PROVIDER_CONFLICT_CODES = /* @__PURE__ */ new Set([
491
127
  "AUTH_PROVIDER_IN_USE",
@@ -516,24 +152,50 @@ function exitForError(err) {
516
152
  if (err instanceof EnginiTimeoutError) return 124 /* TIMEOUT */;
517
153
  return 1 /* GENERIC */;
518
154
  }
155
+ var SCOPE_READ_ONLY_HINT = "Use an API key scoped to the workspace and environment that holds the resource: a key without a scope can only read.";
519
156
  async function apiErrors(fn) {
520
157
  try {
521
158
  return await fn();
522
159
  } catch (err) {
523
160
  if (err instanceof EnginiBuilderError) {
524
- fail(exitForError(err), err.message, err.fix ?? void 0, {
161
+ if (err.code === "API_KEY_REQUIRED") {
162
+ if (activeOAuthProfile() !== void 0) {
163
+ fail(exitForError(err), "This command needs an API-key profile.", KEY_PROFILE_HINT, {
164
+ code: err.code
165
+ });
166
+ }
167
+ }
168
+ const fix = err.code === "SCOPE_NOT_ACCESSIBLE" ? err.fix ?? "Run `engini whoami` to list the workspaces and environments you can open." : err.fix ?? void 0;
169
+ fail(exitForError(err), err.message, fix, {
525
170
  code: err.code,
526
171
  path: err.path,
527
172
  currentRevisionId: err.currentRevisionId,
528
173
  diagnostics: err.diagnostics
529
174
  });
530
175
  }
176
+ if (err instanceof EnginiAuthError && err.errorCode === "SCOPE_READ_ONLY") {
177
+ fail(exitForError(err), err.message, SCOPE_READ_ONLY_HINT);
178
+ }
531
179
  if (err instanceof EnginiError) {
180
+ const code = err.errorCode;
181
+ if (code === "CLI_TOKEN_NOT_ALLOWED") {
182
+ fail(exitForError(err), err.message, KEY_PROFILE_HINT);
183
+ }
532
184
  fail(exitForError(err), err.message);
533
185
  }
534
186
  throw err;
535
187
  }
536
188
  }
189
+ var KEY_PROFILE_HINT = "Save an API key in its own profile: engini login key --profile <name>, then pass --profile <name>.";
190
+ function activeOAuthProfile() {
191
+ try {
192
+ const active = resolveActive();
193
+ if (active.source === "env-credential" || active.profile.auth_kind !== "oauth") return void 0;
194
+ return active.name;
195
+ } catch {
196
+ return void 0;
197
+ }
198
+ }
537
199
 
538
200
  // src/tools/render.ts
539
201
  function clean(value) {
@@ -759,12 +421,12 @@ async function pollSignInStatus(client, state, opts) {
759
421
 
760
422
  // src/connect.ts
761
423
  var PLACEHOLDER = "<value>";
762
- function connectionsUrl(config) {
763
- return `${config.identity_url.replace(/\/+$/, "")}/connections#integrations`;
424
+ function connectionsUrl(identityUrl) {
425
+ return `${identityUrl.replace(/\/+$/, "")}/connections#integrations`;
764
426
  }
765
427
  async function connectBody(application, opts) {
766
428
  if (!application && opts.connection === void 0) {
767
- const url = connectionsUrl(loadConfig());
429
+ const url = connectionsUrl(resolveActive().profile.identity_url);
768
430
  openBrowser(url);
769
431
  printOutput({ url });
770
432
  return;
@@ -912,7 +574,7 @@ async function chooseAuth(methods, auth, application, provider) {
912
574
  need: "auth",
913
575
  application,
914
576
  methods: methods.map(methodSummary),
915
- resume: `engini connect ${application} --auth <id>${providerResumeFlag(provider)}`
577
+ resume: `engini connect ${application} --auth <id>${providerResumeFlag(provider)}${profileResumeFlag()}`
916
578
  });
917
579
  }
918
580
  async function collectFields(method, application, provided, oauthState, fieldOptions, provider, derived) {
@@ -931,7 +593,7 @@ async function collectFields(method, application, provided, oauthState, fieldOpt
931
593
  const schema = method.connectionFields.filter(
932
594
  (f) => !f.isHidden && !(providerPinned && f.setOnProvider)
933
595
  );
934
- const resumeHint = oauthState ? `Resume with: engini connect ${application} --auth ${method.authenticationId} --oauth-state ${oauthState}${providerResumeFlag(provider)}` : void 0;
596
+ const resumeHint = oauthState ? `Resume with: engini connect ${application} --auth ${method.authenticationId} --oauth-state ${oauthState}${providerResumeFlag(provider)}${profileResumeFlag()}` : void 0;
935
597
  for (const [k, v] of Object.entries(provided)) {
936
598
  if (v === PLACEHOLDER) delete provided[k];
937
599
  }
@@ -952,8 +614,8 @@ async function collectFields(method, application, provided, oauthState, fieldOpt
952
614
  }
953
615
  for (const k of derived ?? []) delete provided[k];
954
616
  const isSatisfied = (name) => name in provided || (derived?.has(name) ?? false);
955
- const required = schema.filter((f) => f.isRequired);
956
- const missing = required.filter((f) => !isSatisfied(f.fieldName));
617
+ const required2 = schema.filter((f) => f.isRequired);
618
+ const missing = required2.filter((f) => !isSatisfied(f.fieldName));
957
619
  if (missing.length === 0) return provided;
958
620
  if (isInteractive()) {
959
621
  for (const f of schema) {
@@ -971,6 +633,7 @@ async function collectFields(method, application, provided, oauthState, fieldOpt
971
633
  `--auth ${method.authenticationId}`,
972
634
  ...oauthState ? [`--oauth-state ${oauthState}`] : [],
973
635
  ...provider ? [`--provider ${provider.id}`] : [],
636
+ profileResumeFlag().trim(),
974
637
  fieldsFlags
975
638
  ].filter(Boolean);
976
639
  return need({
@@ -1030,7 +693,7 @@ async function resolveObjects(objs, connectionId, application) {
1030
693
  application,
1031
694
  connection_id: connectionId,
1032
695
  objects: objs.map(objectSummary),
1033
- resume: `engini connect ${app} --connection ${connectionId} --object <id>`
696
+ resume: `engini connect ${app} --connection ${connectionId} --object <id>${profileResumeFlag()}`
1034
697
  });
1035
698
  }
1036
699
  async function oauthFieldsFor(client, application, method, oauthState, field, timing, provider) {
@@ -1081,8 +744,9 @@ async function oauthFieldsFor(client, application, method, oauthState, field, ti
1081
744
  // The state pins the provider server-side, but the replay still needs it client-side to
1082
745
  // know which "Set on provider" fields not to ask for again.
1083
746
  ...provider ? [`--provider ${provider.id}`] : [],
747
+ profileResumeFlag().trim(),
1084
748
  ...(field ?? []).map((spec) => resumeFieldFlag(spec, secretFields))
1085
- ].join(" ")
749
+ ].filter(Boolean).join(" ")
1086
750
  });
1087
751
  }
1088
752
  function providerResumeFlag(provider) {
@@ -2041,7 +1705,7 @@ async function signInUrlBody(application, opts) {
2041
1705
  printOutput({
2042
1706
  sign_in_url: resp.signInUrl,
2043
1707
  state: resp.state,
2044
- resume: `engini connections oauth-complete ${application} --auth ${auth} --state ${resp.state}`
1708
+ resume: `engini connections oauth-complete ${application} --auth ${auth} --state ${resp.state}${profileResumeFlag()}`
2045
1709
  });
2046
1710
  }
2047
1711
  function registerConnectionsSignInUrl(connections) {
@@ -2196,12 +1860,36 @@ CORE COMMANDS
2196
1860
  Typical flow: login \u2192 applications list \u2192 tools list \u2192 tools call
2197
1861
 
2198
1862
  ACCOUNT
2199
- login Store an opaque Engini API key (eng_\u2026): --api-key, or interactive on a TTY.
2200
- The key must start with "eng_"; a malformed or empty one exits 2 and
2201
- stores nothing. Interactive entry needs a terminal on stdin AND stdout.
2202
- logout Clear the stored credentials.
2203
- whoami Show the authenticated user/company, and the workspace + environment an
2204
- API key is scoped to (both null for a login token or an unscoped key).
1863
+ login [--profile <name>] [--workspace <id> --environment <id>] [--no-browser]
1864
+ Sign in in the browser (default). Check that the confirmation code in the
1865
+ terminal matches the browser, then approve either everything you can open in
1866
+ the account (default) or one workspace + environment. The session refreshes
1867
+ itself for up to 30 days. --workspace/--environment set the profile's default
1868
+ pair. --no-browser prints the link instead (the link returns to 127.0.0.1 on
1869
+ the machine that opens it: over SSH, forward the port with ssh -L, or use
1870
+ \`login key\`). --auth-url <url> names the sign-in server (default: the API
1871
+ host with api. -> identity.); --allow-host <host> trusts one outside engini.io.
1872
+ login key [--profile <name>]
1873
+ Paste an API key (eng_\u2026) instead: interactive on a TTY, piped on stdin (CI),
1874
+ or --api-key. The key is checked with the server first; a malformed or empty
1875
+ one exits 2 and stores nothing. No terminal and no key: use this.
1876
+ logout Clear the selected profile's credentials (a browser login is also revoked).
1877
+ whoami Show the authenticated user/company, which profile answered, its scope mode
1878
+ (account | pair | key), the workspace + environment commands act in and
1879
+ every pair the login can open (accessible_scopes, with ids - names repeat).
1880
+ profile list | show [name] | add <name> | use <name> | rename <old> <new> | rm <name>
1881
+ Manage named logins - one per account or environment. Every command takes
1882
+ --profile <name>; \`profile use\` sets the default.
1883
+
1884
+ Workspace + environment (browser logins): every command takes --workspace <id>
1885
+ --environment <id> (GUIDs, always together; or ENGINI_WORKSPACE_ID +
1886
+ ENGINI_ENVIRONMENT_ID), else the profile's default pair. With none, lists cover every
1887
+ pair you can open, and a write exits 2 asking for one - it never lands silently in the
1888
+ account's default workspace. An API-key profile is pinned to its key's pair (naming
1889
+ one exits 2). The workflow builder (workflows search|schema|options|tables|columns|
1890
+ connections|compile|plan|create|update) works on both profile kinds; on a browser login
1891
+ its reads and writes both need a pair and exit 2 without one. Template submit needs an
1892
+ API-key profile.
2205
1893
 
2206
1894
  CONNECTIONS
2207
1895
  connect [<app>] [--provider <name|id|none>]
@@ -2339,7 +2027,7 @@ TRIGGERS
2339
2027
  Note: add/rotate-secret/set(create) print the signing secret in the clear, once.
2340
2028
 
2341
2029
  EXECUTIONS
2342
- Read-only run history of workflows, table automations and business rules (no rerun).
2030
+ Run history of workflows, table automations and business rules; 'rerun' runs one again.
2343
2031
  executions list [--workflow <id>] [--type <t>] [--trigger-type <t>] [--status <s>...]
2344
2032
  [--context <text>] [--created-by <id>] [--created-after|--created-before <iso>]
2345
2033
  [--closed-after|--closed-before <iso>] [--sort <spec>] [--cursor <c>] [--top <n>] [--all]
@@ -2349,6 +2037,7 @@ EXECUTIONS
2349
2037
  executions data <execution_id> <step_no> [--type <kind>] [--loop-path <s:i>...] [--run-number <n>]
2350
2038
  [--retry-no <n>] [--status <s>] [--top <n>] [--offset <n>]
2351
2039
  Recorded step payloads; drains every page unless --top.
2040
+ executions rerun <execution_id> Run it again; prints the new execution. No prompt, no idempotency key.
2352
2041
  Note: step detail is deleted after the workflow's history retention window (410).
2353
2042
 
2354
2043
  WORKFLOW BUILDER
@@ -2360,6 +2049,16 @@ WORKFLOW BUILDER
2360
2049
  Workflows with their ids (no steps); { items, totalCount, offset, top }.
2361
2050
  workflows folders [--name <text>] [--top <n>] [--offset <n>] [--all]
2362
2051
  Workflow folders ({ id, name, workspaceId, environmentId, itemsCount }).
2052
+ workflows get <workflow_id> One workflow with its steps (and webhookUrl for a webhook trigger).
2053
+ workflows revisions <workflow_id> [--created-by <id>] [--created-after|--created-before <iso>]
2054
+ [--sort <spec>] [--top <n>] [--offset <n>]
2055
+ Stored revisions, newest first; { items, totalCount, offset, top }.
2056
+ workflows enable <workflow_id> | workflows disable <workflow_id>
2057
+ Turn it on / off; prints the workflow afterwards.
2058
+ workflows delete <workflow_id> [--force] Soft delete; confirms on a terminal, scripts pass --force.
2059
+ workflows run <workflow_id> [--body <json|@file|->]
2060
+ Start one run now (payload default {}); prints the execution
2061
+ in snake_case. No prompt, no idempotency key.
2363
2062
  workflows search [query] [--kind <k>] [--app <slug>] [--table <id>] [--top <n>]
2364
2063
  workflows schema <slug> [--connection <id>] [--kind <k>] [--table <id>]
2365
2064
  workflows options <slug> [--field <f>] [--connection <id>] [--depends-on <field=value>...]
@@ -2371,6 +2070,8 @@ WORKFLOW BUILDER
2371
2070
  workflows update <workflow_id> [--file <path>|stdin] [--expected-revision-id <n>]
2372
2071
  Note: list/folders print one page of up to 100 unless --all; --folder-id 0 means no folder.
2373
2072
  Note: compile returns a plan with errors (hasErrors: true); create/update refuse it.
2073
+ Note: enable/disable/delete/run/rerun need a workspace-scoped key (403 SCOPE_READ_ONLY -> exit 3);
2074
+ a 409 (not runnable, still running) exits 1 with the server's message.
2374
2075
 
2375
2076
  OUTPUT & EXIT CODES
2376
2077
  Output adapts to context: human-readable on a TTY, compact JSON when piped, pretty
@@ -2384,15 +2085,31 @@ ${exitCodeLines()}
2384
2085
 
2385
2086
  FILES & ENVIRONMENT
2386
2087
  Config: $XDG_CONFIG_HOME/engini/config.toml (Windows: %APPDATA%\\engini\\config.toml)
2387
- Written 0600; stores api_url / identity_url / api_key / auth_kind.
2388
- Re-run \`engini login\` to change it.
2389
- Env: ENGINI_API_KEY (preferred) or ENGINI_API_TOKEN, plus ENGINI_COMPANY_TOKEN.
2390
- Resolution order: flags > environment > config.
2088
+ Written 0600; named profiles, each with api_url / identity_url / a credential (an
2089
+ API key, or a browser login's tokens + scope mode + default pair) and the company
2090
+ it belongs to. Upgrade every engini CLI on a machine together: older versions
2091
+ cannot read this file.
2092
+ Env: ENGINI_PROFILE picks a profile for one shell. ENGINI_API_TOKEN (+ ENGINI_COMPANY_TOKEN)
2093
+ is a credential for scripts. ENGINI_API_KEY is no longer read: set, every command
2094
+ exits 2 - save the key with \`printf %s "$KEY" | engini login key --profile ci\`.
2095
+ Profile order: --profile > ENGINI_PROFILE > ENGINI_API_TOKEN > default profile.
2096
+ ENGINI_PROFILE together with ENGINI_API_TOKEN exits 2; an unknown profile exits 4.
2097
+ ENGINI_WORKSPACE_ID + ENGINI_ENVIRONMENT_ID pick the pair for one shell (browser
2098
+ logins only; beside a key or ENGINI_API_TOKEN they exit 2).
2391
2099
  ENGINI_NO_UPDATE_CHECK=1 skips the "update available" check on a TTY.
2392
2100
 
2393
2101
  EXAMPLES
2394
- # Authenticate (or set ENGINI_API_KEY)
2395
- engini login --api-key eng_\u2026
2102
+ # Authenticate (a profile per account; the first one becomes the default)
2103
+ engini login # browser sign-in
2104
+ engini login --profile staging --api-url https://api.staging.engini.io
2105
+ printf %s "$KEY" | engini login key --profile ci # CI: an API key on stdin
2106
+
2107
+ # Act in one workspace + environment (browser logins; ids from \`engini whoami\`)
2108
+ engini workflows list --workspace <ws-id> --environment <env-id>
2109
+
2110
+ # Act as another profile for one command or one shell
2111
+ engini whoami --profile staging
2112
+ ENGINI_PROFILE=staging engini tools list
2396
2113
 
2397
2114
  # Discover apps and tools; pipe JSON to jq
2398
2115
  engini applications list --available --limit 10
@@ -2429,14 +2146,28 @@ LEARN MORE
2429
2146
  }
2430
2147
  var EXAMPLES = {
2431
2148
  login: `Examples:
2432
- engini login --api-key eng_\u2026 # store a key non-interactively
2433
- engini login --api-url https://staging.engini.io # point at another environment
2149
+ engini login # browser sign-in (default)
2150
+ engini login --profile staging --api-url https://api.staging.engini.io
2151
+ engini login --workspace <ws-id> --environment <env-id> # also store a default pair
2152
+ engini login --no-browser # print the link instead of opening it
2153
+ printf %s "$KEY" | engini login key --profile ci # CI: an API key on stdin, not the command line
2154
+ engini login key # paste an API key when prompted
2434
2155
  engini login --api-key eng_\u2026 --dry-run # preview without writing
2435
- engini login # interactive: paste the key when prompted
2436
2156
 
2437
- The key must start with "eng_". A malformed or empty key exits 2 without writing
2438
- anything, on either path. Interactive entry needs a terminal on both stdin and
2439
- stdout \u2014 pipe stdin (e.g. in CI) and you must pass --api-key.`,
2157
+ Browser login: compare the confirmation code shown here with the one in the browser,
2158
+ then approve everything you can open in the account (default) or one workspace +
2159
+ environment. The session refreshes itself for up to 30 days; \`engini logout\` revokes
2160
+ it. Browser login needs a terminal (or --no-browser); without either, paste a key.
2161
+ Over SSH the sign-in link returns to 127.0.0.1 on the machine that opens it: forward
2162
+ the port the CLI prints (ssh -L) or use \`login key\`. Builder commands
2163
+ (\`engini workflows search|schema|...|create|update\`) work on a browser login too, in
2164
+ the one workspace + environment you name (--workspace/--environment, env vars or the
2165
+ profile's default). Template submit needs an API-key profile.
2166
+
2167
+ API key: it must start with "eng_". A malformed or empty key exits 2 without writing
2168
+ anything, on every path. It is checked with the server before it is stored (a
2169
+ rejected key exits 3). --expect-company <name> refuses a login that belongs to
2170
+ another company (exit 5).`,
2440
2171
  "tools list": `Examples:
2441
2172
  engini tools list --application monday --limit 5
2442
2173
  engini tools list | jq -r '.[].tool_slug'
@@ -2495,8 +2226,213 @@ function installHelp(program) {
2495
2226
  }
2496
2227
 
2497
2228
  // src/login.ts
2498
- function keysUrl(config) {
2499
- return `${config.identity_url.replace(/\/+$/, "")}/api-keys`;
2229
+ import { Option } from "commander";
2230
+ import { EnginiAuthError as EnginiAuthError2 } from "@engini/sdk";
2231
+
2232
+ // src/oauth-login.ts
2233
+ import { createHash, randomBytes, timingSafeEqual } from "crypto";
2234
+ import { createServer } from "http";
2235
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
2236
+ var TOKEN_TIMEOUT_MS = 3e4;
2237
+ var PROBE_TIMEOUT_MS = 15e3;
2238
+ function base32(bytes) {
2239
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
2240
+ let bits = 0;
2241
+ let value = 0;
2242
+ let out = "";
2243
+ for (const byte of bytes) {
2244
+ value = value << 8 | byte;
2245
+ bits += 8;
2246
+ while (bits >= 5) {
2247
+ out += alphabet[value >>> bits - 5 & 31];
2248
+ bits -= 5;
2249
+ }
2250
+ }
2251
+ if (bits > 0) out += alphabet[value << 5 - bits & 31];
2252
+ return out;
2253
+ }
2254
+ function confirmationCode(codeChallenge) {
2255
+ return base32(createHash("sha256").update(codeChallenge, "utf8").digest()).slice(0, 6);
2256
+ }
2257
+ function checkAuthUrl(authUrl, allowHost) {
2258
+ let url;
2259
+ try {
2260
+ url = new URL(authUrl);
2261
+ } catch {
2262
+ fail(2 /* USAGE */, `--auth-url is not a URL: "${authUrl}".`);
2263
+ }
2264
+ const host = url.hostname.toLowerCase();
2265
+ const loopback = LOOPBACK_HOSTS.has(host);
2266
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
2267
+ fail(2 /* USAGE */, `The sign-in server must use https (got ${url.protocol}//${url.host}).`);
2268
+ }
2269
+ const engini = host === "engini.io" || host.endsWith(".engini.io");
2270
+ if (!engini && host !== allowHost?.trim().toLowerCase()) {
2271
+ fail(
2272
+ 2 /* USAGE */,
2273
+ `Refusing to sign in at ${url.host}: not an engini.io host.`,
2274
+ `If you trust it, pass --allow-host ${url.hostname}.`
2275
+ );
2276
+ }
2277
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
2278
+ }
2279
+ async function probe(authUrl) {
2280
+ const noBrowserLogin = () => fail(3 /* AUTH */, "This server has no browser login yet - run engini login key.", "Paste an API key instead: engini login key");
2281
+ let res;
2282
+ try {
2283
+ res = await fetch(`${authUrl}/api/oauth/clients/${CLIENT_ID}/public-info`, {
2284
+ headers: { accept: "application/json" },
2285
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS)
2286
+ });
2287
+ } catch (err) {
2288
+ fail(
2289
+ 1 /* GENERIC */,
2290
+ `Cannot reach the sign-in server at ${authUrl}: ${err instanceof Error ? err.message : String(err)}`,
2291
+ "Check --auth-url / --api-url and your network, or paste an API key: engini login key"
2292
+ );
2293
+ }
2294
+ if (!res.ok) noBrowserLogin();
2295
+ let info;
2296
+ try {
2297
+ info = await res.json();
2298
+ } catch {
2299
+ return noBrowserLogin();
2300
+ }
2301
+ if (info.nativeLoopback !== true) noBrowserLogin();
2302
+ return { sessionLifetimeDays: typeof info.sessionLifetimeDays === "number" ? info.sessionLifetimeDays : void 0 };
2303
+ }
2304
+ async function listenLoopback() {
2305
+ for (let attempt = 0; attempt < 5; attempt++) {
2306
+ const server = createServer();
2307
+ await new Promise((resolve, reject) => {
2308
+ server.once("error", reject);
2309
+ server.listen(0, "127.0.0.1", () => resolve());
2310
+ });
2311
+ const { port } = server.address();
2312
+ if (port >= 1024) return { server, port };
2313
+ await new Promise((resolve) => server.close(() => resolve()));
2314
+ }
2315
+ fail(1 /* GENERIC */, "Could not open a local port (>= 1024) for the sign-in callback.");
2316
+ }
2317
+ var PAGE_HEADERS = {
2318
+ "content-type": "text/html; charset=utf-8",
2319
+ "cache-control": "no-store",
2320
+ "referrer-policy": "no-referrer"
2321
+ };
2322
+ function page(res, status, text) {
2323
+ res.writeHead(status, PAGE_HEADERS);
2324
+ res.end(
2325
+ `<!doctype html><html><head><meta charset="utf-8"><title>Engini CLI</title></head><body style="font-family:system-ui,sans-serif;margin:3rem"><p>${text}</p></body></html>`
2326
+ );
2327
+ }
2328
+ function safeEqual(a, b) {
2329
+ const x = Buffer.from(a, "utf8");
2330
+ const y = Buffer.from(b, "utf8");
2331
+ return x.length === y.length && timingSafeEqual(x, y);
2332
+ }
2333
+ function waitForCallback(server, port, state, timeoutSec) {
2334
+ return new Promise((resolve) => {
2335
+ const timer = setTimeout(() => resolve("timeout"), timeoutSec * 1e3);
2336
+ server.on("request", (req, res) => {
2337
+ const url = new URL(req.url ?? "/", `http://127.0.0.1:${port}`);
2338
+ const ok = req.method === "GET" && url.pathname === "/callback" && req.headers.host === `127.0.0.1:${port}` && safeEqual(url.searchParams.get("state") ?? "", state);
2339
+ if (!ok) {
2340
+ page(res, 404, "Not found.");
2341
+ return;
2342
+ }
2343
+ clearTimeout(timer);
2344
+ const error = url.searchParams.get("error");
2345
+ const code = url.searchParams.get("code");
2346
+ if (error || !code) {
2347
+ page(res, 200, "Sign-in was not completed. You can close this tab and return to the terminal.");
2348
+ resolve({ error: error ?? "no_code" });
2349
+ return;
2350
+ }
2351
+ page(res, 200, "Signed in. You can close this tab and return to the terminal.");
2352
+ resolve({ code });
2353
+ });
2354
+ });
2355
+ }
2356
+ async function exchange(authUrl, code, redirectUri, verifier) {
2357
+ let res;
2358
+ try {
2359
+ res = await fetch(`${authUrl}/api/oauth/token`, {
2360
+ method: "POST",
2361
+ // The token endpoint binds form fields only ([FromForm]); JSON is refused.
2362
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
2363
+ body: new URLSearchParams({
2364
+ grant_type: "authorization_code",
2365
+ code,
2366
+ redirect_uri: redirectUri,
2367
+ client_id: CLIENT_ID,
2368
+ code_verifier: verifier
2369
+ }).toString(),
2370
+ signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS)
2371
+ });
2372
+ } catch (err) {
2373
+ fail(1 /* GENERIC */, `Could not finish signing in: ${err instanceof Error ? err.message : String(err)}`, "Run engini login again.");
2374
+ }
2375
+ if (res.status === 400) fail(3 /* AUTH */, "The sign-in server refused the login code.", "Run engini login again.");
2376
+ if (res.status === 429) fail(1 /* GENERIC */, "The sign-in server is rate limiting.", "Retry shortly.");
2377
+ if (!res.ok) fail(1 /* GENERIC */, `The sign-in server answered ${res.status}.`, "Run engini login again.");
2378
+ let body;
2379
+ try {
2380
+ body = await res.json();
2381
+ } catch {
2382
+ fail(1 /* GENERIC */, "The sign-in server sent an unreadable token response.");
2383
+ }
2384
+ if (typeof body.access_token !== "string" || typeof body.refresh_token !== "string" || typeof body.expires_in !== "number") {
2385
+ fail(1 /* GENERIC */, "The sign-in server sent an incomplete token response.");
2386
+ }
2387
+ return {
2388
+ accessToken: body.access_token,
2389
+ refreshToken: body.refresh_token,
2390
+ expiresIn: body.expires_in,
2391
+ scopeMode: typeof body.scope_mode === "string" ? body.scope_mode : void 0
2392
+ };
2393
+ }
2394
+ async function oauthLogin(opts) {
2395
+ const authUrl = checkAuthUrl(opts.authUrl, opts.allowHost);
2396
+ const { sessionLifetimeDays } = await probe(authUrl);
2397
+ const verifier = randomBytes(32).toString("base64url");
2398
+ const challenge = createHash("sha256").update(verifier, "ascii").digest("base64url");
2399
+ const state = randomBytes(16).toString("base64url");
2400
+ const { server, port } = await listenLoopback();
2401
+ try {
2402
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
2403
+ const link = `${authUrl}/oauth/authorize?response_type=code&client_id=${encodeURIComponent(CLIENT_ID)}&redirect_uri=${encodeURIComponent(redirectUri)}&code_challenge=${encodeURIComponent(challenge)}&code_challenge_method=S256&state=${encodeURIComponent(state)}&scope=${encodeURIComponent("openid profile")}`;
2404
+ console.error(`Sign in to Engini in your browser:
2405
+ ${link}`);
2406
+ console.error(`Confirmation code: ${confirmationCode(challenge)} (the browser shows the same code)`);
2407
+ if (opts.openBrowser) {
2408
+ opts.opener?.(link);
2409
+ } else {
2410
+ console.error(
2411
+ `The link redirects to 127.0.0.1:${port} on the machine that opens it. On a remote shell, forward the port first: ssh -L ${port}:127.0.0.1:${port} <host>. No browser at all? Use engini login key.`
2412
+ );
2413
+ }
2414
+ const outcome = await waitForCallback(server, port, state, opts.timeoutSec);
2415
+ if (outcome === "timeout") {
2416
+ fail(124 /* TIMEOUT */, `No sign-in arrived within ${opts.timeoutSec} s.`, "Run engini login again (or --timeout <sec>).");
2417
+ }
2418
+ if ("error" in outcome) {
2419
+ if (outcome.error === "access_denied") fail(3 /* AUTH */, "Sign-in was declined in the browser.");
2420
+ const reason = outcome.error.replace(/[^\w.-]/g, "").slice(0, 64) || "unknown";
2421
+ fail(3 /* AUTH */, `Sign-in failed in the browser (${reason}).`, "Run engini login again.");
2422
+ }
2423
+ const tokens = await exchange(authUrl, outcome.code, redirectUri, verifier);
2424
+ return { ...tokens, sessionLifetimeDays };
2425
+ } finally {
2426
+ server.closeAllConnections();
2427
+ await new Promise((resolve) => server.close(() => resolve()));
2428
+ }
2429
+ }
2430
+
2431
+ // src/login.ts
2432
+ var DEFAULT_TIMEOUT_SEC = 300;
2433
+ var DEFAULT_SESSION_DAYS = 30;
2434
+ function keysUrl(identityUrl) {
2435
+ return `${identityUrl.replace(/\/+$/, "")}/api-keys`;
2500
2436
  }
2501
2437
  var MAX_KEY_ATTEMPTS = 3;
2502
2438
  function charCount(key) {
@@ -2510,6 +2446,7 @@ function keyProblem(key, truncated = false) {
2510
2446
  }
2511
2447
  return null;
2512
2448
  }
2449
+ var STDIN_HINT = 'Pipe it on stdin: printf %s "$KEY" | engini login key';
2513
2450
  async function askForKey(url) {
2514
2451
  console.log("");
2515
2452
  console.log("Paste your API key below - it will not be echoed.");
@@ -2521,19 +2458,15 @@ async function askForKey(url) {
2521
2458
  try {
2522
2459
  ({ value: key, truncated } = await promptHidden(" API key"));
2523
2460
  } catch (err) {
2524
- if (err instanceof PromptCancelled) fail(2 /* USAGE */, "Cancelled \u2014 no credentials stored.");
2461
+ if (err instanceof PromptCancelled) fail(2 /* USAGE */, "Cancelled - no credentials stored.");
2525
2462
  if (err instanceof PromptStreamEnded) {
2526
- fail(
2527
- 2 /* USAGE */,
2528
- "Input ended before a key was entered.",
2529
- "Pass the key directly instead: engini login --api-key eng_\u2026"
2530
- );
2463
+ fail(2 /* USAGE */, "Input ended before a key was entered.", STDIN_HINT);
2531
2464
  }
2532
2465
  throw err;
2533
2466
  }
2534
2467
  const problem = keyProblem(key, truncated);
2535
2468
  if (!problem) {
2536
- console.log(` \u2713 Received ${charCount(key)} characters \u2014 ${maskSecret(key)}`);
2469
+ console.log(` \u2713 Received ${charCount(key)} characters - ${maskSecret(key)}`);
2537
2470
  console.log("");
2538
2471
  return key;
2539
2472
  }
@@ -2541,18 +2474,68 @@ async function askForKey(url) {
2541
2474
  fail(
2542
2475
  2 /* USAGE */,
2543
2476
  `${problem} Giving up after ${MAX_KEY_ATTEMPTS} attempts.`,
2544
- `Pass the key directly instead: engini login --api-key eng_\u2026 (create one at ${url})`
2477
+ `${STDIN_HINT} (create a key at ${url})`
2545
2478
  );
2546
2479
  }
2547
2480
  console.log(` ! ${problem} Try again, or press Ctrl-C to cancel.`);
2548
2481
  console.log("");
2549
2482
  }
2550
2483
  }
2551
- async function loginBody(opts) {
2552
- const config = loadConfig();
2553
- const hadCredentials = Boolean(config.api_key || config.api_token);
2554
- if (opts.apiUrl) config.api_url = opts.apiUrl;
2555
- if (opts.identityUrl) config.identity_url = opts.identityUrl;
2484
+ async function keyFromStdin() {
2485
+ const raw = (await readStdin()).trim();
2486
+ const multiline = raw.includes("\n");
2487
+ const problem = keyProblem(multiline ? raw.split("\n")[0].trim() : raw, multiline);
2488
+ if (problem) fail(2 /* USAGE */, `The key on stdin is not usable. ${problem}`, STDIN_HINT);
2489
+ return raw;
2490
+ }
2491
+ function sameCompany(a, b) {
2492
+ return a.trim().toLowerCase() === b.trim().toLowerCase();
2493
+ }
2494
+ async function loginBody(method, opts, target) {
2495
+ if (method !== void 0 && method !== "key") {
2496
+ fail(
2497
+ 2 /* USAGE */,
2498
+ `Unknown login method "${method}".`,
2499
+ "Run `engini login` (browser sign-in) or `engini login key` (paste an API key)."
2500
+ );
2501
+ }
2502
+ if (method === "key" && opts.apiKey !== void 0) {
2503
+ fail(2 /* USAGE */, "Pass the key either as `login key` (stdin or prompt) or with --api-key, not both.");
2504
+ }
2505
+ if (method === "key" || opts.apiKey !== void 0) {
2506
+ const browserOnly = [
2507
+ [opts.browser === false, "--no-browser"],
2508
+ [opts.timeout !== void 0, "--timeout"],
2509
+ [opts.authUrl !== void 0, "--auth-url"],
2510
+ [opts.allowHost !== void 0, "--allow-host"],
2511
+ [opts.workspace !== void 0 || opts.environment !== void 0, "--workspace/--environment"]
2512
+ ];
2513
+ const misplaced = browserOnly.filter(([given]) => given).map(([, flag]) => flag);
2514
+ if (misplaced.length > 0) {
2515
+ fail(
2516
+ 2 /* USAGE */,
2517
+ `${misplaced.join(", ")} ${misplaced.length === 1 ? "applies" : "apply"} to the browser login only.`,
2518
+ "Drop them, or run `engini login` without `key` / --api-key."
2519
+ );
2520
+ }
2521
+ return pasteLogin(method, opts, target);
2522
+ }
2523
+ return browserLogin(opts, target);
2524
+ }
2525
+ async function pasteLogin(method, opts, target) {
2526
+ const existing = getProfile(loadConfig(), target.name);
2527
+ if (target.refuseExisting && existing) {
2528
+ fail(
2529
+ 5 /* VALIDATION */,
2530
+ `Profile "${target.name}" already exists.`,
2531
+ `Replace its login with \`engini login --profile ${target.name}\`.`
2532
+ );
2533
+ }
2534
+ const hadCredentials = Boolean(
2535
+ existing?.api_key || existing?.api_token || existing?.access_token || existing?.refresh_token || existing?.auth_kind === "oauth"
2536
+ );
2537
+ const apiUrl = opts.apiUrl ?? existing?.api_url ?? profileDefaults().api_url;
2538
+ const identityUrl = resolveIdentityUrl(opts, existing, apiUrl);
2556
2539
  let apiKey = opts.apiKey?.trim();
2557
2540
  if (opts.apiKey !== void 0) {
2558
2541
  const problem = keyProblem(apiKey ?? "");
@@ -2564,87 +2547,426 @@ async function loginBody(opts) {
2564
2547
  );
2565
2548
  }
2566
2549
  }
2550
+ if (!apiKey && method === "key" && !process.stdin.isTTY) apiKey = await keyFromStdin();
2567
2551
  if (!apiKey) {
2568
2552
  if (!isInteractive()) {
2569
2553
  fail(
2570
2554
  2 /* USAGE */,
2571
- "Provide --api-key when running non-interactively.",
2572
- "Interactive login needs a terminal on both stdin and stdout."
2555
+ "Provide the key when running non-interactively.",
2556
+ `${STDIN_HINT} (or pass --api-key). Interactive login needs a terminal on both stdin and stdout.`
2573
2557
  );
2574
2558
  }
2575
- const url = keysUrl(config);
2559
+ const url = keysUrl(identityUrl);
2576
2560
  let hasKey;
2577
2561
  try {
2578
2562
  hasKey = await confirm("Do you already have an Engini API key?");
2579
2563
  } catch (err) {
2580
2564
  if (err instanceof PromptStreamEnded) {
2581
- fail(
2582
- 2 /* USAGE */,
2583
- "Input ended before the question was answered.",
2584
- "Pass the key directly instead: engini login --api-key eng_\u2026"
2585
- );
2565
+ fail(2 /* USAGE */, "Input ended before the question was answered.", STDIN_HINT);
2586
2566
  }
2587
2567
  throw err;
2588
2568
  }
2589
- if (!hasKey) {
2590
- console.log(`Opening ${url} \u2014 create a key there, then paste it below.`);
2569
+ if (!hasKey && !dryRun()) {
2570
+ console.log(`Opening ${url} - create a key there, then paste it below.`);
2591
2571
  openBrowser(url);
2592
2572
  }
2593
2573
  apiKey = await askForKey(url);
2594
2574
  }
2595
- config.api_key = apiKey;
2596
- config.auth_kind = "api-key";
2597
2575
  const summary6 = {
2576
+ profile: target.name,
2598
2577
  auth_kind: "api-key",
2599
2578
  credential: maskSecret(apiKey),
2600
- api_url: config.api_url
2579
+ api_url: apiUrl
2601
2580
  };
2602
2581
  if (dryRun()) {
2603
2582
  printOutput({ would_store: summary6 });
2604
2583
  return;
2605
2584
  }
2606
2585
  if (hadCredentials) {
2607
- await confirmOrFail("Credentials already exist. Overwrite?", { force: Boolean(opts.force) });
2586
+ await confirmOrFail(`Profile "${target.name}" already has credentials. Overwrite?`, {
2587
+ force: Boolean(opts.force)
2588
+ });
2589
+ }
2590
+ let labels = {};
2591
+ try {
2592
+ const me = await clientFor({ apiKey }, apiUrl).auth.whoami();
2593
+ labels = {
2594
+ company: me.currentCompany ?? void 0,
2595
+ workspace: me.workspace?.name ?? void 0,
2596
+ environment: me.environment?.name ?? void 0
2597
+ };
2598
+ } catch (err) {
2599
+ if (err instanceof EnginiAuthError2) {
2600
+ fail(3 /* AUTH */, "The server rejected that key (401). Nothing was stored.", "Check the key and --api-url, then try again.");
2601
+ }
2602
+ if (opts.expectCompany !== void 0) {
2603
+ fail(1 /* GENERIC */, "Could not verify the key's company before storing it, so --expect-company cannot be honored.");
2604
+ }
2605
+ note("Could not reach the server to check the key; stored it without account labels.");
2606
+ }
2607
+ if (opts.expectCompany !== void 0 && !sameCompany(labels.company ?? "", opts.expectCompany)) {
2608
+ fail(
2609
+ 5 /* VALIDATION */,
2610
+ `This key belongs to "${labels.company ?? "an unknown company"}", not "${opts.expectCompany}". Nothing was stored.`
2611
+ );
2612
+ }
2613
+ let isDefault = false;
2614
+ let previous;
2615
+ await withRefreshLock(
2616
+ target.name,
2617
+ () => updateConfig((fresh) => {
2618
+ const base = getProfile(fresh, target.name);
2619
+ if (target.refuseExisting && base) {
2620
+ fail(5 /* VALIDATION */, `Profile "${target.name}" already exists.`);
2621
+ }
2622
+ previous = oauthSessionOf(base);
2623
+ const next = { ...profileDefaults(), ...base, api_url: apiUrl, identity_url: identityUrl };
2624
+ clearOAuth(next);
2625
+ next.api_key = apiKey;
2626
+ next.auth_kind = "api-key";
2627
+ next.api_token = void 0;
2628
+ next.company_token = void 0;
2629
+ next.login_method = "key";
2630
+ next.company = labels.company;
2631
+ next.workspace = labels.workspace;
2632
+ next.environment = labels.environment;
2633
+ if (opts.description !== void 0) next.description = opts.description;
2634
+ fresh.profiles[target.name] = next;
2635
+ isDefault = claimDefault(fresh, target.name);
2636
+ })
2637
+ );
2638
+ if (previous) await revokePrevious(previous);
2639
+ printOutput({
2640
+ stored: {
2641
+ ...summary6,
2642
+ default: isDefault,
2643
+ company: labels.company ?? null,
2644
+ workspace: labels.workspace ?? null,
2645
+ environment: labels.environment ?? null
2646
+ }
2647
+ });
2648
+ }
2649
+ function oauthSessionOf(profile) {
2650
+ return profile?.auth_kind === "oauth" && profile.refresh_token ? { auth_url: profile.auth_url, refresh_token: profile.refresh_token } : void 0;
2651
+ }
2652
+ function clearOAuth(profile) {
2653
+ for (const key of OAUTH_FIELDS) profile[key] = void 0;
2654
+ }
2655
+ function claimDefault(config, name) {
2656
+ if (config.default_profile === void 0 || !Object.hasOwn(config.profiles, config.default_profile)) {
2657
+ config.default_profile = name;
2658
+ }
2659
+ return config.default_profile === name;
2660
+ }
2661
+ async function revokePrevious(previous) {
2662
+ if (!await revokeSession(previous)) {
2663
+ note("Could not revoke the profile's previous browser session; it ends on its own within 30 days.");
2664
+ }
2665
+ }
2666
+ function deriveAuthUrl(apiUrl) {
2667
+ let url;
2668
+ try {
2669
+ url = new URL(apiUrl);
2670
+ } catch {
2671
+ fail(2 /* USAGE */, `--api-url is not a URL: "${apiUrl}".`);
2672
+ }
2673
+ if (!url.hostname.startsWith("api.")) {
2674
+ fail(
2675
+ 2 /* USAGE */,
2676
+ `Cannot tell the sign-in server for ${url.host}.`,
2677
+ "Pass --auth-url <identity host>, e.g. --auth-url https://identity.engini.io"
2678
+ );
2679
+ }
2680
+ url.hostname = `identity.${url.hostname.slice("api.".length)}`;
2681
+ return url.origin;
2682
+ }
2683
+ function hostOf(url) {
2684
+ try {
2685
+ return url === void 0 ? void 0 : new URL(url).host;
2686
+ } catch {
2687
+ return void 0;
2688
+ }
2689
+ }
2690
+ function resolveIdentityUrl(opts, existing, apiUrl) {
2691
+ if (opts.identityUrl !== void 0) return opts.identityUrl;
2692
+ const apiHostChanged = opts.apiUrl !== void 0 && hostOf(opts.apiUrl) !== hostOf(existing?.api_url);
2693
+ if (existing?.identity_url && !apiHostChanged) return existing.identity_url;
2694
+ let url;
2695
+ try {
2696
+ url = new URL(apiUrl);
2697
+ } catch {
2698
+ }
2699
+ if (url?.hostname.startsWith("api.")) {
2700
+ url.hostname = `app.${url.hostname.slice("api.".length)}`;
2701
+ return url.origin;
2702
+ }
2703
+ note(
2704
+ `Could not derive the app URL for ${url?.host ?? apiUrl}; links (keys page, connections) point to ${profileDefaults().identity_url}. Pass --identity-url <app url> to change it.`
2705
+ );
2706
+ return profileDefaults().identity_url;
2707
+ }
2708
+ function parseTimeout(value) {
2709
+ if (value === void 0) return DEFAULT_TIMEOUT_SEC;
2710
+ const n = Number(value);
2711
+ if (!/^\d+$/.test(value.trim()) || n < 1 || n > 3600) {
2712
+ fail(2 /* USAGE */, `--timeout must be a whole number of seconds between 1 and 3600, got "${value}".`);
2713
+ }
2714
+ return n;
2715
+ }
2716
+ function pairLabels(row2) {
2717
+ return { workspace: row2?.workspace.name ?? void 0, environment: row2?.environment.name ?? void 0 };
2718
+ }
2719
+ async function browserLogin(opts, target) {
2720
+ const named = checkedPair(opts.workspace, opts.environment, ["--workspace", "--environment"]);
2721
+ const timeoutSec = parseTimeout(opts.timeout);
2722
+ const existing = getProfile(loadConfig(), target.name);
2723
+ if (target.refuseExisting && existing) {
2724
+ fail(
2725
+ 5 /* VALIDATION */,
2726
+ `Profile "${target.name}" already exists.`,
2727
+ `Replace its login with \`engini login --profile ${target.name}\`.`
2728
+ );
2729
+ }
2730
+ if (opts.authUrl !== void 0 && opts.apiUrl === void 0 && !existing) {
2731
+ fail(
2732
+ 2 /* USAGE */,
2733
+ "--auth-url on a new profile needs --api-url too, or the API host would default to production.",
2734
+ "Pass both, e.g. --api-url https://api.staging.engini.io --auth-url https://identity.staging.engini.io"
2735
+ );
2736
+ }
2737
+ const apiUrl = opts.apiUrl ?? existing?.api_url ?? profileDefaults().api_url;
2738
+ const identityUrl = resolveIdentityUrl(opts, existing, apiUrl);
2739
+ const storedAuthUrl = opts.apiUrl === void 0 || opts.apiUrl === existing?.api_url ? existing?.auth_url : void 0;
2740
+ const authUrl = checkAuthUrl(opts.authUrl ?? storedAuthUrl ?? deriveAuthUrl(apiUrl), opts.allowHost);
2741
+ if (opts.browser !== false && !isInteractive()) {
2742
+ fail(
2743
+ 2 /* USAGE */,
2744
+ "Browser login needs a terminal.",
2745
+ 'Without one, save an API key: printf %s "$KEY" | engini login key (or --api-key). To print the sign-in link instead of opening a browser, pass --no-browser.'
2746
+ );
2747
+ }
2748
+ const hadCredentials = Boolean(
2749
+ existing?.api_key || existing?.api_token || existing?.access_token || existing?.refresh_token || existing?.auth_kind === "oauth"
2750
+ );
2751
+ const summary6 = {
2752
+ profile: target.name,
2753
+ auth_kind: "oauth",
2754
+ api_url: apiUrl,
2755
+ auth_url: authUrl
2756
+ };
2757
+ if (dryRun()) {
2758
+ printOutput({
2759
+ would_store: {
2760
+ ...summary6,
2761
+ workspace_id: named?.workspaceId ?? null,
2762
+ environment_id: named?.environmentId ?? null
2763
+ }
2764
+ });
2765
+ return;
2766
+ }
2767
+ if (hadCredentials) {
2768
+ await confirmOrFail(`Profile "${target.name}" already has credentials. Overwrite?`, {
2769
+ force: Boolean(opts.force)
2770
+ });
2608
2771
  }
2609
- saveConfig(config);
2610
- printOutput({ stored: summary6 });
2772
+ const session = await oauthLogin({
2773
+ authUrl,
2774
+ allowHost: opts.allowHost,
2775
+ openBrowser: opts.browser !== false,
2776
+ timeoutSec,
2777
+ opener: (url) => {
2778
+ openBrowser(url);
2779
+ }
2780
+ });
2781
+ const newSession = { auth_url: authUrl, refresh_token: session.refreshToken };
2782
+ let stored;
2783
+ let previous;
2784
+ try {
2785
+ const scopeMode = session.scopeMode;
2786
+ if (scopeMode !== "account" && scopeMode !== "pair") {
2787
+ fail(3 /* AUTH */, "This sign-in server is too old for browser login.", "Paste an API key instead: engini login key");
2788
+ }
2789
+ let me;
2790
+ try {
2791
+ me = await clientFor({ token: session.accessToken }, apiUrl).auth.whoami();
2792
+ } catch (err) {
2793
+ if (err instanceof EnginiAuthError2) {
2794
+ fail(3 /* AUTH */, "The API rejected the new sign-in (401/403). Nothing was stored.", "Check --api-url, then try again.");
2795
+ }
2796
+ if (opts.expectCompany !== void 0 || named !== void 0) {
2797
+ fail(1 /* GENERIC */, "Could not reach the API to check the sign-in, so --expect-company / --workspace cannot be honored.");
2798
+ }
2799
+ note("Could not reach the API to check the sign-in; stored it without account labels or a default pair.");
2800
+ }
2801
+ const company = me?.currentCompany ?? void 0;
2802
+ if (opts.expectCompany !== void 0 && !sameCompany(company ?? "", opts.expectCompany)) {
2803
+ fail(
2804
+ 5 /* VALIDATION */,
2805
+ `This sign-in is for "${company ?? "an unknown company"}", not "${opts.expectCompany}". Nothing was stored.`
2806
+ );
2807
+ }
2808
+ const rows = flattenScopes(me?.accessibleScopes);
2809
+ let pair;
2810
+ let row2;
2811
+ if (named) {
2812
+ row2 = findScope(rows, named);
2813
+ if (!row2) {
2814
+ fail(
2815
+ 5 /* VALIDATION */,
2816
+ `${named.workspaceId}/${named.environmentId} is not a workspace/environment this sign-in can open. Nothing was stored.`,
2817
+ "Run without --workspace/--environment, then `engini whoami` lists the pairs you can open."
2818
+ );
2819
+ }
2820
+ pair = named;
2821
+ } else if (rows.length === 1) {
2822
+ row2 = rows[0];
2823
+ pair = { workspaceId: row2.workspace.id, environmentId: row2.environment.id };
2824
+ }
2825
+ const now = Date.now();
2826
+ const accessExpiresAt = new Date(now + session.expiresIn * 1e3).toISOString();
2827
+ const sessionExpiresAt = new Date(
2828
+ now + (session.sessionLifetimeDays ?? DEFAULT_SESSION_DAYS) * 24 * 3600 * 1e3
2829
+ ).toISOString();
2830
+ const labels = pairLabels(row2);
2831
+ let isDefault = false;
2832
+ await withRefreshLock(
2833
+ target.name,
2834
+ () => updateConfig((fresh) => {
2835
+ const base = getProfile(fresh, target.name);
2836
+ if (target.refuseExisting && base) fail(5 /* VALIDATION */, `Profile "${target.name}" already exists.`);
2837
+ previous = oauthSessionOf(base);
2838
+ const next = { ...profileDefaults(), ...base, api_url: apiUrl, identity_url: identityUrl };
2839
+ clearOAuth(next);
2840
+ next.api_key = void 0;
2841
+ next.api_token = void 0;
2842
+ next.company_token = void 0;
2843
+ next.auth_kind = "oauth";
2844
+ next.login_method = "browser";
2845
+ next.auth_url = authUrl;
2846
+ next.access_token = session.accessToken;
2847
+ next.access_expires_at = accessExpiresAt;
2848
+ next.refresh_token = session.refreshToken;
2849
+ next.session_expires_at = sessionExpiresAt;
2850
+ next.scope_mode = scopeMode;
2851
+ next.workspace_id = pair?.workspaceId;
2852
+ next.environment_id = pair?.environmentId;
2853
+ next.company = company;
2854
+ next.workspace = labels.workspace;
2855
+ next.environment = labels.environment;
2856
+ if (opts.description !== void 0) next.description = opts.description;
2857
+ fresh.profiles[target.name] = next;
2858
+ isDefault = claimDefault(fresh, target.name);
2859
+ })
2860
+ );
2861
+ stored = {
2862
+ ...summary6,
2863
+ default: isDefault,
2864
+ scope_mode: scopeMode,
2865
+ session_expires_at: sessionExpiresAt,
2866
+ company: company ?? null,
2867
+ workspace: pair ? { id: pair.workspaceId, name: labels.workspace ?? null } : null,
2868
+ environment: pair ? { id: pair.environmentId, name: labels.environment ?? null } : null
2869
+ };
2870
+ if (!pair && me !== void 0) {
2871
+ note(
2872
+ "No default workspace/environment: lists cover every pair you can open; writes need --workspace/--environment (see `engini whoami`)."
2873
+ );
2874
+ }
2875
+ } catch (err) {
2876
+ await revokeSession(newSession);
2877
+ throw err;
2878
+ }
2879
+ if (previous && previous.refresh_token !== session.refreshToken) await revokePrevious(previous);
2880
+ printOutput({ stored });
2881
+ }
2882
+ function addLoginOptions(cmd) {
2883
+ return cmd.option("--api-key <key>", "Opaque Engini key (eng_\u2026)").option("--api-url <url>", "API base URL to persist (e.g. a staging host)").option("--identity-url <url>", "App base URL to persist; hosts the keys and connections pages (default: the API host with api. -> app.)").option("--description <text>", "A note shown in `engini profile list`").option("--expect-company <name>", "Refuse the login unless it belongs to this company").option("--force", "Overwrite existing credentials without confirming").addOption(new Option("--no-browser", "Browser login: print the sign-in link instead of opening it")).option("--timeout <sec>", `Browser login: seconds to wait for the sign-in (default ${DEFAULT_TIMEOUT_SEC})`).option("--auth-url <url>", "Browser login: the sign-in server (default: the API host with api. -> identity.)").option("--allow-host <host>", "Browser login: trust a sign-in host outside engini.io");
2611
2884
  }
2612
2885
  function registerLogin(program) {
2613
- const cmd = program.command("login").description("Store an opaque Engini API key.").option("--api-key <key>", "Opaque Engini key (eng_\u2026)").option("--api-url <url>", "API base URL to persist (e.g. a staging host)").option("--identity-url <url>", "Dashboard base URL to persist (hosts the keys page)").option("--force", "Overwrite existing credentials without confirming");
2886
+ const cmd = program.command("login").description("Sign a profile in: in the browser (default), or `login key` to paste an API key.").argument("[method]", "`key`: paste an API key (read from stdin when piped); omit it for the browser login");
2887
+ addLoginOptions(cmd);
2888
+ cmd.addHelpText(
2889
+ "after",
2890
+ '\nExamples:\n engini login\n engini login --profile staging --api-url https://api.staging.engini.io\n engini login --profile acme --workspace <ws-id> --environment <env-id>\n engini login --no-browser # print the link (same machine, or ssh -L the port)\n printf %s "$KEY" | engini login key --profile ci'
2891
+ );
2614
2892
  addUniversalOptions(cmd, { mutating: true });
2615
- cmd.action(async (opts, command) => {
2616
- await runCommand(command, opts, true, () => loginBody(opts));
2893
+ cmd.action(async (method, opts, command) => {
2894
+ await runCommand(
2895
+ command,
2896
+ opts,
2897
+ true,
2898
+ () => (
2899
+ // Same target as `logout`: the selected profile, else the stored default.
2900
+ loginBody(method, opts, {
2901
+ name: selectedProfile()?.name ?? loadConfig().default_profile ?? "default"
2902
+ })
2903
+ ),
2904
+ { offline: true }
2905
+ );
2617
2906
  });
2618
2907
  }
2619
2908
 
2620
2909
  // src/logout.ts
2621
- function logoutBody() {
2910
+ function hasLogin(profile) {
2911
+ return Boolean(
2912
+ profile.api_key || profile.api_token || profile.access_token || profile.refresh_token || profile.auth_kind === "oauth"
2913
+ );
2914
+ }
2915
+ function clearLogin(profile) {
2916
+ profile.api_key = void 0;
2917
+ profile.api_token = void 0;
2918
+ profile.company_token = void 0;
2919
+ profile.auth_kind = void 0;
2920
+ profile.login_method = void 0;
2921
+ profile.company = void 0;
2922
+ profile.workspace = void 0;
2923
+ profile.environment = void 0;
2924
+ for (const key of OAUTH_FIELDS) profile[key] = void 0;
2925
+ }
2926
+ async function logoutBody() {
2622
2927
  const config = loadConfig();
2623
- if (!(config.api_key || config.api_token)) {
2624
- printOutput({ logged_out: false, noop: true });
2928
+ const selected = selectedProfile();
2929
+ const name = selected?.name ?? config.default_profile;
2930
+ const profile = name !== void 0 ? getProfile(config, name) : void 0;
2931
+ if (selected && !profile) {
2932
+ fail(4 /* NOT_FOUND */, `Unknown profile "${selected.name}".`, "List profiles with `engini profile list`.");
2933
+ }
2934
+ if (!name || !profile || !hasLogin(profile)) {
2935
+ printOutput({ logged_out: false, noop: true, profile: name ?? null });
2625
2936
  return;
2626
2937
  }
2627
2938
  if (dryRun()) {
2628
- printOutput({ would_logout: true });
2939
+ printOutput({ would_logout: true, profile: name });
2629
2940
  return;
2630
2941
  }
2631
- config.api_key = void 0;
2632
- config.api_token = void 0;
2633
- config.company_token = void 0;
2634
- config.auth_kind = void 0;
2635
- saveConfig(config);
2636
- printOutput({ logged_out: true });
2942
+ const outcome = {};
2943
+ await withRefreshLock(name, async () => {
2944
+ const current = getProfile(loadConfig(), name);
2945
+ if (current?.auth_kind === "oauth" && current.refresh_token) {
2946
+ outcome.revoked = await revokeSession(current);
2947
+ if (!outcome.revoked) {
2948
+ note(
2949
+ `Could not revoke the browser session on the server; it stays valid until ${current.session_expires_at ?? "it expires"}. Cleared it locally.`
2950
+ );
2951
+ }
2952
+ }
2953
+ await updateConfig((fresh) => {
2954
+ const row2 = getProfile(fresh, name);
2955
+ if (row2) clearLogin(row2);
2956
+ });
2957
+ });
2958
+ printOutput({ logged_out: true, profile: name, ...outcome });
2637
2959
  }
2638
2960
  function registerLogout(program) {
2639
- const cmd = program.command("logout").description("Clear the stored credentials.");
2961
+ const cmd = program.command("logout").description("Clear the selected profile's stored credentials.");
2640
2962
  addUniversalOptions(cmd, { mutating: true });
2641
2963
  cmd.action(async (opts, command) => {
2642
- await runCommand(command, opts, true, logoutBody);
2964
+ await runCommand(command, opts, true, logoutBody, { offline: true });
2643
2965
  });
2644
2966
  }
2645
2967
 
2646
2968
  // src/shared/connections.ts
2647
- import { readFileSync as readFileSync2 } from "fs";
2969
+ import { readFileSync } from "fs";
2648
2970
  function collect2(value, previous = []) {
2649
2971
  return [...previous, value];
2650
2972
  }
@@ -2658,10 +2980,10 @@ function splitSlugs(spec) {
2658
2980
  function loadFromFile(spec) {
2659
2981
  let text;
2660
2982
  if (spec === "-") {
2661
- text = readFileSync2(0, "utf8");
2983
+ text = readFileSync(0, "utf8");
2662
2984
  } else if (spec.startsWith("@")) {
2663
2985
  try {
2664
- text = readFileSync2(spec.slice(1), "utf8");
2986
+ text = readFileSync(spec.slice(1), "utf8");
2665
2987
  } catch (err) {
2666
2988
  return fail(2 /* USAGE */, `Cannot read ${spec.slice(1)}: ${err.message}`);
2667
2989
  }
@@ -3282,7 +3604,7 @@ function registerOpaDelete(opa) {
3282
3604
  }
3283
3605
 
3284
3606
  // src/opa/download.ts
3285
- import { createHash } from "crypto";
3607
+ import { createHash as createHash2 } from "crypto";
3286
3608
  import { writeFile } from "fs/promises";
3287
3609
  import { basename } from "path";
3288
3610
  function targetFromManifest(url) {
@@ -3326,7 +3648,7 @@ async function downloadBody(opts) {
3326
3648
  const bytes = new Uint8Array(await response.arrayBuffer());
3327
3649
  let verified;
3328
3650
  if (manifest.sha256) {
3329
- const actual = createHash("sha256").update(bytes).digest("hex");
3651
+ const actual = createHash2("sha256").update(bytes).digest("hex");
3330
3652
  if (actual !== manifest.sha256.toLowerCase()) {
3331
3653
  fail(
3332
3654
  5 /* VALIDATION */,
@@ -3591,34 +3913,38 @@ function registerOpa(program) {
3591
3913
  registerOpaDownload(opa);
3592
3914
  }
3593
3915
 
3594
- // src/tools/call.ts
3595
- import { readFileSync as readFileSync4 } from "fs";
3596
- import {
3597
- AnthropicProvider,
3598
- File,
3599
- OpenAIProvider
3600
- } from "@engini/sdk";
3601
-
3602
3916
  // src/results.ts
3603
- import { randomBytes } from "crypto";
3917
+ import { randomBytes as randomBytes2 } from "crypto";
3604
3918
  import {
3605
- existsSync as existsSync2,
3606
- mkdirSync as mkdirSync2,
3607
- readFileSync as readFileSync3,
3919
+ existsSync,
3920
+ mkdirSync,
3921
+ readFileSync as readFileSync2,
3608
3922
  readdirSync,
3923
+ renameSync,
3609
3924
  rmSync,
3610
3925
  statSync,
3611
- writeFileSync as writeFileSync2
3926
+ writeFileSync
3612
3927
  } from "fs";
3613
- import { homedir as homedir2 } from "os";
3614
- import { join as join2 } from "path";
3928
+ import { homedir } from "os";
3929
+ import { join } from "path";
3615
3930
  var MAX_RESULTS = 20;
3616
3931
  var TTL_SECONDS = 24 * 60 * 60;
3617
3932
  var PREVIEW_BYTES = 512;
3933
+ function resultsRoot() {
3934
+ const base = process.platform === "win32" ? process.env.APPDATA ?? homedir() : process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache");
3935
+ return join(base, "engini", "results");
3936
+ }
3618
3937
  function cacheDir() {
3619
- const base = process.platform === "win32" ? process.env.APPDATA ?? homedir2() : process.env.XDG_CACHE_HOME ?? join2(homedir2(), ".cache");
3620
- return join2(base, "engini", "results");
3938
+ return join(resultsRoot(), sandboxKey());
3939
+ }
3940
+ function moveProfileResults(from, to) {
3941
+ const source = join(resultsRoot(), from);
3942
+ if (existsSync(source)) renameSync(source, join(resultsRoot(), to));
3943
+ }
3944
+ function removeProfileResults(name) {
3945
+ rmSync(join(resultsRoot(), name), { recursive: true, force: true });
3621
3946
  }
3947
+ var HANDLE = /^[hr][0-9a-f]{1,32}$/;
3622
3948
  function serialize(value) {
3623
3949
  return JSON.stringify(value ?? null);
3624
3950
  }
@@ -3626,13 +3952,13 @@ function byteLength(value) {
3626
3952
  return Buffer.byteLength(serialize(value), "utf8");
3627
3953
  }
3628
3954
  function jsonFiles(dir) {
3629
- if (!existsSync2(dir)) return [];
3955
+ if (!existsSync(dir)) return [];
3630
3956
  return readdirSync(dir).filter((name) => name.endsWith(".json"));
3631
3957
  }
3632
3958
  function storeResult(output, historyId) {
3633
- const handle = historyId !== null ? `h${historyId}` : `r${randomBytes(6).toString("hex")}`;
3959
+ const handle = historyId !== null ? `h${historyId}` : `r${randomBytes2(6).toString("hex")}`;
3634
3960
  const dir = cacheDir();
3635
- mkdirSync2(dir, { recursive: true, mode: 448 });
3961
+ mkdirSync(dir, { recursive: true, mode: 448 });
3636
3962
  const dataSize = byteLength(output);
3637
3963
  const payload = {
3638
3964
  output: output ?? null,
@@ -3640,15 +3966,16 @@ function storeResult(output, historyId) {
3640
3966
  data_size: dataSize,
3641
3967
  created: Math.floor(Date.now() / 1e3)
3642
3968
  };
3643
- writeFileSync2(join2(dir, `${handle}.json`), JSON.stringify(payload), { mode: 384 });
3969
+ writeFileSync(join(dir, `${handle}.json`), JSON.stringify(payload), { mode: 384 });
3644
3970
  prune();
3645
3971
  return { handle, dataSize };
3646
3972
  }
3647
3973
  function loadResult(handle) {
3648
- const path = join2(cacheDir(), `${handle}.json`);
3649
- if (!existsSync2(path)) return null;
3974
+ if (!HANDLE.test(handle)) return null;
3975
+ const path = join(cacheDir(), `${handle}.json`);
3976
+ if (!existsSync(path)) return null;
3650
3977
  try {
3651
- const data = JSON.parse(readFileSync3(path, "utf8"));
3978
+ const data = JSON.parse(readFileSync2(path, "utf8"));
3652
3979
  return data && typeof data === "object" ? data : null;
3653
3980
  } catch {
3654
3981
  return null;
@@ -3662,7 +3989,7 @@ function listResults() {
3662
3989
  const handle = name.slice(0, -".json".length);
3663
3990
  let mtimeMs;
3664
3991
  try {
3665
- mtimeMs = statSync(join2(dir, name)).mtimeMs;
3992
+ mtimeMs = statSync(join(dir, name)).mtimeMs;
3666
3993
  } catch {
3667
3994
  continue;
3668
3995
  }
@@ -3684,18 +4011,19 @@ function clearResults() {
3684
4011
  const dir = cacheDir();
3685
4012
  let count = 0;
3686
4013
  for (const name of jsonFiles(dir)) {
3687
- rmSync(join2(dir, name), { force: true });
4014
+ rmSync(join(dir, name), { force: true });
3688
4015
  count += 1;
3689
4016
  }
3690
4017
  return count;
3691
4018
  }
3692
4019
  function prune() {
4020
+ for (const name of jsonFiles(resultsRoot())) rmSync(join(resultsRoot(), name), { force: true });
3693
4021
  const dir = cacheDir();
3694
- if (!existsSync2(dir)) return;
4022
+ if (!existsSync(dir)) return;
3695
4023
  const now = Date.now();
3696
4024
  const entries = [];
3697
4025
  for (const name of jsonFiles(dir)) {
3698
- const path = join2(dir, name);
4026
+ const path = join(dir, name);
3699
4027
  try {
3700
4028
  entries.push({ path, mtime: statSync(path).mtimeMs });
3701
4029
  } catch {
@@ -3832,14 +4160,180 @@ function paginate(value, offset, limit) {
3832
4160
  return limit !== null ? sliced.slice(0, limit) : sliced;
3833
4161
  }
3834
4162
 
4163
+ // src/profile/index.ts
4164
+ function activeName(config) {
4165
+ if (process.env.ENGINI_API_TOKEN) return void 0;
4166
+ const fromEnv = process.env.ENGINI_PROFILE;
4167
+ if (fromEnv && validateProfileName(fromEnv) === null) return fromEnv;
4168
+ return config.default_profile;
4169
+ }
4170
+ function row(name, profile, config) {
4171
+ return {
4172
+ name,
4173
+ default: config.default_profile === name,
4174
+ active: activeName(config) === name,
4175
+ company: profile.company ?? null,
4176
+ workspace: profile.workspace ?? null,
4177
+ environment: profile.environment ?? null,
4178
+ scope_mode: profile.scope_mode ?? null,
4179
+ api_url: profile.api_url,
4180
+ auth_kind: profile.auth_kind ?? null,
4181
+ has_credential: Boolean(profile.api_key || profile.api_token || profile.access_token || profile.refresh_token),
4182
+ login_method: profile.login_method ?? null,
4183
+ session_expires_at: profile.session_expires_at ?? null,
4184
+ description: profile.description ?? null
4185
+ };
4186
+ }
4187
+ function required(value, label) {
4188
+ if (!value) fail(2 /* USAGE */, `Missing required argument '${label}'.`);
4189
+ return value;
4190
+ }
4191
+ function nameOrFail(name) {
4192
+ const problem = validateProfileName(name);
4193
+ if (problem) fail(2 /* USAGE */, problem);
4194
+ return name;
4195
+ }
4196
+ function requireProfile(config, name) {
4197
+ const profile = getProfile(config, name);
4198
+ if (!profile) fail(4 /* NOT_FOUND */, `Unknown profile "${name}".`, "List profiles with `engini profile list`.");
4199
+ return profile;
4200
+ }
4201
+ function listBody8() {
4202
+ const config = loadConfig();
4203
+ printOutput(Object.entries(config.profiles).map(([name, profile]) => row(name, profile, config)));
4204
+ }
4205
+ function showBody(name) {
4206
+ const config = loadConfig();
4207
+ const target = name ?? activeName(config);
4208
+ if (!target) fail(4 /* NOT_FOUND */, "No profile to show.", "Create one with `engini login`.");
4209
+ const profile = requireProfile(config, target);
4210
+ printOutput({
4211
+ ...row(target, profile, config),
4212
+ identity_url: profile.identity_url,
4213
+ auth_url: profile.auth_url ?? null,
4214
+ workspace_id: profile.workspace_id ?? null,
4215
+ environment_id: profile.environment_id ?? null
4216
+ });
4217
+ }
4218
+ async function useBody(name) {
4219
+ requireProfile(loadConfig(), name);
4220
+ if (dryRun()) {
4221
+ printOutput({ would_use: name });
4222
+ return;
4223
+ }
4224
+ await updateConfig((config) => {
4225
+ requireProfile(config, name);
4226
+ config.default_profile = name;
4227
+ });
4228
+ note("Shells that export ENGINI_PROFILE are unaffected; this changes only the default.");
4229
+ printOutput({ default: name });
4230
+ }
4231
+ async function renameBody(from, to) {
4232
+ nameOrFail(to);
4233
+ const config = loadConfig();
4234
+ requireProfile(config, from);
4235
+ if (getProfile(config, to)) fail(5 /* VALIDATION */, `Profile "${to}" already exists.`);
4236
+ if (dryRun()) {
4237
+ printOutput({ would_rename: { from, to } });
4238
+ return;
4239
+ }
4240
+ await updateConfig((fresh) => {
4241
+ const profile = requireProfile(fresh, from);
4242
+ if (getProfile(fresh, to)) fail(5 /* VALIDATION */, `Profile "${to}" already exists.`);
4243
+ fresh.profiles[to] = profile;
4244
+ delete fresh.profiles[from];
4245
+ if (fresh.default_profile === from) fresh.default_profile = to;
4246
+ });
4247
+ moveProfileResults(from, to);
4248
+ printOutput({ renamed: { from, to } });
4249
+ }
4250
+ async function rmBody(name, opts) {
4251
+ const config = loadConfig();
4252
+ requireProfile(config, name);
4253
+ const others = Object.keys(config.profiles).filter((n) => n !== name);
4254
+ if (config.default_profile === name && others.length > 0) {
4255
+ fail(
4256
+ 5 /* VALIDATION */,
4257
+ `"${name}" is the default profile.`,
4258
+ "Pick another default first: `engini profile use <name>`."
4259
+ );
4260
+ }
4261
+ if (dryRun()) {
4262
+ printOutput({ would_remove: name });
4263
+ return;
4264
+ }
4265
+ await confirmOrFail(`Remove profile "${name}" and its stored credentials?`, { force: Boolean(opts.force) });
4266
+ await withRefreshLock(name, async () => {
4267
+ const current = getProfile(loadConfig(), name);
4268
+ if (current?.auth_kind === "oauth" && current.refresh_token && !await revokeSession(current)) {
4269
+ note("Could not revoke the profile's browser session on the server; it ends on its own within 30 days.");
4270
+ }
4271
+ await updateConfig((fresh) => {
4272
+ delete fresh.profiles[name];
4273
+ if (fresh.default_profile === name) fresh.default_profile = void 0;
4274
+ });
4275
+ });
4276
+ removeProfileResults(name);
4277
+ printOutput({ removed: name });
4278
+ }
4279
+ var OFFLINE = { offline: true };
4280
+ function registerProfile(program) {
4281
+ const profile = program.command("profile").description("Manage the named logins in config.toml.");
4282
+ const list = profile.command("list").description("List profiles (never shows a credential).");
4283
+ addUniversalOptions(list, { profile: false });
4284
+ list.action(async (opts, command) => {
4285
+ await runCommand(command, opts, false, listBody8, OFFLINE);
4286
+ });
4287
+ const show = profile.command("show").description("Show one profile (default: the active one).").argument("[name]", "Profile name");
4288
+ addUniversalOptions(show, { profile: false });
4289
+ show.action(async (name, opts, command) => {
4290
+ await runCommand(command, opts, false, () => showBody(name), OFFLINE);
4291
+ });
4292
+ const add = profile.command("add").description("Create a profile (an alias of `engini login --profile <name>` that refuses an existing name).").argument("[name]", "Profile name").argument("[method]", "`key` reads the key from stdin when piped; omit it to be asked");
4293
+ addLoginOptions(add);
4294
+ addUniversalOptions(add, { mutating: true, profile: false });
4295
+ add.action(async (name, method, opts, command) => {
4296
+ await runCommand(
4297
+ command,
4298
+ opts,
4299
+ true,
4300
+ () => loginBody(method, opts, { name: nameOrFail(required(name, "name")), refuseExisting: true }),
4301
+ OFFLINE
4302
+ );
4303
+ });
4304
+ const use = profile.command("use").description("Make a profile the default.").argument("[name]", "Profile name");
4305
+ addUniversalOptions(use, { mutating: true, profile: false });
4306
+ use.action(async (name, opts, command) => {
4307
+ await runCommand(command, opts, true, () => useBody(required(name, "name")), OFFLINE);
4308
+ });
4309
+ const rename = profile.command("rename").description("Rename a profile, keeping its login and stored results.").argument("[old]", "Current name").argument("[new]", "New name");
4310
+ addUniversalOptions(rename, { mutating: true, profile: false });
4311
+ rename.action(
4312
+ async (from, to, opts, command) => {
4313
+ await runCommand(command, opts, true, () => renameBody(required(from, "old"), required(to, "new")), OFFLINE);
4314
+ }
4315
+ );
4316
+ const rm = profile.command("rm").description("Remove a profile and its stored credentials.").argument("[name]", "Profile name").option("--force", "Remove without confirming");
4317
+ addUniversalOptions(rm, { mutating: true, profile: false });
4318
+ rm.action(async (name, opts, command) => {
4319
+ await runCommand(command, opts, true, () => rmBody(required(name, "name"), opts), OFFLINE);
4320
+ });
4321
+ }
4322
+
3835
4323
  // src/tools/call.ts
4324
+ import { readFileSync as readFileSync3 } from "fs";
4325
+ import {
4326
+ AnthropicProvider,
4327
+ File,
4328
+ OpenAIProvider
4329
+ } from "@engini/sdk";
3836
4330
  function loadArgs(spec) {
3837
4331
  let text;
3838
4332
  if (spec === "-") {
3839
- text = readFileSync4(0, "utf8");
4333
+ text = readFileSync3(0, "utf8");
3840
4334
  } else if (spec.startsWith("@")) {
3841
4335
  try {
3842
- text = readFileSync4(spec.slice(1), "utf8");
4336
+ text = readFileSync3(spec.slice(1), "utf8");
3843
4337
  } catch (err) {
3844
4338
  return fail(2 /* USAGE */, `Cannot read ${spec.slice(1)}: ${err.message}`);
3845
4339
  }
@@ -4056,7 +4550,7 @@ function parseLimit2(value) {
4056
4550
  }
4057
4551
  return limit;
4058
4552
  }
4059
- async function listBody8(opts) {
4553
+ async function listBody9(opts) {
4060
4554
  if (opts.application && opts.toolset) {
4061
4555
  fail(2 /* USAGE */, "Pass only one of --application / --toolset.");
4062
4556
  }
@@ -4079,7 +4573,7 @@ function registerToolsList(tools) {
4079
4573
  const cmd = tools.command("list").description("List available tools, optionally filtered.").option("--application <slug>", "Filter by application slug (e.g. monday)").option("--toolset <id>", "List the tools of a server toolset (by id)").option("--limit <n>", "Cap the number of tools returned");
4080
4574
  addUniversalOptions(cmd);
4081
4575
  cmd.action(async (opts, command) => {
4082
- await runCommand(command, opts, false, () => listBody8(opts));
4576
+ await runCommand(command, opts, false, () => listBody9(opts));
4083
4577
  });
4084
4578
  }
4085
4579
 
@@ -4144,12 +4638,9 @@ function registerToolsResult(tools) {
4144
4638
  const cmd = tools.command("result").description("Drill into a sandboxed tools call result.").argument("[handle]", "Result handle from a prior tools call").option("--select <path>", "Dot-path to extract, e.g. items.email (repeatable)", collectSelect).option("--fields <keys>", "Comma-separated keys to project from object(s)").option("--offset <n>", "Skip N items of a list value").option("--limit <m>", "Return at most M list items").option("--full", "Emit the entire stored payload").option("--list", "List stored result handles").option("--clear", "Delete all stored results");
4145
4639
  addUniversalOptions(cmd);
4146
4640
  cmd.action(async (handle, opts, command) => {
4147
- await runCommand(
4148
- command,
4149
- opts,
4150
- false,
4151
- () => resultBody(handle, opts)
4152
- );
4641
+ await runCommand(command, opts, false, () => resultBody(handle, opts), {
4642
+ offline: true
4643
+ });
4153
4644
  });
4154
4645
  }
4155
4646
 
@@ -4355,7 +4846,7 @@ function registerToolsetsGet(toolsets) {
4355
4846
  }
4356
4847
 
4357
4848
  // src/toolsets/list.ts
4358
- async function listBody9() {
4849
+ async function listBody10() {
4359
4850
  const toolsets = await apiErrors(async () => {
4360
4851
  const client = buildClient();
4361
4852
  return client.toolsets.list();
@@ -4370,7 +4861,7 @@ function registerToolsetsList(toolsets) {
4370
4861
  );
4371
4862
  addUniversalOptions(cmd);
4372
4863
  cmd.action(async (opts, command) => {
4373
- await runCommand(command, opts, false, () => listBody9());
4864
+ await runCommand(command, opts, false, () => listBody10());
4374
4865
  });
4375
4866
  }
4376
4867
 
@@ -4760,11 +5251,11 @@ async function addBody(name, url, opts) {
4760
5251
  );
4761
5252
  printOutput(withSecret(created));
4762
5253
  }
4763
- async function listBody10() {
5254
+ async function listBody11() {
4764
5255
  const destinations = await apiErrors(async () => buildClient().triggers.destinations.list());
4765
5256
  printOutput(destinations.map(summarizeDestination));
4766
5257
  }
4767
- async function showBody(raw) {
5258
+ async function showBody2(raw) {
4768
5259
  const name = parseDestName(raw);
4769
5260
  const destination = await apiErrors(async () => buildClient().triggers.destinations.get(name));
4770
5261
  printOutput(summarizeDestination(destination));
@@ -4780,7 +5271,7 @@ async function enableBody(raw) {
4780
5271
  );
4781
5272
  printOutput(summarizeDestination(destination));
4782
5273
  }
4783
- async function rmBody(raw, opts) {
5274
+ async function rmBody2(raw, opts) {
4784
5275
  const name = parseDestName(raw);
4785
5276
  if (dryRun()) {
4786
5277
  printOutput({ would_delete: name, reassign_to: opts.reassign ?? null });
@@ -4826,13 +5317,13 @@ function registerTriggerDestinations(triggers) {
4826
5317
  list.addHelpText("after", "\nExamples:\n engini triggers destinations list --json");
4827
5318
  addUniversalOptions(list);
4828
5319
  list.action(async (opts, command) => {
4829
- await runCommand(command, opts, false, listBody10);
5320
+ await runCommand(command, opts, false, listBody11);
4830
5321
  });
4831
5322
  const show = destinations.command("show").description("One destination's failure counters and status.").argument("[name]", "Destination name");
4832
5323
  show.addHelpText("after", "\nExamples:\n engini triggers destinations show billing");
4833
5324
  addUniversalOptions(show);
4834
5325
  show.action(async (raw, opts, command) => {
4835
- await runCommand(command, opts, false, () => showBody(raw));
5326
+ await runCommand(command, opts, false, () => showBody2(raw));
4836
5327
  });
4837
5328
  const enable = destinations.command("enable").description("Re-enable an auto-disabled destination and reset its failure counter.").argument("[name]", "Destination name");
4838
5329
  enable.addHelpText("after", "\nExamples:\n engini triggers destinations enable billing");
@@ -4848,7 +5339,7 @@ function registerTriggerDestinations(triggers) {
4848
5339
  addUniversalOptions(rm, { mutating: true });
4849
5340
  rm.action(
4850
5341
  async (raw, opts, command) => {
4851
- await runCommand(command, opts, true, () => rmBody(raw, opts));
5342
+ await runCommand(command, opts, true, () => rmBody2(raw, opts));
4852
5343
  }
4853
5344
  );
4854
5345
  const rotate = destinations.command("rotate-secret").description("Issue a new signing secret, invalidating the current one immediately.").argument("[name]", "Destination name").option("--force", "Rotate without confirming");
@@ -4862,7 +5353,7 @@ function registerTriggerDestinations(triggers) {
4862
5353
  }
4863
5354
 
4864
5355
  // src/triggers/events.ts
4865
- async function listBody11(triggerId, opts) {
5356
+ async function listBody12(triggerId, opts) {
4866
5357
  if (triggerId === void 0 || triggerId === "") fail(2 /* USAGE */, "A trigger_id is required.");
4867
5358
  const top = opts.limit !== void 0 ? Number(opts.limit) : void 0;
4868
5359
  const events = await apiErrors(async () => buildClient().triggers.events.list(triggerId, { top }));
@@ -4891,7 +5382,7 @@ function registerTriggerEvents(triggers) {
4891
5382
  addUniversalOptions(events);
4892
5383
  events.action(
4893
5384
  async (triggerId, opts, command) => {
4894
- await runCommand(command, opts, false, () => listBody11(triggerId, opts));
5385
+ await runCommand(command, opts, false, () => listBody12(triggerId, opts));
4895
5386
  }
4896
5387
  );
4897
5388
  const get = events.command("get").description("One event plus its delivery attempts \u2014 the only place a real delivery state is read.").argument("[event_id]", "Event id (te_\u2026)");
@@ -4928,6 +5419,7 @@ function registerTriggersGet(triggers) {
4928
5419
 
4929
5420
  // src/triggers/listen.ts
4930
5421
  import { createHmac } from "crypto";
5422
+ import { EnginiAuthError as EnginiAuthError3 } from "@engini/sdk";
4931
5423
  function emitEvent(frame) {
4932
5424
  console.log(JSON.stringify(frame));
4933
5425
  }
@@ -4973,6 +5465,16 @@ async function forwardEvent(frame, url, secret, signal) {
4973
5465
  return false;
4974
5466
  }
4975
5467
  }
5468
+ function oauthProfileName() {
5469
+ const active = resolveActive();
5470
+ return active.source !== "env-credential" && active.profile.auth_kind === "oauth" ? active.name : void 0;
5471
+ }
5472
+ function storedSession(name) {
5473
+ const profile = getProfile(loadConfig(), name);
5474
+ const expiresAt = profile?.access_expires_at ? Date.parse(profile.access_expires_at) : Number.NaN;
5475
+ return { token: profile?.access_token, expiresAt: Number.isNaN(expiresAt) ? 0 : expiresAt };
5476
+ }
5477
+ var REAUTH_MARGIN_MS = 10 * 60 * 1e3;
4976
5478
  async function listenBody(opts) {
4977
5479
  const secret = opts.signWith ?? process.env.ENGINI_TRIGGER_SIGNING_SECRET;
4978
5480
  if (opts.forward !== void 0 && !secret) {
@@ -4992,24 +5494,48 @@ async function listenBody(opts) {
4992
5494
  let failed = 0;
4993
5495
  try {
4994
5496
  await apiErrors(async () => {
4995
- const stream = buildClient().triggers.subscribe({
4996
- triggerId: opts.trigger,
4997
- triggerSlug: opts.slug,
4998
- applicationSlug: opts.app,
4999
- since: opts.since,
5000
- autoResume: opts.resume,
5001
- signal: controller.signal
5002
- });
5003
- for await (const frame of stream) {
5004
- if (interrupted) break;
5005
- events += 1;
5006
- emitEvent(frame);
5007
- if (opts.forward !== void 0) {
5008
- const ok = await forwardEvent(frame, opts.forward, secret, controller.signal);
5009
- if (ok) forwarded += 1;
5010
- else failed += 1;
5497
+ const oauthProfile = oauthProfileName();
5498
+ let since = opts.since;
5499
+ let reauthBlockedUntil = 0;
5500
+ for (; ; ) {
5501
+ const usedToken = oauthProfile !== void 0 ? storedSession(oauthProfile).token : void 0;
5502
+ const stream = buildClient().triggers.subscribe({
5503
+ triggerId: opts.trigger,
5504
+ triggerSlug: opts.slug,
5505
+ applicationSlug: opts.app,
5506
+ since,
5507
+ autoResume: opts.resume,
5508
+ signal: controller.signal
5509
+ });
5510
+ try {
5511
+ for await (const frame of stream) {
5512
+ if (interrupted) break;
5513
+ events += 1;
5514
+ if (typeof frame.id === "string") since = frame.id;
5515
+ emitEvent(frame);
5516
+ if (opts.forward !== void 0) {
5517
+ const ok = await forwardEvent(frame, opts.forward, secret, controller.signal);
5518
+ if (ok) forwarded += 1;
5519
+ else failed += 1;
5520
+ }
5521
+ if (interrupted) break;
5522
+ }
5523
+ return;
5524
+ } catch (err) {
5525
+ if (!(err instanceof EnginiAuthError3) || err.errorCode !== void 0 || oauthProfile === void 0 || interrupted) {
5526
+ throw err;
5527
+ }
5528
+ if (Date.now() < reauthBlockedUntil) {
5529
+ fail(
5530
+ 3 /* AUTH */,
5531
+ `Your engini session for profile ${oauthProfile} expired.`,
5532
+ `Run \`engini login --profile ${oauthProfile}\`.`
5533
+ );
5534
+ }
5535
+ progress("Session token expired - refreshing and resuming the stream.");
5536
+ await ensureFreshSession(oauthProfile, { force: true, rejectedAccessToken: usedToken });
5537
+ reauthBlockedUntil = storedSession(oauthProfile).expiresAt - REAUTH_MARGIN_MS;
5011
5538
  }
5012
- if (interrupted) break;
5013
5539
  }
5014
5540
  });
5015
5541
  } finally {
@@ -5038,7 +5564,7 @@ function registerTriggerListen(triggers) {
5038
5564
  }
5039
5565
 
5040
5566
  // src/triggers/list.ts
5041
- async function listBody12(opts) {
5567
+ async function listBody13(opts) {
5042
5568
  const top = opts.top !== void 0 ? Number(opts.top) : void 0;
5043
5569
  const triggers = await apiErrors(
5044
5570
  async () => buildClient().triggers.list({
@@ -5067,7 +5593,7 @@ function registerTriggersList(triggers) {
5067
5593
  );
5068
5594
  addUniversalOptions(list);
5069
5595
  list.action(async (opts, command) => {
5070
- await runCommand(command, opts, false, () => listBody12(opts));
5596
+ await runCommand(command, opts, false, () => listBody13(opts));
5071
5597
  });
5072
5598
  }
5073
5599
 
@@ -5106,7 +5632,7 @@ function registerTriggerDisable(triggers) {
5106
5632
  }
5107
5633
 
5108
5634
  // src/triggers/types.ts
5109
- async function listBody13(opts) {
5635
+ async function listBody14(opts) {
5110
5636
  const types = await apiErrors(
5111
5637
  async () => buildClient().triggers.types.list({
5112
5638
  applicationSlug: opts.app,
@@ -5131,7 +5657,7 @@ function registerTriggerTypes(triggers) {
5131
5657
  );
5132
5658
  addUniversalOptions(types);
5133
5659
  types.action(async (opts, command) => {
5134
- await runCommand(command, opts, false, () => listBody13(opts));
5660
+ await runCommand(command, opts, false, () => listBody14(opts));
5135
5661
  });
5136
5662
  const get = types.command("get").description("One trigger type's config_schema, payload_schema and parameters.").argument("[trigger_slug]", "Trigger type slug").option("--app <slug>", "Disambiguate a slug shared by more than one application");
5137
5663
  get.addHelpText("after", "\nExamples:\n engini triggers types get monday_item_created --json");
@@ -5160,7 +5686,7 @@ function registerTriggers(program) {
5160
5686
  }
5161
5687
 
5162
5688
  // src/shared/input.ts
5163
- import { readFileSync as readFileSync5 } from "fs";
5689
+ import { readFileSync as readFileSync4 } from "fs";
5164
5690
  function parseInt1(raw, what) {
5165
5691
  if (raw === void 0 || raw === "") fail(2 /* USAGE */, `${what} is required.`);
5166
5692
  if (!/^\d+$/.test(raw) || Number(raw) < 1) {
@@ -5185,13 +5711,16 @@ function readJsonObject(file, what) {
5185
5711
  fail(2 /* USAGE */, `Pass the ${what} with --file <path>, or pipe it on stdin.`);
5186
5712
  }
5187
5713
  try {
5188
- text = readFileSync5(file === void 0 || file === "-" ? 0 : file, "utf8");
5714
+ text = readFileSync4(file === void 0 || file === "-" ? 0 : file, "utf8");
5189
5715
  } catch (err) {
5190
5716
  return fail(
5191
5717
  2 /* USAGE */,
5192
5718
  file === void 0 || file === "-" ? `Cannot read the ${what} from stdin: ${err.message}` : `Cannot read ${file}: ${err.message}`
5193
5719
  );
5194
5720
  }
5721
+ return parseJsonObject(text, what);
5722
+ }
5723
+ function parseJsonObject(text, what) {
5195
5724
  let data;
5196
5725
  try {
5197
5726
  data = JSON.parse(text);
@@ -5203,6 +5732,25 @@ function readJsonObject(file, what) {
5203
5732
  }
5204
5733
  return data;
5205
5734
  }
5735
+ function readBodyOption(raw, what = "body") {
5736
+ if (raw === void 0) return {};
5737
+ if (raw === "-" || raw.startsWith("@")) {
5738
+ if (raw === "-" && process.stdin.isTTY) {
5739
+ fail(2 /* USAGE */, `Pipe the ${what} on stdin, or pass it inline / with @file.`);
5740
+ }
5741
+ const source = raw === "-" ? 0 : raw.slice(1);
5742
+ try {
5743
+ return parseJsonObject(readFileSync4(source, "utf8"), what);
5744
+ } catch (err) {
5745
+ if (err instanceof CliError) throw err;
5746
+ return fail(
5747
+ 2 /* USAGE */,
5748
+ `Cannot read the ${what} from ${raw === "-" ? "stdin" : source}: ${err.message}`
5749
+ );
5750
+ }
5751
+ }
5752
+ return parseJsonObject(raw, what);
5753
+ }
5206
5754
  var snake = (key) => key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
5207
5755
  function snakeKeys(value, keep = []) {
5208
5756
  if (Array.isArray(value)) return value.map((v) => snakeKeys(v, keep));
@@ -5215,7 +5763,7 @@ function snakeKeys(value, keep = []) {
5215
5763
  }
5216
5764
 
5217
5765
  // src/executions/index.ts
5218
- async function listBody14(opts) {
5766
+ async function listBody15(opts) {
5219
5767
  const top = parseCount(opts.top, "--top");
5220
5768
  const offset = parseCount(opts.offset, "--offset");
5221
5769
  if (opts.all && (top !== void 0 || opts.cursor !== void 0 || offset !== void 0)) {
@@ -5243,19 +5791,27 @@ async function listBody14(opts) {
5243
5791
  printOutput({ items: snakeKeys(items), next_cursor: null, total_count: items.length });
5244
5792
  return;
5245
5793
  }
5246
- const page = await apiErrors(
5794
+ const page2 = await apiErrors(
5247
5795
  async () => client.executions.listPage({ ...filters, top, cursor: opts.cursor, offset })
5248
5796
  );
5249
5797
  printOutput({
5250
- items: snakeKeys(page.items ?? []),
5251
- next_cursor: page.nextCursor ?? null,
5252
- total_count: page.totalCount ?? null
5798
+ items: snakeKeys(page2.items ?? []),
5799
+ next_cursor: page2.nextCursor ?? null,
5800
+ total_count: page2.totalCount ?? null
5253
5801
  });
5254
5802
  }
5255
5803
  async function getBody12(rawId) {
5256
5804
  const id = parseInt1(rawId, "execution id");
5257
5805
  printOutput(snakeKeys(await apiErrors(async () => buildClient().executions.get(id))));
5258
5806
  }
5807
+ async function rerunBody(rawId) {
5808
+ const id = parseInt1(rawId, "execution id");
5809
+ if (dryRun()) {
5810
+ printOutput({ would_rerun: id });
5811
+ return;
5812
+ }
5813
+ printOutput(snakeKeys(await apiErrors(async () => buildClient().executions.rerun(id))));
5814
+ }
5259
5815
  function terminalSafe(text) {
5260
5816
  return text.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim();
5261
5817
  }
@@ -5308,7 +5864,7 @@ async function dataBody(rawId, rawStep, opts) {
5308
5864
  printOutput(snakeKeys(entries, ["value", "additional"]));
5309
5865
  }
5310
5866
  function registerExecutions(program) {
5311
- const executions = program.command("executions").description("Read-only run history: list, inspect, step log and recorded step data.");
5867
+ const executions = program.command("executions").description("Run history: list, inspect, step log and recorded step data; rerun an execution.");
5312
5868
  const list = executions.command("list").description("List executions, newest first. Prints { items, next_cursor, total_count }.").option("--workflow <id>", "Only this workflow / automation / business rule").option("--type <type>", "workflow | automation | businessRule").option("--trigger-type <type>", "instant, scheduled, recordUpdate, api, \u2026").option("--status <status>", "Match a status; repeat to match any of several", collect4).option("--context <text>", "Substring of the caller-supplied context id").option("--created-by <id>", "Account-user id that started the run").option("--created-after <iso>", "Queued at or after").option("--created-before <iso>", "Queued at or before").option("--closed-after <iso>", "Finished at or after").option("--closed-before <iso>", "Finished at or before").option("--sort <spec>", "e.g. 'createdAt desc' (cursor paging needs one createdAt/executionId key)").option("--cursor <cursor>", "next_cursor from a previous page").option("--top <n>", "Page size (server cap 100; default 100)").option("--offset <n>", "Skip n rows (ignored by the server with --cursor)").option("--all", "Drain every page (follows next_cursor); not with --top/--cursor/--offset");
5313
5869
  list.addHelpText(
5314
5870
  "after",
@@ -5316,7 +5872,7 @@ function registerExecutions(program) {
5316
5872
  );
5317
5873
  addUniversalOptions(list);
5318
5874
  list.action(async (opts, command) => {
5319
- await runCommand(command, opts, false, () => listBody14(opts));
5875
+ await runCommand(command, opts, false, () => listBody15(opts));
5320
5876
  });
5321
5877
  const get = executions.command("get").description("One execution: status, timing, activities run, who started it.").argument("[execution_id]", "Execution id");
5322
5878
  get.addHelpText("after", "\nExamples:\n engini executions get 4567 --json");
@@ -5324,6 +5880,15 @@ function registerExecutions(program) {
5324
5880
  get.action(async (id, opts, command) => {
5325
5881
  await runCommand(command, opts, false, () => getBody12(id));
5326
5882
  });
5883
+ const rerun = executions.command("rerun").description("Run an execution again. Prints the new execution.").argument("[execution_id]", "Execution id");
5884
+ rerun.addHelpText(
5885
+ "after",
5886
+ "\nExamples:\n engini executions rerun 4567 --json\nNote: runs immediately, without a prompt. A run still in progress, a kind that cannot be re-run, or an account limit is refused (409, exit 1 with the server's message). Needs a workspace-scoped API key. The API has no idempotency key: a retry after a lost answer starts a second run."
5887
+ );
5888
+ addUniversalOptions(rerun, { mutating: true });
5889
+ rerun.action(async (id, opts, command) => {
5890
+ await runCommand(command, opts, true, () => rerunBody(id));
5891
+ });
5327
5892
  const log = executions.command("log").description(
5328
5893
  "The execution's per-step log (step_no, name, status, runs_count, duration, error_message, loop)."
5329
5894
  ).argument("[execution_id]", "Execution id");
@@ -5349,6 +5914,7 @@ function registerExecutions(program) {
5349
5914
  }
5350
5915
 
5351
5916
  // src/workflows/index.ts
5917
+ var PAIR = { needsPair: true };
5352
5918
  var PLAN_HELP = "Plan JSON: --file <path>, --file -, or piped stdin. A bare WorkflowPlan ({name, trigger, steps, \u2026}) \u2014 the same shape `engini workflows plan <id>` prints.";
5353
5919
  function fileOption(cmd) {
5354
5920
  return cmd.option("--file <path>", "Plan JSON file ('-' or omit to read stdin)");
@@ -5411,13 +5977,13 @@ function pagingOptions(opts) {
5411
5977
  }
5412
5978
  return { top, offset };
5413
5979
  }
5414
- async function printList(all, drain, page) {
5980
+ async function printList(all, drain, page2) {
5415
5981
  if (all) {
5416
5982
  const items = await apiErrors(drain);
5417
5983
  printOutput({ items, totalCount: items.length });
5418
5984
  return;
5419
5985
  }
5420
- const p = await apiErrors(page);
5986
+ const p = await apiErrors(page2);
5421
5987
  printOutput({ items: p.items ?? [], totalCount: p.totalCount ?? null, offset: p.offset ?? null, top: p.top ?? null });
5422
5988
  }
5423
5989
  async function resolveFolderId(client, rawName) {
@@ -5470,8 +6036,51 @@ async function listFoldersBody(opts) {
5470
6036
  () => client.folders.listPage({ ...filters, top, offset })
5471
6037
  );
5472
6038
  }
6039
+ async function revisionsBody(rawId, opts) {
6040
+ const workflowId = parseInt1(rawId, "workflow id");
6041
+ const page2 = await apiErrors(
6042
+ async () => buildClient().workflows.revisions(workflowId, {
6043
+ createdBy: parseOptId(opts.createdBy, "--created-by"),
6044
+ createdAfter: opts.createdAfter,
6045
+ createdBefore: opts.createdBefore,
6046
+ sort: opts.sort,
6047
+ top: parseCount(opts.top, "--top"),
6048
+ offset: parseCount(opts.offset, "--offset")
6049
+ })
6050
+ );
6051
+ printOutput({ items: page2.items ?? [], totalCount: page2.totalCount ?? null, offset: page2.offset ?? null, top: page2.top ?? null });
6052
+ }
6053
+ async function setEnabledBody(rawId, enabled) {
6054
+ const workflowId = parseInt1(rawId, "workflow id");
6055
+ if (dryRun()) {
6056
+ printOutput({ [enabled ? "would_enable" : "would_disable"]: workflowId });
6057
+ return;
6058
+ }
6059
+ printOutput(await apiErrors(async () => buildClient().workflows.setEnabled(workflowId, enabled)));
6060
+ }
6061
+ async function deleteBody6(rawId, opts) {
6062
+ const workflowId = parseInt1(rawId, "workflow id");
6063
+ if (dryRun()) {
6064
+ printOutput({ would_delete: workflowId });
6065
+ return;
6066
+ }
6067
+ await confirmOrFail(`Delete workflow ${workflowId}?`, { force: Boolean(opts.force) });
6068
+ await apiErrors(async () => buildClient().workflows.delete(workflowId));
6069
+ printOutput({ deleted: workflowId });
6070
+ }
6071
+ async function runBody(rawId, opts) {
6072
+ const workflowId = parseInt1(rawId, "workflow id");
6073
+ const body = readBodyOption(opts.body);
6074
+ if (dryRun()) {
6075
+ printOutput({ would_run: workflowId, body });
6076
+ return;
6077
+ }
6078
+ printOutput(snakeKeys(await apiErrors(async () => buildClient().workflows.run(workflowId, body))));
6079
+ }
5473
6080
  function registerWorkflows(program) {
5474
- const workflows = program.command("workflows").description("List workflows and folders; build workflows from a plan: catalog lookups, dry-run compile, create, update.");
6081
+ const workflows = program.command("workflows").description(
6082
+ "List, read, enable/disable, delete and run workflows; build workflows from a plan: catalog lookups, dry-run compile, create, update."
6083
+ );
5475
6084
  const list = workflows.command("list").description("List workflows (id, name, type, folder, enabled) - no steps. Prints { items, totalCount, offset, top }.").option("--name <text>", "Case-insensitive substring of the workflow name").option("--folder <name>", "Only this folder, by its exact name (resolved with `workflows folders`)").option("--folder-id <id>", "Only this folder id; 0 = workflows with no folder").option("--top <n>", "Page size (server cap 100; default 100)").option("--offset <n>", "Skip n rows").option("--all", "Drain every page; not with --top/--offset");
5476
6085
  list.addHelpText(
5477
6086
  "after",
@@ -5481,6 +6090,60 @@ function registerWorkflows(program) {
5481
6090
  list.action(async (opts, command) => {
5482
6091
  await runCommand(command, opts, false, () => listWorkflowsBody(opts));
5483
6092
  });
6093
+ const get = workflows.command("get").description("One workflow with its steps (and webhookUrl for a webhook trigger). Prints the API's camelCase JSON.").argument("[workflow_id]", "Workflow id");
6094
+ get.addHelpText(
6095
+ "after",
6096
+ "\nExamples:\n engini workflows get 1234 --json\nNote: step `configuration` is connector-defined and outside the v1 compatibility guarantee. `webhookUrl` carries the trigger's token: treat it like a credential. To edit, read the workflow back as a plan with `workflows plan`."
6097
+ );
6098
+ addUniversalOptions(get);
6099
+ get.action(async (id, opts, command) => {
6100
+ await runCommand(command, opts, false, async () => {
6101
+ const workflowId = parseInt1(id, "workflow id");
6102
+ printOutput(await apiErrors(async () => buildClient().workflows.get(workflowId)));
6103
+ });
6104
+ });
6105
+ const revisions = workflows.command("revisions").description("A workflow's stored revisions, newest first. Prints { items, totalCount, offset, top }.").argument("[workflow_id]", "Workflow id").option("--created-by <id>", "Account-user id that made the change").option("--created-after <iso>", "Recorded at or after").option("--created-before <iso>", "Recorded at or before").option("--sort <spec>", "e.g. 'createdAt asc,revisionId asc' (default: revisionId desc)").option("--top <n>", "Page size (server cap 100; default 100)").option("--offset <n>", "Skip n rows");
6106
+ revisions.addHelpText(
6107
+ "after",
6108
+ "\nExamples:\n engini workflows revisions 1234 --top 10 --json\nNote: one page; page on with --offset. A revisionId is what `update --expected-revision-id` takes. Restoring a revision is not available."
6109
+ );
6110
+ addUniversalOptions(revisions);
6111
+ revisions.action(async (id, opts, command) => {
6112
+ await runCommand(command, opts, false, () => revisionsBody(id, opts));
6113
+ });
6114
+ for (const enabled of [true, false]) {
6115
+ const verb = enabled ? "enable" : "disable";
6116
+ const toggle = workflows.command(verb).description(`Turn a workflow ${enabled ? "on" : "off"}. Prints the workflow as it stands afterwards.`).argument("[workflow_id]", "Workflow id");
6117
+ toggle.addHelpText(
6118
+ "after",
6119
+ `
6120
+ Examples:
6121
+ engini workflows ${verb} 1234
6122
+ Note: needs a workspace-scoped API key (403 SCOPE_READ_ONLY otherwise). A workflow created through the API starts turned off.`
6123
+ );
6124
+ addUniversalOptions(toggle, { mutating: true });
6125
+ toggle.action(async (id, opts, command) => {
6126
+ await runCommand(command, opts, true, () => setEnabledBody(id, enabled));
6127
+ });
6128
+ }
6129
+ const del = workflows.command("delete").description("Delete a workflow (a soft delete; deleting a deleted one succeeds).").argument("[workflow_id]", "Workflow id").option("--force", "Delete without confirming");
6130
+ del.addHelpText(
6131
+ "after",
6132
+ "\nExamples:\n engini workflows delete 1234 --force\nNote: confirms on a terminal; scripts and pipes must pass --force. Needs a workspace-scoped API key."
6133
+ );
6134
+ addUniversalOptions(del, { mutating: true });
6135
+ del.action(async (id, opts, command) => {
6136
+ await runCommand(command, opts, true, () => deleteBody6(id, opts));
6137
+ });
6138
+ const run = workflows.command("run").description("Start one run of a workflow now. Prints the started execution (snake_case, as `executions get`).").argument("[workflow_id]", "Workflow id").option("--body <json|@file|->", "Trigger payload: inline JSON, @path to a file, or - for stdin (default {})");
6139
+ run.addHelpText(
6140
+ "after",
6141
+ '\nExamples:\n engini workflows run 1234\n engini workflows run 1234 --body \'{"email":"a@b.co"}\'\n engini workflows run 1234 --body @payload.json\nNote: runs immediately, without a prompt, even when the workflow is turned off. The API has no idempotency key: a retry after a lost answer starts a second run. Follow it with `engini executions get <execution_id>`.'
6142
+ );
6143
+ addUniversalOptions(run, { mutating: true });
6144
+ run.action(async (id, opts, command) => {
6145
+ await runCommand(command, opts, true, () => runBody(id, opts));
6146
+ });
5484
6147
  const folders = workflows.command("folders").description("List workflow folders ({ id, name, workspaceId, environmentId, itemsCount }). Prints { items, totalCount, offset, top }.").option("--name <text>", "Case-insensitive substring of the folder name").option("--top <n>", "Page size (server cap 100; default 100)").option("--offset <n>", "Skip n rows").option("--all", "Drain every page; not with --top/--offset");
5485
6148
  folders.addHelpText(
5486
6149
  "after",
@@ -5494,7 +6157,7 @@ function registerWorkflows(program) {
5494
6157
  search.addHelpText("after", "\nExamples:\n engini workflows search 'post message' --app slack --kind action");
5495
6158
  addUniversalOptions(search);
5496
6159
  search.action(async (q, opts, command) => {
5497
- await runCommand(command, opts, false, () => searchBody(q, opts));
6160
+ await runCommand(command, opts, false, () => searchBody(q, opts), PAIR);
5498
6161
  });
5499
6162
  const schema = workflows.command("schema").description("Input/output schema of one catalog entry (the slug from `search`).").argument("[slug]", "Catalog slug, e.g. slack.post_message").option("--connection <id>", "Resolve dynamic fields against this connection").option("--kind <kind>", "action | trigger | block").option("--table <id>", "Table the entry is used on").option("--selected <FIELD=value>", "Pick an object for a picker field; repeatable. Needs --connection", collect4);
5500
6163
  schema.addHelpText(
@@ -5504,7 +6167,7 @@ function registerWorkflows(program) {
5504
6167
  addUniversalOptions(schema);
5505
6168
  schema.action(
5506
6169
  async (slug, opts, command) => {
5507
- await runCommand(command, opts, false, () => schemaBody(slug, opts));
6170
+ await runCommand(command, opts, false, () => schemaBody(slug, opts), PAIR);
5508
6171
  }
5509
6172
  );
5510
6173
  const options = workflows.command("options").description("Dropdown values ({id, label}) for one field of a catalog entry.").argument("[slug]", "Catalog slug").option("--field <name>", "The field to list values for").option("--connection <id>", "Connection to read the values through").option("--kind <kind>", "action | trigger | block").option("--depends-on <field=value>", "Value of a parent field; repeatable", collect4);
@@ -5515,7 +6178,7 @@ function registerWorkflows(program) {
5515
6178
  addUniversalOptions(options);
5516
6179
  options.action(
5517
6180
  async (slug, opts, command) => {
5518
- await runCommand(command, opts, false, () => optionsBody(slug, opts));
6181
+ await runCommand(command, opts, false, () => optionsBody(slug, opts), PAIR);
5519
6182
  }
5520
6183
  );
5521
6184
  const tables = workflows.command("tables").description("The caller's tables ({id, name}).");
@@ -5523,7 +6186,7 @@ function registerWorkflows(program) {
5523
6186
  tables.action(async (opts, command) => {
5524
6187
  await runCommand(command, opts, false, async () => {
5525
6188
  printOutput(await apiErrors(async () => buildClient().workflows.listTables()));
5526
- });
6189
+ }, PAIR);
5527
6190
  });
5528
6191
  const columns = workflows.command("columns").description("A table's columns, as a table automation reads them.").argument("[table_id]", "Table id from `workflows tables`").option("--trigger <slug>", "The automation's Tables trigger slug, e.g. tables.Tableonrecordupdated");
5529
6192
  addUniversalOptions(columns);
@@ -5533,14 +6196,14 @@ function registerWorkflows(program) {
5533
6196
  printOutput(
5534
6197
  await apiErrors(async () => buildClient().workflows.listTableColumns(tableId, { trigger: opts.trigger }))
5535
6198
  );
5536
- });
6199
+ }, PAIR);
5537
6200
  });
5538
6201
  const connections = workflows.command("connections").description("Connections a plan step may bind to.").option("--app <slug>", "Narrow to one application");
5539
6202
  addUniversalOptions(connections);
5540
6203
  connections.action(async (opts, command) => {
5541
6204
  await runCommand(command, opts, false, async () => {
5542
6205
  printOutput(await apiErrors(async () => buildClient().workflows.listConnections({ app: opts.app })));
5543
- });
6206
+ }, PAIR);
5544
6207
  });
5545
6208
  const compile = workflows.command("compile").description("Dry-run a plan: nothing is written. Prints the compiled workflow with its diagnostics and hasErrors.").option("--base-workflow-id <id>", "Compile the plan as an edit of this saved workflow");
5546
6209
  fileOption(compile);
@@ -5560,7 +6223,7 @@ Note: a plan with errors is printed (hasErrors: true), not failed; create/update
5560
6223
  const baseWorkflowId = parseOptId(opts.baseWorkflowId, "--base-workflow-id");
5561
6224
  const plan2 = readJsonObject(opts.file, "plan");
5562
6225
  printOutput(await apiErrors(async () => buildClient().workflows.compile({ plan: plan2, baseWorkflowId })));
5563
- });
6226
+ }, PAIR);
5564
6227
  }
5565
6228
  );
5566
6229
  const plan = workflows.command("plan").description("A saved workflow read back as a plan (the input to `update`).").argument("[workflow_id]", "Workflow id");
@@ -5570,7 +6233,7 @@ Note: a plan with errors is printed (hasErrors: true), not failed; create/update
5570
6233
  await runCommand(command, opts, false, async () => {
5571
6234
  const workflowId = parseInt1(id, "workflow id");
5572
6235
  printOutput(await apiErrors(async () => buildClient().workflows.getPlan(workflowId)));
5573
- });
6236
+ }, PAIR);
5574
6237
  });
5575
6238
  const create = workflows.command("create").description("Create a workflow from a plan. It is created turned off.").option("--folder-id <id>", "Folder to put the workflow in");
5576
6239
  fileOption(create);
@@ -5580,7 +6243,7 @@ Note: a plan with errors is printed (hasErrors: true), not failed; create/update
5580
6243
  ${PLAN_HELP}
5581
6244
  Examples:
5582
6245
  engini workflows create --file plan.json --folder-id 7
5583
- Note: needs a workspace-scoped API key (SCOPE_REQUIRED otherwise). Run \`compile\` first.`
6246
+ Note: works in one workspace + environment (a key's own, or --workspace/--environment on a browser login). Run \`compile\` first.`
5584
6247
  );
5585
6248
  addUniversalOptions(create, { mutating: true });
5586
6249
  create.action(
@@ -5631,7 +6294,49 @@ Note: a turned-on workflow is refused (WORKFLOW_ACTIVE); turn it off in the desi
5631
6294
  }
5632
6295
 
5633
6296
  // src/whoami.ts
5634
- function summary5(me) {
6297
+ function scopeRow(row2) {
6298
+ return {
6299
+ workspace: { id: row2.workspace.id, name: clean(row2.workspace.name) },
6300
+ environment: { id: row2.environment.id, name: clean(row2.environment.name), type: clean(row2.environment.type) }
6301
+ };
6302
+ }
6303
+ function scopeFields(me, active) {
6304
+ const { pair, source } = resolvePair(active);
6305
+ const rows = flattenScopes(me.accessibleScopes);
6306
+ const isOAuth = active.source !== "env-credential" && active.profile.auth_kind === "oauth";
6307
+ const fields = {
6308
+ scope_mode: isOAuth ? active.profile.scope_mode ?? null : me.userType === "apiuser" ? "key" : null,
6309
+ scope_source: source,
6310
+ accessible_scopes: rows.map(scopeRow)
6311
+ };
6312
+ if (!isOAuth) {
6313
+ if (rows.length === 0 && me.workspace && me.environment) {
6314
+ fields.accessible_scopes = [
6315
+ scopeRow({
6316
+ workspace: { id: me.workspace.id, name: me.workspace.name ?? null },
6317
+ environment: { id: me.environment.id, name: me.environment.name ?? null, type: me.environment.type ?? null }
6318
+ })
6319
+ ];
6320
+ }
6321
+ return fields;
6322
+ }
6323
+ fields.session_expires_at = active.profile.session_expires_at ?? null;
6324
+ const row2 = pair ? findScope(rows, pair) : void 0;
6325
+ if (pair && !row2) {
6326
+ note(
6327
+ `${pair.workspaceId}/${pair.environmentId} (from ${source}) is not a workspace/environment you can open now. Pass --workspace/--environment, or set a new default with \`engini login --workspace <id> --environment <id>\`.`
6328
+ );
6329
+ } else if (!pair) {
6330
+ note(
6331
+ "No default workspace/environment: lists cover every pair you can open; creates land in the account's default workspace, Production (the CLI asks for --workspace/--environment on writes)."
6332
+ );
6333
+ }
6334
+ const picked = row2 ? scopeRow(row2) : void 0;
6335
+ fields.workspace = picked?.workspace ?? null;
6336
+ fields.environment = picked?.environment ?? null;
6337
+ return fields;
6338
+ }
6339
+ function summary5(me, source) {
5635
6340
  const ws = me.workspace;
5636
6341
  const env = me.environment;
5637
6342
  return {
@@ -5641,7 +6346,8 @@ function summary5(me) {
5641
6346
  role: clean(me.role),
5642
6347
  user_type: me.userType,
5643
6348
  workspace: ws ? { id: ws.id, name: clean(ws.name) } : null,
5644
- environment: env ? { id: env.id, name: clean(env.name), type: clean(env.type) } : null
6349
+ environment: env ? { id: env.id, name: clean(env.name), type: clean(env.type) } : null,
6350
+ ...source
5645
6351
  };
5646
6352
  }
5647
6353
  async function whoamiBody() {
@@ -5649,13 +6355,23 @@ async function whoamiBody() {
5649
6355
  const client = buildClient();
5650
6356
  return client.auth.whoami();
5651
6357
  });
5652
- printOutput(summary5(me));
6358
+ const active = resolveActive();
6359
+ printOutput(
6360
+ summary5(me, {
6361
+ ...scopeFields(me, active),
6362
+ profile: active.name ?? null,
6363
+ // `flag` | `env` | `default`, or `none` for an ENGINI_API_TOKEN credential.
6364
+ profile_source: active.source === "env-credential" ? "none" : active.source,
6365
+ credential_source: active.source === "env-credential" ? "env" : "profile"
6366
+ })
6367
+ );
5653
6368
  }
5654
6369
  function registerWhoami(program) {
5655
6370
  const cmd = program.command("whoami").description("Report the authenticated user/company and the key's workspace/environment.");
5656
6371
  cmd.addHelpText("after", `
5657
6372
  Examples:
5658
6373
  engini whoami
6374
+ engini whoami --profile staging
5659
6375
  engini whoami --json | jq -r '.email'
5660
6376
  engini whoami --json | jq -r '.workspace.id // "unscoped"'`);
5661
6377
  addUniversalOptions(cmd);
@@ -5670,6 +6386,7 @@ function buildProgram() {
5670
6386
  program.name("engini").description("Engini CLI.").version(VERSION, "--version", "Print the engini SDK/CLI version and exit").showHelpAfterError();
5671
6387
  registerLogin(program);
5672
6388
  registerLogout(program);
6389
+ registerProfile(program);
5673
6390
  registerWhoami(program);
5674
6391
  registerConnect(program);
5675
6392
  registerTools(program);
@@ -5681,23 +6398,25 @@ function buildProgram() {
5681
6398
  registerTriggers(program);
5682
6399
  registerExecutions(program);
5683
6400
  registerWorkflows(program);
6401
+ program.option("--profile <name>", "Use this profile (same as --profile on a command)");
6402
+ program.enablePositionalOptions();
5684
6403
  installHelp(program);
5685
6404
  return program;
5686
6405
  }
5687
6406
 
5688
6407
  // src/update-notice.ts
5689
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "fs";
5690
- import { dirname as dirname2, join as join3 } from "path";
6408
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "fs";
6409
+ import { dirname, join as join2 } from "path";
5691
6410
  var REGISTRY_DIST_TAGS_URL = "https://registry.npmjs.org/-/package/%40engini%2Fcli/dist-tags";
5692
6411
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
5693
6412
  var FETCH_TIMEOUT_MS = 1500;
5694
6413
  var SEMVER_RE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
5695
6414
  function defaultCachePath() {
5696
- return join3(dirname2(configPath()), "update-check.json");
6415
+ return join2(dirname(configPath()), "update-check.json");
5697
6416
  }
5698
6417
  function readCache(path) {
5699
6418
  try {
5700
- const data = JSON.parse(readFileSync6(path, "utf8"));
6419
+ const data = JSON.parse(readFileSync5(path, "utf8"));
5701
6420
  if (typeof data.checked_at === "number" && typeof data.channel === "string" && (data.latest_version === null || typeof data.latest_version === "string")) {
5702
6421
  return data;
5703
6422
  }
@@ -5706,8 +6425,8 @@ function readCache(path) {
5706
6425
  return null;
5707
6426
  }
5708
6427
  function writeCache(path, cache) {
5709
- mkdirSync3(dirname2(path), { recursive: true });
5710
- writeFileSync3(path, JSON.stringify(cache));
6428
+ mkdirSync2(dirname(path), { recursive: true });
6429
+ writeFileSync2(path, JSON.stringify(cache));
5711
6430
  }
5712
6431
  async function fetchLatest(fetchImpl, channel) {
5713
6432
  try {