@everyai/cli 0.7.2 → 0.8.1

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
@@ -7,7 +7,8 @@ Install once, log in once, and teach each coding agent the same `every` command
7
7
  ```bash
8
8
  npm install -g @everyai/cli
9
9
  every docs # offline command tree, output contract, workflows
10
- every login # pick "Create an account" if you're new — signup happens in the browser, then the CLI connects automatically
10
+ every signup # new to Every? one browser step creates your account (an agent can run this for you)
11
+ every login # existing users at an interactive terminal
11
12
  every skills install claude|codex # teach Claude Code or Codex how to use Every
12
13
  every whoami # user, org, environment, tool-count check
13
14
  ```
@@ -17,7 +18,7 @@ One-shot invoice example with inline args:
17
18
  ```bash
18
19
  every invoice list --status overdue --json
19
20
  every tool call create_invoice \
20
- --arg command='{"operation_id":"<uuid>","party":{"kind":"company","id":"client_123"},"line_items":[{"description":"Strategy work","quantity":1,"unit_price":1500}]}' \
21
+ --arg command='{"operation_id":"<uuid>","party":{"kind":"company","id":"<company_id>"},"line_items":[{"description":"Strategy work","quantity":1,"unit_price":1500}]}' \
21
22
  --yes \
22
23
  --json
23
24
  ```
@@ -47,7 +48,11 @@ The CLI talks to the same Every MCP server (`admin-mcp.every.ai`) and inherits i
47
48
 
48
49
  ```bash
49
50
  # Auth
50
- every login [--create-account] [--org <name|slug|id>] [--staging] # browser OAuth; keychain storage; refresh handled
51
+ every signup [--timeout <seconds>] # new account or sign-in via one browser step; works without a TTY
52
+ every signup status
53
+ every signup complete --org-name <name> [--description <text>] [--link <url> ...] --yes
54
+ every login [--org <name|slug|id>] [--staging] # browser OAuth; keychain storage; refresh handled
55
+ # (--create-account is a deprecated alias for every signup)
51
56
  every logout | whoami | auth status
52
57
  every org [switch --org <name|slug|id>]
53
58
 
@@ -62,19 +67,35 @@ every tool call <name> [--args file.json|-] [--arg k=v ...] [--yes] [--allow-des
62
67
 
63
68
  # Curated aliases (same gates, nicer flags)
64
69
  every invoice list [--status <s>] [--search <q>] [--limit <n>]
70
+ every invoice create (--company <name> | --person <name> | --company-id <id> | --person-id <id>) --amount <n>
71
+ # write: needs --yes
65
72
  every invoice send <invoice_id> # destructive: needs --yes --allow-destructive
66
73
  every deal list [--stage <s>] [--search <q>]
67
74
  every deal move <deal_id> <stage> # write: needs --yes
68
- every contact list [--search <q>]
75
+ every person list [--search <q>] # People
69
76
 
70
77
  # Teach your coding agent to use all of this well
71
78
  every skills install claude # → .claude/skills/use-every/
72
79
  every skills install codex # → .agents/skills/use-every/
73
80
  ```
74
81
 
