@everyai/cli 0.6.5 → 0.7.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/README.md CHANGED
@@ -47,8 +47,9 @@ The CLI talks to the same Every MCP server (`admin-mcp.every.ai`) and inherits i
47
47
 
48
48
  ```bash
49
49
  # Auth
50
- every login [--create-account] [--staging] # browser OAuth; keychain storage; refresh handled
51
- every logout | whoami | auth status | org
50
+ every login [--create-account] [--org <name|slug|id>] [--staging] # browser OAuth; keychain storage; refresh handled
51
+ every logout | whoami | auth status
52
+ every org [switch --org <name|slug|id>]
52
53
 
53
54
  # Discovery
54
55
  every docs
@@ -75,6 +76,10 @@ every skills install codex # → .agents/skills/use-every/
75
76
 
76
77
  Run `every login` to choose between logging in and creating an account, or use `every login --create-account` to open Every's signup page directly. After you create your account and workspace, return to the terminal and press Enter; the CLI connects through the normal browser OAuth flow.
77
78
 
79
+ ## Switching workspaces
80
+
81
+ Run `every org switch` and pick the workspace in the browser consent page's selector. The token binds one workspace per environment; add `--staging` to switch staging. Use `every org switch --org "<name|slug|id>"` (or `every login --org "<name|slug|id>"`) to verify the selection after login. `--org` does not preselect a workspace; a mismatch keeps your previous credentials. Names can be ambiguous, so use the workspace id when needed. Verify the result with `every whoami --json`. Unset `EVERY_TOKEN` before switching because it overrides stored credentials.
82
+
78
83
  ## Output contract
79
84
 
80
85
  Every command supports `--json`: exactly one JSON document on stdout, nothing else.
@@ -9,7 +9,7 @@ import { mcpCall } from '../lib/mcp.js';
9
9
  import { loginFlow, openBrowser as openBrowserDefault } from '../lib/auth/flow.js';
10
10
  import { decodeJwtClaims } from '../lib/auth/jwt.js';
11
11
  import { createTokenStore, deleteTokenFromAllStores, getAuthStatus, getToken, resolveAuthTarget, } from '../lib/auth/tokens.js';
12
- import { fetchUserInfo } from '../lib/auth/userinfo.js';
12
+ import { fetchUserInfo, invalidateUserInfoCache, readCachedUserInfo, requestUserInfo, writeUserInfoCache, } from '../lib/auth/userinfo.js';
13
13
  import { maybeShowSkillHint, readHints, writeHints, } from '../lib/hints.js';
14
14
  import { emit } from '../lib/output.js';
15
15
  import { installBundledSkill } from './skills.js';
@@ -134,7 +134,7 @@ function loginHuman(data) {
134
134
  if (data.every_token)
135
135
  return 'EVERY_TOKEN is set; login is unnecessary.';
136
136
  const identity = data.email ?? data.subject;
137
- return identity ? `Logged in as ${identity}` : 'Logged in';
137
+ return `Logged in as ${identity ?? 'unknown'} · workspace ${formatOrg(data.org_name, data.org_id)}\nSwitch workspace: every org switch`;
138
138
  }
139
139
  function loginNextSteps() {
140
140
  return [
@@ -181,6 +181,7 @@ function orgHuman(org) {
181
181
  `Org: ${formatOrg(org.org_name, org.org_id)}`,
182
182
  `Slug: ${org.org_slug ?? 'none'}`,
183
183
  'Note: the server scopes writes to this org.',
184
+ 'Switch: every org switch [--org <name|slug|id>]',
184
185
  ];
185
186
  return lines.join('\n');
186
187
  }
@@ -201,39 +202,131 @@ async function verifyMcpLiveness(baseUrl, token) {
201
202
  tools: Array.isArray(body.tools) ? body.tools.length : 0,
202
203
  };
203
204
  }
204
- async function runBrowserLogin(opts, streams = {
205
- input: process.stdin,
206
- output: process.stdout,
207
- errorOutput: process.stderr,
208
- }) {
205
+ function validateOrgTarget(target) {
206
+ if (!target.trim()) {
207
+ throw new CliError('--org must not be empty or whitespace-only', ExitCode.USAGE, 'usage');
208
+ }
209
+ }
210
+ /** IDs are exact; slugs ignore case; display names also trim and normalize Unicode. */
211
+ export function matchesOrg(target, info) {
212
+ validateOrgTarget(target);
213
+ const name = (value) => value.trim().normalize('NFC').toLowerCase();
214
+ return target === info.org_id ||
215
+ (info.org_slug !== null && target.toLowerCase() === info.org_slug.toLowerCase()) ||
216
+ (info.org_name !== null && name(target) === name(info.org_name));
217
+ }
218
+ function validateBrowserLogin(opts, switching = false) {
219
+ if (opts.org !== undefined)
220
+ validateOrgTarget(opts.org);
221
+ if (process.env.EVERY_TOKEN && (switching || opts.org !== undefined)) {
222
+ throw new CliError('Workspace switching requires stored credentials; unset EVERY_TOKEN and try again.', ExitCode.USAGE, 'usage');
223
+ }
224
+ }
225
+ /** Exchange, verify, then commit. A failed assertion never mutates stored auth or identity. */
226
+ export async function completeBrowserLogin(opts, deps = {}, switching = false) {
227
+ validateBrowserLogin(opts, switching);
228
+ const errorOutput = deps.errorOutput ?? process.stderr;
209
229
  const baseUrl = resolveBaseUrl({ staging: opts.staging });
210
230
  const { environmentKey } = resolveAuthTarget({ baseUrl });
211
- const tokenSet = await loginFlow({
231
+ errorOutput.write(opts.org === undefined
232
+ ? "Pick the workspace in the consent page's selector.\n"
233
+ : `In the consent page's selector, pick "${opts.org}".\n`);
234
+ const tokenSet = await (deps.loginFlow ?? loginFlow)({
212
235
  baseUrl,
213
236
  onAuthorizationUrl(url) {
214
- streams.errorOutput.write(`Open this URL to log in:\n${url}\n`);
237
+ errorOutput.write(`Open this URL to log in:\n${url}\n`);
215
238
  },
216
239
  });
