@superpanel-sdk/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 (78) hide show
  1. package/README.md +16 -2
  2. package/bin/superpanel.mjs +23 -0
  3. package/dist/api/platform.d.ts +31 -0
  4. package/dist/api/platform.js +39 -0
  5. package/dist/auth/auth.d.ts +162 -0
  6. package/dist/auth/auth.js +923 -0
  7. package/dist/auth/backend-url.d.ts +7 -0
  8. package/dist/auth/backend-url.js +41 -0
  9. package/dist/auth/cli-login.d.ts +8 -0
  10. package/dist/auth/cli-login.js +92 -0
  11. package/dist/auth/clipboard.d.ts +8 -0
  12. package/dist/auth/clipboard.js +42 -0
  13. package/dist/auth/file-lock.d.ts +25 -0
  14. package/dist/auth/file-lock.js +173 -0
  15. package/dist/auth/http.d.ts +34 -0
  16. package/dist/auth/http.js +48 -0
  17. package/dist/auth/index.d.ts +13 -0
  18. package/dist/auth/index.js +117 -0
  19. package/dist/auth/origin-guard.d.ts +4 -0
  20. package/dist/auth/origin-guard.js +9 -0
  21. package/dist/auth/origin.d.ts +17 -0
  22. package/dist/auth/origin.js +142 -0
  23. package/dist/auth/pending-login.d.ts +5 -0
  24. package/dist/auth/pending-login.js +67 -0
  25. package/dist/commands/auth-token.d.ts +26 -0
  26. package/dist/commands/auth-token.js +71 -0
  27. package/dist/commands/git-method.d.ts +54 -0
  28. package/dist/commands/git-method.js +180 -0
  29. package/dist/commands/setup.d.ts +88 -0
  30. package/dist/commands/setup.js +366 -0
  31. package/dist/commands/skill.d.ts +29 -0
  32. package/dist/commands/skill.js +169 -0
  33. package/dist/commands/ssh-key.d.ts +13 -0
  34. package/dist/commands/ssh-key.js +83 -0
  35. package/dist/git/credential.d.ts +7 -0
  36. package/dist/git/credential.js +66 -0
  37. package/dist/git/index.d.ts +36 -0
  38. package/dist/git/index.js +119 -0
  39. package/dist/git/run.d.ts +13 -0
  40. package/dist/git/run.js +32 -0
  41. package/dist/git/setup.d.ts +97 -0
  42. package/dist/git/setup.js +471 -0
  43. package/dist/handover/clone.d.ts +8 -0
  44. package/dist/handover/clone.js +39 -0
  45. package/dist/handover/repo-help.d.ts +7 -0
  46. package/dist/handover/repo-help.js +55 -0
  47. package/dist/handover/run.d.ts +5 -0
  48. package/dist/handover/run.js +67 -0
  49. package/dist/inbound/index.d.ts +44 -0
  50. package/dist/inbound/index.js +129 -0
  51. package/dist/index.d.ts +3 -0
  52. package/dist/index.js +251 -0
  53. package/dist/logs/index.d.ts +19 -0
  54. package/dist/logs/index.js +132 -0
  55. package/dist/npm-launch.d.ts +19 -0
  56. package/dist/npm-launch.js +80 -0
  57. package/dist/ops/agent.d.ts +3 -0
  58. package/dist/ops/agent.js +14 -0
  59. package/dist/ops/cache.d.ts +18 -0
  60. package/dist/ops/cache.js +92 -0
  61. package/dist/ops/parse.d.ts +6 -0
  62. package/dist/ops/parse.js +106 -0
  63. package/dist/ops/register.d.ts +18 -0
  64. package/dist/ops/register.js +174 -0
  65. package/dist/ops/run.d.ts +20 -0
  66. package/dist/ops/run.js +127 -0
  67. package/dist/ops/types.d.ts +41 -0
  68. package/dist/ops/types.js +16 -0
  69. package/dist/protocol.d.ts +4 -0
  70. package/dist/protocol.js +17 -0
  71. package/dist/reserved.d.ts +4 -0
  72. package/dist/reserved.js +25 -0
  73. package/dist/turns/index.d.ts +20 -0
  74. package/dist/turns/index.js +108 -0
  75. package/dist/version.d.ts +2 -0
  76. package/dist/version.js +11 -0
  77. package/package.json +48 -4
  78. package/skill/SKILL.md +17 -0
