@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,65 @@
1
+ import { authorized, defaultAuthDeps } from "../auth/session.js";
2
+ import { LOGIN_EXPIRED, accepted, httpFailure, postJson, sendFailureError } from "../http/request.js";
3
+ import { agentResult } from "../output.js";
4
+ import { prettyResult } from "../pretty.js";
5
+ import { spec } from "../registry.js";
6
+ import { splitDryRun } from "../runtime/dry-run.js";
7
+ import { parseFlags } from "../runtime/flags.js";
8
+ import { readText } from "../runtime/text-file.js";
9
+ export const SMS_PATH = '/api/v1/sms';
10
+ const { name: command, usage } = spec('sms send');
11
+ const FLAGS = ['--to', '--body', '--body-file'];
12
+ async function parseSendArgs(args) {
13
+ const parsed = parseFlags(args, FLAGS);
14
+ if ('error' in parsed)
15
+ return parsed;
16
+ const values = Object.fromEntries(parsed.entries);
17
+ const { '--to': to, '--body': body, '--body-file': bodyFile } = values;
18
+ if (to === undefined) {
19
+ return { error: '--to is required.' };
20
+ }
21
+ const content = await readText('--body', body, bodyFile);
22
+ return 'error' in content ? content : { to, body: content.text };
23
+ }
24
+ export async function runSmsSend(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
25
+ const { args: rest, dryRun } = splitDryRun(args);
26
+ const parsed = await parseSendArgs(rest);
27
+ if ('error' in parsed) {
28
+ return pretty
29
+ ? prettyResult(2, depth, command, parsed.error, [['Usage', usage]])
30
+ : agentResult(2, { command, error: { code: 'invalid_arguments', message: parsed.error }, usage });
31
+ }
32
+ const sent = await authorized(deps, ({ siteUrl, token }) => postJson(new URL(SMS_PATH, siteUrl).href, token, dryRun ? { ...parsed, dryRun } : parsed, deps, pretty ? (dryRun ? 'Validating the SMS.' : 'Sending the SMS.') : null));
33
+ if ('login' in sent)
34
+ return sent.login;
35
+ const { session: { siteUrl }, result } = sent;
36
+ let failure = null;
37
+ let rejected = false;
38
+ if ('failure' in result) {
39
+ failure = result.failure;
40
+ }
41
+ else if (result.status === 401) {
42
+ failure = LOGIN_EXPIRED;
43
+ }
44
+ else if (!accepted(result)) {
45
+ rejected = result.status === 400 && result.body?.rejected === true;
46
+ failure = rejected
47
+ ? { code: 'spam_rejected', message: 'The server rejected the message as advertising or spam. The account may be blocked if this continues.', display: 'The server rejected the message as advertising or spam. The account may be blocked if this continues.' }
48
+ : result.status === 400
49
+ ? { code: 'rejected', message: 'The server rejected the message. Check the recipient and body.', display: 'The server rejected the message. Check the recipient and body.' }
50
+ : httpFailure(result.status);
51
+ }
52
+ if (failure) {
53
+ return pretty
54
+ ? prettyResult(1, depth, command, rejected ? 'The SMS was rejected.' : dryRun ? 'Could not validate the SMS.' : 'Could not send the SMS.', [['Server', siteUrl], ['Reason', failure.display]])
55
+ : agentResult(1, { command, siteUrl, delivered: false, ...(rejected ? { rejected } : {}), error: sendFailureError(result, failure) });
56
+ }
57
+ const { dryRun: checked, delivered, id, to } = result.body;
58
+ if (!pretty) {
59
+ return agentResult(0, { command, siteUrl, ...(checked === true ? { dryRun: true } : {}), delivered, rejected, id, to });
60
+ }
61
+ return prettyResult(0, depth, command, checked === true ? 'Validated the SMS. Nothing was sent.' : 'Sent the SMS.', [
62
+ ['Server', siteUrl],
63
+ ['To', to]
64
+ ]);
65
+ }
@@ -0,0 +1,87 @@
1
+ import { readLoginSiteUrl } from "../auth/credentials.js";
2
+ import { call } from "../http/call.js";
3
+ import { UNEXPECTED, failureError, httpFailure } from "../http/request.js";
4
+ import { SITE_URL } from "../metadata.js";
5
+ import { agentResult } from "../output.js";
6
+ import { prettyResult } from "../pretty.js";
7
+ import { spec } from "../registry.js";
8
+ import { plannedRequest, splitDryRun } from "../runtime/dry-run.js";
9
+ import { parseServerArgs } from "../runtime/server-options.js";
10
+ import { startSpinner } from "../runtime/spinner.js";
11
+ import { supportFailure } from "../runtime/support.js";
12
+ const { name: command, usage } = spec('system status');
13
+ const BACKEND_UNAVAILABLE = supportFailure('backend_unavailable');
14
+ async function checkBackend(siteUrl, signal, fetcher) {
15
+ try {
16
+ const response = await call(new URL('/api/v1/status/backend', siteUrl).href, { method: 'GET', redirect: 'manual', signal }, fetcher);
17
+ const body = await response.json().catch(() => null);
18
+ return response.status === 200 && body?.status === 'ok' ? 'ok' : 'unavailable';
19
+ }
20
+ catch {
21
+ return 'unavailable';
22
+ }
23
+ }
24
+ export async function runStatus(args, pretty, depth, deps = { fetch, stream: process.stderr, timeoutMs: 10_000 }) {
25
+ const { args: rest, dryRun } = splitDryRun(args);
26
+ const options = parseServerArgs(rest);
27
+ if ('error' in options) {
28
+ return pretty
29
+ ? prettyResult(2, depth, command, options.error, [['Usage', usage]])
30
+ : agentResult(2, {
31
+ command,
32
+ error: { code: 'invalid_arguments', message: options.error },
33
+ usage
34
+ });
35
+ }
36
+ const siteUrl = options.siteUrl ?? await readLoginSiteUrl() ?? SITE_URL;
37
+ if (dryRun)
38
+ return plannedRequest(command, pretty, depth, siteUrl, new URL('/api/v1/status', siteUrl).href);
39
+ const stop = pretty ? startSpinner('Connecting to the deployment server.', deps.stream) : () => { };
40
+ const controller = new AbortController();
41
+ const timer = setTimeout(() => controller.abort(), deps.timeoutMs);
42
+ let httpStatus = null;
43
+ let backend = null;
44
+ let failure = null;
45
+ try {
46
+ const response = await call(new URL('/api/v1/status', siteUrl).href, {
47
+ method: 'GET',
48
+ redirect: 'manual',
49
+ signal: controller.signal
50
+ }, deps.fetch);
51
+ httpStatus = response.status;
52
+ if (response.status !== 200) {
53
+ await response.body?.cancel();
54
+ failure = httpFailure(response.status);
55
+ }
56
+ else if (await response.text() !== 'OK') {
57
+ failure = UNEXPECTED;
58
+ }
59
+ else {
60
+ backend = await checkBackend(siteUrl, controller.signal, deps.fetch);
61
+ if (backend === 'unavailable')
62
+ failure = BACKEND_UNAVAILABLE;
63
+ }
64
+ }
65
+ catch {
66
+ failure = controller.signal.aborted
67
+ ? { code: 'connection_timeout', message: 'The connection timed out.', display: 'The server did not respond in time.' }
68
+ : { code: 'connection_failed', message: 'Could not connect to the deployment server.', display: 'Check the server URL and your network connection.' };
69
+ }
70
+ finally {
71
+ clearTimeout(timer);
72
+ stop();
73
+ }
74
+ if (!pretty) {
75
+ return agentResult(failure ? 1 : 0, {
76
+ command,
77
+ siteUrl,
78
+ httpStatus,
79
+ backend,
80
+ ...(failure ? { error: failureError(failure) } : {})
81
+ });
82
+ }
83
+ if (!failure)
84
+ return prettyResult(0, depth, command, 'Connected to the deployment server.', [['Server', siteUrl], ['Services', 'OK']]);
85
+ const target = backend === 'unavailable' ? 'the services' : 'the deployment server';
86
+ return prettyResult(1, depth, command, `Could not connect to ${target}.`, [['Server', siteUrl], ['Reason', failure.display]]);
87
+ }
@@ -0,0 +1,115 @@
1
+ import { readAccountEmail, readLoginSiteUrl } from "../auth/credentials.js";
2
+ import { authorized, defaultAuthDeps } from "../auth/session.js";
3
+ import { LOGIN_EXPIRED, UNEXPECTED, accepted, defaultDeps, failureError, httpFailure, postJson, request, sendFailureError } from "../http/request.js";
4
+ import { SITE_URL } from "../metadata.js";
5
+ import { agentResult } from "../output.js";
6
+ import { prettyResult } from "../pretty.js";
7
+ import { parseFlags } from "../runtime/flags.js";
8
+ import { spec } from "../registry.js";
9
+ import { plannedRequest, splitDryRun } from "../runtime/dry-run.js";
10
+ import { readText } from "../runtime/text-file.js";
11
+ import { parseServerArgs } from "../runtime/server-options.js";
12
+ export const CONTACT_PATH = '/api/v1/ai/contact';
13
+ const QA = spec('support qa');
14
+ const CONTACT = spec('support contact');
15
+ const CONTACT_FLAGS = ['--message', '--message-file', '--team'];
16
+ function isGuide(body) {
17
+ return typeof body === 'object' && body !== null && Array.isArray(body.faq);
18
+ }
19
+ export async function runQa(args, pretty, depth, deps = defaultDeps()) {
20
+ const command = QA.name;
21
+ const { args: rest, dryRun } = splitDryRun(args);
22
+ const options = parseServerArgs(rest);
23
+ if ('error' in options) {
24
+ return pretty
25
+ ? prettyResult(2, depth, command, options.error, [['Usage', QA.usage]])
26
+ : agentResult(2, { command, error: { code: 'invalid_arguments', message: options.error }, usage: QA.usage });
27
+ }
28
+ const siteUrl = options.siteUrl ?? await readLoginSiteUrl() ?? SITE_URL;
29
+ if (dryRun)
30
+ return plannedRequest(command, pretty, depth, siteUrl, new URL(CONTACT_PATH, siteUrl).href);
31
+ const result = await request(new URL(CONTACT_PATH, siteUrl).href, { method: 'GET' }, deps, pretty ? 'Loading the FAQ.' : null);
32
+ if ('failure' in result || result.status !== 200 || !isGuide(result.body)) {
33
+ const failure = 'failure' in result
34
+ ? result.failure
35
+ : result.status !== 200
36
+ ? httpFailure(result.status)
37
+ : UNEXPECTED;
38
+ return pretty
39
+ ? prettyResult(1, depth, command, 'Could not load the FAQ.', [['Server', siteUrl], ['Reason', failure.display]])
40
+ : agentResult(1, { command, siteUrl, error: failureError(failure) });
41
+ }
42
+ const guide = result.body;
43
+ if (!pretty) {
44
+ return agentResult(0, { command, siteUrl, ...guide, send: CONTACT.usage });
45
+ }
46
+ return prettyResult(0, depth, command, 'Loaded the FAQ.', [
47
+ ...guide.faq.flatMap(({ question, answer }, index) => [
48
+ [`Q${index + 1}`, question.en],
49
+ ['', answer.en]
50
+ ]),
51
+ ['Contact', 'deepdynamic support contact --message <text>']
52
+ ]);
53
+ }
54
+ async function parseContactArgs(args) {
55
+ const parsed = parseFlags(args, CONTACT_FLAGS);
56
+ if ('error' in parsed)
57
+ return parsed;
58
+ let message;
59
+ let messageFile;
60
+ const teamEmails = [];
61
+ for (const [flag, value] of parsed.entries) {
62
+ if (flag === '--message')
63
+ message = value;
64
+ else if (flag === '--message-file')
65
+ messageFile = value;
66
+ else
67
+ teamEmails.push(value);
68
+ }
69
+ const content = await readText('--message', message, messageFile);
70
+ return 'error' in content ? content : { message: content.text, teamEmails };
71
+ }
72
+ export async function runContact(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
73
+ const command = CONTACT.name;
74
+ const { args: rest, dryRun } = splitDryRun(args);
75
+ const parsed = await parseContactArgs(rest);
76
+ if ('error' in parsed) {
77
+ return pretty
78
+ ? prettyResult(2, depth, command, parsed.error, [['Usage', CONTACT.usage]])
79
+ : agentResult(2, { command, error: { code: 'invalid_arguments', message: parsed.error }, usage: CONTACT.usage });
80
+ }
81
+ const sent = await authorized(deps, ({ siteUrl, token }) => postJson(new URL(CONTACT_PATH, siteUrl).href, token, { message: parsed.message, ...(parsed.teamEmails.length ? { teamEmails: parsed.teamEmails } : {}), ...(dryRun ? { dryRun } : {}) }, deps, pretty ? (dryRun ? 'Validating the inquiry.' : 'Sending the inquiry.') : null));
82
+ if ('login' in sent)
83
+ return sent.login;
84
+ const { session: { siteUrl }, result } = sent;
85
+ let failure = null;
86
+ if ('failure' in result) {
87
+ failure = result.failure;
88
+ }
89
+ else if (result.status === 401) {
90
+ failure = LOGIN_EXPIRED;
91
+ }
92
+ else if (!accepted(result)) {
93
+ failure = result.status === 429
94
+ ? { code: 'rate_limited', message: 'Too many inquiries. Try again later.', display: 'Too many inquiries. Try again later.' }
95
+ : result.status === 400
96
+ ? { code: 'rejected', message: 'The server rejected the inquiry. Check the message and team emails.', display: 'The server rejected the inquiry. Check the message and team emails.' }
97
+ : httpFailure(result.status);
98
+ }
99
+ if (failure) {
100
+ return pretty
101
+ ? prettyResult(1, depth, command, dryRun ? 'Could not validate the inquiry.' : 'Could not send the inquiry.', [['Server', siteUrl], ['Reason', failure.display]])
102
+ : agentResult(1, { command, siteUrl, error: sendFailureError(result, failure) });
103
+ }
104
+ const { id, dryRun: checked } = result.body;
105
+ const email = await readAccountEmail();
106
+ if (checked === true) {
107
+ return pretty
108
+ ? prettyResult(0, depth, command, 'Validated the inquiry. Nothing was sent.', [['Server', siteUrl]])
109
+ : agentResult(0, { command, siteUrl, dryRun: true, replyTo: email });
110
+ }
111
+ if (!pretty) {
112
+ return agentResult(0, { command, siteUrl, id: typeof id === 'string' ? id : null, replyTo: email });
113
+ }
114
+ return prettyResult(0, depth, command, 'Sent the inquiry. Replies go to the account email.', [['Server', siteUrl], ['Reply to', email ?? 'The logged-in account']]);
115
+ }
@@ -0,0 +1,100 @@
1
+ import { defaultDeps, failureError, request } from "../http/request.js";
2
+ import { agentResult } from "../output.js";
3
+ import { prettyResult } from "../pretty.js";
4
+ import { confirmationRequired, splitYes } from "../runtime/confirm.js";
5
+ import { splitDryRun } from "../runtime/dry-run.js";
6
+ import { unknownArgument } from "../runtime/flags.js";
7
+ import { startSpinner } from "../runtime/spinner.js";
8
+ import { REGISTRY_URL, isNewer, latestOf, saveUpdateCache, startSkillRefresh, updateCachePath, updateLockPath, withUpdateLock } from "../runtime/update-check.js";
9
+ import { PACKAGE_DIR, findPackageManager, installArgs, packageManagerOf, runProgram } from "../runtime/update-install.js";
10
+ import { usageError } from "../runtime/usage-error.js";
11
+ const command = 'update';
12
+ export const defaultUpdateCommandDeps = () => ({
13
+ ...defaultDeps(),
14
+ cachePath: updateCachePath(),
15
+ now: Date.now,
16
+ packageManager: packageManagerOf(PACKAGE_DIR),
17
+ find: findPackageManager,
18
+ install: runProgram,
19
+ refreshSkills: startSkillRefresh
20
+ });
21
+ const registryFailure = (status) => ({
22
+ code: 'http_error',
23
+ message: 'The npm registry answered with an error.',
24
+ display: 'The npm registry returned an error. Try again later.',
25
+ retryable: status >= 500 || status === 429
26
+ });
27
+ const REGISTRY_UNEXPECTED = {
28
+ code: 'unexpected_response',
29
+ message: 'The npm registry did not return the latest version.',
30
+ display: 'The npm registry did not return the latest version.'
31
+ };
32
+ const UPDATE_IN_PROGRESS = {
33
+ code: 'update_in_progress',
34
+ message: 'An automatic update is running in the background. Retry in a minute.',
35
+ display: 'An automatic update is running in the background. Retry in a minute.',
36
+ retryable: true
37
+ };
38
+ function failed(failure, pretty, depth, data, rows = [], detail) {
39
+ return pretty
40
+ ? prettyResult(1, depth, command, failure.display, rows)
41
+ : agentResult(1, { command, ...data, error: { ...failureError(failure), ...(detail === undefined ? {} : { detail }) } });
42
+ }
43
+ export async function runUpdate(args, current, pretty, depth, deps = defaultUpdateCommandDeps()) {
44
+ const { args: withoutYes, yes } = splitYes(args);
45
+ const { args: rest, dryRun } = splitDryRun(withoutYes);
46
+ if (rest.length)
47
+ return usageError(command, unknownArgument(rest[0]), pretty, depth);
48
+ const manager = deps.packageManager;
49
+ if (dryRun) {
50
+ return pretty
51
+ ? prettyResult(0, depth, command, 'Checked without sending the request or installing.', [['Current', current], ['Request', `GET ${REGISTRY_URL}`], ['Install', `${manager} ${installArgs(manager, '<latest-version>').join(' ')}`]])
52
+ : agentResult(0, { command, current, packageManager: manager, dryRun: true, request: { method: 'GET', url: REGISTRY_URL } });
53
+ }
54
+ const response = await request(REGISTRY_URL, { method: 'GET' }, deps, pretty ? 'Checking for the latest version.' : null);
55
+ const latest = 'failure' in response || response.status !== 200 ? null : latestOf(response.body);
56
+ if (!latest) {
57
+ const failure = 'failure' in response ? response.failure : response.status !== 200 ? registryFailure(response.status) : REGISTRY_UNEXPECTED;
58
+ return failed(failure, pretty, depth, { current }, [['Current', current]]);
59
+ }
60
+ await saveUpdateCache(deps.cachePath, { checkedAt: deps.now(), latest }).catch(() => { });
61
+ if (!isNewer(latest, current)) {
62
+ return pretty
63
+ ? prettyResult(0, depth, command, 'Already on the latest version.', [['Current', current], ['Latest', latest]])
64
+ : agentResult(0, { command, current, latest, packageManager: manager, updated: false });
65
+ }
66
+ const argv = installArgs(manager, latest);
67
+ const install = `${manager} ${argv.join(' ')}`;
68
+ const data = { current, latest, packageManager: manager, install };
69
+ const rows = [['Current', current], ['Latest', latest], ['Install', install]];
70
+ if (!yes) {
71
+ return confirmationRequired(command, args, pretty, depth, {
72
+ message: `DeepDynamic CLI ${latest} is available (current ${current}). The update runs: ${install}.`,
73
+ display: `A new version is available (current ${current}, latest ${latest}). Updating runs ${install}.`
74
+ }, data);
75
+ }
76
+ const path = await deps.find(manager);
77
+ if (!path) {
78
+ return failed({
79
+ code: 'package_manager_not_found',
80
+ message: `${manager} was not found on PATH. Update the CLI with the package manager that installed it, for example: ${install}`,
81
+ display: `${manager} was not found on PATH. Update the CLI with the package manager that installed it.`
82
+ }, pretty, depth, data, rows);
83
+ }
84
+ const stop = pretty ? startSpinner(`Installing the latest version (${latest}).`, deps.stream) : () => { };
85
+ const installed = await withUpdateLock(updateLockPath(deps.cachePath), () => deps.install(path, argv), deps.now);
86
+ stop();
87
+ if (!installed)
88
+ return failed(UPDATE_IN_PROGRESS, pretty, depth, data, rows);
89
+ if (installed.status !== 0) {
90
+ return failed({
91
+ code: 'update_failed',
92
+ message: `${install} failed. Read error.detail, fix the cause (for example permissions of the global folder) or run the command yourself.`,
93
+ display: `${manager} failed to install the update. Check the output below or run the install command yourself.`
94
+ }, pretty, depth, data, [...rows, [manager, installed.output]], installed.output);
95
+ }
96
+ deps.refreshSkills();
97
+ return pretty
98
+ ? prettyResult(0, depth, command, `Updated ${current} → ${latest}.`, [['Previous', current], ['Current', latest]])
99
+ : agentResult(0, { command, current, latest, packageManager: manager, updated: true });
100
+ }
@@ -0,0 +1,51 @@
1
+ import { defaultAuthDeps } from "../auth/session.js";
2
+ import { httpFailure } from "../http/request.js";
3
+ import { agentResult } from "../output.js";
4
+ import { prettyResult } from "../pretty.js";
5
+ import { plannedRequest } from "../runtime/dry-run.js";
6
+ import { unknownArgument } from "../runtime/flags.js";
7
+ import { spec } from "../registry.js";
8
+ import { supportFailure } from "../runtime/support.js";
9
+ import { rehearsed } from "./dns.js";
10
+ export const USAGE_PATH = '/api/v1/usage';
11
+ const { name: command } = spec('usage');
12
+ const UNAVAILABLE = supportFailure('unavailable');
13
+ const STEPS = [
14
+ { stage: 'check_options', message: 'Checking the options.' },
15
+ { stage: 'prepare_request', message: 'Preparing the usage request.' }
16
+ ];
17
+ const count = (value) => value.toLocaleString('en-US');
18
+ const channelText = ({ limit, used, remaining }) => `${count(used)} / ${count(limit)} sent · ${count(remaining)} left`;
19
+ function shown(pretty, depth, body, siteUrl) {
20
+ const { plan, period, resetsAt, sms, email, daily } = body;
21
+ if (!pretty)
22
+ return agentResult(0, { command, siteUrl, plan, period, resetsAt, sms, email, daily });
23
+ return prettyResult(0, depth, command, `Loaded the sending usage for ${period}.`, [
24
+ ['Server', siteUrl],
25
+ ['Plan', plan],
26
+ ['SMS', channelText(sms)],
27
+ ['Email', channelText(email)],
28
+ ['Resets', `${resetsAt.slice(0, 10)} 00:00 KST`]
29
+ ]);
30
+ }
31
+ export async function runUsage(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
32
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
33
+ if (rest.length)
34
+ return { error: unknownArgument(rest[0]) };
35
+ const url = (siteUrl) => new URL(USAGE_PATH, siteUrl).href;
36
+ return {
37
+ steps: STEPS,
38
+ result: (siteUrl) => plannedRequest(command, pretty, depth, siteUrl, url(siteUrl)),
39
+ send: {
40
+ method: 'GET',
41
+ url,
42
+ spinner: 'Loading the usage.',
43
+ failed: 'Could not load the usage.',
44
+ notFound: httpFailure(404),
45
+ failures: { unavailable: UNAVAILABLE },
46
+ succeeded: ({ status }) => status === 200,
47
+ done: (body, siteUrl) => shown(pretty, depth, body, siteUrl)
48
+ }
49
+ };
50
+ });
51
+ }
@@ -0,0 +1,149 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, writeFile } from 'node:fs/promises';
3
+ import { readLoginSiteUrl } from "../auth/credentials.js";
4
+ import { call } from "../http/call.js";
5
+ import { UNEXPECTED, failureError, httpFailure } from "../http/request.js";
6
+ import { SITE_URL } from "../metadata.js";
7
+ import { agentResult } from "../output.js";
8
+ import { prettyResult } from "../pretty.js";
9
+ import { spec } from "../registry.js";
10
+ import { plannedRequest, splitDryRun } from "../runtime/dry-run.js";
11
+ import { parseServerArgs } from "../runtime/server-options.js";
12
+ import { startSpinner } from "../runtime/spinner.js";
13
+ import { supportFailure } from "../runtime/support.js";
14
+ export const FILE_OPTION = '--file';
15
+ export const SAVE_OPTION = '--save';
16
+ export const MANIFEST_PATH = '/api/v1/sdk/manifest';
17
+ const { name: command, usage } = spec('verify');
18
+ const MISMATCH = supportFailure('integrity_mismatch', { note: 'Nothing was saved.' });
19
+ export const integrityOf = (bytes) => `sha384-${createHash('sha384').update(bytes).digest('base64')}`;
20
+ function splitPaths(args) {
21
+ const rest = [];
22
+ const paths = { [FILE_OPTION]: null, [SAVE_OPTION]: null };
23
+ for (let index = 0; index < args.length; index++) {
24
+ const arg = args[index];
25
+ const option = [FILE_OPTION, SAVE_OPTION].find((name) => arg === name || arg.startsWith(`${name}=`));
26
+ if (!option) {
27
+ rest.push(arg);
28
+ continue;
29
+ }
30
+ const value = arg === option ? args[++index] : arg.slice(option.length + 1);
31
+ if (!value?.trim())
32
+ return { error: `${option} requires a path.` };
33
+ paths[option] = value;
34
+ }
35
+ return { args: rest, file: paths[FILE_OPTION], save: paths[SAVE_OPTION] };
36
+ }
37
+ function readScript(body, siteUrl) {
38
+ const script = body?.scripts?.[0];
39
+ if (!script)
40
+ return null;
41
+ const { client, src, integrity, download } = script;
42
+ if ([client, src, integrity, download].some((value) => typeof value !== 'string'))
43
+ return null;
44
+ const served = URL.canParse(download) ? new URL(download) : null;
45
+ const site = new URL(siteUrl);
46
+ if (served?.protocol !== site.protocol || served.origin !== site.origin)
47
+ return null;
48
+ return { client, src, integrity, download };
49
+ }
50
+ export async function runVerify(args, pretty, depth, deps = { fetch, stream: process.stderr, timeoutMs: 10_000, readFile: (path) => readFile(path), writeFile: (path, bytes) => writeFile(path, bytes) }) {
51
+ const { args: withoutDryRun, dryRun } = splitDryRun(args);
52
+ const split = splitPaths(withoutDryRun);
53
+ const options = 'error' in split ? split : parseServerArgs(split.args);
54
+ if ('error' in options) {
55
+ return pretty
56
+ ? prettyResult(2, depth, command, options.error, [['Usage', usage]])
57
+ : agentResult(2, { command, error: { code: 'invalid_arguments', message: options.error }, usage });
58
+ }
59
+ const file = 'file' in split ? split.file : null;
60
+ const save = 'save' in split ? split.save : null;
61
+ const siteUrl = options.siteUrl ?? await readLoginSiteUrl() ?? SITE_URL;
62
+ const manifestUrl = new URL(MANIFEST_PATH, siteUrl).href;
63
+ if (dryRun)
64
+ return plannedRequest(command, pretty, depth, siteUrl, manifestUrl);
65
+ const stop = pretty ? startSpinner('Checking the script manifest.', deps.stream) : () => { };
66
+ const controller = new AbortController();
67
+ const timer = setTimeout(() => controller.abort(), deps.timeoutMs);
68
+ let script = null;
69
+ let served = null;
70
+ let local = null;
71
+ let saved = null;
72
+ let failure = null;
73
+ try {
74
+ const response = await call(manifestUrl, { method: 'GET', redirect: 'manual', signal: controller.signal }, deps.fetch);
75
+ if (response.status !== 200) {
76
+ await response.body?.cancel();
77
+ failure = httpFailure(response.status);
78
+ }
79
+ else {
80
+ script = readScript(await response.json().catch(() => null), siteUrl);
81
+ if (!script)
82
+ failure = UNEXPECTED;
83
+ }
84
+ if (script) {
85
+ const download = await call(script.download, { method: 'GET', redirect: 'manual', signal: controller.signal }, deps.fetch);
86
+ if (download.status !== 200) {
87
+ await download.body?.cancel();
88
+ failure = httpFailure(download.status);
89
+ }
90
+ else {
91
+ const bytes = new Uint8Array(await download.arrayBuffer());
92
+ const integrity = integrityOf(bytes);
93
+ served = { integrity, matches: integrity === script.integrity };
94
+ if (save !== null && served.matches) {
95
+ try {
96
+ await deps.writeFile(save, bytes);
97
+ saved = { path: save, bytes: bytes.byteLength };
98
+ }
99
+ catch {
100
+ failure = { code: 'save_failed', message: `Could not write ${save}.`, display: `Could not write ${save}.` };
101
+ }
102
+ }
103
+ }
104
+ }
105
+ if (script && file !== null) {
106
+ try {
107
+ const integrity = integrityOf(await deps.readFile(file));
108
+ local = { path: file, integrity, matches: integrity === script.integrity };
109
+ }
110
+ catch {
111
+ failure = { code: 'file_unreadable', message: `Could not read ${file}.`, display: `Could not read ${file}.` };
112
+ }
113
+ }
114
+ if (!failure && (served?.matches === false || local?.matches === false))
115
+ failure = MISMATCH;
116
+ }
117
+ catch {
118
+ failure = controller.signal.aborted
119
+ ? { code: 'connection_timeout', message: 'The connection timed out.', display: 'The server did not respond in time.' }
120
+ : { code: 'connection_failed', message: 'Could not connect to the deployment server.', display: 'Check the server URL and your network connection.' };
121
+ }
122
+ finally {
123
+ clearTimeout(timer);
124
+ stop();
125
+ }
126
+ if (!pretty) {
127
+ return agentResult(failure ? 1 : 0, {
128
+ command,
129
+ siteUrl,
130
+ script,
131
+ served,
132
+ ...(local ? { file: local } : {}),
133
+ ...(saved ? { saved } : {}),
134
+ ...(failure ? { error: failureError(failure) } : {})
135
+ });
136
+ }
137
+ const rows = [['Server', siteUrl]];
138
+ if (script)
139
+ rows.push(['Script', script.src], ['Integrity', script.integrity], ['Download', script.download]);
140
+ if (served)
141
+ rows.push(['Served file', served.matches ? 'Match' : `Mismatch (${served.integrity})`]);
142
+ if (local)
143
+ rows.push(['Local file', local.matches ? `Match (${local.path})` : `Mismatch (${local.integrity})`]);
144
+ if (saved)
145
+ rows.push(['Saved', `${saved.path} (${saved.bytes.toLocaleString('en-US')} bytes)`]);
146
+ if (!failure)
147
+ return prettyResult(0, depth, command, 'The script hash matches the manifest.', rows);
148
+ return prettyResult(1, depth, command, failure.code === 'integrity_mismatch' ? failure.display : 'Could not verify the script.', [...rows, ['Reason', failure.display]]);
149
+ }
@@ -0,0 +1,6 @@
1
+ import { agentResult } from "../output.js";
2
+ export function runVersion(version, pretty) {
3
+ return pretty
4
+ ? { code: 0, stdout: '', stderr: '' }
5
+ : agentResult(0, { command: 'version', version });
6
+ }
package/dist/guide.js ADDED
@@ -0,0 +1,37 @@
1
+ import { SITE_URL } from "./site.js";
2
+ import { commands } from "./registry.js";
3
+ const TITLE = '# DeepDynamic Cloud CLI Guide';
4
+ const SECTIONS = `## CLI projects and deploys
5
+ - Guidance level: run \`deepdynamic account get\` first and follow \`guide\` in its result. If the user has turned on captain mode (기장 모드) on My Projects (${SITE_URL}/projects), it is \`audience: "developer"\`: explain with technical terms and relay only \`percent\` and \`forHuman.detail\` for deploy progress. If it is off or cannot be checked, it is \`audience: "non_developer"\`: explain plainly for a non-developer with the airline terms of the My Projects page and relay only \`percent\` and \`forHuman.message\` for deploy progress.
6
+ - Projects are created only from the CLI. Run \`deepdynamic projects create my-site\` once before the first deploy. Each project gets one server inside a customer-dedicated network and one Git repository; a pre-provisioned server is assigned, turned on and connected to the issued address. Check the status with \`deepdynamic projects status my-site\` and list your projects with \`deepdynamic projects\` without a subcommand (20 per page by recent activity, \`--page\`). \`status\` in the list is the result of the last deploy run, and when \`live\` is present that deploy is still published. Deploying to a name that is not your project is rejected with \`project_not_found\` before the upload.
7
+ - Naming a project: if the user did not give a name, first check \`deepdynamic projects\` for a project made from this source and deploy there if one exists. Otherwise read the source and look for evidence in this order: \`name\` in \`package.json\` (without \`@scope/\`) → the site \`<title>\` and first heading → the folder name, then make a name of 3-30 lowercase English letters, digits and hyphens (render Korean by its meaning in English or romanization, e.g. 목동 국수집 → \`mokdong-noodle\`). Do not use names that say nothing about the content, such as \`app\`, \`site\`, \`test\`, \`my-app\` or \`vite-project\`, nor personal data or secrets. Names are globally unique, so check each candidate with \`deepdynamic projects create <name> --dry-run\` (checks only \`available\` and \`owned\` without creating), then show the user one available recommendation and two alternatives with your reasons and create it after they confirm. If a name is taken, add a word that describes the content instead of random digits. The full rules are in the notes of \`deepdynamic projects create --help\`.
8
+ - Renaming: for a project made with a name that says nothing about the content, such as \`demo-site\`, do not create a new one; name it from the source by the same rules and rename it with \`deepdynamic projects rename demo-site <new-name>\` (\`POST /api/v1/projects/{project}/rename\`). Check first with \`--dry-run\` that the name is available and have the user confirm one recommendation and two alternatives. The issued address changes to the new name and is connected on the next deploy. The server, repository and deploy history stay, and later commands use the new name.
9
+ - Installable app (PWA): \`deepdynamic projects pwa my-site\` (\`GET /api/v1/projects/{project}/pwa\`) returns in \`pwa\` whether the gateway advertises the site as an installable web app, and \`deepdynamic projects pwa my-site on|off\` (\`POST /api/v1/projects/{project}/pwa\`, \`{ enabled }\`) changes it. It is on by default; when on, the gateway always appends \`<link rel="manifest">\` before \`</head>\` while browsers use only the first manifest link on the page, so a manifest the site declares wins, and it serves \`/__dd/manifest.webmanifest\`, which Android Chrome uses for "Install app" and iOS Safari for "Add to Home Screen". No UI is injected into the page and the site files are not changed; when the gateway cannot be synchronized the command fails with \`unavailable\` and the setting stays as it was.
10
+ - Deploy settings go in \`deepdynamic.json\` at the root of the deploy folder. The only accepted fields are \`packageManager\` (\`pnpm\` only), \`build\` (\`pnpm build\` or \`pnpm run <script>\`), \`output\` (relative path of the build output folder), \`start\` and \`port\`; without the file the uploaded files are served as they are. For an app server set \`start\` (\`pnpm start\` or \`pnpm run <script>\`) and \`port\` (1024-65535) instead of \`output\`: the project server starts it with \`PORT\` set and proxies the site to that port. Follow the notes of \`deepdynamic projects deploy --help\` for the full rules.
11
+ - Security rules: use pnpm only and upload \`pnpm-lock.yaml\` with the source (the server installs with \`pnpm install --frozen-lockfile\`). Do not call npm, npx, yarn, curl or wget from package.json scripts, and list only the packages that really need install scripts in \`pnpm.onlyBuiltDependencies\`. Never put API keys, tokens or .env values into the source or settings. The build runs on the project server as a non-root user without deploy credentials.
12
+ - Environment variables: \`deepdynamic projects env push my-site [.env]\` (\`GET\` and \`POST /api/v1/projects/{project}/env\`) seals the \`.env\` file on this device with the project server's public key, so the web server never sees the values. They reach the build and the app server from the next deploy or rollback and are masked as \`***\` in build and app logs. \`deepdynamic projects env list my-site\` shows only the names and \`deepdynamic projects env clear my-site --yes\` (\`POST /api/v1/projects/{project}/env/clear\`) removes them all. Values inlined into browser code such as \`VITE_*\` or \`NEXT_PUBLIC_*\` are visible on the site anyway.
13
+ - Rollback: \`deepdynamic projects history my-site\` (\`GET /api/v1/projects/{project}/deployments\`) lists only deploys that finished publishing, the latest 20 by commit, and the first entry is the deploy published now. \`deepdynamic projects rollback my-site --yes\` rolls back to the previous deploy, and \`--to <commit>\` to the chosen one. It pushes a new commit holding exactly the files of the target commit, then builds and publishes again in the same stages as \`deepdynamic projects deploy\`; history is never erased. If the user did not name a target, show the history and have them confirm. Until \`deployed: true\` the previous site stays published.
14
+ - Visit statistics: \`deepdynamic projects metric my-site [--period 24h|7d|30d]\` (\`GET /api/v1/projects/{project}/metric\`) returns the same visits, page views, average stay, bounce rate, sources, devices and top pages as the Metric page of My Projects, in Korea time. The default period is 7d, and the \`previous*\` values are the same numbers for the period of the same length right before; when one is 0, do not quote a percentage change.
15
+ - Photocard: \`deepdynamic projects photocard my-site [--out <directory>]\` (\`GET /api/v1/projects/{project}/photocard?side=1|2\`) has the server render the front and back of the project photocard from My Projects as 1000 × 1500 PNG files and saves them as \`<project name>-1.png\` and \`<project name>-2.png\`. The flight number comes from the first deploy with \`--agent\`, so a project never deployed that way fails with \`flight_required\`.
16
+ - Stop and delete: \`deepdynamic projects stop my-site --yes\` (\`POST /api/v1/projects/{project}/stop\`) ends a deploy in progress with \`deploy_stopped\` and turns the project server off. While the server is off the site does not open, and the next deploy turns it on again. While the server is installing its periodic package updates it is not turned off and the command is rejected with \`server_updating\`; run it again until it is no longer rejected. \`deepdynamic projects delete my-site --yes\` (\`POST /api/v1/projects/{project}/delete\`) erases the project's Git repository and deploy records, then turns off and deletes the server in the background. After deletion you cannot roll back to an earlier deploy. Because it cannot be undone, run it with \`--yes\` only for a project the user asked to delete, after they confirm the name. If the server is still being created the command is rejected with \`server_busy\`; check readiness with \`deepdynamic projects status my-site\` and run it again.
17
+
18
+ ## Tracking CLI deploy progress
19
+ - On every deploy, pass the code of the agent running it to \`--agent\`: \`CLD\` (Claude), \`CCD\` (Claude Code), \`CDX\` (Codex), \`GPT\` (ChatGPT), \`OPC\` (OpenCode), \`CRS\` (Crush), \`CUR\` (Cursor), \`OTH\` (any other agent or a person). If you do not know your code, ask the user before deploying. The first deploy gives the project a flight number such as \`KR4821\`, and the My Projects page shows the flight number and the agent. A project deployed earlier gets its flight number on its next deploy.
20
+ - \`deepdynamic projects deploy my-site ./my-site --agent CCD\` starts tracking with \`POST /api/v1/deployments\` and updates the repository preparation, file cleanup and Git push stages automatically with \`POST /api/v1/deployments/{id}\`. \`GET /api/v1/deployments/{id}\` reads the server's Git commit check and the publishing progress.
21
+ - Authentication uses the \`Authorization: Bearer\` header with the existing CLI login token. Creating and updating need \`projects:write\`, reading needs \`projects:read\`, and only your own records are accessible.
22
+ - Relay to the user \`percent\` and the \`forHuman\` field named by \`guide\` of \`deepdynamic account get\`. As the agent, decide with \`forAgent.stage\`, \`status\`, \`gitUploaded\`, \`deployed\` and \`nextAction\`. Stop automatic polling when \`pollAfterMs\` is null.
23
+ - Progress is based on stages. Once the Git push is confirmed it moves to 90% \`publishing\` while the project server builds and publishes, and when that finishes it becomes 100% \`published\` with \`deployed: true\`. While \`deployed: false\`, do not tell the user the deploy is done or the live site is public. If the build fails you get \`publish_failed\` and the tail of the build output in \`forAgent.publishLog\`; fix the problem from it and deploy again. \`gitUploaded: false\` means the push has not been confirmed yet. \`publishing_not_configured\` in old records is the state from before publishing was connected.
24
+ - The CLI streams live progress as JSON lines on stderr (human-readable text with \`--pretty\`) and prints the final result as JSON on stdout. \`progress\` in a failure response is the last checked state and may not be current. If the status check after the Git run fails, the exit code is 1 even with \`uploaded: true\`; start by checking \`deepdynamic deployments <id>\`. If it ends with \`server_pending\`, keep running \`deepdynamic projects status <name>\`, and if it ends with \`publish_pending\`, keep running \`deepdynamic deployments <id>\` (the \`id\` of the result), every \`pollAfterMs\` until preparation or publishing finishes or fails. The server moves a deploy to the next stage only when this check arrives, so if you stop checking it is never published. You do not need to call \`statusUrl\` in the result yourself.
25
+ - If your shell commands have a time limit, give \`deepdynamic projects deploy\`, \`deepdynamic projects rollback\` and \`deepdynamic projects create\` a shorter \`--timeout <seconds>\` (deploy and rollback 0-900, create 0-1200). When it runs out the command ends with \`publish_pending\` or \`server_pending\` (exit code 1) while the work continues on the server, so keep checking with the commands above.
26
+ - Commands that need a login open a browser sign-in window and wait up to 10 minutes. If your shell time limit is shorter, give any command a shorter \`--login-timeout <seconds>\` (1-600). The window still opens; when the time runs out the command ends with \`login_timeout\` and that window can no longer approve the sign-in.
27
+ - In a failed result (\`ok: false\`), \`error.retryable\` tells whether the same command can be run again as is, and \`error.next\` is the command to run next. For an unknown command, subcommand or option, the closest candidates are in \`suggestions\`. Group help (such as \`deepdynamic projects --help\`) only summarizes the subcommands, so run the \`help\` of a summary entry (such as \`deepdynamic projects create --help\`) for details.
28
+ - Commands that are hard to undo (those with \`confirm\`) send nothing without \`--yes\` and end with exit code 3 and \`confirmation_required\`, and \`error.next\` holds the command with \`--yes\`. Run that command only after the user agrees. \`--dry-run\` returns the request it would send without \`--yes\`.
29
+ - CLI updates: at most once a day the CLI checks npm in the background, updates its own global install and uses the new version from the next run. That first run writes a \`{"event":"updated",...}\` line once on stderr; mention it to the user briefly. A \`{"event":"update_available",...}\` line means the automatic install was not possible (not a global install, permission error and so on): finish the current task, tell the user and, after they agree, install it with \`deepdynamic update --yes\` (\`deepdynamic update\` alone only checks). Checking, installing and notices are off when \`DEEPDYNAMIC_NO_UPDATE_CHECK=1\` or \`CI\` is set.
30
+ - Pass long bodies with line breaks or quotes as a file instead of a shell argument: \`--body-file <path>\` for \`deepdynamic emails send\` and \`deepdynamic sms send\`, and \`--message-file <path>\` for \`deepdynamic support contact\` (UTF-8; a leading BOM and one trailing line break are removed).`;
31
+ const COMMAND_INTRO = '## CLI commands\n- Get the whole command tree (with effect, login, `--dry-run` and `--yes`) in one call with `deepdynamic commands` (or `deepdynamic help --all`). Each command has its options, result fields and errors in `deepdynamic <command> --help`.';
32
+ export function cliGuideSections() {
33
+ return `${SECTIONS}\n\n${[COMMAND_INTRO, ...commands.map(({ usage, description }) => `- \`${usage}\` — ${description}`)].join('\n')}`;
34
+ }
35
+ export function cliGuideMarkdown() {
36
+ return `${TITLE}\n\n${cliGuideSections()}\n`;
37
+ }
@@ -0,0 +1,6 @@
1
+ import { USER_AGENT } from "../metadata.js";
2
+ export function call(url, init = {}, fetcher = fetch) {
3
+ const headers = new Headers(init.headers);
4
+ headers.set('user-agent', USER_AGENT);
5
+ return fetcher(url, { ...init, headers });
6
+ }