217
- const store = await createTokenStore();
218
- await store.set(environmentKey, tokenSet);
240
+ let userinfo;
241
+ try {
242
+ userinfo = await requestUserInfo({ baseUrl, accessToken: tokenSet.access_token });
243
+ }
244
+ catch {
245
+ if (switching || opts.org !== undefined) {
246
+ throw new CliError('Could not verify the workspace because userinfo is unreachable. Previous credentials kept; try again.', ExitCode.NETWORK, 'network');
247
+ }
248
+ }
249
+ if (opts.org !== undefined && userinfo && !matchesOrg(opts.org, userinfo)) {
250
+ throw new CliError(`Token is bound to workspace ${formatOrg(userinfo.org_name, userinfo.org_id)}, but requested "${opts.org}". ` +
251
+ `Retry: every org switch --org "${opts.org}" and pick that workspace in the consent page. ` +
252
+ 'Use the workspace id as the unambiguous form.', ExitCode.GENERIC, 'org_mismatch');
253
+ }
254
+ const store = deps.store ?? await createTokenStore();
255
+ const previous = await store.get(environmentKey);
256
+ try {
257
+ await store.set(environmentKey, tokenSet);
258
+ }
259
+ catch (err) {
260
+ try {
261
+ if (previous)
262
+ await store.set(environmentKey, previous);
263
+ else
264
+ await store.delete(environmentKey);
265
+ }
266
+ catch {
267
+ errorOutput.write('Warning: could not restore previous credentials after a storage failure.\n');
268
+ }
269
+ throw err;
270
+ }
271
+ if (userinfo) {
272
+ try {
273
+ await writeUserInfoCache(baseUrl, userinfo);
274
+ }
275
+ catch {
276
+ // A failed write may have left the old identity behind. Remove it if possible.
277
+ await invalidateUserInfoCache(baseUrl).catch(() => undefined);
278
+ errorOutput.write('Warning: logged in, but could not cache the current identity.\n');
279
+ }
280
+ }
281
+ else {
282
+ await invalidateUserInfoCache(baseUrl).catch(() => {
283
+ errorOutput.write('Warning: could not invalidate the previous identity cache.\n');
284
+ });
285
+ errorOutput.write('Warning: logged in, but userinfo is unreachable; workspace identity is unknown.\n');
286
+ }
219
287
  const identity = identityFromToken(tokenSet.access_token);