@@ -0,0 +1,44 @@
1
+ export type InboundOptions = {
2
+ env?: string;
3
+ channel?: string;
4
+ outcome?: string;
5
+ since?: string;
6
+ until?: string;
7
+ after?: string;
8
+ limit?: number;
9
+ number?: string;
10
+ json?: boolean;
11
+ url?: string;
12
+ };
13
+ export type InboundItem = {
14
+ channel: 'call' | 'sms' | 'email';
15
+ id: string;
16
+ at: string;
17
+ from: string | null;
18
+ to: string | null;
19
+ outcome: 'handled' | 'rejected' | 'failed' | 'in_progress' | 'skipped';
20
+ simulated?: boolean;
21
+ reason: {
22
+ code: string;
23
+ message: string;
24
+ } | null;
25
+ subject?: string | null;
26
+ body?: string | null;
27
+ runId: string | null;
28
+ instanceIds: string[];
29
+ };
30
+ export declare function listOf(value: string | undefined, allowed: string[], flag: string): string[] | undefined;
31
+ export declare function afterOf(value: string | undefined): {
32
+ afterAt: string;
33
+ afterId: string;
34
+ } | undefined;
35
+ export declare function nextPageCommand(options: InboundOptions, query: {
36
+ environment: string;
37
+ since: string | undefined;
38
+ }, next: {
39
+ at: string;
40
+ id: string;
41
+ }): string;
42
+ export declare function formatInboundItem(item: InboundItem): string;
43
+ export declare function runInbound(cwd: string, options: InboundOptions): Promise<void>;
44
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,129 @@
1
+ import { getValidCliAuthorization, loginCommand, resolveBackendUrl } from '../auth/auth.js';
2
+ import { guardNetworkedClone } from '../auth/origin-guard.js';
3
+ import { apiUrl, cliRequestHeaders } from '../auth/http.js';
4
+ function timeOf(value, now = Date.now()) {
5
+ if (!value)
6
+ return undefined;
7
+ const ago = /^(\d+)\s*(s|m|h|d)$/.exec(value.trim());
8
+ if (ago) {
9
+ const unit = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 }[ago[2]];
10
+ return new Date(now - Number(ago[1]) * unit).toISOString();
11
+ }
12
+ const at = Date.parse(value);
13
+ if (Number.isNaN(at))
14
+ throw new Error(`${value}: a time is 15m, 2h, 3d (that long ago) or ISO 8601`);
15
+ return new Date(at).toISOString();
16
+ }
17
+ const CHANNELS = ['call', 'sms', 'email'];
18
+ const OUTCOMES = ['handled', 'rejected', 'failed', 'in_progress', 'skipped'];
19
+ export function listOf(value, allowed, flag) {
20
+ if (!value)
21
+ return undefined;
22
+ const asked = value
23
+ .split(',')
24
+ .map((part) => part.trim().toLowerCase())
25
+ .filter(Boolean);
26
+ for (const item of asked)
27
+ if (!allowed.includes(item))
28
+ throw new Error(`${flag}: ${item} is not one of ${allowed.join(', ')}`);
29
+ return asked;
30
+ }
31
+ function oneLine(text, max) {
32
+ const flat = text.replace(/\s+/g, ' ').trim();
33
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
34
+ }
35
+ export function afterOf(value) {
36
+ if (!value)
37
+ return undefined;
38
+ const [at, id, ...rest] = value.split(',').map((part) => part.trim());
39
+ if (!at || !id || rest.length || Number.isNaN(Date.parse(at)))
40
+ throw new Error(`--after: ${value} is not <time>,<id> (the "more:" line prints it)`);
41
+ return { afterAt: new Date(at).toISOString(), afterId: id };
42
+ }
43
+ export function nextPageCommand(options, query, next) {
44
+ const flags = [
45
+ `--env ${query.environment}`,
46
+ ...(options.channel ? [`--channel ${options.channel}`] : []),
47
+ ...(options.outcome ? [`--outcome ${options.outcome}`] : []),
48
+ ...(query.since ? [`--since ${query.since}`] : []),
49
+ ...(options.limit ? [`--limit ${options.limit}`] : []),
50
+ ...(options.url ? [`--url ${options.url}`] : []),
51
+ `--after ${next.at},${next.id}`,
52
+ ];
53
+ return `superpanel inbound ${flags.join(' ')}`;
54
+ }
55
+ export function formatInboundItem(item) {
56
+ const time = item.at.replace('T', ' ').replace(/\.\d+Z$|Z$/, '');
57
+ const head = `${time} ${item.channel.toUpperCase().padEnd(5)} ${item.from ?? '?'} → ${item.to ?? '?'} ${item.outcome}${item.simulated ? ' [test]' : ''}`;
58
+ const lines = [item.reason ? `${head} ${item.reason.code}: ${item.reason.message}` : head];
59
+ const sent = [item.subject, item.body].filter((part) => Boolean(part?.trim())).join(' — ');
60
+ if (sent)
61
+ lines.push(` ${oneLine(sent, 160)}`);
62
+ const ids = [
63
+ ...(item.runId ? [`run ${item.runId}`] : []),
64
+ ...item.instanceIds.map((id) => `case ${id}`),
65
+ `${item.channel} ${item.id}`,
66
+ ];
67
+ lines.push(` ${ids.join(' ')}`);
68
+ return lines.join('\n');
69
+ }
70
+ async function post(backendUrl, token, route, body) {
71
+ const response = await fetch(apiUrl(backendUrl, route), {
72
+ method: 'POST',
73
+ headers: cliRequestHeaders({
74
+ Authorization: `Bearer ${token}`,
75
+ 'Content-Type': 'application/json',
76
+ }),
77
+ body: JSON.stringify(body),
78
+ signal: AbortSignal.timeout(60_000),
79
+ });
80
+ const payload = (await response.json().catch(() => ({})));
81
+ if (response.status === 401)
82
+ throw new Error(`the login was refused: run \`${loginCommand(backendUrl)}\` again`);
83
+ if (!response.ok)
84
+ throw new Error(`inbound: ${payload.error ?? `the backend answered ${response.status}`}`);
85
+ return payload;
86
+ }
87
+ export async function runInbound(cwd, options) {
88
+ const backendUrl = resolveBackendUrl(options.url);
89
+ const authorization = await getValidCliAuthorization(backendUrl);
90
+ if (!authorization)
91
+ throw new Error(`not logged in: run "${loginCommand(backendUrl)}" first`);
92
+ await guardNetworkedClone(cwd, backendUrl, authorization.accessToken);
93
+ if (options.number) {
94
+ const check = await post(backendUrl, authorization.accessToken, 'cli-auth/inbound/number', {
95
+ number: options.number,
96
+ });
97
+ if (options.json)
98
+ console.log(JSON.stringify(check));
99
+ else if (!check.found)
100
+ console.log(`${check.number}: not a number of this company on the platform; what comes in on it shows on no environment's list`);
101
+ else
102
+ console.log(`${check.number}: in environment ${check.environment.name} (${check.environment.id}), ${check.status}`);
103
+ return;
104
+ }
105
+ const channels = listOf(options.channel, CHANNELS, '--channel');
106
+ const outcomes = listOf(options.outcome, OUTCOMES, '--outcome');
107
+ const since = timeOf(options.since);
108
+ const until = timeOf(options.until);
109
+ const after = afterOf(options.after);
110
+ const result = await post(backendUrl, authorization.accessToken, 'cli-auth/inbound', {
111
+ environment: options.env ?? 'sandbox',
112
+ ...(channels ? { channels } : {}),
113
+ ...(outcomes ? { outcomes } : {}),
114
+ ...(since ? { since } : {}),
115
+ ...(until ? { until } : {}),
116
+ ...(after ?? {}),
117
+ ...(options.limit ? { limit: options.limit } : {}),
118
+ });
119
+ for (const item of result.items)
120
+ console.log(options.json ? JSON.stringify(item) : formatInboundItem(item));
121
+ if (options.json)
122
+ return;
123
+ if (!result.items.length)
124
+ console.error(`nothing came in on ${result.environment.name} in that window`);
125
+ if (result.items.some((item) => item.reason?.code === 'no_resolve'))
126
+ console.error('no_resolve: check the release status, and that the code exports `resolve`');
127
+ if (result.next)
128
+ console.error(`more: ${nextPageCommand(options, { environment: result.environment.name, since }, result.next)}`);
129
+ }
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,251 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { loadBackendFromConfig } from './auth/auth.js';
4
+ import { runInbound } from './inbound/index.js';
5
+ import { runLogs } from './logs/index.js';
6
+ import { runTurns } from './turns/index.js';
7
+ import { runGitCredential } from './git/credential.js';
8
+ import { answersFromSetupGitOptions, runSetupGit, setupGitCommand } from './git/index.js';
9
+ import { runLogin, runLogout, runWhoami } from './auth/index.js';
10
+ import { runAuthToken } from './commands/auth-token.js';
11
+ import { answersFromSetupOptions, runSetup } from './commands/setup.js';
12
+ import { refreshInstalledSkill, runSkillInstall } from './commands/skill.js';
13
+ import { runSshKeyAdd, runSshKeyList, runSshKeyRemove } from './commands/ssh-key.js';
14
+ import { AuthorizationPendingError } from './auth/auth.js';
15
+ import { confirmationOptionHelp, NeedsPersonError } from './ops/types.js';
16
+ import { repoHelpText } from './handover/repo-help.js';
17
+ import { handover } from './handover/run.js';
18
+ import { CATALOG_ROOTS, registerPlatformCommands } from './ops/register.js';
19
+ import { isReservedCommand } from './reserved.js';
20
+ import { cliVersion } from './version.js';
21
+ const REPO_COMMANDS = new Set(['serve', 'type:gen', 'compile', 'brief', 'exec', 'turn', 'mobile']);
22
+ const program = new Command();
23
+ program
24
+ .name('superpanel')
25
+ .description('Superpanel CLI')
26
+ .showHelpAfterError()
27
+ .configureHelp({ sortSubcommands: true })
28
+ .enablePositionalOptions();
29
+ program.version(cliVersion(), '-v, --version', 'Print the version of this CLI');
30
+ program
31
+ .command('login')
32
+ .description('Log in with a device code. A working login is left as it is: log out first to switch company.')
33
+ .option('--url <url>', 'Backend URL')
34
+ .option('--no-open', 'Print the link instead of opening a browser')
35
+ .option('--wait-seconds <seconds>', 'How long an agent waits for approval', '20')
36
+ .action(async (options) => {
37
+ const waitSeconds = Number(options.waitSeconds ?? '20');
38
+ if (!Number.isInteger(waitSeconds) || waitSeconds < 0 || waitSeconds > 60) {
39
+ throw new Error('--wait-seconds is a whole number from 0 to 60');
40
+ }
41
+ await runLogin({ url: options.url, open: options.open, waitSeconds });
42
+ });
43
+ program
44
+ .command('logout')
45
+ .description('End the login on the backend and clear it on this machine')
46
+ .option('--url <url>', 'Backend URL')
47
+ .action(async (options) => {
48
+ await runLogout(options);
49
+ });
50
+ program
51
+ .command('whoami')
52
+ .description('The login on this machine, then what the backend says')
53
+ .option('--url <url>', 'Backend URL')
54
+ .action(async (options) => {
55
+ await runWhoami(options);
56
+ });
57
+ const auth = program.command('auth').description('Credentials for a runtime or a script');
58
+ auth
59
+ .command('token')
60
+ .description('Print an access token. Do not paste the output into a chat.')
61
+ .option('--json', 'One JSON line: version, backendUrl, accessToken, expiresAt, login, identity')
62
+ .option('--protocol <versions>', 'Comma-separated protocol versions the caller speaks')
63
+ .option('--url <url>', 'Backend URL')
64
+ .action(async (options) => {
65
+ await runAuthToken(options);
66
+ });
67
+ program
68
+ .command('inbound')
69
+ .description('Inbound calls, texts and emails, newest first')
70
+ .option('--env <name|id>', 'The environment', 'sandbox')
71
+ .option('--channel <list>', 'call, sms, email, or a comma-separated list')
72
+ .option('--outcome <list>', 'handled, rejected, failed, in_progress, skipped, or a comma-separated list')
73
+ .option('--since <time>', '15m, 2h, 3d, or ISO 8601')
74
+ .option('--until <time>', 'The same forms')
75
+ .option('--after <time,id>', 'The next page')
76
+ .option('--limit <n>', 'At most this many', (value) => Number(value))
77
+ .option('--number <number>', 'Where this number stands')
78
+ .option('--json', 'One JSON per line')
79
+ .option('--url <url>', 'Backend URL')
80
+ .action(async (options) => {
81
+ await runInbound(process.cwd(), options);
82
+ });
83
+ program
84
+ .command('logs')
85
+ .description("What this repository's code wrote in an environment, oldest first")
86
+ .option('--env <name|id>', 'The environment', 'sandbox')
87
+ .option('--since <time>', '15m, 2h, 3d, or ISO 8601')
88
+ .option('--until <time>', 'The same forms')
89
+ .option('--instance <id>', 'One case')
90
+ .option('--run <id>', 'One run')
91
+ .option('--contact <id>', 'One contact')
92
+ .option('--sequence <name>', 'One sequence')
93
+ .option('--request <id>', 'One request')
94
+ .option('--level <level>', 'warn, or a list such as info,error')
95
+ .option('--search <text>', 'Text in the line or its data')
96
+ .option('--limit <n>', 'Lines at most', (value) => Number(value))
97
+ .option('--follow', 'Keep showing new lines')
98
+ .option('--json', 'One JSON per line')
99
+ .option('--url <url>', 'Backend URL')
100
+ .action(async (options) => {
101
+ await runLogs(process.cwd(), options);
102
+ });
103
+ program
104
+ .command('turns [action] [turnId]')
105
+ .description('Turns of a case, a run or a call, prod included. `turns export <turnId>` writes one turn.')
106
+ .option('--env <name|id>', 'The environment (prod too)', 'sandbox')
107
+ .option('--instance <id>', 'One case')
108
+ .option('--call <id>', 'One call')
109
+ .option('--run <id>', 'One run')
110
+ .option('--since <time>', '15m, 2h, 3d, or ISO 8601')
111
+ .option('--limit <n>', 'Turns at most', (value) => Number(value))
112
+ .option('--out <dir>', 'export: where to write')
113
+ .option('--json', 'One JSON per turn')
114
+ .option('--url <url>', 'Backend URL')
115
+ .action(async (action, turnId, options) => {
116
+ await runTurns(process.cwd(), action, turnId, options);
117
+ });
118
+ const sshKey = program.command('ssh-key').description('SSH keys on the Git account');
119
+ sshKey
120
+ .command('list')
121
+ .description('List SSH keys')
122
+ .option('--url <url>', 'Backend URL')
123
+ .action(async (options) => {
124
+ await runSshKeyList(options);
125
+ });
126
+ sshKey
127
+ .command('add')
128
+ .description('Add a public key')
129
+ .requiredOption('--public-key <key>', 'The public key')
130
+ .option('--title <title>', 'A name for the key')
131
+ .option('--url <url>', 'Backend URL')
132
+ .action(async (options) => {
133
+ await runSshKeyAdd(options);
134
+ });
135
+ sshKey
136
+ .command('remove')
137
+ .description('Remove an SSH key')
138
+ .argument('<id>', 'The key id')
139
+ .option('--allow-remove <words>', confirmationOptionHelp("The person's words agreeing to delete the key"))
140
+ .option('--url <url>', 'Backend URL')
141
+ .action(async (id, options) => {
142
+ await runSshKeyRemove(id, options);
143
+ });
144
+ program
145
+ .command('skill')
146
+ .description('Install the Superpanel skill for an agent')
147
+ .command('install')
148
+ .description('Write the skill into the agent directories')
149
+ .option('--allow-overwrite', confirmationOptionHelp('Replace a skill directory that Superpanel did not write'))
150
+ .action(async (options) => {
151
+ await runSkillInstall(options);
152
+ });
153
+ program
154
+ .command('setup')
155
+ .description('Set up this computer and clone the company repo into ~/Superpanel')
156
+ .option('--url <url>', 'Backend URL')
157
+ .option('--company <name>', 'Company name')
158
+ .option('--git-protocol <https|ssh>', 'Protocol for the first clone; existing clones keep their Git addresses')
159
+ .option('--install-cli', confirmationOptionHelp('Install the CLI globally for this user (recommended)'))
160
+ .option('--no-install-cli', confirmationOptionHelp('Do not install the CLI for this user'))
161
+ .option('--install-skill', confirmationOptionHelp('Install the Superpanel skill (the default), and ask about a folder Superpanel did not write instead of skipping it'))
162
+ .option('--no-install-skill', confirmationOptionHelp('Do not install the Superpanel skill (installed by default)'))
163
+ .option('--allow-ssh-config <words>', confirmationOptionHelp("The person's words agreeing to edit ~/.ssh/config"))
164
+ .option('--allow-backend-change', confirmationOptionHelp('Allow replacing a backend address already written for this repo'))
165
+ .option('--allow-agent-instructions <words>', confirmationOptionHelp("The person's words agreeing to agent instruction files"))
166
+ .option('--no-agent-instructions', confirmationOptionHelp('Do not write agent instruction files'))
167
+ .option('--wait-seconds <seconds>', 'How long an agent waits for login approval', '20')
168
+ .action(async (options) => {
169
+ await runSetup(answersFromSetupOptions(options));
170
+ });
171
+ const setupGit = setupGitCommand();
172
+ setupGit.action(async (options) => {
173
+ await runSetupGit(answersFromSetupGitOptions(options));
174
+ });
175
+ program.addCommand(setupGit);
176
+ program
177
+ .command('git-credential')
178
+ .description('git credential helper for the company repo host')
179
+ .argument('<action>', 'get, store or erase')
180
+ .requiredOption('--url <url>', 'Backend URL')
181
+ .action(async (action, options) => {
182
+ await runGitCredential(action, options.url, {
183
+ stdin: process.stdin,
184
+ stdout: process.stdout,
185
+ stderr: process.stderr,
186
+ });
187
+ });
188
+ function urlFlag(argv) {
189
+ const index = argv.indexOf('--url');
190
+ if (index >= 0 && argv[index + 1])
191
+ return argv[index + 1];
192
+ const inline = argv.find((arg) => arg.startsWith('--url='));
193
+ return inline?.slice('--url='.length);
194
+ }
195
+ function wantsHandover(argv) {
196
+ const name = argv[2];
197
+ if (!name || name.startsWith('-'))
198
+ return false;
199
+ if (isReservedCommand(name))
200
+ return false;
201
+ return REPO_COMMANDS.has(name) || true;
202
+ }
203
+ async function main() {
204
+ if (process.argv.length === 3 && ['--version', '-v', '-V'].includes(process.argv[2])) {
205
+ console.log(cliVersion());
206
+ return;
207
+ }
208
+ if (process.argv[2] !== 'setup')
209
+ await refreshInstalledSkill();
210
+ if (process.argv[2] !== 'git-credential')
211
+ loadBackendFromConfig();
212
+ if (wantsHandover(process.argv) && !program.commands.some((command) => command.name() === process.argv[2])) {
213
+ const { status } = await handover(process.argv.slice(2));
214
+ process.exit(status);
215
+ }
216
+ const head = process.argv[2];
217
+ const help = !head || head === '--help' || head === '-h' || head === 'help';
218
+ if (help)
219
+ program.addHelpText('after', `\n${repoHelpText()}\n`);
220
+ if (help || (head !== undefined && CATALOG_ROOTS.includes(head))) {
221
+ try {
222
+ await registerPlatformCommands(program, { url: urlFlag(process.argv) });
223
+ }
224
+ catch (error) {
225
+ const message = error instanceof Error ? error.message : String(error);
226
+ if (!help) {
227
+ console.error(message);
228
+ process.exit(1);
229
+ }
230
+ console.error(message);
231
+ }
232
+ }
233
+ try {
234
+ await program.parseAsync(process.argv);
235
+ }
236
+ catch (error) {
237
+ if (error instanceof AuthorizationPendingError) {
238
+ console.error(error.message);
239
+ process.stdout.write(`${JSON.stringify({ reason: 'authorization_pending' })}\n`);
240
+ process.exit(2);
241
+ }
242
+ if (error instanceof NeedsPersonError) {
243
+ console.error(error.message);
244
+ console.log(JSON.stringify({ reason: error.reason }));
245
+ process.exit(2);
246
+ }
247
+ console.error(error instanceof Error ? error.message : error);
248
+ process.exit(1);
249
+ }
250
+ }
251
+ void main();
@@ -0,0 +1,19 @@
1
+ type LogsQuery = {
2
+ env?: string;
3
+ since?: string;
4
+ until?: string;
5
+ instance?: string;
6
+ run?: string;
7
+ contact?: string;
8
+ sequence?: string;
9
+ request?: string;
10
+ level?: string;
11
+ search?: string;
12
+ limit?: number;
13
+ follow?: boolean;
14
+ json?: boolean;
15
+ url?: string;
16
+ };
17
+ export declare function runLogs(cwd: string, query: LogsQuery): Promise<void>;
18
+ export {};
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,132 @@
1
+ import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import { randomUUID } from 'node:crypto';
3
+ import path from 'node:path';
4
+ import { getValidCliAuthorization, loginCommand, resolveBackendUrl } from '../auth/auth.js';
5
+ import { apiUrl, cliRequestHeaders } from '../auth/http.js';
6
+ import { guardNetworkedClone } from '../auth/origin-guard.js';
7
+ import { findCloneRoot } from '../handover/clone.js';
8
+ const LEVELS = ['debug', 'info', 'warn', 'error'];
9
+ function timeOf(value, now = Date.now()) {
10
+ if (!value)
11
+ return undefined;
12
+ const ago = /^(\d+)\s*(s|m|h|d)$/.exec(value.trim());
13
+ if (ago) {
14
+ const unit = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 }[ago[2]];
15
+ return new Date(now - Number(ago[1]) * unit).toISOString();
16
+ }
17
+ const at = Date.parse(value);
18
+ if (Number.isNaN(at))
19
+ throw new Error(`${value}: a time is 15m, 2h, 3d (that long ago) or ISO 8601`);
20
+ return new Date(at).toISOString();
21
+ }
22
+ function levelsOf(value) {
23
+ if (!value)
24
+ return undefined;
25
+ const asked = value
26
+ .split(',')
27
+ .map((level) => level.trim().toLowerCase())
28
+ .filter(Boolean);
29
+ for (const level of asked)
30
+ if (!LEVELS.includes(level))
31
+ throw new Error(`--level: ${level} is not one of ${LEVELS.join(', ')}`);
32
+ return asked.length === 1 ? LEVELS.slice(LEVELS.indexOf(asked[0])) : asked;
33
+ }
34
+ function formatLine(line) {
35
+ const time = line.at.replace('T', ' ').replace(/Z$/, '');
36
+ const data = line.data && (typeof line.data !== 'object' || Object.keys(line.data).length > 0)
37
+ ? ` ${typeof line.data === 'string' ? line.data : JSON.stringify(line.data)}`
38
+ : '';
39
+ return `${time} ${line.level.toUpperCase().padEnd(5)} ${line.sequence ? `[${line.sequence}] ` : ''}${line.message ?? ''}${data}`;
40
+ }
41
+ async function readLogs(backendUrl, token, query) {
42
+ const response = await fetch(apiUrl(backendUrl, 'cli-auth/logs'), {
43
+ method: 'POST',
44
+ headers: cliRequestHeaders({
45
+ Authorization: `Bearer ${token}`,
46
+ 'Content-Type': 'application/json',
47
+ }),
48
+ body: JSON.stringify({
49
+ environment: query.env ?? 'sandbox',
50
+ ...(timeOf(query.since) ? { since: timeOf(query.since) } : {}),
51
+ ...(timeOf(query.until) ? { until: timeOf(query.until) } : {}),
52
+ ...(query.instance ? { instanceId: query.instance } : {}),
53
+ ...(query.run ? { runId: query.run } : {}),
54
+ ...(query.contact ? { contactId: query.contact } : {}),
55
+ ...(query.sequence ? { sequence: query.sequence } : {}),
56
+ ...(query.request ? { requestId: query.request } : {}),
57
+ ...(levelsOf(query.level) ? { levels: levelsOf(query.level) } : {}),
58
+ ...(query.search ? { search: query.search } : {}),
59
+ cursor: query.cursor,
60
+ ...(query.order ? { order: query.order } : {}),
61
+ ...(query.limit ? { limit: query.limit } : {}),
62
+ }),
63
+ signal: AbortSignal.timeout(60_000),
64
+ });
65
+ const payload = (await response.json().catch(() => ({})));
66
+ if (response.status === 401)
67
+ throw new Error(`the login was refused: run \`${loginCommand(backendUrl)}\` again`);
68
+ if (!response.ok)
69
+ throw new Error(`logs: ${payload.error ?? `the backend answered ${response.status}`}`);
70
+ return payload;
71
+ }
72
+ function stamp(date) {
73
+ const pad = (n) => String(n).padStart(2, '0');
74
+ return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
75
+ }
76
+ export async function runLogs(cwd, query) {
77
+ const repoRoot = findCloneRoot(cwd);
78
+ const show = (line) => {
79
+ if (file)
80
+ appendFileSync(file, `${JSON.stringify(line)}\n`);
81
+ process.stdout.write(`${query.json ? JSON.stringify(line) : formatLine(line)}\n`);
82
+ };
83
+ const backendUrl = resolveBackendUrl(query.url);
84
+ const authorization = await getValidCliAuthorization(backendUrl);
85
+ if (!authorization)
86
+ throw new Error(`not logged in: run "${loginCommand(backendUrl)}" first`);
87
+ await guardNetworkedClone(cwd, backendUrl, authorization.accessToken);
88
+ const followStart = new Date().toISOString();
89
+ const first = await readLogs(backendUrl, authorization.accessToken, { ...query, order: 'desc' });
90
+ const file = repoRoot
91
+ ? path.join(repoRoot, '.superpanel', 'logs', `${stamp(new Date())}-${randomUUID()}.jsonl`)
92
+ : null;
93
+ if (file) {
94
+ mkdirSync(path.dirname(file), { recursive: true });
95
+ writeFileSync(file, '', { flag: 'wx', mode: 0o600 });
96
+ }
97
+ const lines = [...first.lines].reverse();
98
+ lines.forEach(show);
99
+ const where = file
100
+ ? `kept in ${path.relative(repoRoot, file)}`
101
+ : 'not saved. Run this inside the company repo to keep a copy in .superpanel/logs/';
102
+ process.stderr.write(`${lines.length} line${lines.length === 1 ? '' : 's'} from ${first.environment.name}${first.hasMore ? ' (more before: narrow it, or --since / --limit)' : ''}; ${where}\n`);
103
+ if (!query.follow)
104
+ return;
105
+ let after = lines.at(-1)?.at ?? followStart;
106
+ let cursor = first.followCursor ?? undefined;
107
+ const seen = new Set(lines.filter((line) => line.at === after).map((line) => line.id));
108
+ let token = authorization.accessToken;
109
+ for (;;) {
110
+ await new Promise((resolve) => setTimeout(resolve, 3_000));
111
+ const renewed = await getValidCliAuthorization(backendUrl);
112
+ if (!renewed)
113
+ throw new Error(`not logged in: run "${loginCommand(backendUrl)}" first`);
114
+ if (renewed.accessToken !== token) {
115
+ if (renewed.companyId !== authorization.companyId || renewed.user.id !== authorization.user.id)
116
+ throw new Error('The active login changed. Restart logs with the intended company login.');
117
+ await guardNetworkedClone(cwd, backendUrl, renewed.accessToken);
118
+ token = renewed.accessToken;
119
+ }
120
+ const next = await readLogs(backendUrl, token, { ...query, cursor, since: after, until: undefined, order: 'asc' });
121
+ for (const line of next.lines) {
122
+ if (line.at !== after)
123
+ seen.clear();
124
+ if (seen.has(line.id))
125
+ continue;
126
+ seen.add(line.id);
127
+ show(line);
128
+ after = line.at;
129
+ }
130
+ cursor = next.followCursor ?? ('followCursor' in next ? cursor : undefined);
131
+ }
132
+ }
@@ -0,0 +1,19 @@
1
+ import path from 'node:path';
2
+ type PathFor = typeof path.win32;
3
+ export type LaunchFs = {
4
+ platform?: NodeJS.Platform;
5
+ execPath?: string;
6
+ env?: NodeJS.ProcessEnv;
7
+ exists?: (file: string) => boolean;
8
+ readFile?: (file: string) => string;
9
+ };
10
+ export declare function jsEntryFromCmd(cmdFile: string, paths: PathFor, exists: (file: string) => boolean, readFile: (file: string) => string, sibling: string | null): string | null;
11
+ export declare function globalBinDir(prefix: string, platform?: NodeJS.Platform): string;
12
+ export type NpmLaunch = {
13
+ command: string;
14
+ args: string[];
15
+ verbatim?: boolean;
16
+ };
17
+ export declare function npmLaunch(args: string[], input?: LaunchFs): NpmLaunch;
18
+ export {};
19
+ //# sourceMappingURL=npm-launch.d.ts.map