75
- ## Login and account creation
82
+ Deprecated aliases still work and print a one-line note to stderr: `every contact list` (use `every person list`) and `every invoice create --client <name>` / `--client-id <id>` (use `--company`, `--company-id` or `--person-id`). They are hidden from help and `every docs`.
76
83
 
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.
84
+ ## Signing up
85
+
86
+ `every signup` creates an Every account, or signs an existing user in, through a single browser authorization. It never opens a separate sign-up page and never waits for Enter, so a coding agent can run it on the user's behalf without a TTY:
87
+
88
+ 1. It prints the authorization URL first, tries to open the browser, then waits on a local loopback callback for up to `--timeout` seconds (default 300). With `--json`, stdout is NDJSON: `{"event":"authorization_required","url":"..."}`, then `{"event":"waiting_for_authorization","browser_opened":true|false,"timeout_seconds":300}`, then the usual envelope as the last line. If `browser_opened` is false, open the printed URL yourself.
89
+ 2. After the browser step it reports the server's signup status: `signup_status` is `ready` for an account that is good to go, or `needs_profile` with the one required field (`organization_name`) and unverified `profile_suggestions` to confirm with the user.
90
+ 3. `every signup complete --org-name "<name>" [--description "<text>"] [--link <https url> ...] --yes` saves the confirmed profile and returns `account_ready: true`. Background setup (Business DNA and friends) is reported separately and never blocks the account. It is an ordinary write: `--yes` when non-interactive, never `--allow-destructive`.
91
+
92
+ `every signup status` re-reads the state at any time. Signup commands always fetch a fresh tool list. A server without agent signup yields exit `6` with `error.code: "signup_unsupported"` ("this server does not support agent signup yet"). Denials and timeouts exit `3`; rerun `every signup`. While signup is unfinished, other tools are refused with `error.code: "signup_incomplete"`, and the CLI says which commands finish it. `EVERY_TOKEN` is never a signup path.
93
+
94
+ The CLI sends the RFC 8707 `resource` parameter (the MCP server's canonical URL from its protected-resource metadata) on the authorization request, the code exchange and every refresh.
95
+
96
+ After a successful `every signup` or `every login`, the CLI updates any copy of the `use-every` skill it installed earlier whose revision stamp is older than the bundled one. It never installs a copy where none exists and skips symlinked installs.
97
+
98
+ `every login` remains the interactive login for existing users; `every login --create-account` still works as a deprecated alias for `every signup`.
78
99
 
79
100
  ## Switching workspaces
80
101
 
@@ -89,7 +110,7 @@ Every command supports `--json`: exactly one JSON document on stdout, nothing el
89
110
  { "ok": false, "error": { "message": "...", "code": "..." }, "env": "production", "schema_version": 1 }
90
111
  ```
91
112
 
92
- Exit codes: `0` ok · `1` tool/generic error · `2` usage · `3` auth (run `every login`) · `4` permission/confirmation needed · `5` rate-limited · `6` not found · `7` network/timeout.
113
+ Exit codes: `0` ok · `1` tool/generic error · `2` usage · `3` auth (run `every signup`, or `every login` at a terminal) · `4` permission/confirmation needed · `5` rate-limited · `6` not found · `7` network/timeout.
93
114
 
94
115
  When a tool refuses (exit `1`) and the server attached a structured error, `error.code` is the server's stable, machine-readable code — e.g. `duplicate_deal`, `party_unresolved`, `contact_suppressed`, `deal_archived`, `person_has_references` — and `error.tool_error` carries the server's full error object (e.g. `existing_deal_id`). Branch on the code, never on the message. Servers that send no structured error still produce `error.code: "generic"`. Successful creates return the new record's id in `data.structured_content` (e.g. `structured_content.deal.id`).
95
116
 
@@ -99,7 +120,7 @@ In `--json` mode, a server approval response uses exit `4` and includes a struct
99
120
 
100
121
  ## Headless / CI
101
122
 
102
- Set `EVERY_TOKEN` to a valid access token to skip the browser flow entirely. `login` requires a TTY by design and fails fast (exit `3`) without one.
123
+ Set `EVERY_TOKEN` to a valid access token to skip the browser flow entirely. `login` requires a TTY by design and fails fast (exit `3`) without one; `signup` does not need one.
103
124
 
104
125
  Target precedence: `--staging` > `EVERY_MCP_URL` > `EVERY_ENV=staging|production` > production.
105
126
 
@@ -190,20 +190,24 @@ export function parseClientCandidates(result) {
190
190
  ...parseClientCandidatesFromText(textFromContent(result.content)),
191
191
  ]);
192
192
  }
193
- function partyCandidatesMessage(label, query, candidates) {
193
+ const PARTY_ID_FLAG = {
194
+ company: '--company-id',
195
+ person: '--person-id',
196
+ };
197
+ function partyCandidatesMessage(kind, query, candidates) {
194
198
  return [
195
- `Multiple ${label}s matching "${query}".`,
199
+ `Multiple ${kind === 'person' ? 'People' : 'Companies'} matching "${query}".`,
196
200
  ...candidates.map((candidate) => `${candidate.client_id} ${candidate.name}`),
197
- 'Re-run with --client-id <id>',
201
+ `Re-run with ${PARTY_ID_FLAG[kind]} <id>`,
198
202
  ].join('\n');
199
203
  }
200
- // --client is the deprecated alias for --company (the historical "client" concept is
201
- // now the Company record); --person resolves via the People half of the same schema.
204
+ // --client is the deprecated alias for --company (the CLI's older word for the
205
+ // invoice recipient); --person resolves via the People half of the same schema.
202
206
  function selectParty(opts) {
203
207
  const companyName = nonEmpty(opts.company) ?? nonEmpty(opts.client);
204
208
  const personName = nonEmpty(opts.person);
205
209
  if (companyName && personName) {
206
- throw new CliError('Use only one of --company/--client or --person to resolve the invoice recipient', ExitCode.USAGE, 'usage');
210
+ throw new CliError('Use only one of --company or --person to resolve the invoice recipient', ExitCode.USAGE, 'usage');
207
211
  }
208
212
  if (personName)
209
213
  return { kind: 'person', name: personName };
@@ -211,14 +215,37 @@ function selectParty(opts) {
211
215
  return { kind: 'company', name: companyName };
212
216
  return undefined;
213
217
  }
214
- async function resolveClient(opts) {
218
+ function selectPartyId(opts) {
219
+ const given = [];
220
+ const companyId = nonEmpty(opts.companyId);
221
+ const personId = nonEmpty(opts.personId);
215
222
  const clientId = nonEmpty(opts.clientId);
223
+ if (companyId)
224
+ given.push({ kind: 'company', id: companyId, flag: '--company-id' });
225
+ if (personId)
226
+ given.push({ kind: 'person', id: personId, flag: '--person-id' });
227
+ if (clientId)
228
+ given.push({ kind: undefined, id: clientId, flag: '--client-id' });
229
+ if (given.length > 1) {
230
+ throw new CliError(`Use only one of --company-id or --person-id (got ${given.map((entry) => entry.flag).join(' and ')})`, ExitCode.USAGE, 'usage');
231
+ }
232
+ return given[0];
233
+ }
234
+ async function resolveClient(opts) {
235
+ const partyId = selectPartyId(opts);
216
236
  const selector = selectParty(opts);
217
- if (clientId) {
218
- return { client_id: clientId, kind: selector?.kind ?? 'company', name: selector?.name ?? null };
237
+ if (partyId) {
238
+ if (partyId.kind && selector && selector.kind !== partyId.kind) {
239
+ throw new CliError(`${partyId.flag} names a ${partyId.kind}; use ${PARTY_ID_FLAG[selector.kind]} for a ${selector.kind}`, ExitCode.USAGE, 'usage');
240
+ }
241
+ return {
242
+ client_id: partyId.id,
243
+ kind: partyId.kind ?? selector?.kind ?? 'company',
244
+ name: selector?.name ?? null,
245
+ };
219
246
  }
220
247
  if (!selector) {
221
- throw new CliError('--client, --company, --person, or --client-id is required', ExitCode.USAGE, 'usage');
248
+ throw new CliError('One of --company, --person, --company-id, or --person-id is required', ExitCode.USAGE, 'usage');
222
249
  }
223
250
  const tool = selector.kind === 'person' ? 'list_people' : 'list_companies';
224
251
  const label = selector.kind;
@@ -232,7 +259,7 @@ async function resolveClient(opts) {
232
259
  if (candidates.length === 0) {
233
260
  throw new CliError(`No ${label} matching "${selector.name}". Run: every tool call ${tool} --json`, ExitCode.NOT_FOUND, 'not_found');
234
261
  }
235
- throw new CliError(partyCandidatesMessage(label, selector.name, candidates), ExitCode.NOT_FOUND, 'not_found', { candidates });
262
+ throw new CliError(partyCandidatesMessage(selector.kind, selector.name, candidates), ExitCode.NOT_FOUND, 'not_found', { candidates });
236
263
  }
237
264
  export async function invoiceListCommand(opts = {}) {
238
265
  const args = {};
@@ -287,11 +314,10 @@ export async function dealMoveCommand(dealId, stage, opts = {}) {
287
314
  assertDealStage(stage);
288
315
  await executeToolCall('move_deal_stage', opts, async () => ({ deal_id: dealId, stage }));
289
316
  }
290
- export async function contactListCommand(opts = {}) {
317
+ export async function personListCommand(opts = {}) {
291
318
  const args = {};
292
319
  if (opts.search !== undefined)
293
320
  args[NETWORK_SEARCH_QUERY_PARAM] = opts.search;
294
321
  addLimit(args, opts.limit);
295
- // list_contacts is retired; list_people is the live People/Companies replacement.
296
322
  await executeToolCall('list_people', opts, async () => args);
297
323
  }
@@ -2,18 +2,20 @@ import { access } from 'node:fs/promises';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { createInterface } from 'node:readline/promises';
5
- import { apiKeysUrlForBaseUrl, environmentNameForBaseUrl, resolveBaseUrl, signupUrlForBaseUrl, } from '../lib/config.js';
5
+ import { apiKeysUrlForBaseUrl, environmentNameForBaseUrl, resolveBaseUrl, } from '../lib/config.js';
6
6
  import { CliError } from '../lib/errors.js';
7
7
  import { ExitCode } from '../lib/exit-codes.js';
8
8
  import { mcpCall } from '../lib/mcp.js';
9
- import { loginFlow, openBrowser as openBrowserDefault } from '../lib/auth/flow.js';
9
+ import { loginFlow } from '../lib/auth/flow.js';
10
10
  import { activeCredentialIsApiKey, isApiKeyToken } from '../lib/auth/api-key.js';
11
11
  import { decodeJwtClaims } from '../lib/auth/jwt.js';
12
12
  import { createTokenStore, deleteTokenFromAllStores, getAuthStatus, getToken, resolveAuthTarget, } from '../lib/auth/tokens.js';
13
13
  import { fetchUserInfo, invalidateUserInfoCache, readCachedUserInfo, requestUserInfo, writeUserInfoCache, } from '../lib/auth/userinfo.js';
14
14
  import { maybeShowSkillHint, readHints, writeHints, } from '../lib/hints.js';
15
15
  import { emit } from '../lib/output.js';
16
+ import { refreshInstalledSkills, skillInstallPaths, } from '../lib/skill-refresh.js';
16
17
  import { installBundledSkill } from './skills.js';
18
+ import { signupCommand } from './signup.js';
17
19
  const WHOAMI_TIMEOUT_MS = 10_000;
18
20
  const SKILL_OFFER_PROMPT = 'Teach your coding agent to use Every? Install the use-every skill: [1] Claude Code [2] Codex [3] Both [Enter=skip]';
19
21
  async function pathExists(filePath) {
@@ -31,21 +33,15 @@ const defaultSkillOfferFileSystem = {
31
33
  writeHints,
32
34
  };
33
35
  function hostPaths(cwd, homeDir) {
36
+ const installed = skillInstallPaths(cwd, homeDir);
34
37
  return {
35
38
  claude: {
36
39
  markers: [path.join(cwd, '.claude'), path.join(homeDir, '.claude')],
37
- installed: [
38
- path.join(cwd, '.claude', 'skills', 'use-every'),
39
- path.join(homeDir, '.claude', 'skills', 'use-every'),
40
- ],
40
+ installed: installed.claude,
41
41
  },
42
42
  codex: {
43
43
  markers: [path.join(cwd, '.agents'), path.join(homeDir, '.codex')],
44
- installed: [
45
- path.join(cwd, '.agents', 'skills', 'use-every'),
46
- path.join(homeDir, '.codex', 'skills', 'use-every'),
47
- path.join(homeDir, '.agents', 'skills', 'use-every'),
48
- ],
44
+ installed: installed.codex,
49
45
  },
50
46
  };
51
47
  }
@@ -263,20 +259,31 @@ function validateBrowserLogin(opts, switching = false) {
263
259
  : 'Workspace switching requires stored credentials; unset EVERY_TOKEN and try again.', ExitCode.USAGE, 'usage');
264
260
  }
265
261
  }
262
+ /** Refresh stale installed skills, then offer an install where none exists. */
263
+ export async function afterBrowserLogin(opts, deps = {}) {
264
+ await refreshInstalledSkills({
265
+ ...deps.skillRefresh,
266
+ errorOutput: deps.errorOutput ?? process.stderr,
267
+ });
268
+ await maybeOfferSkillAfterLogin({ json: opts.json, ...deps, ...deps.skillRefresh });
269
+ }
266
270
  /** Exchange, verify, then commit. A failed assertion never mutates stored auth or identity. */
267
271
  export async function completeBrowserLogin(opts, deps = {}, switching = false) {
268
272
  validateBrowserLogin(opts, switching);
269
273
  const errorOutput = deps.errorOutput ?? process.stderr;
270
274
  const baseUrl = resolveBaseUrl({ staging: opts.staging });
271
275
  const { environmentKey } = resolveAuthTarget({ baseUrl });
272
- errorOutput.write(opts.org === undefined
273
- ? "Pick the workspace in the consent page's selector.\n"
274
- : `In the consent page's selector, pick "${opts.org}".\n`);
276
+ if (!deps.flow) {
277
+ errorOutput.write(opts.org === undefined
278
+ ? "Pick the workspace in the consent page's selector.\n"
279
+ : `In the consent page's selector, pick "${opts.org}".\n`);
280
+ }
275
281
  const tokenSet = await (deps.loginFlow ?? loginFlow)({
276
282
  baseUrl,
277
283
  onAuthorizationUrl(url) {
278
284
  errorOutput.write(`Open this URL to log in:\n${url}\n`);
279
285
  },
286
+ ...deps.flow,
280
287
  });
281
288
  let userinfo;
282
289
  try {
@@ -342,7 +349,7 @@ export async function completeBrowserLogin(opts, deps = {}, switching = false) {
342
349
  export async function runBrowserLogin(opts, deps = {}) {
343
350
  const data = await completeBrowserLogin(opts, deps);
344
351
  emitLogin(data, opts, deps.output, deps.errorOutput);
345
- await maybeOfferSkillAfterLogin({ json: opts.json, ...deps });
352
+ await afterBrowserLogin(opts, deps);
346
353
  }
347
354
  export async function orgSwitchCommand(opts = {}, deps = {}) {
348
355
  validateBrowserLogin(opts, true);
@@ -366,24 +373,6 @@ export async function orgSwitchCommand(opts = {}, deps = {}) {
366
373
  (deps.output ?? process.stdout).write(`Switched to ${formatOrg(data.org_name, data.org_id)} · ${login.email ?? 'unknown'}\n`);
367
374
  await maybeOfferSkillAfterLogin({ json: opts.json, ...deps });
368
375
  }
369
- export async function createAccountFlow(opts = {}) {
370
- validateBrowserLogin(opts);
371
- const input = opts.input ?? process.stdin;
372
- const output = opts.output ?? process.stdout;
373
- const errorOutput = opts.errorOutput ?? process.stderr;
374
- const signupUrl = signupUrlForBaseUrl(resolveBaseUrl({ staging: opts.staging }));
375
- errorOutput.write(`Opening the Every sign-up page:\n ${signupUrl}\nCreate your account and set up your workspace in the browser.\n`);
376
- await (opts.openBrowser ?? openBrowserDefault)(signupUrl);
377
- const rl = createInterface({ input, output: errorOutput, terminal: false });
378
- try {
379
- await rl.question("When you're done, press Enter to connect your terminal... ");
380
- }
381
- finally {
382
- rl.close();
383
- }
384
- const runLogin = opts.runLogin ?? (() => runBrowserLogin(opts, { input, output, errorOutput }));
385
- await runLogin();
386
- }
387
376
  async function promptForLoggedOutAction() {
388
377
  process.stderr.write([
389
378
  "You're not signed in to Every.",
@@ -398,7 +387,7 @@ async function promptForLoggedOutAction() {
398
387
  try {
399
388
  const answer = (await rl.question('Choose [1]: ')).trim();
400
389
  if (answer === '2')
401
- return 'createAccount';
390
+ return 'signup';
402
391
  if (answer !== '' && answer !== '1') {
403
392
  process.stderr.write('Unrecognized choice; continuing with log in.\n');
404
393
  }
@@ -427,17 +416,17 @@ export async function loginCommand(opts = {}) {
427
416
  emitLogin(data, opts);
428
417
  return;
429
418
  }
430
- if (!process.stdout.isTTY) {
431
- throw new CliError('login requires a browser; set EVERY_TOKEN for headless use', ExitCode.AUTH, 'auth');
432
- }
433
419
  if (opts.createAccount) {
434
- // The pause-for-signup prompt reads stdin; a piped/closed stdin would hang there.
435
- if (process.stdin.isTTY !== true) {
436
- throw new CliError('create-account requires an interactive terminal; set EVERY_TOKEN for headless use', ExitCode.AUTH, 'auth');
420
+ // Deprecated alias. Signup needs no TTY, so it runs before the login TTY check.
421
+ if (!opts.json) {
422
+ process.stderr.write('Note: `every login --create-account` is deprecated; use `every signup`.\n');
437
423
  }
438
- await createAccountFlow(opts);
424
+ await signupCommand({ json: opts.json, staging: opts.staging });
439
425
  return;
440
426
  }
427
+ if (!process.stdout.isTTY) {
428
+ throw new CliError('login requires a browser; set EVERY_TOKEN for headless use', ExitCode.AUTH, 'auth');
429
+ }
441
430
  const baseUrl = resolveBaseUrl({ staging: opts.staging });
442
431
  if (!opts.json &&
443
432
  !opts.skipMenu &&
@@ -446,8 +435,8 @@ export async function loginCommand(opts = {}) {
446
435
  process.stderr.isTTY === true &&
447
436
  !(await getAuthStatus({ baseUrl })).logged_in) {
448
437
  const action = await promptForLoggedOutAction();
449
- if (action === 'createAccount') {
450
- await createAccountFlow(opts);
438
+ if (action === 'signup') {
439
+ await signupCommand({ json: opts.json, staging: opts.staging });
451
440
  return;
452
441
  }
453
442
  }
@@ -18,9 +18,16 @@ function commandLine(command, parents) {
18
18
  const parts = [names.join(' '), ...argumentUsage(command), ...optionFlags(command)];
19
19
  return parts.join(' ').replace(/\s+/g, ' ').trim();
20
20
  }
21
+ // Deprecated aliases (e.g. `every contact`) are registered hidden; like hidden
22
+ // options, they stay out of the offline docs so agents learn only current names.
23
+ function isHidden(command) {
24
+ return command._hidden === true;
25
+ }
21
26
  function walkCommands(command, parents = []) {
22
27
  const line = commandLine(command, parents);
23
- const children = command.commands.flatMap((child) => walkCommands(child, [...parents, command.name()]));
28
+ const children = command.commands
29
+ .filter((child) => !isHidden(child))
30
+ .flatMap((child) => walkCommands(child, [...parents, command.name()]));
24
31
  return [line, ...children];
25
32
  }
26
33
  export function commandTree(program) {
@@ -31,6 +38,8 @@ export function conventionsBlock() {
31
38
  'JSON envelope:',
32
39
  ' Success: {"ok":true,"data":...,"env":"production|staging|custom","schema_version":1}',
33
40
  ' Error: {"ok":false,"error":{"message":"...","code":"..."},"env":"production|staging|custom","schema_version":1}',
41
+ ' every signup --json is NDJSON: {"event":"authorization_required","url":...},',
42
+ ' {"event":"waiting_for_authorization","browser_opened":...}, then the envelope as the last line.',
34
43
  '',
35
44
  'Exit codes:',
36
45
  ' 0 ok',
@@ -39,7 +48,7 @@ export function conventionsBlock() {
39
48
  ' 3 auth',
40
49
  ' 4 permission/confirmation needed',
41
50
  ' 5 rate limited',
42
- ' 6 not found',
51
+ ' 6 not found (code signup_unsupported: the server has no agent signup yet)',
43
52
  ' 7 network/timeout',
44
53
  '',
45
54
  'Safety tiers:',
@@ -55,7 +64,7 @@ export function conventionsBlock() {
55
64
  ' every tool call <name> --args file.json',
56
65
  '',
57
66
  'Environment:',
58
- ' EVERY_TOKEN skips browser login for headless use.',
67
+ ' EVERY_TOKEN skips browser login for headless use; it never creates an account (use every signup).',
59
68
  ' Target precedence: --staging > EVERY_MCP_URL > EVERY_ENV=staging|production > production.',
60
69
  ].join('\n');
61
70
  }
@@ -0,0 +1,239 @@
1
+ import { resolveBaseUrl } from '../lib/config.js';
2
+ import { CliError } from '../lib/errors.js';
3
+ import { ExitCode } from '../lib/exit-codes.js';
4
+ import { formatSuccess } from '../lib/output.js';
5
+ import { invalidateUserInfoCache } from '../lib/auth/userinfo.js';
6
+ import { afterBrowserLogin, completeBrowserLogin } from './auth.js';
7
+ import { invokeToolCall } from './tools.js';
8
+ export const SIGNUP_STATUS_TOOL = 'get_signup_status';
9
+ export const SIGNUP_COMPLETE_TOOL = 'complete_signup';
10
+ export const SIGNUP_UNSUPPORTED_MESSAGE = 'this server does not support agent signup yet';
11
+ export const DEFAULT_SIGNUP_TIMEOUT_SECONDS = 300;
12
+ const MAX_ORG_NAME_LENGTH = 256;
13
+ const MAX_PUBLIC_LINKS = 10;
14
+ const signupHooks = {
15
+ missingTool: () => new CliError(`${SIGNUP_UNSUPPORTED_MESSAGE}. Finish setting up your account in the Every web app.`, ExitCode.NOT_FOUND, 'signup_unsupported'),
16
+ };
17
+ function parseTimeoutSeconds(value) {
18
+ if (value === undefined)
19
+ return DEFAULT_SIGNUP_TIMEOUT_SECONDS;
20
+ const seconds = Number(value);
21
+ if (!Number.isFinite(seconds) || seconds <= 0) {
22
+ throw new CliError('--timeout must be a positive number of seconds', ExitCode.USAGE, 'usage');
23
+ }
24
+ return seconds;
25
+ }
26
+ function writeLine(output, value) {
27
+ output.write(`${typeof value === 'string' ? value : JSON.stringify(value)}\n`);
28
+ }
29
+ function emitEnvelope(output, envelope, opts) {
30
+ writeLine(output, opts.json
31
+ ? formatSuccess(envelope, { json: true, staging: opts.staging })
32
+ : signupHuman(envelope));
33
+ }
34
+ /** The tool's structured result is the envelope; tolerate a server that only sends it as JSON text. */
35
+ function envelopeFrom(data) {
36
+ const structured = data.structured_content;
37
+ if (structured && typeof structured === 'object' && !Array.isArray(structured)) {
38
+ return structured;
39
+ }
40
+ const text = Array.isArray(data.content)
41
+ ? data.content
42
+ .map((block) => (block && typeof block === 'object' ? block.text : undefined))
43
+ .filter((value) => typeof value === 'string')
44
+ .join('')
45
+ : '';
46
+ try {
47
+ const parsed = JSON.parse(text);
48
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
49
+ return parsed;
50
+ }
51
+ catch {
52
+ // Fall through to the error below.
53
+ }
54
+ throw new CliError(`${data.tool} returned no signup status`, ExitCode.GENERIC, 'generic');
55
+ }
56
+ function quoted(value) {
57
+ return `"${value.replaceAll('"', '\\"')}"`;
58
+ }
59
+ function suggestionLine(label, suggestion) {
60
+ if (!suggestion?.value)
61
+ return undefined;
62
+ const provenance = [suggestion.source, suggestion.confidence].filter(Boolean).join(', ');
63
+ return ` ${label}: ${suggestion.value}${provenance ? ` (${provenance})` : ''}`;
64
+ }
65
+ export function signupHuman(envelope) {
66
+ const lines = [];
67
+ const orgName = envelope.organization?.name ?? envelope.current_profile?.organization_name ?? null;
68
+ const orgId = envelope.organization?.org_id ?? null;
69
+ const workspace = orgName ? `${orgName}${orgId ? ` (${orgId})` : ''}` : orgId;
70
+ if (envelope.account_ready) {
71
+ lines.push(`Account ready${workspace ? ` · workspace ${workspace}` : ''}.`);
72
+ }
73
+ else {
74
+ lines.push(`Signup is not finished${workspace ? ` · workspace ${workspace}` : ''}.`);
75
+ }
76
+ if (envelope.user?.email)
77
+ lines.push(`Signed in as ${envelope.user.email}`);
78
+ if (envelope.saved_fields?.length)
79
+ lines.push(`Saved: ${envelope.saved_fields.join(', ')}`);
80
+ if (!envelope.account_ready) {
81
+ const required = envelope.required_fields?.length ? envelope.required_fields : ['organization_name'];
82
+ lines.push(`Required: ${required.join(', ')}`);
83
+ const suggestions = envelope.profile_suggestions;
84
+ if (suggestions?.status === 'ready') {
85
+ lines.push('Suggestions (unverified candidates from the mailbox and public web; confirm with the user):');
86
+ const linkLines = (suggestions.public_links ?? [])
87
+ .filter((link) => link?.url)
88
+ .map((link) => {
89
+ const provenance = [link.source, link.confidence].filter(Boolean).join(', ');
90
+ return ` link: ${link.url}${provenance ? ` (${provenance})` : ''}`;
91
+ });
92
+ lines.push(...[
93
+ suggestionLine('name', suggestions.organization_name),
94
+ suggestionLine('description', suggestions.description),
95
+ ...linkLines,
96
+ ].filter((line) => Boolean(line)));
97
+ }
98
+ else if (suggestions?.status) {
99
+ lines.push(`Suggestions: ${suggestions.status}${suggestions.reason ? ` (${suggestions.reason})` : ''}`);
100
+ }
101
+ const nameHint = suggestions?.organization_name?.value ?? '<name>';
102
+ lines.push(`Finish: every signup complete --org-name ${quoted(nameHint)} [--description "<text>"] [--link <url>] --yes`);
103
+ }
104
+ const background = envelope.background_setup;
105
+ if (background?.state) {
106
+ const dna = background.business_dna ? `, business DNA ${background.business_dna}` : '';
107
+ lines.push(`Background setup: ${background.state}${dna} (does not affect account readiness)`);
108
+ if (background.improve_with?.length) {
109
+ lines.push(` Improve it by adding: ${background.improve_with.join(', ')}`);
110
+ }
111
+ }
112
+ if (envelope.optional_setup_url)
113
+ lines.push(`Optional browser setup: ${envelope.optional_setup_url}`);
114
+ return lines.join('\n');
115
+ }
116
+ function resumeHint(err, timeoutSeconds) {
117
+ if (!(err instanceof CliError) || err.code !== 'auth')
118
+ return err;
119
+ const timedOut = err.details?.reason === 'timeout';
120
+ const message = timedOut
121
+ ? `Signup timed out after ${timeoutSeconds}s waiting for the browser authorization. ` +
122
+ 'Run `every signup` again to get a new link (add --timeout <seconds> for more time).'
123
+ : `${err.message}. Run \`every signup\` again to retry.`;
124
+ return new CliError(message, err.exitCode, err.code, err.details);
125
+ }
126
+ async function fetchSignupStatus(opts) {
127
+ const data = await invokeToolCall(SIGNUP_STATUS_TOOL, { staging: opts.staging, noCache: true }, async () => ({}), signupHooks);
128
+ return envelopeFrom(data);
129
+ }
130
+ async function forgetCachedIdentity(staging) {
131
+ // A new or renamed workspace makes the cached userinfo org name wrong.
132
+ await invalidateUserInfoCache(resolveBaseUrl({ staging })).catch(() => undefined);
133
+ }
134
+ /**
135
+ * `every signup`: one browser authorization, then the server's signup status.
136
+ *
137
+ * Built for coding agents, which run commands without a TTY: it never waits for
138
+ * Enter and never opens the web sign-up page. The authorization URL is printed
139
+ * before the browser is tried (in --json mode as the first NDJSON line), so an
140
+ * agent can hand it to the user when no browser opens. The last line is the
141
+ * normal envelope.
142
+ */
143
+ export async function signupCommand(opts = {}, deps = {}) {
144
+ if (process.env.EVERY_TOKEN) {
145
+ throw new CliError('EVERY_TOKEN is set. It is an automation override and never a signup path; ' +
146
+ 'unset EVERY_TOKEN, then run `every signup`.', ExitCode.USAGE, 'usage');
147
+ }
148
+ const timeoutSeconds = parseTimeoutSeconds(opts.timeout);
149
+ const output = deps.output ?? process.stdout;
150
+ const errorOutput = deps.errorOutput ?? process.stderr;
151
+ try {
152
+ await completeBrowserLogin({ json: opts.json, staging: opts.staging }, {
153
+ ...deps,
154
+ flow: {
155
+ timeoutMs: timeoutSeconds * 1000,
156
+ onAuthorizationUrl(url) {
157
+ if (opts.json)
158
+ writeLine(output, { event: 'authorization_required', url });
159
+ else
160
+ writeLine(errorOutput, `Authorize Every in your browser: ${url}`);
161
+ },
162
+ onBrowserOpened(opened) {
163
+ if (opts.json) {
164
+ writeLine(output, {
165
+ event: 'waiting_for_authorization',
166
+ browser_opened: opened,
167
+ timeout_seconds: timeoutSeconds,
168
+ });
169
+ return;
170
+ }
171
+ if (!opened)
172
+ writeLine(errorOutput, 'Could not open a browser. Open the URL above to continue.');
173
+ writeLine(errorOutput, `Waiting up to ${timeoutSeconds}s for the browser step to finish...`);
174
+ },
175
+ },
176
+ });
177
+ }
178
+ catch (err) {
179
+ throw resumeHint(err, timeoutSeconds);
180
+ }
181
+ const envelope = await fetchSignupStatus(opts);
182
+ await forgetCachedIdentity(opts.staging);
183
+ emitEnvelope(output, envelope, opts);
184
+ await afterBrowserLogin({ json: opts.json }, deps);
185
+ }
186
+ /** `every signup status`: the current signup envelope for the stored login. */
187
+ export async function signupStatusCommand(opts = {}) {
188
+ const envelope = await fetchSignupStatus(opts);
189
+ emitEnvelope(process.stdout, envelope, opts);
190
+ }
191
+ function normalizeLinks(links) {
192
+ const normalized = links.map((link) => link.trim()).filter(Boolean);
193
+ if (normalized.length > MAX_PUBLIC_LINKS) {
194
+ throw new CliError(`--link accepts at most ${MAX_PUBLIC_LINKS} links`, ExitCode.USAGE, 'usage');
195
+ }
196
+ for (const link of normalized) {
197
+ let url;
198
+ try {
199
+ url = new URL(link);
200
+ }
201
+ catch {
202
+ url = undefined;
203
+ }
204
+ if (url?.protocol !== 'https:') {
205
+ throw new CliError(`--link must be an https URL: ${link}`, ExitCode.USAGE, 'usage');
206
+ }
207
+ }
208
+ return Array.from(new Set(normalized));
209
+ }
210
+ export function completeSignupArgs(opts) {
211
+ const name = opts.orgName?.trim() ?? '';
212
+ if (!name) {
213
+ throw new CliError('--org-name is required and must not be blank', ExitCode.USAGE, 'usage');
214
+ }
215
+ if (name.length > MAX_ORG_NAME_LENGTH) {
216
+ throw new CliError(`--org-name must be at most ${MAX_ORG_NAME_LENGTH} characters`, ExitCode.USAGE, 'usage');
217
+ }
218
+ const args = { organization_name: name };
219
+ const description = opts.description?.trim();
220
+ if (description)
221
+ args.description = description;
222
+ const links = normalizeLinks(opts.link ?? []);
223
+ if (links.length)
224
+ args.public_links = links;
225
+ return args;
226
+ }
227
+ /**
228
+ * `every signup complete`: commit the profile the user confirmed. It is an
229
+ * ordinary write, so it needs --yes when non-interactive and never
230
+ * --allow-destructive; the server's text confirmation is retried once by the
231
+ * shared executor.
232
+ */
233
+ export async function signupCompleteCommand(opts = {}) {
234
+ const args = completeSignupArgs(opts);
235
+ const data = await invokeToolCall(SIGNUP_COMPLETE_TOOL, { json: opts.json, staging: opts.staging, noCache: true, yes: opts.yes, readOnly: opts.readOnly }, async () => args, signupHooks);
236
+ const envelope = envelopeFrom(data);
237
+ await forgetCachedIdentity(opts.staging);
238
+ emitEnvelope(process.stdout, envelope, opts);
239
+ }