220
- const data = {
288
+ return {
221
289
  logged_in: true,
222
290
  issuer: tokenSet.issuer,
223
- subject: identity.subject,
224
- email: identity.email,
291
+ subject: userinfo?.user_id ?? identity.subject,
292
+ email: userinfo?.email ?? identity.email,
225
293
  storage_backend: store.backend,
226
294
  every_token: false,
295
+ user_id: userinfo?.user_id ?? null,
296
+ org_id: userinfo?.org_id ?? null,
297
+ org_slug: userinfo?.org_slug ?? null,
298
+ org_name: userinfo?.org_name ?? null,
227
299
  };
228
- emitLogin(data, opts, streams.output, streams.errorOutput);
229
- await maybeOfferSkillAfterLogin({
230
- json: opts.json,
231
- input: streams.input,
232
- output: streams.output,
233
- errorOutput: streams.errorOutput,
234
- });
300
+ }
301
+ export async function runBrowserLogin(opts, deps = {}) {
302
+ const data = await completeBrowserLogin(opts, deps);
303
+ emitLogin(data, opts, deps.output, deps.errorOutput);
304
+ await maybeOfferSkillAfterLogin({ json: opts.json, ...deps });
305
+ }
306
+ export async function orgSwitchCommand(opts = {}, deps = {}) {
307
+ validateBrowserLogin(opts, true);
308
+ if (!(deps.output ?? process.stdout).isTTY) {
309
+ throw new CliError('org switch requires a browser and an interactive terminal', ExitCode.AUTH, 'auth');
310
+ }
311
+ const baseUrl = resolveBaseUrl({ staging: opts.staging });
312
+ const previous = await readCachedUserInfo(baseUrl, { allowStale: true }).catch(() => undefined);
313
+ const login = await completeBrowserLogin(opts, deps, true);
314
+ const data = {
315
+ switched: true,
316
+ org_id: login.org_id,
317
+ org_slug: login.org_slug,
318
+ org_name: login.org_name,
319
+ previous_org_id: previous?.org_id ?? null,
320
+ environment: environmentNameForBaseUrl(baseUrl),
321
+ };
322
+ if (opts.json)
323
+ emit(data, { json: true, staging: opts.staging });
324
+ else
325
+ (deps.output ?? process.stdout).write(`Switched to ${formatOrg(data.org_name, data.org_id)} · ${login.email ?? 'unknown'}\n`);
326
+ await maybeOfferSkillAfterLogin({ json: opts.json, ...deps });
235
327
  }
236
328
  export async function createAccountFlow(opts = {}) {
329
+ validateBrowserLogin(opts);
237
330
  const input = opts.input ?? process.stdin;
238
331
  const output = opts.output ?? process.stdout;
239
332
  const errorOutput = opts.errorOutput ?? process.stderr;
@@ -275,6 +368,7 @@ async function promptForLoggedOutAction() {
275
368
  }
276
369
  }
