@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.
package/README.md CHANGED
@@ -1,16 +1,41 @@
1
1
  # @everyai/cli
2
2
 
3
- The **agent-agnostic** command line for [Every AI](https://every.ai) — manage your business (invoices, clients, contacts, proposals, deals) from any shell, any coding agent, or CI.
3
+ The **agent-agnostic** command line for [Every AI](https://every.ai) — manage invoices, clients, contacts, proposals, deals, and pipeline work from any shell, coding agent, or CI job.
4
4
 
5
- Install once, log in once, and the same `every` command works everywhere your agents run — Claude Code, Codex, Cursor, plain terminals, cron, CI — instead of wiring a bespoke MCP + OAuth setup into each host.
5
+ Install once, log in once, and teach each coding agent the same `every` command instead of wiring MCP + OAuth separately into every host.
6
6
 
7
7
  ```bash
8
8
  npm install -g @everyai/cli
9
- every login # opens your browser (OAuth + PKCE); tokens land in your OS keychain
10
- every whoami --json # authenticated check: who you are + how many tools you have
11
- every tools list # the full tool surface, with safety classifications
9
+ every docs # offline command tree, output contract, workflows
10
+ every login # opens your browser; tokens land in your OS keychain
11
+ every skills install claude|codex # teach Claude Code or Codex how to use Every
12
+ every whoami # user, org, environment, tool-count check
12
13
  ```
13
14
 
15
+ One-shot invoice example with inline args:
16
+
17
+ ```bash
18
+ every invoice list --status overdue --json
19
+ every tool call create_invoice \
20
+ --arg client_id=client_123 \
21
+ --arg line_items='[{"description":"Strategy work","quantity":1,"unit_price":1500}]' \
22
+ --yes \
23
+ --json
24
+ ```
25
+
26
+ ## Install as an agent plugin
27
+
28
+ The npm install remains the primary path. Agent plugins distribute the bundled `use-every` skill, which teaches the agent how to install and use the CLI.
29
+
30
+ In Claude Code:
31
+
32
+ ```text
33
+ /plugin marketplace add Every-AI-Inc/everyai-cli
34
+ /plugin install every@everyai-cli
35
+ ```
36
+
37
+ Codex's repo-scoped marketplace location is `.agents/plugins/marketplace.json`.
38
+
14
39
  ## Why a CLI (vs. adding the MCP server to each host)
15
40
 
16
41
  The CLI talks to the same Every MCP server (`admin-mcp.every.ai`) and inherits its full tool surface automatically — new tools appear with no CLI upgrade. What the CLI adds:
@@ -27,7 +52,8 @@ every login [--staging] # browser OAuth; keychain storage; refresh handle
27
52
  every logout | whoami | auth status | org
28
53
 
29
54
  # Discovery
30
- every tools list [--no-cache]
55
+ every docs
56
+ every tools list [--filter <substr>] [--no-cache]
31
57
  every tools describe <name>
32
58
  every policy explain <name> # classification + exactly what running it requires
33
59
 
@@ -51,8 +77,8 @@ every skills install codex # → .agents/skills/use-every/
51
77
  Every command supports `--json`: exactly one JSON document on stdout, nothing else.
52
78
 
53
79
  ```jsonc
54
- { "ok": true, "data": { /* ... */ }, "schema_version": 1 }
55
- { "ok": false, "error": { "message": "...", "code": "..." }, "schema_version": 1 }
80
+ { "ok": true, "data": { /* ... */ }, "env": "production", "schema_version": 1 }
81
+ { "ok": false, "error": { "message": "...", "code": "..." }, "env": "production", "schema_version": 1 }
56
82
  ```
57
83
 
58
84
  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.
@@ -61,6 +87,8 @@ Exit codes: `0` ok · `1` tool/generic error · `2` usage · `3` auth (run `ever
61
87
 
62
88
  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.
63
89
 
90
+ Target precedence: `--staging` > `EVERY_MCP_URL` > `EVERY_ENV=staging|production` > production.
91
+
64
92
  ## Status
65
93
 
66
94
  Pre-release. Built against Every's production MCP surface; `--staging` targets Every's internal staging environment.
@@ -1,9 +1,15 @@
1
1
  import { CliError } from '../lib/errors.js';
2
2
  import { ExitCode } from '../lib/exit-codes.js';
3
- import { executeToolCall } from './tools.js';
3
+ import { executeToolCall, invokeToolCall, } from './tools.js';
4
4
  const INVOICE_STATUSES = new Set(['draft', 'issued', 'void']);
5
5
  const PAYMENT_STATUSES = new Set(['unpaid', 'paid', 'overdue', 'partial']);
6
6
  const DEAL_STAGES = new Set(['lead', 'opportunity', 'won', 'lost']);
7
+ const LIST_CLIENTS_NAME_PARAM = 'name';
8
+ const CREATE_INVOICE_CLIENT_ID_PARAM = 'client_id';
9
+ const CREATE_INVOICE_LINE_ITEMS_PARAM = 'line_items';
10
+ const LINE_ITEM_DESCRIPTION_PARAM = 'description';
11
+ const LINE_ITEM_QUANTITY_PARAM = 'quantity';
12
+ const LINE_ITEM_UNIT_PRICE_PARAM = 'unit_price';
7
13
  function parseLimit(value) {
8
14
  if (value === undefined)
9
15
  return undefined;
@@ -39,6 +45,158 @@ function addInvoiceStatus(args, value) {
39
45
  ...Array.from(PAYMENT_STATUSES),
40
46
  ].join(', ')}`, ExitCode.USAGE, 'usage');
41
47
  }
48
+ function parsePositiveNumber(value, flag) {
49
+ if (value === undefined || value.trim() === '') {
50
+ throw new CliError(`${flag} is required`, ExitCode.USAGE, 'usage');
51
+ }
52
+ const parsed = Number(value);
53
+ if (!Number.isFinite(parsed) || parsed <= 0) {
54
+ throw new CliError(`${flag} must be a positive number`, ExitCode.USAGE, 'usage');
55
+ }
56
+ return parsed;
57
+ }
58
+ function nonEmpty(value) {
59
+ const trimmed = value?.trim();
60
+ return trimmed ? trimmed : undefined;
61
+ }
62
+ function stringField(record, keys) {
63
+ for (const key of keys) {
64
+ const value = record[key];
65
+ if (typeof value === 'string' && value.trim())
66
+ return value.trim();
67
+ }
68
+ return undefined;
69
+ }
70
+ function stripMarkdown(value) {
71
+ return value
72
+ .replace(/\*\*/g, '')
73
+ .replace(/__/g, '')
74
+ .replace(/`/g, '')
75
+ .replace(/\[(.*?)\]\([^)]*\)/g, '$1');
76
+ }
77
+ function cleanClientNameFromLine(value) {
78
+ let name = stripMarkdown(value)
79
+ .replace(/^\s*(?:[-*+]|\d+[.)])\s*/, '')
80
+ .replace(/^client(?:\s+name)?:\s*/i, '')
81
+ // Drop a trailing status parenthetical like "(active)" / "(archived)".
82
+ .replace(/\s*\((?:active|inactive|archived)\)\s*$/i, '')
83
+ .trim();
84
+ if (name.includes('|')) {
85
+ const cells = name.split('|').map((cell) => cell.trim()).filter(Boolean);
86
+ name = cells.find((cell) => !/^id$/i.test(cell) && !/@/.test(cell)) ?? cells[0] ?? '';
87
+ }
88
+ name = name
89
+ .replace(/\s+[–—]\s+.*$/, '')
90
+ .replace(/\s+-\s+.*$/, '')
91
+ .replace(/\s+<[^>]+>\s*$/, '')
92
+ .replace(/\s+\([^)]*@[^)]*\)\s*$/, '')
93
+ .trim();
94
+ return name || undefined;
95
+ }
96
+ function parseClientCandidatesFromText(text) {
97
+ const candidates = [];
98
+ for (const line of text.split(/\r?\n/)) {
99
+ const match = line.match(/\[id:\s*([^\]\s]+)\s*\]/i);
100
+ if (!match?.[1])
101
+ continue;
102
+ const name = cleanClientNameFromLine(line.slice(0, match.index));
103
+ if (!name)
104
+ continue;
105
+ candidates.push({ client_id: match[1], name });
106
+ }
107
+ return candidates;
108
+ }
109
+ function candidateFromObject(value) {
110
+ const clientId = stringField(value, ['client_id', 'clientId', 'id']);
111
+ const name = stringField(value, ['name', 'client_name', 'clientName']);
112
+ if (!clientId || !name)
113
+ return undefined;
114
+ return { client_id: clientId, name };
115
+ }
116
+ function collectStructuredCandidates(value, seen = new Set()) {
117
+ if (!value || typeof value !== 'object')
118
+ return [];
119
+ if (seen.has(value))
120
+ return [];
121
+ seen.add(value);
122
+ if (Array.isArray(value)) {
123
+ return value.flatMap((entry) => collectStructuredCandidates(entry, seen));
124
+ }
125
+ const record = value;
126
+ const direct = candidateFromObject(record);
127
+ const nested = Object.values(record).flatMap((entry) => collectStructuredCandidates(entry, seen));
128
+ return direct ? [direct, ...nested] : nested;
129
+ }
130
+ function textFromContent(content) {
131
+ if (typeof content === 'string')
132
+ return content;
133
+ if (!Array.isArray(content))
134
+ return '';
135
+ return content
136
+ .map((block) => {
137
+ if (!block || typeof block !== 'object')
138
+ return undefined;
139
+ const candidate = block;
140
+ return candidate.type === 'text' && typeof candidate.text === 'string'
141
+ ? candidate.text
142
+ : undefined;
143
+ })
144
+ .filter((text) => text !== undefined)
145
+ .join('\n');
146
+ }
147
+ function textFromStructuredContent(value) {
148
+ if (typeof value === 'string')
149
+ return value;
150
+ if (!value || typeof value !== 'object')
151
+ return '';
152
+ const result = value.result;
153
+ return typeof result === 'string' ? result : '';
154
+ }
155
+ function dedupeCandidates(candidates) {
156
+ const seen = new Set();
157
+ const deduped = [];
158
+ for (const candidate of candidates) {
159
+ const key = `${candidate.client_id}\0${candidate.name}`;
160
+ if (seen.has(key))
161
+ continue;
162
+ seen.add(key);
163
+ deduped.push(candidate);
164
+ }
165
+ return deduped;
166
+ }
167
+ export function parseClientCandidates(result) {
168
+ return dedupeCandidates([
169
+ ...collectStructuredCandidates(result.structured_content),
170
+ ...parseClientCandidatesFromText(textFromStructuredContent(result.structured_content)),
171
+ ...parseClientCandidatesFromText(textFromContent(result.content)),
172
+ ]);
173
+ }
174
+ function clientCandidatesMessage(query, candidates) {
175
+ return [
176
+ `Multiple clients matching "${query}".`,
177
+ ...candidates.map((candidate) => `${candidate.client_id} ${candidate.name}`),
178
+ 'Re-run with --client-id <id>',
179
+ ].join('\n');
180
+ }
181
+ async function resolveClient(opts) {
182
+ const clientId = nonEmpty(opts.clientId);
183
+ const clientName = nonEmpty(opts.client);
184
+ if (clientId)
185
+ return { client_id: clientId, name: clientName ?? null };
186
+ if (!clientName) {
187
+ throw new CliError('--client or --client-id is required', ExitCode.USAGE, 'usage');
188
+ }
189
+ const result = await invokeToolCall('list_clients', opts, async () => ({
190
+ [LIST_CLIENTS_NAME_PARAM]: clientName,
191
+ }));
192
+ const candidates = parseClientCandidates(result);
193
+ if (candidates.length === 1)
194
+ return candidates[0];
195
+ if (candidates.length === 0) {
196
+ throw new CliError(`No client matching "${clientName}". Run: every tool call list_clients --json`, ExitCode.NOT_FOUND, 'not_found');
197
+ }
198
+ throw new CliError(clientCandidatesMessage(clientName, candidates), ExitCode.NOT_FOUND, 'not_found', { candidates });
199
+ }
42
200
  export async function invoiceListCommand(opts = {}) {
43
201
  const args = {};
44
202
  addInvoiceStatus(args, opts.status);
@@ -50,6 +208,24 @@ export async function invoiceListCommand(opts = {}) {
50
208
  export async function invoiceSendCommand(invoiceId, opts = {}) {
51
209
  await executeToolCall('send_invoice', opts, async () => ({ invoice_id: invoiceId }));
52
210
  }
211
+ export async function invoiceCreateCommand(opts = {}) {
212
+ const amount = parsePositiveNumber(opts.amount, '--amount');
213
+ const quantity = opts.quantity === undefined
214
+ ? 1
215
+ : parsePositiveNumber(opts.quantity, '--quantity');
216
+ const resolvedClient = await resolveClient(opts);
217
+ const args = {
218
+ [CREATE_INVOICE_CLIENT_ID_PARAM]: resolvedClient.client_id,
219
+ [CREATE_INVOICE_LINE_ITEMS_PARAM]: [
220
+ {
221
+ [LINE_ITEM_DESCRIPTION_PARAM]: opts.description ?? 'Services',
222
+ [LINE_ITEM_QUANTITY_PARAM]: quantity,
223
+ [LINE_ITEM_UNIT_PRICE_PARAM]: amount,
224
+ },
225
+ ],
226
+ };
227
+ await executeToolCall('create_invoice', opts, async () => args, (data) => ({ ...data, resolved_client: resolvedClient }));
228
+ }
53
229
  export async function dealListCommand(opts = {}) {
54
230
  const args = {};
55
231
  if (opts.stage !== undefined) {
@@ -1,15 +1,124 @@
1
- import { resolveBaseUrl } from '../lib/config.js';
1
+ import { access } from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { environmentNameForBaseUrl, resolveBaseUrl } from '../lib/config.js';
2
6
  import { CliError } from '../lib/errors.js';
3
7
  import { ExitCode } from '../lib/exit-codes.js';
4
8
  import { mcpCall } from '../lib/mcp.js';
5
9
  import { loginFlow } from '../lib/auth/flow.js';
6
10
  import { decodeJwtClaims } from '../lib/auth/jwt.js';
7
11
  import { createTokenStore, deleteTokenFromAllStores, getAuthStatus, getToken, resolveAuthTarget, } from '../lib/auth/tokens.js';
12
+ import { fetchUserInfo } from '../lib/auth/userinfo.js';
13
+ import { maybeShowSkillHint, readHints, writeHints, } from '../lib/hints.js';
8
14
  import { emit } from '../lib/output.js';
15
+ import { installBundledSkill } from './skills.js';
9
16
  const WHOAMI_TIMEOUT_MS = 10_000;
17
+ 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]';
18
+ async function pathExists(filePath) {
19
+ try {
20
+ await access(filePath);
21
+ return true;
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ const defaultSkillOfferFileSystem = {
28
+ pathExists,
29
+ readHints,
30
+ writeHints,
31
+ };
32
+ function hostPaths(cwd, homeDir) {
33
+ return {
34
+ claude: {
35
+ markers: [path.join(cwd, '.claude'), path.join(homeDir, '.claude')],
36
+ installed: [
37
+ path.join(cwd, '.claude', 'skills', 'use-every'),
38
+ path.join(homeDir, '.claude', 'skills', 'use-every'),
39
+ ],
40
+ },
41
+ codex: {
42
+ markers: [path.join(cwd, '.agents'), path.join(homeDir, '.codex')],
43
+ installed: [
44
+ path.join(cwd, '.agents', 'skills', 'use-every'),
45
+ path.join(homeDir, '.codex', 'skills', 'use-every'),
46
+ path.join(homeDir, '.agents', 'skills', 'use-every'),
47
+ ],
48
+ },
49
+ };
50
+ }
51
+ async function anyPathExists(fileSystem, paths) {
52
+ const matches = await Promise.all(paths.map((filePath) => fileSystem.pathExists(filePath)));
53
+ return matches.some(Boolean);
54
+ }
55
+ function targetsForAnswer(answer) {
56
+ if (answer === '1')
57
+ return ['claude'];
58
+ if (answer === '2')
59
+ return ['codex'];
60
+ if (answer === '3')
61
+ return ['claude', 'codex'];
62
+ return [];
63
+ }
64
+ function targetLabel(target) {
65
+ return target === 'claude' ? 'Claude Code' : 'Codex';
66
+ }
67
+ /** Best-effort interactive offer shown only after a browser login succeeds. */
68
+ export async function maybeOfferSkillAfterLogin(opts = {}) {
69
+ const input = opts.input ?? process.stdin;
70
+ const output = opts.output ?? process.stdout;
71
+ const errorOutput = opts.errorOutput ?? process.stderr;
72
+ if (opts.json ||
73
+ input.isTTY !== true ||
74
+ output.isTTY !== true ||
75
+ (opts.errorOutput === undefined && process.stderr.isTTY !== true))
76
+ return;
77
+ try {
78
+ const fileSystem = opts.fileSystem ?? defaultSkillOfferFileSystem;
79
+ const hints = await fileSystem.readHints();
80
+ if (hints.skill_offer_declined)
81
+ return;
82
+ const cwd = opts.cwd ?? process.cwd();
83
+ const paths = hostPaths(cwd, opts.homeDir ?? os.homedir());
84
+ const [claudeDetected, claudeInstalled, codexDetected, codexInstalled] = await Promise.all([
85
+ anyPathExists(fileSystem, paths.claude.markers),
86
+ anyPathExists(fileSystem, paths.claude.installed),
87
+ anyPathExists(fileSystem, paths.codex.markers),
88
+ anyPathExists(fileSystem, paths.codex.installed),
89
+ ]);
90
+ if (!(claudeDetected && !claudeInstalled) && !(codexDetected && !codexInstalled))
91
+ return;
92
+ const rl = createInterface({ input, output: errorOutput, terminal: false });
93
+ let answer;
94
+ try {
95
+ answer = (await rl.question(`${SKILL_OFFER_PROMPT}\n`)).trim();
96
+ }
97
+ finally {
98
+ rl.close();
99
+ }
100
+ if (answer === '') {
101
+ await fileSystem.writeHints({ ...hints, skill_offer_declined: true });
102
+ return;
103
+ }
104
+ const installSkill = opts.installSkill ?? ((target) => {
105
+ const installRoot = target === 'claude'
106
+ ? path.join(cwd, '.claude', 'skills')
107
+ : path.join(cwd, '.agents', 'skills');
108
+ return installBundledSkill(target, { dir: installRoot });
109
+ });
110
+ for (const target of targetsForAnswer(answer)) {
111
+ const installed = await installSkill(target);
112
+ output.write(`Installed use-every for ${targetLabel(target)} to ${installed.installed_to} — commit it to share with your team.\n`);
113
+ }
114
+ }
115
+ catch {
116
+ // An optional offer must never turn a successful login into a failure.
117
+ }
118
+ }
10
119
  function emitCommand(data, human, opts) {
11
120
  if (opts.json)
12
- emit(data, { json: true });
121
+ emit(data, { json: true, staging: opts.staging });
13
122
  else
14
123
  process.stdout.write(`${human}\n`);
15
124
  }
@@ -26,6 +135,24 @@ function loginHuman(data) {
26
135
  const identity = data.email ?? data.subject;
27
136
  return identity ? `Logged in as ${identity}` : 'Logged in';
28
137
  }
138
+ function loginNextSteps() {
139
+ return [
140
+ 'Next steps:',
141
+ ' every whoami',
142
+ ' every tools list',
143
+ ' every skills install claude|codex',
144
+ ].join('\n');
145
+ }
146
+ function emitLogin(data, opts) {
147
+ const human = `${loginHuman(data)}\n${loginNextSteps()}`;
148
+ if (opts.json) {
149
+ emit(data, { json: true, staging: opts.staging });
150
+ process.stderr.write(`${loginNextSteps()}\n`);
151
+ }
152
+ else {
153
+ process.stdout.write(`${human}\n`);
154
+ }
155
+ }
29
156
  function statusHuman(status) {
30
157
  return [
31
158
  `Logged in: ${status.logged_in ? 'yes' : 'no'}`,
@@ -38,29 +165,34 @@ function statusHuman(status) {
38
165
  `Refresh token: ${status.refresh_token ? 'yes' : 'no'}`,
39
166
  ].join('\n');
40
167
  }
41
- function orgFromClaims(claims) {
168
+ function orgFromUserInfo(userinfo) {
42
169
  return {
43
- org_id: typeof claims?.org_id === 'string' ? claims.org_id : null,
44
- org_slug: typeof claims?.org_slug === 'string' ? claims.org_slug : null,
45
- org_name: typeof claims?.org_name === 'string' ? claims.org_name : null,
46
- organization_id: typeof claims?.organization_id === 'string' ? claims.organization_id : null,
47
- organization_slug: typeof claims?.organization_slug === 'string' ? claims.organization_slug : null,
48
- organization_name: typeof claims?.organization_name === 'string' ? claims.organization_name : null,
170
+ org_id: userinfo.org_id,
171
+ org_slug: userinfo.org_slug,
172
+ org_name: userinfo.org_name,
173
+ organization_id: userinfo.org_id,
174
+ organization_slug: userinfo.org_slug,
175
+ organization_name: userinfo.org_name,
49
176
  };
50
177
  }
51
178
  function orgHuman(org) {
52
179
  const lines = [
53
- `org_id: ${org.org_id ?? 'none'}`,
54
- `org_slug: ${org.org_slug ?? 'none'}`,
55
- `org_name: ${org.org_name ?? 'none'}`,
180
+ `Org: ${formatOrg(org.org_name, org.org_id)}`,
181
+ `Slug: ${org.org_slug ?? 'none'}`,
182
+ 'Note: the server scopes writes to this org.',
56
183
  ];
57
- if (org.organization_id || org.organization_slug || org.organization_name) {
58
- lines.push(`organization_id: ${org.organization_id ?? 'none'}`);
59
- lines.push(`organization_slug: ${org.organization_slug ?? 'none'}`);
60
- lines.push(`organization_name: ${org.organization_name ?? 'none'}`);
61
- }
62
184
  return lines.join('\n');
63
185
  }
186
+ function formatUser(userinfo) {
187
+ if (userinfo.name && userinfo.email)
188
+ return `${userinfo.name} (${userinfo.email})`;
189
+ return userinfo.name ?? userinfo.email ?? userinfo.user_id ?? 'unknown';
190
+ }
191
+ function formatOrg(orgName, orgId) {
192
+ if (orgName && orgId)
193
+ return `${orgName} (${orgId})`;
194
+ return orgName ?? orgId ?? 'none';
195
+ }
64
196
  async function verifyMcpLiveness(baseUrl, token) {
65
197
  const body = await mcpCall(baseUrl, token, 'tools/list', {}, { timeoutMs: WHOAMI_TIMEOUT_MS });
66
198
  return {
@@ -79,7 +211,7 @@ export async function loginCommand(opts = {}) {
79
211
  storage_backend: null,
80
212
  every_token: true,
81
213
  };
82
- emitCommand(data, loginHuman(data), opts);
214
+ emitLogin(data, opts);
83
215
  return;
84
216
  }
85
217
  if (!process.stdout.isTTY) {
@@ -104,7 +236,8 @@ export async function loginCommand(opts = {}) {
104
236
  storage_backend: store.backend,
105
237
  every_token: false,
106
238
  };
107
- emitCommand(data, loginHuman(data), opts);
239
+ emitLogin(data, opts);
240
+ await maybeOfferSkillAfterLogin({ json: opts.json });
108
241
  }
109
242
  export async function logoutCommand(opts = {}) {
110
243
  const { environmentKey } = resolveAuthTarget({ staging: opts.staging });
@@ -121,30 +254,34 @@ export async function authStatusCommand(opts = {}) {
121
254
  }
122
255
  export async function whoamiCommand(opts = {}) {
123
256
  const baseUrl = resolveBaseUrl({ staging: opts.staging });
257
+ const userinfo = await fetchUserInfo({ baseUrl });
124
258
  const token = await getToken({ baseUrl });
125
- const claims = decodeJwtClaims(token);
126
259
  const liveness = await verifyMcpLiveness(baseUrl, token);
260
+ const environment = environmentNameForBaseUrl(baseUrl);
127
261
  const data = {
128
262
  authenticated: liveness.authenticated,
129
- subject: claims?.sub ?? null,
130
- email: claims?.email ?? null,
131
- org_id: typeof claims?.org_id === 'string'
132
- ? claims.org_id
133
- : typeof claims?.organization_id === 'string'
134
- ? claims.organization_id
135
- : null,
263
+ user_id: userinfo.user_id,
264
+ subject: userinfo.user_id,
265
+ email: userinfo.email,
266
+ name: userinfo.name,
267
+ org_id: userinfo.org_id,
268
+ org_slug: userinfo.org_slug,
269
+ org_name: userinfo.org_name,
270
+ environment,
271
+ base_url: baseUrl,
136
272
  tools: liveness.tools,
137
273
  };
138
- const identity = data.email ?? data.subject ?? 'unknown';
139
274
  emitCommand(data, [
140
275
  `Authenticated: yes`,
141
- `User: ${identity}`,
142
- `Org: ${data.org_id ?? 'none'}`,
276
+ `User: ${formatUser(userinfo)}`,
277
+ `Org: ${formatOrg(userinfo.org_name, userinfo.org_id)}`,
278
+ `Environment: ${environment} (${baseUrl})`,
143
279
  `Tools: ${data.tools}`,
144
280
  ].join('\n'), opts);
281
+ await maybeShowSkillHint();
145
282
  }
146
283
  export async function orgCommand(opts = {}) {
147
- const token = await getToken({ staging: opts.staging });
148
- const org = orgFromClaims(decodeJwtClaims(token));
284
+ const baseUrl = resolveBaseUrl({ staging: opts.staging });
285
+ const org = orgFromUserInfo(await fetchUserInfo({ baseUrl }));
149
286
  emitCommand(org, orgHuman(org), opts);
150
287
  }
@@ -0,0 +1,91 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { emit } from '../lib/output.js';
4
+ function optionFlags(command) {
5
+ return command.options
6
+ .filter((option) => !option.hidden)
7
+ .map((option) => option.flags);
8
+ }
9
+ function argumentUsage(command) {
10
+ const registered = command.registeredArguments;
11
+ return (registered ?? []).map((arg) => {
12
+ const name = arg.name?.() ?? 'arg';
13
+ return arg.required ? `<${name}>` : `[${name}]`;
14
+ });
15
+ }
16
+ function commandLine(command, parents) {
17
+ const names = [...parents, command.name()].filter(Boolean);
18
+ const parts = [names.join(' '), ...argumentUsage(command), ...optionFlags(command)];
19
+ return parts.join(' ').replace(/\s+/g, ' ').trim();
20
+ }
21
+ function walkCommands(command, parents = []) {
22
+ const line = commandLine(command, parents);
23
+ const children = command.commands.flatMap((child) => walkCommands(child, [...parents, command.name()]));
24
+ return [line, ...children];
25
+ }
26
+ export function commandTree(program) {
27
+ return walkCommands(program).join('\n');
28
+ }
29
+ export function conventionsBlock() {
30
+ return [
31
+ 'JSON envelope:',
32
+ ' Success: {"ok":true,"data":...,"env":"production|staging|custom","schema_version":1}',
33
+ ' Error: {"ok":false,"error":{"message":"...","code":"..."},"env":"production|staging|custom","schema_version":1}',
34
+ '',
35
+ 'Exit codes:',
36
+ ' 0 ok',
37
+ ' 1 tool/generic error',
38
+ ' 2 usage',
39
+ ' 3 auth',
40
+ ' 4 permission/confirmation needed',
41
+ ' 5 rate limited',
42
+ ' 6 not found',
43
+ ' 7 network/timeout',
44
+ '',
45
+ 'Safety tiers:',
46
+ ' read: runs without confirmation',
47
+ ' write: requires y/N interactively or --yes non-interactively',
48
+ ' destructive: requires typed confirmation interactively or --yes --allow-destructive non-interactively',
49
+ ' ai-mediated: treated as write-capable because it routes to Every AI',
50
+ '',
51
+ 'Argument forms:',
52
+ ' every tool call <name> --arg k=v --arg count=2',
53
+ ' every tool call <name> --args -',
54
+ ' every tool call <name> --args file.json',
55
+ '',
56
+ 'Environment:',
57
+ ' EVERY_TOKEN skips browser login for headless use.',
58
+ ' Target precedence: --staging > EVERY_MCP_URL > EVERY_ENV=staging|production > production.',
59
+ ].join('\n');
60
+ }
61
+ function bundledSkillPath() {
62
+ return fileURLToPath(new URL('../../skills/use-every/SKILL.md', import.meta.url));
63
+ }
64
+ function canonicalWorkflows(markdown) {
65
+ const match = markdown.match(/## Canonical Workflows\s*([\s\S]*?)(?:\n## |\s*$)/);
66
+ return match?.[1]?.trim() ?? markdown.trim();
67
+ }
68
+ export async function docsCommand(program, opts = {}) {
69
+ const workflows = canonicalWorkflows(await readFile(bundledSkillPath(), 'utf8'));
70
+ const data = {
71
+ commands: commandTree(program),
72
+ conventions: conventionsBlock(),
73
+ workflows,
74
+ };
75
+ if (opts.json) {
76
+ emit(data, { json: true, staging: opts.staging });
77
+ return;
78
+ }
79
+ process.stdout.write([
80
+ '# every docs',
81
+ '',
82
+ '## Commands',
83
+ data.commands,
84
+ '',
85
+ '## Conventions',
86
+ data.conventions,
87
+ '',
88
+ '## Workflows',
89
+ data.workflows,
90
+ ].join('\n') + '\n');
91
+ }
@@ -53,5 +53,5 @@ export async function pingCommand(opts = {}) {
53
53
  status: body.status ?? 'ok',
54
54
  service: body.service ?? null,
55
55
  base_url: baseUrl,
56
- }, { json: opts.json });
56
+ }, { json: opts.json, baseUrl });
57
57
  }
@@ -4,7 +4,7 @@ import { emit } from '../lib/output.js';
4
4
  import { classify, requirementDescription } from '../lib/policy.js';
5
5
  function emitCommand(data, human, opts) {
6
6
  if (opts.json)
7
- emit(data, { json: true });
7
+ emit(data, { json: true, staging: opts.staging });
8
8
  else
9
9
  process.stdout.write(`${human}\n`);
10
10
  }