@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,220 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { resolveBaseUrl } from '../lib/config.js';
3
+ import { CliError } from '../lib/errors.js';
4
+ import { ExitCode } from '../lib/exit-codes.js';
5
+ import { callTool, listTools } from '../lib/mcp.js';
6
+ import { emit } from '../lib/output.js';
7
+ import { classify, promptForTool, requirementDescription, requirementFor, } from '../lib/policy.js';
8
+ import { getToken } from '../lib/auth/tokens.js';
9
+ function emitCommand(data, human, opts) {
10
+ if (opts.json)
11
+ emit(data, { json: true });
12
+ else
13
+ process.stdout.write(`${human}\n`);
14
+ }
15
+ function compactText(value) {
16
+ return typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '';
17
+ }
18
+ function firstSentence(value) {
19
+ const compact = compactText(value);
20
+ const match = compact.match(/^(.+?[.!?])(?:\s|$)/);
21
+ return match?.[1] ?? compact;
22
+ }
23
+ function truncate(value, max = 70) {
24
+ if (value.length <= max)
25
+ return value;
26
+ return `${value.slice(0, Math.max(0, max - 3))}...`;
27
+ }
28
+ function toolSummary(tool) {
29
+ const title = compactText(tool.title);
30
+ const sentence = firstSentence(tool.description);
31
+ if (title && sentence && sentence !== title)
32
+ return truncate(`${title} - ${sentence}`);
33
+ return truncate(title || sentence || '');
34
+ }
35
+ function withClassification(tool) {
36
+ return { ...tool, classification: classify(tool) };
37
+ }
38
+ function toolsListHuman(tools) {
39
+ const nameWidth = Math.min(36, Math.max('name'.length, ...tools.map((tool) => tool.name.length)));
40
+ const levelWidth = 'ai-mediated'.length;
41
+ const lines = [
42
+ `${'name'.padEnd(nameWidth)} ${'classification'.padEnd(levelWidth)} description`,
43
+ `${'-'.repeat(nameWidth)} ${'-'.repeat(levelWidth)} ${'-'.repeat(11)}`,
44
+ ];
45
+ for (const tool of tools) {
46
+ lines.push(`${tool.name.padEnd(nameWidth)} ${tool.classification.level.padEnd(levelWidth)} ${toolSummary(tool)}`);
47
+ }
48
+ return lines.join('\n');
49
+ }
50
+ function findTool(tools, name) {
51
+ const tool = tools.find((candidate) => candidate.name === name);
52
+ if (!tool)
53
+ throw new CliError(`Tool not found: ${name}`, ExitCode.NOT_FOUND, 'not_found');
54
+ return tool;
55
+ }
56
+ function describeHuman(tool) {
57
+ const requirements = requirementDescription(tool.classification.level);
58
+ const lines = [
59
+ `Name: ${tool.name}`,
60
+ `Classification: ${tool.classification.level}`,
61
+ `Source: ${tool.classification.source}`,
62
+ `Reason: ${tool.classification.reason}`,
63
+ `Interactive: ${requirements.interactive}`,
64
+ `Non-interactive: ${requirements.non_interactive}`,
65
+ ];
66
+ if (tool.title)
67
+ lines.push(`Title: ${tool.title}`);
68
+ if (tool.description)
69
+ lines.push('', 'Description:', String(tool.description).trim());
70
+ lines.push('', 'Input schema:', JSON.stringify(tool.inputSchema ?? {}, null, 2));
71
+ return lines.join('\n');
72
+ }
73
+ async function resolveTools(opts) {
74
+ const baseUrl = resolveBaseUrl({ staging: opts.staging });
75
+ const token = await getToken({ baseUrl });
76
+ return listTools(baseUrl, token, { noCache: opts.noCache });
77
+ }
78
+ export async function toolsListCommand(opts = {}) {
79
+ const tools = (await resolveTools(opts)).map(withClassification);
80
+ emitCommand(tools, toolsListHuman(tools), opts);
81
+ }
82
+ export async function toolsDescribeCommand(name, opts = {}) {
83
+ const tool = withClassification(findTool(await resolveTools(opts), name));
84
+ const requirements = requirementDescription(tool.classification.level);
85
+ emitCommand({
86
+ tool,
87
+ classification: tool.classification,
88
+ requirements,
89
+ input_schema: tool.inputSchema ?? {},
90
+ }, describeHuman(tool), opts);
91
+ }
92
+ async function readStdin() {
93
+ process.stdin.setEncoding('utf8');
94
+ let text = '';
95
+ for await (const chunk of process.stdin)
96
+ text += chunk;
97
+ return text;
98
+ }
99
+ function assertJsonObject(value, source) {
100
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
101
+ throw new CliError(`${source} must be a JSON object`, ExitCode.USAGE, 'usage');
102
+ }
103
+ }
104
+ async function readArgsFile(file) {
105
+ const text = file === '-' ? await readStdin() : await readFile(file, 'utf8');
106
+ let parsed;
107
+ try {
108
+ parsed = JSON.parse(text);
109
+ }
110
+ catch (err) {
111
+ const detail = err instanceof Error ? err.message : String(err);
112
+ throw new CliError(`Failed to parse --args JSON: ${detail}`, ExitCode.USAGE, 'usage');
113
+ }
114
+ assertJsonObject(parsed, '--args');
115
+ return parsed;
116
+ }
117
+ function parseArgValue(value) {
118
+ try {
119
+ return JSON.parse(value);
120
+ }
121
+ catch {
122
+ return value;
123
+ }
124
+ }
125
+ function applyArgOverlay(args, entry) {
126
+ const equals = entry.indexOf('=');
127
+ if (equals <= 0) {
128
+ throw new CliError(`--arg must be k=v: ${entry}`, ExitCode.USAGE, 'usage');
129
+ }
130
+ const key = entry.slice(0, equals);
131
+ const value = entry.slice(equals + 1);
132
+ args[key] = parseArgValue(value);
133
+ }
134
+ async function assembleArgs(opts) {
135
+ const args = opts.args ? await readArgsFile(opts.args) : {};
136
+ for (const entry of opts.arg ?? [])
137
+ applyArgOverlay(args, entry);
138
+ return args;
139
+ }
140
+ function timeoutMs(value) {
141
+ if (value === undefined)
142
+ return 120_000;
143
+ const seconds = Number(value);
144
+ if (!Number.isFinite(seconds) || seconds <= 0) {
145
+ throw new CliError('--timeout must be a positive number of seconds', ExitCode.USAGE, 'usage');
146
+ }
147
+ return Math.round(seconds * 1000);
148
+ }
149
+ function textBlocks(content) {
150
+ if (!Array.isArray(content))
151
+ return [];
152
+ return content
153
+ .map((block) => {
154
+ if (!block || typeof block !== 'object')
155
+ return undefined;
156
+ const candidate = block;
157
+ return candidate.type === 'text' && typeof candidate.text === 'string'
158
+ ? candidate.text
159
+ : undefined;
160
+ })
161
+ .filter((text) => text !== undefined);
162
+ }
163
+ function contentAsText(content) {
164
+ const text = textBlocks(content).join('\n');
165
+ if (text)
166
+ return text;
167
+ if (content === undefined || content === null)
168
+ return '';
169
+ return typeof content === 'string' ? content : JSON.stringify(content, null, 2);
170
+ }
171
+ function toolCallHuman(result) {
172
+ const parts = [];
173
+ const text = contentAsText(result.content);
174
+ if (text)
175
+ parts.push(text);
176
+ if (result.structured_content !== undefined) {
177
+ parts.push(JSON.stringify(result.structured_content, null, 2));
178
+ }
179
+ return parts.join('\n');
180
+ }
181
+ export async function executeToolCall(name, opts = {}, argsFactory = async () => ({})) {
182
+ const baseUrl = resolveBaseUrl({ staging: opts.staging });
183
+ const token = await getToken({ baseUrl });
184
+ const tools = await listTools(baseUrl, token, { noCache: opts.noCache });
185
+ const tool = findTool(tools, name);
186
+ const classification = classify(tool);
187
+ const interactive = Boolean(process.stdin.isTTY && process.stderr.isTTY);
188
+ const readOnlyMode = opts.readOnly === true || process.env.EVERY_READ_ONLY === '1';
189
+ const requirement = requirementFor(classification.level, {
190
+ interactive,
191
+ yes: opts.yes,
192
+ allowDestructive: opts.allowDestructive,
193
+ readOnlyMode,
194
+ });
195
+ if (!requirement.allowed) {
196
+ throw new CliError(requirement.denialMessage ?? 'Tool call denied by policy.', ExitCode.PERMISSION, 'permission');
197
+ }
198
+ if (requirement.prompt) {
199
+ const confirmed = await promptForTool(name, classification.level, requirement.prompt);
200
+ if (!confirmed) {
201
+ throw new CliError('Tool call cancelled.', ExitCode.PERMISSION, 'permission');
202
+ }
203
+ }
204
+ const args = await argsFactory();
205
+ const result = await callTool(baseUrl, token, name, args, { timeoutMs: timeoutMs(opts.timeout) });
206
+ const data = {
207
+ tool: name,
208
+ is_error: result.isError,
209
+ content: result.content,
210
+ structured_content: result.structuredContent,
211
+ };
212
+ if (result.isError) {
213
+ const message = contentAsText(result.content) || 'Tool returned an error.';
214
+ throw new CliError(message, ExitCode.GENERIC, 'generic');
215
+ }
216
+ emitCommand(data, toolCallHuman(data), opts);
217
+ }
218
+ export async function toolCallCommand(name, opts = {}) {
219
+ await executeToolCall(name, opts, () => assembleArgs(opts));
220
+ }
package/dist/index.js ADDED
@@ -0,0 +1,309 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ import { Command, CommanderError } from 'commander';
4
+ import { pingCommand } from './commands/ping.js';
5
+ import { authStatusCommand, loginCommand, logoutCommand, orgCommand, whoamiCommand, } from './commands/auth.js';
6
+ import { policyExplainCommand } from './commands/policy.js';
7
+ import { toolCallCommand, toolsDescribeCommand, toolsListCommand, } from './commands/tools.js';
8
+ import { contactListCommand, dealListCommand, dealMoveCommand, invoiceListCommand, invoiceSendCommand, } from './commands/aliases.js';
9
+ import { skillsInstallCommand, skillsListCommand } from './commands/skills.js';
10
+ import { CliError } from './lib/errors.js';
11
+ import { emit, emitError } from './lib/output.js';
12
+ import { ExitCode } from './lib/exit-codes.js';
13
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
14
+ /** Attach the global options every command accepts (before OR after the name). */
15
+ function withGlobalOptions(cmd) {
16
+ return cmd
17
+ .option('--json', 'emit machine-readable JSON output')
18
+ .option('--staging', 'target the staging MCP server');
19
+ }
20
+ const program = new Command();
21
+ let jsonMode = false;
22
+ let commanderStdout = '';
23
+ program.exitOverride();
24
+ program.configureOutput({
25
+ writeOut(str) {
26
+ if (jsonMode)
27
+ commanderStdout += str;
28
+ else
29
+ process.stdout.write(str);
30
+ },
31
+ outputError(str, write) {
32
+ if (!jsonMode)
33
+ write(str);
34
+ },
35
+ });
36
+ withGlobalOptions(program
37
+ .name('every')
38
+ .description('Every AI CLI — the agent-agnostic surface for Every AI')
39
+ .version(pkg.version, '-v, --version', 'print the CLI version'));
40
+ withGlobalOptions(program
41
+ .command('ping')
42
+ .description('Check connectivity to the Every MCP server (unauthenticated)')).action(async (_options, command) => {
43
+ const opts = command.optsWithGlobals();
44
+ await pingCommand({ json: opts.json, staging: opts.staging });
45
+ });
46
+ withGlobalOptions(program
47
+ .command('login')
48
+ .description('Log in with browser-based OAuth and store tokens locally')).action(async (_options, command) => {
49
+ const opts = command.optsWithGlobals();
50
+ await loginCommand({ json: opts.json, staging: opts.staging });
51
+ });
52
+ withGlobalOptions(program
53
+ .command('logout')
54
+ .description('Delete stored auth tokens for the selected environment')).action(async (_options, command) => {
55
+ const opts = command.optsWithGlobals();
56
+ await logoutCommand({ json: opts.json, staging: opts.staging });
57
+ });
58
+ withGlobalOptions(program
59
+ .command('whoami')
60
+ .description('Show the current authenticated user and verify MCP liveness')).action(async (_options, command) => {
61
+ const opts = command.optsWithGlobals();
62
+ await whoamiCommand({ json: opts.json, staging: opts.staging });
63
+ });
64
+ const authCommand = withGlobalOptions(program.command('auth').description('Inspect authentication state'));
65
+ withGlobalOptions(authCommand.command('status').description('Show local auth status without network access')).action(async (_options, command) => {
66
+ const opts = command.optsWithGlobals();
67
+ await authStatusCommand({ json: opts.json, staging: opts.staging });
68
+ });
69
+ withGlobalOptions(program
70
+ .command('org')
71
+ .description('Show org claims from the current token; multi-org selection lands in a later phase')).action(async (_options, command) => {
72
+ const opts = command.optsWithGlobals();
73
+ await orgCommand({ json: opts.json, staging: opts.staging });
74
+ });
75
+ const toolsCommand = withGlobalOptions(program.command('tools').description('Inspect the Every MCP tool registry'));
76
+ withGlobalOptions(toolsCommand
77
+ .command('list')
78
+ .description('List available MCP tools')
79
+ .option('--no-cache', 'bypass and rewrite the local tool registry cache')).action(async (_options, command) => {
80
+ const opts = command.optsWithGlobals();
81
+ await toolsListCommand({
82
+ json: opts.json,
83
+ staging: opts.staging,
84
+ noCache: opts.noCache,
85
+ });
86
+ });
87
+ withGlobalOptions(toolsCommand
88
+ .command('describe')
89
+ .description('Describe an MCP tool and its input schema')
90
+ .argument('<name>', 'tool name')
91
+ .option('--no-cache', 'bypass and rewrite the local tool registry cache')).action(async (name, _options, command) => {
92
+ const opts = command.optsWithGlobals();
93
+ await toolsDescribeCommand(name, {
94
+ json: opts.json,
95
+ staging: opts.staging,
96
+ noCache: opts.noCache,
97
+ });
98
+ });
99
+ const toolCommand = withGlobalOptions(program.command('tool').description('Invoke a single Every MCP tool'));
100
+ function collectOption(value, previous) {
101
+ previous.push(value);
102
+ return previous;
103
+ }
104
+ function withToolExecutionOptions(cmd) {
105
+ return cmd
106
+ .option('--no-cache', 'bypass and rewrite the local tool registry cache')
107
+ .option('--yes', 'confirm write or AI-mediated tool calls')
108
+ .option('--allow-destructive', 'allow destructive tool calls when combined with --yes')
109
+ .option('--read-only', 'deny write, destructive, and AI-mediated tool calls')
110
+ .option('--timeout <secs>', 'tool call timeout in seconds');
111
+ }
112
+ withGlobalOptions(withToolExecutionOptions(toolCommand
113
+ .command('call')
114
+ .description('Call an MCP tool with JSON arguments')
115
+ .argument('<name>', 'tool name')
116
+ .option('--args <file>', 'JSON object file to use for tool arguments; use - for stdin')
117
+ .option('--arg <k=v>', 'overlay one argument value; value is parsed as JSON when possible', collectOption, []))).action(async (name, _options, command) => {
118
+ const opts = command.optsWithGlobals();
119
+ await toolCallCommand(name, {
120
+ json: opts.json,
121
+ staging: opts.staging,
122
+ noCache: opts.noCache,
123
+ args: opts.args,
124
+ arg: opts.arg,
125
+ yes: opts.yes,
126
+ allowDestructive: opts.allowDestructive,
127
+ readOnly: opts.readOnly,
128
+ timeout: opts.timeout,
129
+ });
130
+ });
131
+ const invoiceCommand = withToolExecutionOptions(withGlobalOptions(program
132
+ .command('invoice')
133
+ .description('Work with invoices')
134
+ .addHelpText('after', '\nCreate invoices with line items using: every tool call create_invoice --args <file>\n')));
135
+ withGlobalOptions(withToolExecutionOptions(invoiceCommand
136
+ .command('list')
137
+ .description('List invoices')
138
+ .option('--status <s>', 'invoice or payment status filter')
139
+ .option('--search <q>', 'invoice search query')
140
+ .option('--limit <n>', 'maximum number of invoices to return'))).action(async (_options, command) => {
141
+ const opts = command.optsWithGlobals();
142
+ await invoiceListCommand({
143
+ json: opts.json,
144
+ staging: opts.staging,
145
+ noCache: opts.noCache,
146
+ yes: opts.yes,
147
+ allowDestructive: opts.allowDestructive,
148
+ readOnly: opts.readOnly,
149
+ timeout: opts.timeout,
150
+ status: opts.status,
151
+ search: opts.search,
152
+ limit: opts.limit,
153
+ });
154
+ });
155
+ withGlobalOptions(withToolExecutionOptions(invoiceCommand
156
+ .command('send')
157
+ .description('Send an invoice')
158
+ .argument('<invoice_id>', 'invoice id'))).action(async (invoiceId, _options, command) => {
159
+ const opts = command.optsWithGlobals();
160
+ await invoiceSendCommand(invoiceId, {
161
+ json: opts.json,
162
+ staging: opts.staging,
163
+ noCache: opts.noCache,
164
+ yes: opts.yes,
165
+ allowDestructive: opts.allowDestructive,
166
+ readOnly: opts.readOnly,
167
+ timeout: opts.timeout,
168
+ });
169
+ });
170
+ const dealCommand = withToolExecutionOptions(withGlobalOptions(program.command('deal').description('Work with deals')));
171
+ withGlobalOptions(withToolExecutionOptions(dealCommand
172
+ .command('list')
173
+ .description('List deals')
174
+ .option('--stage <s>', 'deal stage filter')
175
+ .option('--search <q>', 'deal search query')
176
+ .option('--limit <n>', 'maximum number of deals to return'))).action(async (_options, command) => {
177
+ const opts = command.optsWithGlobals();
178
+ await dealListCommand({
179
+ json: opts.json,
180
+ staging: opts.staging,
181
+ noCache: opts.noCache,
182
+ yes: opts.yes,
183
+ allowDestructive: opts.allowDestructive,
184
+ readOnly: opts.readOnly,
185
+ timeout: opts.timeout,
186
+ stage: opts.stage,
187
+ search: opts.search,
188
+ limit: opts.limit,
189
+ });
190
+ });
191
+ withGlobalOptions(withToolExecutionOptions(dealCommand
192
+ .command('move')
193
+ .description('Move a deal to another stage')
194
+ .argument('<deal_id>', 'deal id')
195
+ .argument('<stage>', 'target stage'))).action(async (dealId, stage, _options, command) => {
196
+ const opts = command.optsWithGlobals();
197
+ await dealMoveCommand(dealId, stage, {
198
+ json: opts.json,
199
+ staging: opts.staging,
200
+ noCache: opts.noCache,
201
+ yes: opts.yes,
202
+ allowDestructive: opts.allowDestructive,
203
+ readOnly: opts.readOnly,
204
+ timeout: opts.timeout,
205
+ });
206
+ });
207
+ const contactCommand = withToolExecutionOptions(withGlobalOptions(program.command('contact').description('Work with contacts')));
208
+ withGlobalOptions(withToolExecutionOptions(contactCommand
209
+ .command('list')
210
+ .description('List contacts')
211
+ .option('--search <q>', 'contact name search query')
212
+ .option('--limit <n>', 'maximum number of contacts to return'))).action(async (_options, command) => {
213
+ const opts = command.optsWithGlobals();
214
+ await contactListCommand({
215
+ json: opts.json,
216
+ staging: opts.staging,
217
+ noCache: opts.noCache,
218
+ yes: opts.yes,
219
+ allowDestructive: opts.allowDestructive,
220
+ readOnly: opts.readOnly,
221
+ timeout: opts.timeout,
222
+ search: opts.search,
223
+ limit: opts.limit,
224
+ });
225
+ });
226
+ const policyCommand = withGlobalOptions(program.command('policy').description('Explain local tool safety policy'));
227
+ withGlobalOptions(policyCommand
228
+ .command('explain')
229
+ .description('Explain how a tool is classified and gated')
230
+ .argument('<name>', 'tool name')).action(async (name, _options, command) => {
231
+ const opts = command.optsWithGlobals();
232
+ await policyExplainCommand(name, { json: opts.json, staging: opts.staging });
233
+ });
234
+ const skillsCommand = withGlobalOptions(program.command('skills').description('Install bundled Every agent skills'));
235
+ withGlobalOptions(skillsCommand
236
+ .command('list')
237
+ .description('List bundled skills and install locations')
238
+ .option('--global', 'show global install locations')
239
+ .option('--dir <path>', 'override the destination root')).action(async (_options, command) => {
240
+ const opts = command.optsWithGlobals();
241
+ await skillsListCommand({
242
+ json: opts.json,
243
+ global: opts.global,
244
+ dir: opts.dir,
245
+ });
246
+ });
247
+ withGlobalOptions(skillsCommand
248
+ .command('install')
249
+ .description('Install a bundled skill for an agent target')
250
+ .argument('<target>', 'agent target: claude or codex')
251
+ .option('--global', 'install into the global target skill directory')
252
+ .option('--dir <path>', 'override the destination root')).action(async (target, _options, command) => {
253
+ const opts = command.optsWithGlobals();
254
+ await skillsInstallCommand(target, {
255
+ json: opts.json,
256
+ global: opts.global,
257
+ dir: opts.dir,
258
+ });
259
+ });
260
+ const CLEAN_EXIT_CODES = new Set([
261
+ 'commander.version',
262
+ 'commander.help',
263
+ 'commander.helpDisplayed',
264
+ ]);
265
+ function cleanCommanderMessage(err) {
266
+ return err.message.replace(/^error:\s*/i, '');
267
+ }
268
+ function emitCommanderSuccess(err) {
269
+ if (err.code === 'commander.version') {
270
+ emit({ version: pkg.version }, { json: true });
271
+ return;
272
+ }
273
+ emit({ help: commanderStdout.trimEnd() }, { json: true });
274
+ }
275
+ async function main() {
276
+ jsonMode = process.argv.includes('--json');
277
+ commanderStdout = '';
278
+ try {
279
+ await program.parseAsync(process.argv);
280
+ if (program.args.length === 0) {
281
+ if (jsonMode) {
282
+ emit({ help: program.helpInformation().trimEnd() }, { json: true });
283
+ }
284
+ else {
285
+ program.outputHelp();
286
+ }
287
+ }
288
+ }
289
+ catch (err) {
290
+ if (err instanceof CommanderError) {
291
+ if (CLEAN_EXIT_CODES.has(err.code)) {
292
+ if (jsonMode)
293
+ emitCommanderSuccess(err);
294
+ process.exit(ExitCode.OK);
295
+ }
296
+ if (jsonMode)
297
+ emitError(cleanCommanderMessage(err), 'usage', { json: true });
298
+ process.exit(ExitCode.USAGE);
299
+ }
300
+ if (err instanceof CliError) {
301
+ emitError(err.message, err.code, { json: jsonMode });
302
+ process.exit(err.exitCode);
303
+ }
304
+ const message = err instanceof Error ? err.message : String(err);
305
+ emitError(message, 'generic', { json: jsonMode });
306
+ process.exit(ExitCode.GENERIC);
307
+ }
308
+ }
309
+ void main();
@@ -0,0 +1,80 @@
1
+ import { mkdir, readFile, rename, 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 { fetchJsonWithTimeout } from './discovery.js';
7
+ const DCR_TIMEOUT_MS = 10_000;
8
+ const CLIENT_NAME = 'Every AI CLI';
9
+ export const DEFAULT_SCOPE = 'openid profile email offline_access user:org:read';
10
+ function clientsPath() {
11
+ return path.join(getConfigDir(), 'oauth-clients.json');
12
+ }
13
+ async function readRegistrations(filePath) {
14
+ try {
15
+ const text = await readFile(filePath, 'utf8');
16
+ const parsed = JSON.parse(text);
17
+ return {
18
+ issuers: parsed && typeof parsed.issuers === 'object' && parsed.issuers ? parsed.issuers : {},
19
+ };
20
+ }
21
+ catch (err) {
22
+ if (err && typeof err === 'object' && 'code' in err && err.code === 'ENOENT') {
23
+ return { issuers: {} };
24
+ }
25
+ throw err;
26
+ }
27
+ }
28
+ async function writeRegistrations(filePath, registrations) {
29
+ await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
30
+ const tempPath = `${filePath}.${process.pid}.tmp`;
31
+ await writeFile(tempPath, JSON.stringify(registrations, null, 2), { mode: 0o600 });
32
+ await chmod(tempPath, 0o600);
33
+ await rename(tempPath, filePath);
34
+ await chmod(filePath, 0o600);
35
+ }
36
+ async function postClientRegistration(metadata, redirectUri) {
37
+ if (!metadata.registration_endpoint) {
38
+ throw new CliError(`OAuth issuer ${metadata.issuer} does not advertise dynamic client registration`, ExitCode.AUTH, 'auth');
39
+ }
40
+ let response;
41
+ try {
42
+ response = await fetchJsonWithTimeout(metadata.registration_endpoint, {
43
+ method: 'POST',
44
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
45
+ body: JSON.stringify({
46
+ client_name: CLIENT_NAME,
47
+ redirect_uris: [redirectUri],
48
+ grant_types: ['authorization_code', 'refresh_token'],
49
+ response_types: ['code'],
50
+ token_endpoint_auth_method: 'none',
51
+ scope: DEFAULT_SCOPE,
52
+ }),
53
+ }, DCR_TIMEOUT_MS);
54
+ }
55
+ catch (err) {
56
+ if (err instanceof CliError)
57
+ throw err;
58
+ const detail = err instanceof Error ? err.message : String(err);
59
+ throw new CliError(`Failed to register OAuth client: ${detail}`, ExitCode.NETWORK, 'network');
60
+ }
61
+ if (!response.client_id) {
62
+ throw new CliError('OAuth client registration did not return client_id', ExitCode.AUTH, 'auth');
63
+ }
64
+ return {
65
+ client_id: response.client_id,
66
+ redirect_uris: response.redirect_uris ?? [redirectUri],
67
+ };
68
+ }
69
+ export async function getOrRegisterClient(metadata, redirectUri, opts = {}) {
70
+ const filePath = opts.filePath ?? clientsPath();
71
+ const registrations = await readRegistrations(filePath);
72
+ const cached = registrations.issuers[metadata.issuer];
73
+ if (cached?.client_id && cached.redirect_uris.includes(redirectUri)) {
74
+ return cached;
75
+ }
76
+ const registered = await postClientRegistration(metadata, redirectUri);
77
+ registrations.issuers[metadata.issuer] = registered;
78
+ await writeRegistrations(filePath, registrations);
79
+ return registered;
80
+ }