@deepdynamic/cli 0.0.0-stage → 0.1.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.
Files changed (84) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +32 -2
  3. package/THIRD_PARTY_NOTICES.txt +102 -0
  4. package/dist/agents/content.js +12 -0
  5. package/dist/agents/edit.js +140 -0
  6. package/dist/agents/install.js +190 -0
  7. package/dist/agents/refresh.js +20 -0
  8. package/dist/agents/setup.js +29 -0
  9. package/dist/agents/targets.js +91 -0
  10. package/dist/auth/credentials.js +63 -0
  11. package/dist/auth/session.js +49 -0
  12. package/dist/cli.js +198 -0
  13. package/dist/commands/account.js +96 -0
  14. package/dist/commands/activity.js +80 -0
  15. package/dist/commands/blocked.js +89 -0
  16. package/dist/commands/deploy/agents.js +11 -0
  17. package/dist/commands/deploy/files.js +62 -0
  18. package/dist/commands/deploy/index.js +95 -0
  19. package/dist/commands/deploy/manifest.js +24 -0
  20. package/dist/commands/deploy/minify.js +27 -0
  21. package/dist/commands/deploy/progress.js +85 -0
  22. package/dist/commands/deploy/ship.js +117 -0
  23. package/dist/commands/deploy/upload.js +125 -0
  24. package/dist/commands/deployments.js +60 -0
  25. package/dist/commands/dns.js +777 -0
  26. package/dist/commands/domains.js +639 -0
  27. package/dist/commands/emails.js +74 -0
  28. package/dist/commands/env.js +194 -0
  29. package/dist/commands/help.js +148 -0
  30. package/dist/commands/keys.js +263 -0
  31. package/dist/commands/login/flow.js +155 -0
  32. package/dist/commands/login/index.js +26 -0
  33. package/dist/commands/logout.js +71 -0
  34. package/dist/commands/mail.js +241 -0
  35. package/dist/commands/notifications.js +133 -0
  36. package/dist/commands/plan.js +355 -0
  37. package/dist/commands/projects.js +838 -0
  38. package/dist/commands/reference.js +2187 -0
  39. package/dist/commands/search.js +86 -0
  40. package/dist/commands/server.js +301 -0
  41. package/dist/commands/sessions.js +114 -0
  42. package/dist/commands/sites.js +102 -0
  43. package/dist/commands/sms.js +65 -0
  44. package/dist/commands/status.js +87 -0
  45. package/dist/commands/support.js +115 -0
  46. package/dist/commands/update.js +100 -0
  47. package/dist/commands/usage.js +51 -0
  48. package/dist/commands/verify.js +149 -0
  49. package/dist/commands/version.js +6 -0
  50. package/dist/guide.js +37 -0
  51. package/dist/http/call.js +6 -0
  52. package/dist/http/request.js +54 -0
  53. package/dist/index.js +11 -0
  54. package/dist/metadata.js +4 -0
  55. package/dist/output.js +9 -0
  56. package/dist/pretty.js +70 -0
  57. package/dist/refresh-skills.js +5 -0
  58. package/dist/registry.js +688 -0
  59. package/dist/runtime/browser.js +15 -0
  60. package/dist/runtime/card-request.js +55 -0
  61. package/dist/runtime/confirm.js +21 -0
  62. package/dist/runtime/development.js +13 -0
  63. package/dist/runtime/domain-name.js +5 -0
  64. package/dist/runtime/dry-run.js +28 -0
  65. package/dist/runtime/env-file.js +55 -0
  66. package/dist/runtime/error-hints.js +26 -0
  67. package/dist/runtime/flags.js +48 -0
  68. package/dist/runtime/login-screen.js +78 -0
  69. package/dist/runtime/page.js +18 -0
  70. package/dist/runtime/project-name.js +1 -0
  71. package/dist/runtime/run-mode.js +7 -0
  72. package/dist/runtime/server-options.js +28 -0
  73. package/dist/runtime/spinner.js +17 -0
  74. package/dist/runtime/suggest.js +22 -0
  75. package/dist/runtime/support.js +13 -0
  76. package/dist/runtime/text-file.js +20 -0
  77. package/dist/runtime/timeout.js +22 -0
  78. package/dist/runtime/update-check.js +158 -0
  79. package/dist/runtime/update-install.js +80 -0
  80. package/dist/runtime/usage-error.js +9 -0
  81. package/dist/setup-agents.js +15 -0
  82. package/dist/site.js +1 -0
  83. package/dist/update-refresh.js +5 -0
  84. package/package.json +46 -3
