@everyai/cli 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { cp, mkdir, readdir, rm } from 'node:fs/promises';
1
+ import { cp, mkdir, readdir, rm, stat } from 'node:fs/promises';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
@@ -59,13 +59,58 @@ function emitCommand(data, human, opts) {
59
59
  else
60
60
  process.stdout.write(`${human}\n`);
61
61
  }
62
- function installHuman(target, files) {
62
+ async function pathIsDirectory(filePath) {
63
+ try {
64
+ return (await stat(filePath)).isDirectory();
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ }
70
+ async function hostDetected(target) {
71
+ const cwd = process.cwd();
72
+ const home = os.homedir();
73
+ const candidates = target === 'claude'
74
+ ? [path.join(cwd, '.claude'), path.join(home, '.claude')]
75
+ : [path.join(cwd, '.agents'), path.join(home, '.codex')];
76
+ for (const candidate of candidates) {
77
+ if (await pathIsDirectory(candidate))
78
+ return true;
79
+ }
80
+ return false;
81
+ }
82
+ async function hostSkillInstalled(target) {
83
+ const cwd = process.cwd();
84
+ const home = os.homedir();
85
+ const candidates = target === 'claude'
86
+ ? [
87
+ path.join(cwd, '.claude', 'skills', SKILL_NAME),
88
+ path.join(home, '.claude', 'skills', SKILL_NAME),
89
+ ]
90
+ : [
91
+ path.join(cwd, '.agents', 'skills', SKILL_NAME),
92
+ path.join(home, '.codex', 'skills', SKILL_NAME),
93
+ path.join(home, '.agents', 'skills', SKILL_NAME),
94
+ ];
95
+ for (const candidate of candidates) {
96
+ if (await pathIsDirectory(candidate))
97
+ return true;
98
+ }
99
+ return false;
100
+ }
101
+ async function installHuman(target, files) {
63
102
  const lines = [`Installed ${SKILL_NAME} for ${target.target} to ${target.install_to}`];
64
103
  for (const file of files)
65
104
  lines.push(`- ${file}`);
105
+ const otherTarget = target.target === 'claude' ? 'codex' : 'claude';
106
+ if ((await hostDetected(otherTarget)) && !(await hostSkillInstalled(otherTarget))) {
107
+ const hostName = otherTarget === 'claude' ? 'Claude Code' : 'Codex';
108
+ lines.push(`${hostName} detected — also run: every skills install ${otherTarget}`);
109
+ }
110
+ lines.push('For a global install, use --dir <path>.');
66
111
  return lines.join('\n');
67
112
  }
68
- export async function skillsInstallCommand(target, opts = {}) {
113
+ export async function installBundledSkill(target, opts = {}) {
69
114
  assertTarget(target);
70
115
  const info = targetInfo(target, opts);
71
116
  const source = bundledSkillDir();
@@ -73,7 +118,13 @@ export async function skillsInstallCommand(target, opts = {}) {
73
118
  await mkdir(info.root, { recursive: true });
74
119
  await rm(info.install_to, { recursive: true, force: true });
75
120
  await cp(source, info.install_to, { recursive: true, force: true });
76
- emitCommand({ installed_to: info.install_to, files }, installHuman(info, files), opts);
121
+ return { installed_to: info.install_to, files };
122
+ }
123
+ export async function skillsInstallCommand(target, opts = {}) {
124
+ assertTarget(target);
125
+ const info = targetInfo(target, opts);
126
+ const result = await installBundledSkill(target, opts);
127
+ emitCommand(result, await installHuman(info, result.files), opts);
77
128
  }
78
129
  function listHuman(skills) {
79
130
  const lines = ['Available bundled skills:'];
@@ -1,14 +1,16 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- import { resolveBaseUrl } from '../lib/config.js';
2
+ import { environmentNameForBaseUrl, resolveBaseUrl } from '../lib/config.js';
3
3
  import { CliError } from '../lib/errors.js';
4
4
  import { ExitCode } from '../lib/exit-codes.js';
5
5
  import { callTool, listTools } from '../lib/mcp.js';
6
6
  import { emit } from '../lib/output.js';
7
7
  import { classify, promptForTool, requirementDescription, requirementFor, } from '../lib/policy.js';
8
8
  import { getToken } from '../lib/auth/tokens.js';
9
+ import { fetchUserInfo } from '../lib/auth/userinfo.js';
10
+ import { maybeShowSkillHint } from '../lib/hints.js';
9
11
  function emitCommand(data, human, opts) {
10
12
  if (opts.json)
11
- emit(data, { json: true });
13
+ emit(data, { json: true, staging: opts.staging });
12
14
  else
13
15
  process.stdout.write(`${human}\n`);
14
16
  }
@@ -68,6 +70,7 @@ function describeHuman(tool) {
68
70
  if (tool.description)
69
71
  lines.push('', 'Description:', String(tool.description).trim());
70
72
  lines.push('', 'Input schema:', JSON.stringify(tool.inputSchema ?? {}, null, 2));
73
+ lines.push('', 'Fastest argument forms:', ` every tool call ${tool.name} --arg key=value --arg other='{"json":true}'`, ` every tool call ${tool.name} --args -`, ` every tool call ${tool.name} --args file.json`);
71
74
  return lines.join('\n');
72
75
  }
73
76
  async function resolveTools(opts) {
@@ -76,8 +79,17 @@ async function resolveTools(opts) {
76
79
  return listTools(baseUrl, token, { noCache: opts.noCache });
77
80
  }
78
81
  export async function toolsListCommand(opts = {}) {
79
- const tools = (await resolveTools(opts)).map(withClassification);
82
+ const filter = opts.filter?.toLowerCase();
83
+ const tools = (await resolveTools(opts))
84
+ .filter((tool) => {
85
+ if (!filter)
86
+ return true;
87
+ return (tool.name.toLowerCase().includes(filter) ||
88
+ compactText(tool.description).toLowerCase().includes(filter));
89
+ })
90
+ .map(withClassification);
80
91
  emitCommand(tools, toolsListHuman(tools), opts);
92
+ await maybeShowSkillHint();
81
93
  }
82
94
  export async function toolsDescribeCommand(name, opts = {}) {
83
95
  const tool = withClassification(findTool(await resolveTools(opts), name));
@@ -88,6 +100,7 @@ export async function toolsDescribeCommand(name, opts = {}) {
88
100
  requirements,
89
101
  input_schema: tool.inputSchema ?? {},
90
102
  }, describeHuman(tool), opts);
103
+ await maybeShowSkillHint();
91
104
  }
92
105
  async function readStdin() {
93
106
  process.stdin.setEncoding('utf8');
@@ -178,7 +191,28 @@ function toolCallHuman(result) {
178
191
  }
179
192
  return parts.join('\n');
180
193
  }
181
- export async function executeToolCall(name, opts = {}, argsFactory = async () => ({})) {
194
+ function orgLabel(userinfo) {
195
+ return {
196
+ org_id: userinfo?.org_id ?? null,
197
+ org_name: userinfo?.org_name ?? null,
198
+ };
199
+ }
200
+ function targetLabel(userinfo, environment) {
201
+ const orgName = userinfo?.org_name ?? 'unknown org';
202
+ const orgId = userinfo?.org_id ?? 'unknown';
203
+ return `${orgName} (${orgId}) · ${environment}`;
204
+ }
205
+ async function resolveWriteTarget(baseUrl) {
206
+ try {
207
+ return await fetchUserInfo({ baseUrl });
208
+ }
209
+ catch (err) {
210
+ const message = err instanceof Error ? err.message : String(err);
211
+ process.stderr.write(`Warning: could not verify target org: ${message}\n`);
212
+ return undefined;
213
+ }
214
+ }
215
+ export async function invokeToolCall(name, opts = {}, argsFactory = async () => ({})) {
182
216
  const baseUrl = resolveBaseUrl({ staging: opts.staging });
183
217
  const token = await getToken({ baseUrl });
184
218
  const tools = await listTools(baseUrl, token, { noCache: opts.noCache });
@@ -195,12 +229,19 @@ export async function executeToolCall(name, opts = {}, argsFactory = async () =>
195
229
  if (!requirement.allowed) {
196
230
  throw new CliError(requirement.denialMessage ?? 'Tool call denied by policy.', ExitCode.PERMISSION, 'permission');
197
231
  }
232
+ const gated = classification.level !== 'read';
233
+ const environment = environmentNameForBaseUrl(baseUrl);
234
+ const userinfo = gated ? await resolveWriteTarget(baseUrl) : undefined;
235
+ const target = gated ? targetLabel(userinfo, environment) : undefined;
198
236
  if (requirement.prompt) {
199
- const confirmed = await promptForTool(name, classification.level, requirement.prompt);
237
+ const confirmed = await promptForTool(name, classification.level, requirement.prompt, target);
200
238
  if (!confirmed) {
201
239
  throw new CliError('Tool call cancelled.', ExitCode.PERMISSION, 'permission');
202
240
  }
203
241
  }
242
+ if (gated && !opts.json && target) {
243
+ process.stderr.write(`→ ${target}\n`);
244
+ }
204
245
  const args = await argsFactory();
205
246
  const result = await callTool(baseUrl, token, name, args, { timeoutMs: timeoutMs(opts.timeout) });
206
247
  const data = {
@@ -208,12 +249,18 @@ export async function executeToolCall(name, opts = {}, argsFactory = async () =>
208
249
  is_error: result.isError,
209
250
  content: result.content,
210
251
  structured_content: result.structuredContent,
252
+ ...(gated ? { org: orgLabel(userinfo) } : {}),
211
253
  };
212
254
  if (result.isError) {
213
255
  const message = contentAsText(result.content) || 'Tool returned an error.';
214
256
  throw new CliError(message, ExitCode.GENERIC, 'generic');
215
257
  }
258
+ return data;
259
+ }
260
+ export async function executeToolCall(name, opts = {}, argsFactory = async () => ({}), augmentData = (data) => data) {
261
+ const data = await augmentData(await invokeToolCall(name, opts, argsFactory));
216
262
  emitCommand(data, toolCallHuman(data), opts);
263
+ await maybeShowSkillHint();
217
264
  }
218
265
  export async function toolCallCommand(name, opts = {}) {
219
266
  await executeToolCall(name, opts, () => assembleArgs(opts));
package/dist/index.js CHANGED
@@ -2,14 +2,16 @@
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { Command, CommanderError } from 'commander';
4
4
  import { pingCommand } from './commands/ping.js';
5
+ import { docsCommand } from './commands/docs.js';
5
6
  import { authStatusCommand, loginCommand, logoutCommand, orgCommand, whoamiCommand, } from './commands/auth.js';
6
7
  import { policyExplainCommand } from './commands/policy.js';
7
8
  import { toolCallCommand, toolsDescribeCommand, toolsListCommand, } from './commands/tools.js';
8
- import { contactListCommand, dealListCommand, dealMoveCommand, invoiceListCommand, invoiceSendCommand, } from './commands/aliases.js';
9
+ import { contactListCommand, dealListCommand, dealMoveCommand, invoiceCreateCommand, invoiceListCommand, invoiceSendCommand, } from './commands/aliases.js';
9
10
  import { skillsInstallCommand, skillsListCommand } from './commands/skills.js';
10
11
  import { CliError } from './lib/errors.js';
11
12
  import { emit, emitError } from './lib/output.js';
12
13
  import { ExitCode } from './lib/exit-codes.js';
14
+ import { runDefaultFirstRunMenu } from './lib/first-run.js';
13
15
  const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
14
16
  /** Attach the global options every command accepts (before OR after the name). */
15
17
  function withGlobalOptions(cmd) {
@@ -28,6 +30,12 @@ program.configureOutput({
28
30
  else
29
31
  process.stdout.write(str);
30
32
  },
33
+ writeErr(str) {
34
+ if (jsonMode)
35
+ commanderStdout += str;
36
+ else
37
+ process.stderr.write(str);
38
+ },
31
39
  outputError(str, write) {
32
40
  if (!jsonMode)
33
41
  write(str);
@@ -43,6 +51,12 @@ withGlobalOptions(program
43
51
  const opts = command.optsWithGlobals();
44
52
  await pingCommand({ json: opts.json, staging: opts.staging });
45
53
  });
54
+ withGlobalOptions(program
55
+ .command('docs')
56
+ .description('Print complete offline CLI docs for humans and agents')).action(async (_options, command) => {
57
+ const opts = command.optsWithGlobals();
58
+ await docsCommand(program, { json: opts.json, staging: opts.staging });
59
+ });
46
60
  withGlobalOptions(program
47
61
  .command('login')
48
62
  .description('Log in with browser-based OAuth and store tokens locally')).action(async (_options, command) => {
@@ -76,12 +90,14 @@ const toolsCommand = withGlobalOptions(program.command('tools').description('Ins
76
90
  withGlobalOptions(toolsCommand
77
91
  .command('list')
78
92
  .description('List available MCP tools')
79
- .option('--no-cache', 'bypass and rewrite the local tool registry cache')).action(async (_options, command) => {
93
+ .option('--no-cache', 'bypass and rewrite the local tool registry cache')
94
+ .option('--filter <substr>', 'case-insensitive substring filter for name or description')).action(async (_options, command) => {
80
95
  const opts = command.optsWithGlobals();
81
96
  await toolsListCommand({
82
97
  json: opts.json,
83
98
  staging: opts.staging,
84
99
  noCache: opts.noCache,
100
+ filter: opts.filter,
85
101
  });
86
102
  });
87
103
  withGlobalOptions(toolsCommand
@@ -109,6 +125,14 @@ function withToolExecutionOptions(cmd) {
109
125
  .option('--read-only', 'deny write, destructive, and AI-mediated tool calls')
110
126
  .option('--timeout <secs>', 'tool call timeout in seconds');
111
127
  }
128
+ const TOOL_CALL_HELP = [
129
+ '',
130
+ 'Fastest full-tool argument forms:',
131
+ ' every tool call <name> --arg key=value --arg count=2',
132
+ ' every tool call <name> --args -',
133
+ ' every tool call <name> --args file.json',
134
+ '',
135
+ ].join('\n');
112
136
  withGlobalOptions(withToolExecutionOptions(toolCommand
113
137
  .command('call')
114
138
  .description('Call an MCP tool with JSON arguments')
@@ -131,7 +155,41 @@ withGlobalOptions(withToolExecutionOptions(toolCommand
131
155
  const invoiceCommand = withToolExecutionOptions(withGlobalOptions(program
132
156
  .command('invoice')
133
157
  .description('Work with invoices')
134
- .addHelpText('after', '\nCreate invoices with line items using: every tool call create_invoice --args <file>\n')));
158
+ .addHelpText('after', [
159
+ '',
160
+ 'Create a simple invoice:',
161
+ ' every invoice create --client "Acme" --amount 100 --yes --json',
162
+ '',
163
+ 'For rich invoices, use the full tool:',
164
+ ' every tool call create_invoice --arg client_id=<id> --arg line_items=\'[{"description":"Work","quantity":1,"unit_price":100}]\'',
165
+ ' every tool call create_invoice --args -',
166
+ ' every tool call create_invoice --args file.json',
167
+ '',
168
+ ].join('\n'))));
169
+ withGlobalOptions(withToolExecutionOptions(invoiceCommand
170
+ .command('create')
171
+ .description('Create a simple draft invoice')
172
+ .option('--client <name>', 'client name to resolve with list_clients')
173
+ .option('--client-id <id>', 'client id; skips client-name resolution')
174
+ .requiredOption('--amount <n>', 'unit price for the single line item')
175
+ .option('--description <text>', 'line item description')
176
+ .option('--quantity <q>', 'line item quantity'))).action(async (_options, command) => {
177
+ const opts = command.optsWithGlobals();
178
+ await invoiceCreateCommand({
179
+ json: opts.json,
180
+ staging: opts.staging,
181
+ noCache: opts.noCache,
182
+ yes: opts.yes,
183
+ allowDestructive: opts.allowDestructive,
184
+ readOnly: opts.readOnly,
185
+ timeout: opts.timeout,
186
+ client: opts.client,
187
+ clientId: opts.clientId,
188
+ amount: opts.amount,
189
+ description: opts.description,
190
+ quantity: opts.quantity,
191
+ });
192
+ });
135
193
  withGlobalOptions(withToolExecutionOptions(invoiceCommand
136
194
  .command('list')
137
195
  .description('List invoices')
@@ -167,7 +225,10 @@ withGlobalOptions(withToolExecutionOptions(invoiceCommand
167
225
  timeout: opts.timeout,
168
226
  });
169
227
  });
170
- const dealCommand = withToolExecutionOptions(withGlobalOptions(program.command('deal').description('Work with deals')));
228
+ const dealCommand = withToolExecutionOptions(withGlobalOptions(program
229
+ .command('deal')
230
+ .description('Work with deals')
231
+ .addHelpText('after', TOOL_CALL_HELP)));
171
232
  withGlobalOptions(withToolExecutionOptions(dealCommand
172
233
  .command('list')
173
234
  .description('List deals')
@@ -204,7 +265,10 @@ withGlobalOptions(withToolExecutionOptions(dealCommand
204
265
  timeout: opts.timeout,
205
266
  });
206
267
  });
207
- const contactCommand = withToolExecutionOptions(withGlobalOptions(program.command('contact').description('Work with contacts')));
268
+ const contactCommand = withToolExecutionOptions(withGlobalOptions(program
269
+ .command('contact')
270
+ .description('Work with contacts')
271
+ .addHelpText('after', TOOL_CALL_HELP)));
208
272
  withGlobalOptions(withToolExecutionOptions(contactCommand
209
273
  .command('list')
210
274
  .description('List contacts')
@@ -270,7 +334,21 @@ function emitCommanderSuccess(err) {
270
334
  emit({ version: pkg.version }, { json: true });
271
335
  return;
272
336
  }
273
- emit({ help: commanderStdout.trimEnd() }, { json: true });
337
+ emit({ help: commanderStdout.trimEnd() || program.helpInformation().trimEnd() }, { json: true });
338
+ }
339
+ function isBareInvocation() {
340
+ return process.argv.slice(2).length === 0;
341
+ }
342
+ async function maybeRunFirstRunMenu() {
343
+ if (!isBareInvocation() || jsonMode || !process.stdin.isTTY || !process.stdout.isTTY) {
344
+ return false;
345
+ }
346
+ await runDefaultFirstRunMenu({
347
+ staging: program.opts().staging,
348
+ showHelp: () => program.outputHelp(),
349
+ login: () => loginCommand({ staging: program.opts().staging }),
350
+ });
351
+ return true;
274
352
  }
275
353
  async function main() {
276
354
  jsonMode = process.argv.includes('--json');
@@ -278,6 +356,8 @@ async function main() {
278
356
  try {
279
357
  await program.parseAsync(process.argv);
280
358
  if (program.args.length === 0) {
359
+ if (await maybeRunFirstRunMenu())
360
+ return;
281
361
  if (jsonMode) {
282
362
  emit({ help: program.helpInformation().trimEnd() }, { json: true });
283
363
  }
@@ -298,7 +378,7 @@ async function main() {
298
378
  process.exit(ExitCode.USAGE);
299
379
  }
300
380
  if (err instanceof CliError) {
301
- emitError(err.message, err.code, { json: jsonMode });
381
+ emitError(err.message, err.code, { json: jsonMode }, err.details);
302
382
  process.exit(err.exitCode);
303
383
  }
304
384
  const message = err instanceof Error ? err.message : String(err);
@@ -0,0 +1,126 @@
1
+ import { mkdir, readFile, rename, stat, writeFile, chmod } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { getConfigDir } from '../config.js';
4
+ import { CliError } from '../errors.js';
5
+ import { ExitCode } from '../exit-codes.js';
6
+ import { discoverOAuth, fetchJsonWithTimeout, HttpStatusError } from './discovery.js';
7
+ import { environmentKeyForBaseUrl, getToken, resolveAuthTarget, } from './tokens.js';
8
+ const USERINFO_TIMEOUT_MS = 10_000;
9
+ const USERINFO_CACHE_TTL_MS = 10 * 60 * 1000;
10
+ function trimTrailingSlash(value) {
11
+ return value.replace(/\/+$/, '');
12
+ }
13
+ function safeEnvironmentKey(baseUrl) {
14
+ return environmentKeyForBaseUrl(baseUrl).replace(/[^a-zA-Z0-9._-]/g, '_');
15
+ }
16
+ export function userInfoCacheFilePath(baseUrl) {
17
+ return path.join(getConfigDir(), 'cache', `userinfo-${safeEnvironmentKey(baseUrl)}.json`);
18
+ }
19
+ function fetchedAtMs(value) {
20
+ if (typeof value === 'number')
21
+ return value;
22
+ const parsed = Date.parse(value);
23
+ return Number.isFinite(parsed) ? parsed : 0;
24
+ }
25
+ function stringOrNull(value) {
26
+ return typeof value === 'string' && value.length > 0 ? value : null;
27
+ }
28
+ function normalizeUserInfo(value) {
29
+ return {
30
+ user_id: stringOrNull(value.user_id) ?? stringOrNull(value.sub),
31
+ email: stringOrNull(value.email),
32
+ name: stringOrNull(value.name),
33
+ org_id: stringOrNull(value.org_id),
34
+ org_slug: stringOrNull(value.org_slug),
35
+ org_name: stringOrNull(value.org_name),
36
+ };
37
+ }
38
+ function isUserInfo(value) {
39
+ if (!value || typeof value !== 'object')
40
+ return false;
41
+ const candidate = value;
42
+ return ('user_id' in candidate &&
43
+ 'email' in candidate &&
44
+ 'name' in candidate &&
45
+ 'org_id' in candidate &&
46
+ 'org_slug' in candidate &&
47
+ 'org_name' in candidate);
48
+ }
49
+ export async function readCachedUserInfo(baseUrl, { allowStale = false, now = Date.now, } = {}) {
50
+ let parsed;
51
+ try {
52
+ parsed = JSON.parse(await readFile(userInfoCacheFilePath(baseUrl), 'utf8'));
53
+ }
54
+ catch (err) {
55
+ if (err && typeof err === 'object' && 'code' in err && err.code === 'ENOENT') {
56
+ return undefined;
57
+ }
58
+ throw err;
59
+ }
60
+ if (!isUserInfo(parsed.userinfo))
61
+ return undefined;
62
+ if (!allowStale && now() - fetchedAtMs(parsed.fetched_at) > USERINFO_CACHE_TTL_MS) {
63
+ return undefined;
64
+ }
65
+ return parsed.userinfo;
66
+ }
67
+ async function writeUserInfoCache(baseUrl, userinfo) {
68
+ const filePath = userInfoCacheFilePath(baseUrl);
69
+ await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
70
+ const tempPath = `${filePath}.${process.pid}.tmp`;
71
+ await writeFile(tempPath, JSON.stringify({ fetched_at: new Date().toISOString(), userinfo }, null, 2), { mode: 0o600 });
72
+ await chmod(tempPath, 0o600);
73
+ await rename(tempPath, filePath);
74
+ await chmod(filePath, 0o600);
75
+ }
76
+ export async function userInfoCacheFileMode(baseUrl) {
77
+ try {
78
+ return (await stat(userInfoCacheFilePath(baseUrl))).mode & 0o777;
79
+ }
80
+ catch (err) {
81
+ if (err && typeof err === 'object' && 'code' in err && err.code === 'ENOENT') {
82
+ return undefined;
83
+ }
84
+ throw err;
85
+ }
86
+ }
87
+ async function fetchOpenIdConfiguration(issuer) {
88
+ const url = `${trimTrailingSlash(issuer)}/.well-known/openid-configuration`;
89
+ const metadata = await fetchJsonWithTimeout(url, { headers: { accept: 'application/json' } }, USERINFO_TIMEOUT_MS);
90
+ if (typeof metadata.userinfo_endpoint !== 'string' || metadata.userinfo_endpoint.length === 0) {
91
+ throw new CliError(`OpenID configuration at ${url} did not include userinfo_endpoint`, ExitCode.NETWORK, 'network');
92
+ }
93
+ return metadata;
94
+ }
95
+ export async function fetchUserInfo(opts = {}) {
96
+ const { baseUrl } = resolveAuthTarget(opts);
97
+ const token = await getToken({ baseUrl, store: opts.store, now: opts.now });
98
+ if (!opts.forceRefresh) {
99
+ const cached = await readCachedUserInfo(baseUrl, { now: opts.now }).catch(() => undefined);
100
+ if (cached)
101
+ return cached;
102
+ }
103
+ const discovery = await discoverOAuth(baseUrl);
104
+ const openid = await fetchOpenIdConfiguration(discovery.authServer.issuer);
105
+ let raw;
106
+ try {
107
+ raw = await fetchJsonWithTimeout(openid.userinfo_endpoint, {
108
+ headers: {
109
+ accept: 'application/json',
110
+ authorization: `Bearer ${token}`,
111
+ },
112
+ }, USERINFO_TIMEOUT_MS);
113
+ }
114
+ catch (err) {
115
+ if (err instanceof HttpStatusError && err.status === 401) {
116
+ throw new CliError('Not logged in. Run \'every login\'.', ExitCode.AUTH, 'auth');
117
+ }
118
+ if (err instanceof HttpStatusError) {
119
+ throw new CliError(`User info request failed for ${err.url}: HTTP ${err.status}`, ExitCode.NETWORK, 'network');
120
+ }
121
+ throw err;
122
+ }
123
+ const userinfo = normalizeUserInfo(raw);
124
+ await writeUserInfoCache(baseUrl, userinfo);
125
+ return userinfo;
126
+ }
@@ -1,13 +1,16 @@
1
1
  import os from 'node:os';
2
2
  import path from 'node:path';
3
3
  /**
4
- * On-disk config location for the `every` CLI (auth tokens land here in a
5
- * later phase). Kept under the XDG-style `~/.config/everyai`.
4
+ * Default on-disk config location for the `every` CLI.
6
5
  */
7
6
  export const CONFIG_DIR = path.join(os.homedir(), '.config', 'everyai');
8
7
  /** Resolve the config directory dynamically so tests can isolate state. */
9
8
  export function getConfigDir() {
10
- return process.env.EVERY_CONFIG_DIR ?? CONFIG_DIR;
9
+ if (process.env.EVERY_CONFIG_DIR)
10
+ return process.env.EVERY_CONFIG_DIR;
11
+ if (process.env.XDG_CONFIG_HOME)
12
+ return path.join(process.env.XDG_CONFIG_HOME, 'everyai');
13
+ return CONFIG_DIR;
11
14
  }
12
15
  /** Deployed MCP base URLs. */
13
16
  export const PROD_BASE_URL = 'https://admin-mcp.every.ai';
@@ -16,13 +19,32 @@ export const STAGING_BASE_URL = 'https://admin-mcp-staging.up.railway.app';
16
19
  * Resolve the MCP base URL to target.
17
20
  *
18
21
  * Precedence:
19
- * 1. `EVERY_MCP_URL` env override (any value, wins over `staging`)
20
- * 2. `{ staging: true }` -> staging deployment
21
- * 3. default -> production deployment
22
+ * 1. `{ staging: true }` -> staging deployment
23
+ * 2. `EVERY_MCP_URL` env override
24
+ * 3. `EVERY_ENV=staging|production`
25
+ * 4. default -> production deployment
22
26
  */
23
27
  export function resolveBaseUrl({ staging } = {}) {
28
+ if (staging)
29
+ return STAGING_BASE_URL;
24
30
  const override = process.env.EVERY_MCP_URL;
25
31
  if (override)
26
32
  return override;
27
- return staging ? STAGING_BASE_URL : PROD_BASE_URL;
33
+ const env = process.env.EVERY_ENV?.toLowerCase();
34
+ if (env === 'staging')
35
+ return STAGING_BASE_URL;
36
+ if (env === 'production')
37
+ return PROD_BASE_URL;
38
+ return PROD_BASE_URL;
39
+ }
40
+ function trimTrailingSlash(value) {
41
+ return value.replace(/\/+$/, '');
42
+ }
43
+ export function environmentNameForBaseUrl(baseUrl) {
44
+ const normalized = trimTrailingSlash(baseUrl);
45
+ if (normalized === trimTrailingSlash(PROD_BASE_URL))
46
+ return 'production';
47
+ if (normalized === trimTrailingSlash(STAGING_BASE_URL))
48
+ return 'staging';
49
+ return 'custom';
28
50
  }
@@ -7,10 +7,12 @@
7
7
  export class CliError extends Error {
8
8
  exitCode;
9
9
  code;
10
- constructor(message, exitCode = 1, code = 'generic') {
10
+ details;
11
+ constructor(message, exitCode = 1, code = 'generic', details) {
11
12
  super(message);
12
13
  this.exitCode = exitCode;
13
14
  this.code = code;
15
+ this.details = details;
14
16
  this.name = 'CliError';
15
17
  }
16
18
  }
@@ -0,0 +1,58 @@
1
+ import { createInterface } from 'node:readline/promises';
2
+ import { resolveBaseUrl } from './config.js';
3
+ import { getAuthStatus } from './auth/tokens.js';
4
+ import { readCachedUserInfo } from './auth/userinfo.js';
5
+ function write(output, text) {
6
+ output.write(text);
7
+ }
8
+ export async function runFirstRunMenu(opts) {
9
+ const status = await opts.getStatus();
10
+ if (status.logged_in) {
11
+ const identity = await opts.getCachedIdentity();
12
+ if (identity) {
13
+ const email = identity.email ?? 'unknown';
14
+ const org = identity.org_name ?? 'unknown';
15
+ write(opts.output, `Logged in as ${email} · org ${org} · try: every tools list\n\n`);
16
+ }
17
+ opts.showHelp();
18
+ return;
19
+ }
20
+ write(opts.output, [
21
+ "Welcome to Every AI — you're not logged in.",
22
+ '',
23
+ '1) Log in or create an account (opens your browser)',
24
+ '2) Show all commands',
25
+ '3) Exit',
26
+ '',
27
+ ].join('\n'));
28
+ const rl = createInterface({ input: opts.input, output: opts.output });
29
+ let action = 'exit';
30
+ try {
31
+ const answer = (await rl.question('Choose [1]: ')).trim();
32
+ if (answer === '' || answer === '1') {
33
+ action = 'login';
34
+ }
35
+ else if (answer === '2') {
36
+ action = 'help';
37
+ }
38
+ }
39
+ finally {
40
+ rl.close();
41
+ }
42
+ // Login may open its own post-login prompt, so release stdin first.
43
+ if (action === 'login')
44
+ await opts.login();
45
+ else if (action === 'help')
46
+ opts.showHelp();
47
+ }
48
+ export async function runDefaultFirstRunMenu(params) {
49
+ const baseUrl = resolveBaseUrl({ staging: params.staging });
50
+ await runFirstRunMenu({
51
+ input: process.stdin,
52
+ output: process.stdout,
53
+ showHelp: params.showHelp,
54
+ login: params.login,
55
+ getStatus: () => getAuthStatus({ baseUrl }),
56
+ getCachedIdentity: () => readCachedUserInfo(baseUrl, { allowStale: true }),
57
+ });
58
+ }