@everyai/cli 0.1.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.
@@ -0,0 +1,214 @@
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 { environmentKeyForBaseUrl } from './auth/tokens.js';
7
+ const DEFAULT_MCP_TIMEOUT_MS = 30_000;
8
+ const DEFAULT_TOOL_TIMEOUT_MS = 120_000;
9
+ const TOOL_CACHE_TTL_MS = 10 * 60 * 1000;
10
+ function mcpUrl(baseUrl) {
11
+ return `${baseUrl.replace(/\/+$/, '')}/`;
12
+ }
13
+ function isTimeoutError(err) {
14
+ return err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError');
15
+ }
16
+ function classifyHttpStatus(status) {
17
+ if (status === 401)
18
+ return { exitCode: ExitCode.AUTH, code: 'auth' };
19
+ if (status === 402 || status === 403) {
20
+ return { exitCode: ExitCode.PERMISSION, code: 'permission' };
21
+ }
22
+ if (status === 404)
23
+ return { exitCode: ExitCode.NOT_FOUND, code: 'not_found' };
24
+ if (status === 429)
25
+ return { exitCode: ExitCode.RATE_LIMIT, code: 'rate_limit' };
26
+ if (status === 406 || status >= 500)
27
+ return { exitCode: ExitCode.NETWORK, code: 'network' };
28
+ return { exitCode: ExitCode.GENERIC, code: 'generic' };
29
+ }
30
+ function dataBlocksFromSse(raw) {
31
+ const blocks = [];
32
+ let current = [];
33
+ for (const line of raw.split(/\r?\n/)) {
34
+ if (line === '') {
35
+ if (current.length > 0) {
36
+ blocks.push(current.join('\n'));
37
+ current = [];
38
+ }
39
+ continue;
40
+ }
41
+ if (line.startsWith('data:'))
42
+ current.push(line.slice('data:'.length).trimStart());
43
+ }
44
+ if (current.length > 0)
45
+ blocks.push(current.join('\n'));
46
+ return blocks;
47
+ }
48
+ function jsonTextFromResponse(raw) {
49
+ const trimmed = raw.trim();
50
+ const blocks = dataBlocksFromSse(raw);
51
+ if (blocks.length === 0)
52
+ return trimmed;
53
+ const parseable = blocks.find((block) => {
54
+ try {
55
+ JSON.parse(block);
56
+ return true;
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ });
62
+ return parseable ?? blocks[0].trim();
63
+ }
64
+ function toolNameFromParams(params) {
65
+ if (!params || typeof params !== 'object')
66
+ return undefined;
67
+ const name = params.name;
68
+ return typeof name === 'string' ? name : undefined;
69
+ }
70
+ function isUnknownToolError(error, toolName) {
71
+ const message = error.message ?? '';
72
+ const lower = message.toLowerCase();
73
+ const mentionsTool = toolName ? lower.includes(toolName.toLowerCase()) : false;
74
+ const messageMatches = /unknown tool|tool .*not found|tool not found|no such tool|not found.*tool/i.test(message);
75
+ if (messageMatches)
76
+ return true;
77
+ if (error.code === -32601)
78
+ return true;
79
+ return error.code === -32602 && mentionsTool;
80
+ }
81
+ function jsonRpcErrorToCliError(error, params) {
82
+ const message = error.message ?? 'MCP JSON-RPC request failed';
83
+ const toolName = toolNameFromParams(params);
84
+ if (isUnknownToolError(error, toolName)) {
85
+ return new CliError(message, ExitCode.NOT_FOUND, 'not_found');
86
+ }
87
+ if (error.code === -32602)
88
+ return new CliError(message, ExitCode.USAGE, 'usage');
89
+ return new CliError(message, ExitCode.GENERIC, 'generic');
90
+ }
91
+ function parseJsonRpcResponse(raw, params) {
92
+ let body;
93
+ try {
94
+ body = JSON.parse(jsonTextFromResponse(raw));
95
+ }
96
+ catch {
97
+ throw new CliError('Unexpected response from MCP server (not JSON)', ExitCode.NETWORK, 'network');
98
+ }
99
+ if (body.error)
100
+ throw jsonRpcErrorToCliError(body.error, params);
101
+ return body.result;
102
+ }
103
+ export async function mcpCall(baseUrl, token, method, params = {}, { timeoutMs = DEFAULT_MCP_TIMEOUT_MS } = {}) {
104
+ const url = mcpUrl(baseUrl);
105
+ let response;
106
+ try {
107
+ response = await fetch(url, {
108
+ method: 'POST',
109
+ headers: {
110
+ authorization: `Bearer ${token}`,
111
+ 'content-type': 'application/json',
112
+ accept: 'application/json, text/event-stream',
113
+ },
114
+ body: JSON.stringify({
115
+ jsonrpc: '2.0',
116
+ id: `everyai-cli-${Date.now()}`,
117
+ method,
118
+ params,
119
+ }),
120
+ signal: AbortSignal.timeout(timeoutMs),
121
+ });
122
+ }
123
+ catch (err) {
124
+ if (isTimeoutError(err)) {
125
+ throw new CliError(`Timed out reaching ${url} after ${timeoutMs}ms`, ExitCode.NETWORK, 'network');
126
+ }
127
+ const detail = err instanceof Error ? err.message : String(err);
128
+ throw new CliError(`Failed to reach ${url}: ${detail}`, ExitCode.NETWORK, 'network');
129
+ }
130
+ if (response.status === 401) {
131
+ throw new CliError('Not logged in. Run \'every login\'.', ExitCode.AUTH, 'auth');
132
+ }
133
+ if (!response.ok) {
134
+ const classified = classifyHttpStatus(response.status);
135
+ throw new CliError(`MCP ${method} failed for ${url}: HTTP ${response.status}`, classified.exitCode, classified.code);
136
+ }
137
+ return parseJsonRpcResponse(await response.text(), params);
138
+ }
139
+ function safeEnvironmentKey(baseUrl) {
140
+ return environmentKeyForBaseUrl(baseUrl).replace(/[^a-zA-Z0-9._-]/g, '_');
141
+ }
142
+ export function toolsCacheFilePath(baseUrl) {
143
+ return path.join(getConfigDir(), 'cache', `tools-${safeEnvironmentKey(baseUrl)}.json`);
144
+ }
145
+ function fetchedAtMs(value) {
146
+ if (typeof value === 'number')
147
+ return value;
148
+ const parsed = Date.parse(value);
149
+ return Number.isFinite(parsed) ? parsed : 0;
150
+ }
151
+ function isToolArray(value) {
152
+ return Array.isArray(value) && value.every((tool) => {
153
+ return Boolean(tool && typeof tool === 'object' && typeof tool.name === 'string');
154
+ });
155
+ }
156
+ export async function readCachedTools(baseUrl, { allowStale = false } = {}) {
157
+ let parsed;
158
+ try {
159
+ parsed = JSON.parse(await readFile(toolsCacheFilePath(baseUrl), 'utf8'));
160
+ }
161
+ catch (err) {
162
+ if (err && typeof err === 'object' && 'code' in err && err.code === 'ENOENT') {
163
+ return undefined;
164
+ }
165
+ throw err;
166
+ }
167
+ if (!isToolArray(parsed.tools))
168
+ return undefined;
169
+ if (!allowStale && Date.now() - fetchedAtMs(parsed.fetched_at) > TOOL_CACHE_TTL_MS) {
170
+ return undefined;
171
+ }
172
+ return parsed.tools;
173
+ }
174
+ async function writeToolCache(baseUrl, tools) {
175
+ const filePath = toolsCacheFilePath(baseUrl);
176
+ await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
177
+ const tempPath = `${filePath}.${process.pid}.tmp`;
178
+ await writeFile(tempPath, JSON.stringify({ fetched_at: new Date().toISOString(), tools }, null, 2), { mode: 0o600 });
179
+ await chmod(tempPath, 0o600);
180
+ await rename(tempPath, filePath);
181
+ await chmod(filePath, 0o600);
182
+ }
183
+ export async function toolCacheFileMode(baseUrl) {
184
+ try {
185
+ return (await stat(toolsCacheFilePath(baseUrl))).mode & 0o777;
186
+ }
187
+ catch (err) {
188
+ if (err && typeof err === 'object' && 'code' in err && err.code === 'ENOENT') {
189
+ return undefined;
190
+ }
191
+ throw err;
192
+ }
193
+ }
194
+ export async function listTools(baseUrl, token, { noCache } = {}) {
195
+ if (!noCache) {
196
+ const cached = await readCachedTools(baseUrl);
197
+ if (cached)
198
+ return cached;
199
+ }
200
+ const result = await mcpCall(baseUrl, token, 'tools/list', {});
201
+ if (!isToolArray(result?.tools)) {
202
+ throw new CliError('MCP tools/list returned an invalid tool registry', ExitCode.GENERIC, 'generic');
203
+ }
204
+ await writeToolCache(baseUrl, result.tools);
205
+ return result.tools;
206
+ }
207
+ export async function callTool(baseUrl, token, name, args, { timeoutMs = DEFAULT_TOOL_TIMEOUT_MS } = {}) {
208
+ const result = await mcpCall(baseUrl, token, 'tools/call', { name, arguments: args }, { timeoutMs });
209
+ return {
210
+ content: result?.content ?? [],
211
+ structuredContent: result?.structuredContent,
212
+ isError: result?.isError === true,
213
+ };
214
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Stable output envelope for the `every` CLI.
3
+ *
4
+ * `--json` mode is a CLI CONTRACT that agents and scripts parse. Rules:
5
+ * - Success: `{ ok: true, data, schema_version: 1 }`
6
+ * - Failure: `{ ok: false, error: { message, code }, schema_version: 1 }`
7
+ * - In `--json` mode the ONLY thing written is a single JSON object — never
8
+ * mix human prose into machine output.
9
+ */
10
+ export const SCHEMA_VERSION = 1;
11
+ export function successEnvelope(data) {
12
+ return { ok: true, data, schema_version: SCHEMA_VERSION };
13
+ }
14
+ export function errorEnvelope(message, code) {
15
+ return { ok: false, error: { message, code }, schema_version: SCHEMA_VERSION };
16
+ }
17
+ function humanize(data) {
18
+ if (data === null || data === undefined)
19
+ return 'OK';
20
+ if (typeof data === 'string')
21
+ return data;
22
+ if (typeof data !== 'object')
23
+ return String(data);
24
+ return Object.entries(data)
25
+ .map(([key, value]) => `${key}: ${value}`)
26
+ .join('\n');
27
+ }
28
+ /** Render a success result as a string (pure JSON when `json`, else human text). */
29
+ export function formatSuccess(data, opts = {}) {
30
+ if (opts.json)
31
+ return JSON.stringify(successEnvelope(data));
32
+ return humanize(data);
33
+ }
34
+ /** Render an error as a string (pure JSON when `json`, else human text). */
35
+ export function formatError(message, code, opts = {}) {
36
+ if (opts.json)
37
+ return JSON.stringify(errorEnvelope(message, code));
38
+ return `Error: ${message}`;
39
+ }
40
+ /** Emit a success result to stdout. */
41
+ export function emit(data, opts = {}) {
42
+ process.stdout.write(formatSuccess(data, opts) + '\n');
43
+ }
44
+ /**
45
+ * Emit an error. In `--json` mode the envelope goes to stdout so a single
46
+ * parse of stdout always yields the machine result; human errors go to stderr.
47
+ */
48
+ export function emitError(message, code, opts = {}) {
49
+ const rendered = formatError(message, code, opts);
50
+ if (opts.json) {
51
+ process.stdout.write(rendered + '\n');
52
+ }
53
+ else {
54
+ process.stderr.write(rendered + '\n');
55
+ }
56
+ }
@@ -0,0 +1,165 @@
1
+ import { createInterface } from 'node:readline/promises';
2
+ function annotationFlag(tool, flattened, hint) {
3
+ const direct = tool[flattened];
4
+ if (typeof direct === 'boolean')
5
+ return direct;
6
+ const annotations = tool.annotations;
7
+ const hinted = annotations?.[hint];
8
+ if (typeof hinted === 'boolean')
9
+ return hinted;
10
+ const alternate = annotations?.[flattened];
11
+ return typeof alternate === 'boolean' ? alternate : false;
12
+ }
13
+ /**
14
+ * Annotations are hints; this table encodes what we know the server actually
15
+ * does. Keep these overrides conservative because they define the local safety
16
+ * boundary before any network-side tool invocation.
17
+ */
18
+ function overrideClassification(name) {
19
+ if (name === 'ask_assistant') {
20
+ return {
21
+ level: 'ai-mediated',
22
+ source: 'override',
23
+ reason: 'ask_assistant routes to a write-capable Every AI agent despite its read-only annotation.',
24
+ };
25
+ }
26
+ if (/^delete_|^void_/.test(name)) {
27
+ return {
28
+ level: 'destructive',
29
+ source: 'override',
30
+ reason: 'Tool name matches delete_/void_, which can remove or void account records.',
31
+ };
32
+ }
33
+ if (/^send_/.test(name)) {
34
+ return {
35
+ level: 'destructive',
36
+ source: 'override',
37
+ reason: 'Tool name matches send_; sending has external impact on real recipients.',
38
+ };
39
+ }
40
+ if (name === 'record_payment') {
41
+ return {
42
+ level: 'destructive',
43
+ source: 'override',
44
+ reason: 'record_payment changes financial records.',
45
+ };
46
+ }
47
+ return undefined;
48
+ }
49
+ export function classify(tool) {
50
+ const overridden = overrideClassification(tool.name);
51
+ if (overridden)
52
+ return overridden;
53
+ const readOnly = annotationFlag(tool, 'readOnly', 'readOnlyHint');
54
+ const destructive = annotationFlag(tool, 'destructive', 'destructiveHint');
55
+ const openWorld = annotationFlag(tool, 'openWorld', 'openWorldHint');
56
+ if (readOnly) {
57
+ return {
58
+ level: 'read',
59
+ source: 'annotation',
60
+ reason: 'Tool annotation marks it read-only.',
61
+ };
62
+ }
63
+ if (destructive) {
64
+ return {
65
+ level: 'destructive',
66
+ source: 'annotation',
67
+ reason: 'Tool annotation marks it destructive.',
68
+ };
69
+ }
70
+ if (openWorld) {
71
+ return {
72
+ level: 'destructive',
73
+ source: 'annotation',
74
+ reason: 'Tool annotation marks it open-world and not read-only.',
75
+ };
76
+ }
77
+ return {
78
+ level: 'write',
79
+ source: 'annotation',
80
+ reason: 'Tool is not annotated read-only; defaulting to write.',
81
+ };
82
+ }
83
+ function readOnlyDenial(level) {
84
+ if (level === 'ai-mediated') {
85
+ return 'Denied by read-only mode (--read-only/EVERY_READ_ONLY=1): ai-mediated tools are not allowed.';
86
+ }
87
+ return `Denied by read-only mode (--read-only/EVERY_READ_ONLY=1): ${level} tools are not allowed.`;
88
+ }
89
+ function aiMediatedExplanation() {
90
+ return "This tool sends your request to Every's AI agent, which can take actions on your account; it is not mechanically read-only.";
91
+ }
92
+ export function requirementFor(level, { interactive, yes, allowDestructive, readOnlyMode }) {
93
+ if (level === 'read')
94
+ return { allowed: true };
95
+ if (readOnlyMode) {
96
+ return { allowed: false, denialMessage: readOnlyDenial(level) };
97
+ }
98
+ if (level === 'write' || level === 'ai-mediated') {
99
+ if (yes)
100
+ return { allowed: true };
101
+ if (interactive)
102
+ return { allowed: true, prompt: 'confirm' };
103
+ const prefix = level === 'ai-mediated' ? `${aiMediatedExplanation()} ` : '';
104
+ return {
105
+ allowed: false,
106
+ denialMessage: `${prefix}Re-run with --yes to confirm this write.`,
107
+ };
108
+ }
109
+ if (yes && allowDestructive)
110
+ return { allowed: true };
111
+ if (interactive)
112
+ return { allowed: true, prompt: 'typed' };
113
+ const missing = [
114
+ yes ? undefined : '--yes',
115
+ allowDestructive ? undefined : '--allow-destructive',
116
+ ].filter((flag) => Boolean(flag));
117
+ return {
118
+ allowed: false,
119
+ denialMessage: `This destructive tool requires ${missing.join(' and ')} in non-interactive mode.`,
120
+ };
121
+ }
122
+ export function requirementDescription(level) {
123
+ if (level === 'read') {
124
+ return {
125
+ interactive: 'Allowed with no confirmation.',
126
+ non_interactive: 'Allowed with no confirmation.',
127
+ };
128
+ }
129
+ if (level === 'write') {
130
+ return {
131
+ interactive: 'Requires y/N confirmation unless --yes is supplied.',
132
+ non_interactive: 'Requires --yes.',
133
+ };
134
+ }
135
+ if (level === 'ai-mediated') {
136
+ return {
137
+ interactive: `${aiMediatedExplanation()} Requires y/N confirmation unless --yes is supplied.`,
138
+ non_interactive: `${aiMediatedExplanation()} Requires --yes.`,
139
+ };
140
+ }
141
+ return {
142
+ interactive: 'Requires typing the tool name unless both --yes and --allow-destructive are supplied.',
143
+ non_interactive: 'Requires --yes and --allow-destructive.',
144
+ };
145
+ }
146
+ function confirmationPrompt(level) {
147
+ if (level === 'ai-mediated') {
148
+ return `${aiMediatedExplanation()}\nContinue? [y/N] `;
149
+ }
150
+ return 'This tool can modify your Every account. Continue? [y/N] ';
151
+ }
152
+ export async function promptForTool(toolName, level, prompt) {
153
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
154
+ try {
155
+ if (prompt === 'confirm') {
156
+ const answer = await rl.question(confirmationPrompt(level));
157
+ return answer.trim().toLowerCase() === 'y' || answer.trim().toLowerCase() === 'yes';
158
+ }
159
+ const answer = await rl.question(`Type ${toolName} to confirm: `);
160
+ return answer.trim() === toolName;
161
+ }
162
+ finally {
163
+ rl.close();
164
+ }
165
+ }
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@everyai/cli",
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "description": "The agent-agnostic command-line surface for Every AI.",
6
+ "type": "module",
7
+ "bin": {
8
+ "every": "dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "skills"
13
+ ],
14
+ "engines": {
15
+ "node": ">=18"
16
+ },
17
+ "publishConfig": {
18
+ "access": "public",
19
+ "provenance": true
20
+ },
21
+ "scripts": {
22
+ "build": "tsc",
23
+ "dev": "tsx src/index.ts",
24
+ "test": "vitest run",
25
+ "typecheck": "tsc --noEmit",
26
+ "prepublishOnly": "npm run build"
27
+ },
28
+ "dependencies": {
29
+ "@napi-rs/keyring": "^1.2.0",
30
+ "commander": "^12.1.0"
31
+ },
32
+ "devDependencies": {
33
+ "@changesets/cli": "^2.27.9",
34
+ "@types/node": "^20.16.0",
35
+ "tsx": "^4.19.0",
36
+ "typescript": "^5.6.0",
37
+ "vitest": "^2.1.0"
38
+ }
39
+ }
@@ -0,0 +1,102 @@
1
+ ---
2
+ name: use-every
3
+ description: Drive the Every AI CLI (`every`) to manage the user's business — invoices, clients, contacts, proposals, deals, pipeline, payments. Use when the user asks to look up, create, update, or send any of those, or mentions their Every workspace.
4
+ ---
5
+
6
+ # Use Every
7
+
8
+ ## Setup Check
9
+
10
+ Run `every --version` first. If the CLI is missing, suggest `npm install -g @everyai/cli`. If any authenticated command exits `3`, tell the user to run `every login` (it opens their browser; you cannot complete it for them).
11
+
12
+ ## What Every Is
13
+
14
+ Use Every as an SMB business-ops workspace for invoices, clients, contacts, proposals, deals, payments, and pipeline work.
15
+
16
+ Use the `every` CLI as authenticated access to the user's Every workspace from any coding agent shell. Assume the user must have run `every login` once before authenticated commands can work.
17
+
18
+ ## Conventions
19
+
20
+ Always pass `--json`. Parse the envelope every time:
21
+
22
+ - `ok: true` means read `data`.
23
+ - `ok: false` means read `error.code` and `error.message`.
24
+ - `schema_version` must be present and understood before automating against the response.
25
+
26
+ Check process exit codes:
27
+
28
+ - `0`: success.
29
+ - `2`: usage error. Fix the command or arguments.
30
+ - `3`: auth error. Tell the user to run `every login`.
31
+ - `4`: permission or confirmation needed. Ask the user before adding confirmation flags.
32
+ - `5`: rate limited. Back off and retry later.
33
+ - `6`: not found. Re-list records and verify the ID.
34
+ - `7`: network error. Retry after checking connectivity.
35
+
36
+ Never infer or guess IDs. List first, then act only with the exact ID shown in the result, such as `[id: ...]`.
37
+
38
+ ## Discovery
39
+
40
+ Use these commands to discover current tools and policy:
41
+
42
+ ```bash
43
+ every tools list --json
44
+ every tools describe <name> --json
45
+ every policy explain <name> --json
46
+ ```
47
+
48
+ ## Safety Rules
49
+
50
+ Run read tools freely.
51
+
52
+ For WRITE tools, add `--yes` only when the human user explicitly asked for the change.
53
+
54
+ For DESTRUCTIVE tools, including sends, deletes, voids, and payments, add both `--yes` and `--allow-destructive` only when the human user explicitly asked for that external or irreversible action. Never add `--allow-destructive` unprompted.
55
+
56
+ In automation, prefer `--read-only` unless writes were requested.
57
+
58
+ Treat `ask_assistant` as AI-mediated. It routes to Every's agent and can act on the account. Prefer deterministic tools. Do not use `ask_assistant` in read-only automation.
59
+
60
+ ## Canonical Workflows
61
+
62
+ Review pipeline:
63
+
64
+ ```bash
65
+ every deal list --json
66
+ every tool call view_deal --arg deal_id=<id> --json
67
+ ```
68
+
69
+ Move a deal:
70
+
71
+ ```bash
72
+ every deal move <id> <stage> --yes --json
73
+ ```
74
+
75
+ Invoice flow:
76
+
77
+ ```bash
78
+ every invoice list --status overdue --json
79
+ every tool call create_invoice --args invoice.json --yes --json
80
+ every invoice send <id> --yes --allow-destructive --json
81
+ ```
82
+
83
+ Contacts:
84
+
85
+ ```bash
86
+ every contact list --search "acme" --json
87
+ ```
88
+
89
+ ## Recovery And Debug
90
+
91
+ Use these commands when auth, identity, or connectivity is unclear:
92
+
93
+ ```bash
94
+ every auth status --json
95
+ every whoami --json
96
+ every ping --json
97
+ every logout && every login
98
+ ```
99
+
100
+ ## Staging
101
+
102
+ Use `--staging` only for Every's staging environment. Treat it as internal/testing only.