@@ -0,0 +1,190 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { accessSync, constants, statSync } from 'node:fs';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import { dirname, isAbsolute, join } from 'node:path';
5
+ import { INSTRUCTIONS, MCP_URL, NAME, SKILL } from "./content.js";
6
+ import { appendJsonArray, jsonValue, setJson, upsertBlock, upsertCrushrc, upsertTomlServer, upsertYamlExtension } from "./edit.js";
7
+ import { agentTargets } from "./targets.js";
8
+ const BOM = '';
9
+ const OPENCODE_SEED = '{\n "$schema": "https://opencode.ai/config.json"\n}';
10
+ const isDirectory = (path) => {
11
+ try {
12
+ return statSync(path).isDirectory();
13
+ }
14
+ catch {
15
+ return false;
16
+ }
17
+ };
18
+ const isFile = (path) => {
19
+ try {
20
+ return statSync(path).isFile();
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ };
26
+ const reason = (error) => error.code ?? String(error);
27
+ async function editFile(path, edit) {
28
+ let original;
29
+ try {
30
+ original = await readFile(path, 'utf8');
31
+ }
32
+ catch (error) {
33
+ if (error.code !== 'ENOENT')
34
+ return { ok: false, code: 'read_failed', path, detail: reason(error) };
35
+ original = null;
36
+ }
37
+ const bom = original?.startsWith(BOM) ? BOM : '';
38
+ const next = edit((original ?? '').slice(bom.length));
39
+ if (next === null)
40
+ return { ok: false, code: 'invalid_config', path };
41
+ if (original !== null && bom + next === original)
42
+ return { ok: true, path };
43
+ try {
44
+ await mkdir(dirname(path), { recursive: true });
45
+ await writeFile(path, bom + next);
46
+ return { ok: true, path };
47
+ }
48
+ catch (error) {
49
+ return { ok: false, code: 'write_failed', path, detail: reason(error) };
50
+ }
51
+ }
52
+ const pick = (files) => files.find(isFile) ?? files[0];
53
+ const editJson = (mcp) => editFile(pick(mcp.files), (text) => setJson(text, mcp.path, mcp.value, mcp.seed));
54
+ async function runCommand(commands, name, remove, add) {
55
+ const path = commands.find(name);
56
+ if (!path)
57
+ return null;
58
+ if (remove.length)
59
+ await commands.run(path, remove);
60
+ const result = await commands.run(path, add);
61
+ return result.status === 0
62
+ ? { ok: true, command: `${name} ${add.join(' ')}` }
63
+ : { ok: false, code: 'command_failed', command: `${name} ${add.join(' ')}`, detail: result.output };
64
+ }
65
+ async function installMcp(agent, commands) {
66
+ const { mcp } = agent;
67
+ switch (mcp.kind) {
68
+ case 'json':
69
+ return editJson(mcp);
70
+ case 'command': {
71
+ const ran = await runCommand(commands, mcp.command, mcp.remove, mcp.add);
72
+ if (ran)
73
+ return ran;
74
+ return mcp.fallback ? editJson(mcp.fallback) : { ok: false, code: 'command_not_found', command: mcp.command };
75
+ }
76
+ case 'amp': {
77
+ const file = pick(mcp.settings.files);
78
+ let existing = false;
79
+ try {
80
+ existing = jsonValue((await readFile(file, 'utf8')).replace(/^/, ''), mcp.settings.path) !== undefined;
81
+ }
82
+ catch {
83
+ existing = false;
84
+ }
85
+ if (!existing) {
86
+ const ran = await runCommand(commands, mcp.command, [], mcp.add);
87
+ if (ran)
88
+ return ran;
89
+ }
90
+ return editJson(mcp.settings);
91
+ }
92
+ case 'toml':
93
+ return editFile(mcp.file, (text) => upsertTomlServer(text, MCP_URL));
94
+ case 'yaml':
95
+ return editFile(mcp.file, (text) => upsertYamlExtension(text, { type: 'streamable_http', name: NAME, enabled: true, uri: MCP_URL, headers: {}, env_keys: [], envs: {}, timeout: 300 }));
96
+ case 'crush':
97
+ return isFile(mcp.rc) ? editFile(mcp.rc, (text) => upsertCrushrc(text, MCP_URL)) : editJson(mcp.settings);
98
+ case 'opencode':
99
+ return editFile(pick(mcp.files), (text) => {
100
+ const v2 = jsonValue(text, ['mcp', 'servers']);
101
+ const path = v2 !== null && typeof v2 === 'object' && !Array.isArray(v2) ? ['mcp', 'servers', NAME] : ['mcp', NAME];
102
+ return setJson(text, path, { type: 'remote', url: MCP_URL }, OPENCODE_SEED);
103
+ });
104
+ }
105
+ }
106
+ async function installInstructions(agent) {
107
+ const { instructions } = agent;
108
+ if (!instructions)
109
+ return null;
110
+ if (instructions.kind !== 'opencode') {
111
+ return editFile(instructions.file, instructions.kind === 'block' ? (text) => upsertBlock(text, INSTRUCTIONS) : () => INSTRUCTIONS);
112
+ }
113
+ const { file, settings } = instructions;
114
+ const written = await editFile(file, () => INSTRUCTIONS);
115
+ if (!written.ok)
116
+ return written;
117
+ const listed = await editFile(pick(settings), (text) => appendJsonArray(text, 'instructions', file, OPENCODE_SEED));
118
+ return listed.ok ? written : listed;
119
+ }
120
+ const outcome = (agent, item, step) => ({
121
+ agent,
122
+ item,
123
+ status: step.ok ? 'installed' : 'failed',
124
+ ...(step.path ? { path: step.path } : {}),
125
+ ...(step.command ? { command: step.command } : {}),
126
+ ...(!step.ok ? { code: step.code, ...(step.detail ? { detail: step.detail } : {}) } : {})
127
+ });
128
+ export async function installAgentFiles(env, commands, onStep = () => { }) {
129
+ const skills = new Map();
130
+ const outcomes = [];
131
+ for (const agent of agentTargets(env).filter(({ dir }) => isDirectory(dir))) {
132
+ onStep(agent.id, 'skill');
133
+ for (const root of agent.skills) {
134
+ const file = join(root, NAME, 'SKILL.md');
135
+ if (!skills.has(file))
136
+ skills.set(file, editFile(file, () => SKILL));
137
+ outcomes.push(outcome(agent.id, 'skill', await skills.get(file)));
138
+ }
139
+ onStep(agent.id, 'instructions');
140
+ const instructions = await installInstructions(agent);
141
+ outcomes.push(instructions ? outcome(agent.id, 'instructions', instructions) : { agent: agent.id, item: 'instructions', status: 'unsupported' });
142
+ onStep(agent.id, 'mcp');
143
+ outcomes.push(outcome(agent.id, 'mcp', await installMcp(agent, commands)));
144
+ }
145
+ return outcomes;
146
+ }
147
+ export function systemCommands(env) {
148
+ const windows = env.platform === 'win32';
149
+ const extensions = windows ? (env.vars.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean) : [''];
150
+ const directories = (env.vars.PATH ?? '').split(windows ? ';' : ':').filter((dir) => dir && isAbsolute(dir) && !/[\\/]node_modules([\\/]|$)/.test(dir));
151
+ const executable = (path) => {
152
+ if (!isFile(path))
153
+ return false;
154
+ if (windows)
155
+ return true;
156
+ try {
157
+ accessSync(path, constants.X_OK);
158
+ return true;
159
+ }
160
+ catch {
161
+ return false;
162
+ }
163
+ };
164
+ return {
165
+ find(name) {
166
+ for (const dir of directories) {
167
+ for (const extension of extensions) {
168
+ const path = join(dir, `${name}${extension.toLowerCase()}`);
169
+ if (executable(path))
170
+ return path;
171
+ }
172
+ }
173
+ return null;
174
+ },
175
+ run(path, args) {
176
+ const options = { stdio: ['ignore', 'pipe', 'pipe'], timeout: 60_000, windowsHide: true };
177
+ const child = windows && /\.(cmd|bat)$/i.test(path)
178
+ ? spawn(`"${path}" ${args.join(' ')}`, { ...options, shell: true })
179
+ : spawn(path, args, options);
180
+ let stdout = '';
181
+ let stderr = '';
182
+ child.stdout?.setEncoding('utf8').on('data', (chunk) => { stdout += chunk; });
183
+ child.stderr?.setEncoding('utf8').on('data', (chunk) => { stderr += chunk; });
184
+ return new Promise((resolve) => {
185
+ child.on('error', (error) => resolve({ status: null, output: error.message.slice(-500) }));
186
+ child.on('close', (status) => resolve({ status, output: `${stderr}${stdout}`.trim().slice(-500) }));
187
+ });
188
+ }
189
+ };
190
+ }
@@ -0,0 +1,20 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { NAME, SKILL } from "./content.js";
4
+ import { agentTargets } from "./targets.js";
5
+ const BOM = '\uFEFF';
6
+ export async function refreshSkills(env) {
7
+ const files = [...new Set(agentTargets(env).flatMap(({ skills }) => skills.map((root) => join(root, NAME, 'SKILL.md'))))];
8
+ const updated = [];
9
+ for (const file of files) {
10
+ const text = await readFile(file, 'utf8').catch(() => null);
11
+ if (text === null)
12
+ continue;
13
+ const bom = text.startsWith(BOM) ? BOM : '';
14
+ if (text.slice(bom.length) === SKILL)
15
+ continue;
16
+ if (await writeFile(file, bom + SKILL).then(() => true, () => false))
17
+ updated.push(file);
18
+ }
19
+ return updated;
20
+ }
@@ -0,0 +1,29 @@
1
+ import { jsonLine } from "../output.js";
2
+ import { MCP_URL, NAME } from "./content.js";
3
+ import { installAgentFiles } from "./install.js";
4
+ const COMMAND = 'agents-setup';
5
+ const label = ({ agent, item, code, path, command, detail }) => `- ${agent} ${item}: ${code}${path ? ` (${path})` : command ? ` (${command})` : ''}${detail ? ` ${detail.split('\n')[0]}` : ''}`;
6
+ export async function runAgentSetup(env, commands, uid, onStep) {
7
+ if (uid === 0 && env.vars.SUDO_USER) {
8
+ return {
9
+ code: 0,
10
+ stdout: jsonLine({ ok: true, command: COMMAND, agents: [], outcomes: [], warning: { code: 'sudo_skipped', message: 'Run the install script again without sudo to add the agent settings.' } }),
11
+ stderr: 'Skipped agent setup: running under sudo, so files in your home were not changed. Run the install script again without sudo to add them.\n'
12
+ };
13
+ }
14
+ const outcomes = await installAgentFiles(env, commands, onStep);
15
+ const agents = [...new Set(outcomes.map(({ agent }) => agent))];
16
+ const failed = outcomes.filter(({ status }) => status === 'failed');
17
+ const lines = !agents.length
18
+ ? ['No AI agent config folders found. Skipped agent setup.']
19
+ : [
20
+ `Installed skills: ${agents.join(', ')} (skill ${NAME}, global instructions, MCP ${MCP_URL})`,
21
+ ...(failed.length ? ['Some items could not be installed. The CLI is installed and ready to use.', ...failed.map(label)] : []),
22
+ 'Restart your agents to load the new skill and MCP.'
23
+ ];
24
+ return {
25
+ code: 0,
26
+ stdout: jsonLine({ ok: true, command: COMMAND, agents, outcomes, ...(failed.length ? { warning: { code: 'agent_setup_partial', failed: failed.length } } : {}) }),
27
+ stderr: `${lines.join('\n')}\n`
28
+ };
29
+ }
@@ -0,0 +1,91 @@
1
+ import { isAbsolute, join } from 'node:path';
2
+ import { MCP_URL, NAME } from "./content.js";
3
+ const absolute = (value) => (value && isAbsolute(value) ? value : undefined);
4
+ const json = (files, path, value, seed) => ({ kind: 'json', files, path, value, ...(seed ? { seed } : {}) });
5
+ const servers = (file, value) => json([file], ['mcpServers', NAME], value);
6
+ export function agentTargets({ home, platform, vars }) {
7
+ const config = absolute(vars.XDG_CONFIG_HOME) ?? join(home, '.config');
8
+ const shared = join(home, '.agents', 'skills');
9
+ const claude = absolute(vars.CLAUDE_CONFIG_DIR) ?? join(home, '.claude');
10
+ const codex = absolute(vars.CODEX_HOME) ?? join(home, '.codex');
11
+ const geminiBase = absolute(vars.GEMINI_CLI_HOME) ?? home;
12
+ const gemini = join(geminiBase, '.gemini');
13
+ const cursor = join(home, '.cursor');
14
+ const copilot = absolute(vars.COPILOT_HOME) ?? join(home, '.copilot');
15
+ const windsurf = join(home, '.codeium', 'windsurf');
16
+ const devin = platform === 'win32' && absolute(vars.APPDATA) ? join(vars.APPDATA, 'devin') : join(config, 'devin');
17
+ const opencode = join(config, 'opencode');
18
+ const crush = absolute(vars.CRUSH_GLOBAL_CONFIG) ?? join(config, 'crush');
19
+ const amp = join(home, '.config', 'amp');
20
+ const kiro = absolute(vars.KIRO_HOME) ?? join(home, '.kiro');
21
+ const gooseRoot = absolute(vars.GOOSE_PATH_ROOT);
22
+ const goose = gooseRoot ? join(gooseRoot, 'config') : platform === 'win32' && absolute(vars.APPDATA) ? join(vars.APPDATA, 'Block', 'goose', 'config') : join(home, '.config', 'goose');
23
+ const qwen = absolute(vars.QWEN_HOME) ?? join(home, '.qwen');
24
+ const command = (name, remove, add, fallback) => ({ kind: 'command', command: name, remove, add, fallback });
25
+ return [
26
+ {
27
+ id: 'claude-code', dir: claude, skills: [join(claude, 'skills')],
28
+ instructions: { kind: 'file', file: join(claude, 'rules', `${NAME}.md`) },
29
+ mcp: command('claude', ['mcp', 'remove', NAME, '--scope', 'user'], ['mcp', 'add', '--transport', 'http', '--scope', 'user', NAME, MCP_URL], null)
30
+ },
31
+ {
32
+ id: 'codex', dir: codex, skills: [shared],
33
+ instructions: { kind: 'block', file: join(codex, 'AGENTS.md') },
34
+ mcp: { kind: 'toml', file: join(codex, 'config.toml') }
35
+ },
36
+ {
37
+ id: 'gemini-cli', dir: gemini, skills: [join(geminiBase, '.agents', 'skills')],
38
+ instructions: { kind: 'block', file: join(gemini, 'GEMINI.md') },
39
+ mcp: command('gemini', ['mcp', 'remove', '--scope', 'user', NAME], ['mcp', 'add', '--scope', 'user', '--transport', 'http', NAME, MCP_URL], servers(join(gemini, 'settings.json'), { httpUrl: MCP_URL }))
40
+ },
41
+ {
42
+ id: 'cursor', dir: cursor, skills: [shared], instructions: null,
43
+ mcp: servers(join(cursor, 'mcp.json'), { url: MCP_URL })
44
+ },
45
+ {
46
+ id: 'copilot-cli', dir: copilot, skills: [shared],
47
+ instructions: { kind: 'block', file: join(copilot, 'copilot-instructions.md') },
48
+ mcp: command('copilot', ['mcp', 'remove', NAME], ['mcp', 'add', '--transport', 'http', NAME, MCP_URL], servers(join(copilot, 'mcp-config.json'), { type: 'http', url: MCP_URL, tools: ['*'] }))
49
+ },
50
+ {
51
+ id: 'windsurf', dir: windsurf, skills: [shared],
52
+ instructions: { kind: 'block', file: join(windsurf, 'memories', 'global_rules.md') },
53
+ mcp: servers(join(windsurf, 'mcp_config.json'), { serverUrl: MCP_URL })
54
+ },
55
+ {
56
+ id: 'devin', dir: devin, skills: [shared],
57
+ instructions: { kind: 'block', file: join(devin, 'AGENTS.md') },
58
+ mcp: command('devin', ['mcp', 'remove', NAME], ['mcp', 'add', '-s', 'user', NAME, MCP_URL], servers(join(devin, 'mcp_config.json'), { url: MCP_URL, transport: 'http' }))
59
+ },
60
+ {
61
+ id: 'opencode', dir: opencode, skills: [shared],
62
+ instructions: { kind: 'opencode', file: join(opencode, `${NAME}.md`), settings: [join(opencode, 'opencode.json'), join(opencode, 'opencode.jsonc')] },
63
+ mcp: { kind: 'opencode', files: [join(opencode, 'opencode.json'), join(opencode, 'opencode.jsonc')] }
64
+ },
65
+ {
66
+ id: 'crush', dir: crush, skills: [absolute(vars.CRUSH_SKILLS_DIR) ?? shared],
67
+ instructions: { kind: 'block', file: join(crush, 'CRUSH.md') },
68
+ mcp: { kind: 'crush', rc: join(crush, 'crushrc'), settings: json([join(crush, 'crush.json')], ['mcp', NAME], { type: 'http', url: MCP_URL }, '{\n "$schema": "https://charm.land/crush.json"\n}') }
69
+ },
70
+ {
71
+ id: 'amp', dir: amp, skills: [shared],
72
+ instructions: { kind: 'block', file: join(amp, 'AGENTS.md') },
73
+ mcp: { kind: 'amp', command: 'amp', add: ['mcp', 'add', NAME, MCP_URL], settings: json([join(amp, 'settings.json'), join(amp, 'settings.jsonc')], ['amp.mcpServers', NAME], { url: MCP_URL }) }
74
+ },
75
+ {
76
+ id: 'kiro', dir: kiro, skills: [join(kiro, 'skills')],
77
+ instructions: { kind: 'file', file: join(kiro, 'steering', `${NAME}.md`) },
78
+ mcp: servers(join(kiro, 'settings', 'mcp.json'), { url: MCP_URL })
79
+ },
80
+ {
81
+ id: 'goose', dir: goose, skills: [shared],
82
+ instructions: { kind: 'block', file: join(goose, '.goosehints') },
83
+ mcp: { kind: 'yaml', file: join(goose, 'config.yaml') }
84
+ },
85
+ {
86
+ id: 'qwen-code', dir: qwen, skills: [shared],
87
+ instructions: { kind: 'block', file: join(qwen, 'QWEN.md') },
88
+ mcp: command('qwen', ['mcp', 'remove', NAME], ['mcp', 'add', '--scope', 'user', '--transport', 'http', NAME, MCP_URL], servers(join(qwen, 'settings.json'), { httpUrl: MCP_URL }))
89
+ }
90
+ ];
91
+ }
@@ -0,0 +1,63 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { chmod, mkdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join, win32 } from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { allowedServer } from "../runtime/run-mode.js";
7
+ const run = promisify(execFile);
8
+ const system32 = (program) => win32.join(process.env.SystemRoot || 'C:\\Windows', 'System32', program);
9
+ let userSid;
10
+ const currentUserSid = () => userSid ??= run(system32('whoami.exe'), ['/user', '/fo', 'csv', '/nh'], { windowsHide: true })
11
+ .then(({ stdout }) => /"(S-1-[0-9-]+)"\s*$/.exec(stdout.trim())?.[1] ?? null, () => null);
12
+ async function restrictToOwner(directory) {
13
+ if (process.platform !== 'win32')
14
+ return;
15
+ const sid = await currentUserSid();
16
+ if (sid)
17
+ await run(system32('icacls.exe'), [win32.toNamespacedPath(await realpath(directory)), '/inheritance:r', '/grant:r', `*${sid}:(OI)(CI)F`], { windowsHide: true }).catch(() => { });
18
+ }
19
+ export function credentialsPath(env = process.env, home = homedir()) {
20
+ return join(env.XDG_CONFIG_HOME || join(home, '.config'), 'deepdynamic', env.DEEPDYNAMIC_DEVELOPMENT ? 'credentials.local.json' : 'credentials.json');
21
+ }
22
+ export async function readAccountEmail(path = credentialsPath()) {
23
+ try {
24
+ const credentials = JSON.parse(await readFile(path, 'utf8'));
25
+ return typeof credentials?.email === 'string' ? credentials.email : null;
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ export async function readAccessToken(path = credentialsPath()) {
32
+ try {
33
+ const credentials = JSON.parse(await readFile(path, 'utf8'));
34
+ return typeof credentials?.accessToken === 'string' && credentials.accessToken ? credentials.accessToken : null;
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ export async function readLoginSiteUrl(path = credentialsPath()) {
41
+ try {
42
+ const credentials = JSON.parse(await readFile(path, 'utf8'));
43
+ const url = typeof credentials?.siteUrl === 'string' ? new URL(credentials.siteUrl) : null;
44
+ return url && (url.protocol === 'http:' || url.protocol === 'https:') && allowedServer(url.origin) ? url.origin : null;
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }
50
+ export async function saveCredentials(credentials, path = credentialsPath()) {
51
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
52
+ await restrictToOwner(dirname(path));
53
+ const existing = await stat(path).catch(() => null);
54
+ if (existing?.isFile())
55
+ await chmod(path, existing.mode & 0o600);
56
+ await writeFile(path, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600 });
57
+ await chmod(path, 0o600);
58
+ return path;
59
+ }
60
+ export async function removeCredentials(path = credentialsPath()) {
61
+ await rm(path, { force: true });
62
+ return path;
63
+ }
@@ -0,0 +1,49 @@
1
+ import { defaultLoginDeps, login } from "../commands/login/flow.js";
2
+ import { defaultDeps, request } from "../http/request.js";
3
+ import { SITE_URL } from "../metadata.js";
4
+ import { LOCAL_SITE_URL } from "../runtime/development.js";
5
+ import { developmentRun } from "../runtime/run-mode.js";
6
+ import { readAccessToken, readLoginSiteUrl } from "./credentials.js";
7
+ export const CAPTAIN_MODE_TIMEOUT_MS = 5_000;
8
+ export const defaultAuthDeps = (pretty, depth, loginDeps) => ({
9
+ ...defaultDeps(),
10
+ signIn: (siteUrl) => login({ ...(loginDeps ?? defaultLoginDeps()), siteUrl }, pretty, depth)
11
+ });
12
+ export async function loginSiteUrl() {
13
+ return await readLoginSiteUrl() ?? (developmentRun() ? LOCAL_SITE_URL : SITE_URL);
14
+ }
15
+ export async function fetchCaptainMode(deps = { ...defaultDeps(), timeoutMs: CAPTAIN_MODE_TIMEOUT_MS }) {
16
+ const token = await readAccessToken();
17
+ if (!token)
18
+ return null;
19
+ const result = await request(new URL('/api/v1/me', await loginSiteUrl()).href, {
20
+ method: 'GET',
21
+ headers: { authorization: `Bearer ${token}` }
22
+ }, deps, null);
23
+ if ('failure' in result || result.status !== 200)
24
+ return null;
25
+ const enabled = result.body?.user?.captainMode;
26
+ return typeof enabled === 'boolean' ? enabled : null;
27
+ }
28
+ export async function signedIn(deps, renew = false) {
29
+ const saved = renew ? null : await readAccessToken();
30
+ if (saved)
31
+ return { token: saved, siteUrl: await loginSiteUrl() };
32
+ const result = await deps.signIn(await loginSiteUrl());
33
+ const token = result.code === 0 ? await readAccessToken() : null;
34
+ return token ? { token, siteUrl: await loginSiteUrl() } : { login: result };
35
+ }
36
+ export async function authorized(deps, send) {
37
+ let session = await signedIn(deps);
38
+ if ('login' in session)
39
+ return session;
40
+ let result = await send(session);
41
+ if (!('failure' in result) && result.status === 401) {
42
+ const renewed = await signedIn(deps, true);
43
+ if ('login' in renewed)
44
+ return renewed;
45
+ session = renewed;
46
+ result = await send(session);
47
+ }
48
+ return { session, result };
49
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,198 @@
1
+ import { readAccountEmail } from "./auth/credentials.js";
2
+ import { defaultAuthDeps } from "./auth/session.js";
3
+ import { runAccountDelete, runAccountGet } from "./commands/account.js";
4
+ import { runActivity } from "./commands/activity.js";
5
+ import { runBlocked } from "./commands/blocked.js";
6
+ import { runDeploy } from "./commands/deploy/index.js";
7
+ import { restoreDeployment, uploadDeployment } from "./commands/deploy/upload.js";
8
+ import { runDeployments } from "./commands/deployments.js";
9
+ import { runDnsAdd, runDnsAnalytics, runDnsDelete, runDnsDnssec, runDnsGoogle, runDnsList, runDnsRecords, runDnsRestore, runDnsSync, runDnsUpdate } from "./commands/dns.js";
10
+ import { runDomainsAutoRenew, runDomainsBuy, runDomainsList, runDomainsRegister, runDomainsRemove, runDomainsSearch, runDomainsTlds, runDomainsVerify } from "./commands/domains.js";
11
+ import { runEmailSend } from "./commands/emails.js";
12
+ import { runEnvClear, runEnvList, runEnvPush } from "./commands/env.js";
13
+ import { CLI_USAGE, runCommandHelp, runCommands, runHelp } from "./commands/help.js";
14
+ import { runKeysCreate, runKeysIssue, runKeysList, runKeysRevoke } from "./commands/keys.js";
15
+ import { defaultLoginDeps, LOGIN_TIMEOUT_MS } from "./commands/login/flow.js";
16
+ import { runLogin } from "./commands/login/index.js";
17
+ import { runLogout } from "./commands/logout.js";
18
+ import { runMailList, runMailReset, runMailSet, runMailShow } from "./commands/mail.js";
19
+ import { runNotificationsList, runNotificationsRead } from "./commands/notifications.js";
20
+ import { writeFile } from 'node:fs/promises';
21
+ import { runProjectsCreate, runProjectsDelete, runProjectsHistory, runProjectsList, runProjectsMetric, runProjectsPhotocard, runProjectsPwa, runProjectsRename, runProjectsRollback, runProjectsStatus, runProjectsStop } from "./commands/projects.js";
22
+ import { runPlanCancel, runPlanPay, runPlanResume, runPlanShow, runPlanSubscribe } from "./commands/plan.js";
23
+ import { runSearch } from "./commands/search.js";
24
+ import { runServerAutopilot, runServerList, runServerSet } from "./commands/server.js";
25
+ import { runSessionsList, runSessionsRevoke } from "./commands/sessions.js";
26
+ import { runSites } from "./commands/sites.js";
27
+ import { runSmsSend } from "./commands/sms.js";
28
+ import { runStatus } from "./commands/status.js";
29
+ import { runVerify } from "./commands/verify.js";
30
+ import { runContact, runQa } from "./commands/support.js";
31
+ import { runUpdate } from "./commands/update.js";
32
+ import { runUsage } from "./commands/usage.js";
33
+ import { runVersion } from "./commands/version.js";
34
+ import { agentResult } from "./output.js";
35
+ import { prettyResult, renderBanner, renderWordmark } from "./pretty.js";
36
+ import { commands } from "./registry.js";
37
+ import { closest } from "./runtime/suggest.js";
38
+ import { LOGIN_TIMEOUT_OPTION, parseTimeout } from "./runtime/timeout.js";
39
+ import { updateLine } from "./runtime/update-check.js";
40
+ const NAMES = commands.map(({ name }) => name);
41
+ const TOP_COMMANDS = [...new Set(NAMES.map((name) => name.split(' ')[0]))];
42
+ const TOP_OPTIONS = ['-h', '--help', '-v', '--version', '--pretty', LOGIN_TIMEOUT_OPTION];
43
+ const withDeps = (run) => (args, pretty, depth, { deps }) => run(args, pretty, depth, deps);
44
+ const actions = {
45
+ login: (args, pretty, depth, { loginDeps }) => runLogin(args, pretty, depth, loginDeps),
46
+ logout: withDeps(runLogout),
47
+ 'account get': (args, pretty, depth) => runAccountGet(args, pretty, depth),
48
+ 'account activity': withDeps(runActivity),
49
+ 'account notifications': withDeps(runNotificationsList),
50
+ 'account notifications read': withDeps(runNotificationsRead),
51
+ 'account delete': withDeps(runAccountDelete),
52
+ 'system status': (args, pretty, depth) => runStatus(args, pretty, depth),
53
+ verify: (args, pretty, depth) => runVerify(args, pretty, depth),
54
+ help: (args, pretty, depth, { version }) => runHelp(args, version, depth, pretty),
55
+ commands: (args, pretty, depth, { version }) => runCommands(args, version, depth, pretty),
56
+ update: (args, pretty, depth, { version }) => runUpdate(args, version, pretty, depth),
57
+ sites: (args, pretty, depth) => runSites(args, pretty, depth),
58
+ 'sites blocked': withDeps(runBlocked),
59
+ search: (args, pretty, depth) => runSearch(args, pretty, depth),
60
+ 'support qa': withDeps(runQa),
61
+ 'support contact': withDeps(runContact),
62
+ 'emails send': withDeps(runEmailSend),
63
+ 'sms send': withDeps(runSmsSend),
64
+ projects: withDeps(runProjectsList),
65
+ 'projects create': withDeps(runProjectsCreate),
66
+ 'projects status': withDeps(runProjectsStatus),
67
+ 'projects metric': withDeps(runProjectsMetric),
68
+ 'projects photocard': (args, pretty, depth, { deps }) => runProjectsPhotocard(args, pretty, depth, { ...deps, writeFile: (path, bytes) => writeFile(path, bytes) }),
69
+ 'projects deploy': (args, pretty, depth, { deps }) => runDeploy(args, pretty, depth, { ...deps, upload: uploadDeployment }),
70
+ 'projects env push': withDeps(runEnvPush),
71
+ 'projects env list': withDeps(runEnvList),
72
+ 'projects env clear': withDeps(runEnvClear),
73
+ deployments: withDeps(runDeployments),
74
+ 'projects history': withDeps(runProjectsHistory),
75
+ 'projects rollback': (args, pretty, depth, { deps }) => runProjectsRollback(args, pretty, depth, { ...deps, restore: restoreDeployment }),
76
+ 'projects rename': withDeps(runProjectsRename),
77
+ 'projects pwa': withDeps(runProjectsPwa),
78
+ 'projects stop': withDeps(runProjectsStop),
79
+ 'projects delete': withDeps(runProjectsDelete),
80
+ domains: withDeps(runDomainsList),
81
+ 'domains search': withDeps(runDomainsSearch),
82
+ 'domains tlds': withDeps(runDomainsTlds),
83
+ 'domains buy': withDeps(runDomainsBuy),
84
+ 'domains register': withDeps(runDomainsRegister),
85
+ 'domains verify': withDeps(runDomainsVerify),
86
+ 'domains remove': withDeps(runDomainsRemove),
87
+ 'domains auto-renew': withDeps(runDomainsAutoRenew),
88
+ dns: withDeps(runDnsList),
89
+ 'dns records': withDeps(runDnsRecords),
90
+ 'dns add': withDeps(runDnsAdd),
91
+ 'dns update': withDeps(runDnsUpdate),
92
+ 'dns delete': withDeps(runDnsDelete),
93
+ 'dns restore': withDeps(runDnsRestore),
94
+ 'dns sync': withDeps(runDnsSync),
95
+ 'dns dnssec': withDeps(runDnsDnssec),
96
+ 'dns google': withDeps(runDnsGoogle),
97
+ 'dns analytics': withDeps(runDnsAnalytics),
98
+ server: withDeps(runServerList),
99
+ 'server set': withDeps(runServerSet),
100
+ 'server autopilot': withDeps(runServerAutopilot),
101
+ plan: withDeps(runPlanShow),
102
+ 'plan subscribe': withDeps(runPlanSubscribe),
103
+ 'plan cancel': withDeps(runPlanCancel),
104
+ 'plan resume': withDeps(runPlanResume),
105
+ 'plan pay': withDeps(runPlanPay),
106
+ usage: withDeps(runUsage),
107
+ keys: withDeps(runKeysList),
108
+ 'keys issue': withDeps(runKeysIssue),
109
+ 'keys create': withDeps(runKeysCreate),
110
+ 'keys revoke': withDeps(runKeysRevoke),
111
+ sessions: withDeps(runSessionsList),
112
+ 'sessions revoke': withDeps(runSessionsRevoke),
113
+ mail: withDeps(runMailList),
114
+ 'mail show': withDeps(runMailShow),
115
+ 'mail set': withDeps(runMailSet),
116
+ 'mail reset': withDeps(runMailReset)
117
+ };
118
+ const isName = (name) => NAMES.includes(name);
119
+ export async function run(args, version, depth, loginDeps, update = null) {
120
+ const pretty = args.includes('--pretty');
121
+ const commandArgs = args.filter((arg) => arg !== '--pretty');
122
+ const timeout = parseTimeout(commandArgs, LOGIN_TIMEOUT_MS / 1000, LOGIN_TIMEOUT_OPTION, 1);
123
+ const result = 'error' in timeout
124
+ ? pretty
125
+ ? prettyResult(2, depth, LOGIN_TIMEOUT_OPTION, timeout.error, [['Usage', CLI_USAGE]])
126
+ : agentResult(2, { error: { code: 'invalid_arguments', message: timeout.error }, usage: CLI_USAGE })
127
+ : await dispatch(timeout.rest, version, depth, pretty, timeout.rest.length < commandArgs.length ? { ...(loginDeps ?? defaultLoginDeps()), timeoutMs: timeout.waitMs } : loginDeps);
128
+ const notice = update?.event === 'update_available' && !('error' in timeout) && timeout.rest[0] === 'update' ? null : update;
129
+ if (!pretty)
130
+ return notice ? { ...result, stderr: result.stderr + updateLine(version, notice) } : result;
131
+ const wordmark = !('error' in timeout) && isHome(timeout.rest) ? renderWordmark(depth) : '';
132
+ return { ...result, stdout: wordmark + renderBanner(version, depth, await readAccountEmail(), notice) + result.stdout };
133
+ }
134
+ function isHome([input, ...rest]) {
135
+ return input === undefined || input === '-h' || input === '--help' || (input === 'help' && rest.length === 0);
136
+ }
137
+ function unknownSubcommand(group, action, pretty, depth) {
138
+ const members = commands.filter(({ name }) => name === group || name.startsWith(`${group} `));
139
+ const subcommands = members.filter(({ name }) => name !== group).map(({ name }) => name.slice(group.length + 1));
140
+ const suggestion = action === undefined ? null : closest(action, subcommands);
141
+ return pretty
142
+ ? prettyResult(2, depth, group, action === undefined ? 'Give a subcommand.' : `Unknown subcommand: ${action}`, [
143
+ ['Usage', members.map(({ usage }) => usage).join(' | ')], ...(suggestion ? [['Did you mean', `deepdynamic ${group} ${suggestion}`]] : [])
144
+ ])
145
+ : agentResult(2, {
146
+ command: group,
147
+ error: { code: 'unknown_subcommand', message: action === undefined ? 'A subcommand is required.' : `Unknown subcommand: ${action}` },
148
+ ...(suggestion ? { suggestions: [suggestion] } : {}),
149
+ subcommands,
150
+ usage: members.map(({ usage }) => usage).join(' | ')
151
+ });
152
+ }
153
+ async function dispatch(commandArgs, version, depth, pretty, loginDeps) {
154
+ const [input, action, subaction] = commandArgs;
155
+ const context = { deps: defaultAuthDeps(pretty, depth, loginDeps), loginDeps, version };
156
+ if (input === undefined || input === '-h' || input === '--help') {
157
+ return runHelp([], version, depth, pretty);
158
+ }
159
+ const commandHelp = runCommandHelp(commandArgs, pretty, depth);
160
+ if (commandHelp) {
161
+ return commandHelp;
162
+ }
163
+ if (input === '-v' || input === '--version') {
164
+ return runVersion(version, pretty);
165
+ }
166
+ const pair = `${input} ${action}`;
167
+ const triple = `${pair} ${subaction}`;
168
+ if (subaction !== undefined && isName(triple)) {
169
+ return actions[triple](commandArgs.slice(3), pretty, depth, context);
170
+ }
171
+ if (action !== undefined && isName(pair)) {
172
+ return actions[pair](commandArgs.slice(2), pretty, depth, context);
173
+ }
174
+ if (action !== undefined && NAMES.some((name) => name.startsWith(`${pair} `))) {
175
+ return unknownSubcommand(pair, subaction, pretty, depth);
176
+ }
177
+ const grouped = NAMES.some((name) => name.startsWith(`${input} `));
178
+ if (isName(input) && (!grouped || action === undefined || action.startsWith('-'))) {
179
+ return actions[input](commandArgs.slice(1), pretty, depth, context);
180
+ }
181
+ if (grouped) {
182
+ return unknownSubcommand(input, action, pretty, depth);
183
+ }
184
+ const option = input.startsWith('-');
185
+ const suggestion = closest(input, option ? TOP_OPTIONS : TOP_COMMANDS);
186
+ if (!pretty) {
187
+ const kind = option ? 'option' : 'command';
188
+ return agentResult(2, {
189
+ error: { code: `unknown_${kind}`, message: `Unknown ${kind}: ${input}` },
190
+ ...(suggestion ? { suggestions: [suggestion] } : {}),
191
+ usage: 'deepdynamic --help'
192
+ });
193
+ }
194
+ return prettyResult(2, depth, input, `Unknown ${option ? 'option' : 'command'}: ${input}`, [
195
+ ['Help', 'deepdynamic --help'],
196
+ ...(suggestion ? [['Did you mean', option ? suggestion : `deepdynamic ${suggestion}`]] : [])
197
+ ]);
198
+ }