277
370
  export async function loginCommand(opts = {}) {
371
+ validateBrowserLogin(opts);
278
372
  if (process.env.EVERY_TOKEN) {
279
373
  const identity = identityFromToken(process.env.EVERY_TOKEN);
280
374
  const data = {
@@ -284,6 +378,10 @@ export async function loginCommand(opts = {}) {
284
378
  email: identity.email,
285
379
  storage_backend: null,
286
380
  every_token: true,
381
+ user_id: null,
382
+ org_id: null,
383
+ org_slug: null,
384
+ org_name: null,
287
385
  };
288
386
  emitLogin(data, opts);
289
387
  return;
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import { readFileSync } from 'node:fs';
3
3
  import { Command, CommanderError } from 'commander';
4
4
  import { pingCommand } from './commands/ping.js';
5
5
  import { docsCommand } from './commands/docs.js';
6
- import { authStatusCommand, loginCommand, logoutCommand, orgCommand, whoamiCommand, } from './commands/auth.js';
6
+ import { authStatusCommand, loginCommand, logoutCommand, orgCommand, orgSwitchCommand, whoamiCommand, } from './commands/auth.js';
7
7
  import { policyExplainCommand } from './commands/policy.js';
8
8
  import { toolCallCommand, toolsDescribeCommand, toolsListCommand, } from './commands/tools.js';
9
9
  import { contactListCommand, dealListCommand, dealMoveCommand, invoiceCreateCommand, invoiceListCommand, invoiceSendCommand, } from './commands/aliases.js';
@@ -60,12 +60,14 @@ withGlobalOptions(program
60
60
  withGlobalOptions(program
61
61
  .command('login')
62
62
  .description('Log in (or create an account) with browser-based OAuth and store tokens locally')
63
- .option('--create-account', 'create a new Every account, then connect the CLI')).action(async (_options, command) => {
63
+ .option('--create-account', 'create a new Every account, then connect the CLI')
64
+ .option('--org <id|slug|name>', 'verify the workspace selected during login')).action(async (_options, command) => {
64
65
  const opts = command.optsWithGlobals();
65
66
  await loginCommand({
66
67
  json: opts.json,
67
68
  staging: opts.staging,
68
69
  createAccount: opts.createAccount,
70
+ org: opts.org,
69
71
  });
70
72
  });
71
73
  withGlobalOptions(program
@@ -85,12 +87,19 @@ withGlobalOptions(authCommand.command('status').description('Show local auth sta
85
87
  const opts = command.optsWithGlobals();
86
88
  await authStatusCommand({ json: opts.json, staging: opts.staging });
87
89
  });
88
- withGlobalOptions(program
90
+ const org = withGlobalOptions(program
89
91
  .command('org')
90
- .description('Show org claims from the current token; multi-org selection lands in a later phase')).action(async (_options, command) => {
92
+ .allowExcessArguments(false)
93
+ .description('Show or switch the workspace bound to the current token')).action(async (_options, command) => {
91
94
  const opts = command.optsWithGlobals();
92
95
  await orgCommand({ json: opts.json, staging: opts.staging });
93
96
  });
97
+ withGlobalOptions(org.command('switch')
98
+ .description('Switch workspace using the browser consent selector')
99
+ .option('--org <ref>', 'verify the selected workspace by id, slug, or name')).action(async (_options, command) => {
100
+ const opts = command.optsWithGlobals();
101
+ await orgSwitchCommand({ json: opts.json, staging: opts.staging, org: opts.org });
102
+ });
94
103
  const toolsCommand = withGlobalOptions(program.command('tools').description('Inspect the Every MCP tool registry'));
95
104
  withGlobalOptions(toolsCommand
96
105
  .command('list')
@@ -136,7 +136,7 @@ export async function loginFlow(opts) {
136
136
  const startedAt = Date.now();
137
137
  const state = createState();
138
138
  const pkce = createPkcePair();
139
- const loopback = await createLoopbackCallbackServer(state);
139
+ const loopback = await (opts.createCallbackServer ?? createLoopbackCallbackServer)(state);
140
140
  const timeout = new Promise((_, reject) => {
141
141
  setTimeout(() => {
142
142
  reject(new CliError('Login timed out after 300s', ExitCode.AUTH, 'auth'));
@@ -1,4 +1,4 @@
1
- import { mkdir, readFile, rename, stat, writeFile, chmod } from 'node:fs/promises';
1
+ import { mkdir, readFile, rename, stat, writeFile, chmod, rm } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { getConfigDir } from '../config.js';
4
4
  import { CliError } from '../errors.js';
@@ -64,7 +64,7 @@ export async function readCachedUserInfo(baseUrl, { allowStale = false, now = Da
64
64
  }
65
65
  return parsed.userinfo;
66
66
  }
67
- async function writeUserInfoCache(baseUrl, userinfo) {
67
+ export async function writeUserInfoCache(baseUrl, userinfo) {
68
68
  const filePath = userInfoCacheFilePath(baseUrl);
69
69
  await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
70
70
  const tempPath = `${filePath}.${process.pid}.tmp`;
@@ -73,6 +73,9 @@ async function writeUserInfoCache(baseUrl, userinfo) {
73
73
  await rename(tempPath, filePath);
74
74
  await chmod(filePath, 0o600);
75
75
  }
76
+ export async function invalidateUserInfoCache(baseUrl) {
77
+ await rm(userInfoCacheFilePath(baseUrl), { force: true });
78
+ }
76
79
  export async function userInfoCacheFileMode(baseUrl) {
77
80
  try {
78
81
  return (await stat(userInfoCacheFilePath(baseUrl))).mode & 0o777;
@@ -100,6 +103,12 @@ export async function fetchUserInfo(opts = {}) {
100
103
  if (cached)
101
104
  return cached;
102
105
  }
106
+ const userinfo = await requestUserInfo({ baseUrl, accessToken: token });
107
+ await writeUserInfoCache(baseUrl, userinfo);
108
+ return userinfo;
109
+ }
110
+ /** Verify a candidate credential without reading or changing stored auth/identity. */
111
+ export async function requestUserInfo({ baseUrl, accessToken }) {
103
112
  const discovery = await discoverOAuth(baseUrl);
104
113
  const openid = await fetchOpenIdConfiguration(discovery.authServer.issuer);
105
114
  let raw;
@@ -107,7 +116,7 @@ export async function fetchUserInfo(opts = {}) {
107
116
  raw = await fetchJsonWithTimeout(openid.userinfo_endpoint, {
108
117
  headers: {
109
118
  accept: 'application/json',
110
- authorization: `Bearer ${token}`,
119
+ authorization: `Bearer ${accessToken}`,
111
120
  },
112
121
  }, USERINFO_TIMEOUT_MS);
113
122
  }
@@ -120,7 +129,5 @@ export async function fetchUserInfo(opts = {}) {
120
129
  }
121
130
  throw err;
122
131
  }
123
- const userinfo = normalizeUserInfo(raw);
124
- await writeUserInfoCache(baseUrl, userinfo);
125
- return userinfo;
132
+ return normalizeUserInfo(raw);
126
133
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@everyai/cli",
3
- "version": "0.6.5",
3
+ "version": "0.7.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Every-AI-Inc/everyai-cli.git"
@@ -13,7 +13,7 @@ For headless use, accept `EVERY_TOKEN` from the environment instead of browser l
13
13
 
14
14
  ## What Every Is
15
15
 
16
- Use Every as a service-business workspace for the sales pipeline, deals, People and Companies, proposals, invoices, payments, and services. The authenticated CLI operates on one connected Every workspace at a time. If the user means a different business, tell them to switch accounts in Every.
16
+ Use Every as a service-business workspace for the sales pipeline, deals, People and Companies, proposals, invoices, payments, and services. The authenticated CLI operates on one connected Every workspace at a time. The token binds one workspace per environment; follow the workspace switching rule below when the user means a different business.
17
17
 
18
18
  ## Required Workflow
19
19
 
@@ -69,6 +69,10 @@ Use `every whoami --json` to verify the authenticated user, org, environment, ba
69
69
 
70
70
  ## Domain Rules
71
71
 
72
+ ### Verify the workspace before acting
73
+
74
+ Never assume the bound workspace. When the user names a different workspace, run `every org switch --org "<name>" --json`, then re-verify with `every whoami --json` before continuing. The browser consent page is the picker; `--org` verifies the selection after login. A token binds one workspace per environment. Use the workspace id when names are ambiguous. If `EVERY_TOKEN` is set, ask the user to unset it before switching.
75
+
72
76
  ### Deal activity auto-tracking is creation-only
73
77
 
74
78
  Creating a proposal or invoice automatically records activity on a matching deal when exactly one deal/party (Person or Company) matches. After an Every creation command, never double-log that action: