@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,366 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { getGitAccount } from '../api/platform.js';
6
+ import { BACKEND_CONFIG_FILE, CliLoginRejectedError, cliCommand, loginCommand, getValidCliAuthorization, parseBackendConfig, requestCliIdentity, shellBackendUrl, resolveBackendUrl, writeBackendConfig, } from '../auth/auth.js';
7
+ import { isDefaultBackend, sameBackend } from '../auth/backend-url.js';
8
+ import { runLogin } from '../auth/index.js';
9
+ import { companyCloneStatus, orgFromCloneUrl, remotesMatch } from '../auth/origin.js';
10
+ import { isolatedGit, sshSetupQuestions } from '../git/setup.js';
11
+ import { setUpGit } from '../git/index.js';
12
+ import { npmLaunch } from '../npm-launch.js';
13
+ import { hasTerminal, runningAsAgent } from '../ops/agent.js';
14
+ import { NeedsPersonError } from '../ops/types.js';
15
+ import { chooseGitProtocol, confirm as confirmAnswer, defaultCloneUsesSsh, gitSetupRefusal, globalCliInstalled, GLOBAL_INSTALL_AGENT_PROMPT, offerGlobalCli, prepareGitMethod, } from './git-method.js';
16
+ import { refreshInstalledSkill, runSkillInstall } from './skill.js';
17
+ export { chooseGitProtocol, defaultCloneUsesSsh, gitSetupRefusal, installFallback, } from './git-method.js';
18
+ export function answersFromSetupOptions(options) {
19
+ if (options.gitProtocol && options.gitProtocol !== 'https' && options.gitProtocol !== 'ssh') {
20
+ throw new Error('--git-protocol is https or ssh');
21
+ }
22
+ const waitSeconds = Number(options.waitSeconds ?? '20');
23
+ if (!Number.isInteger(waitSeconds) || waitSeconds < 0 || waitSeconds > 60) {
24
+ throw new Error('--wait-seconds is a whole number from 0 to 60');
25
+ }
26
+ return {
27
+ url: options.url,
28
+ company: options.company,
29
+ gitProtocol: options.gitProtocol,
30
+ installCli: options.installCli,
31
+ installSkill: options.installSkill,
32
+ allowSshConfig: options.allowSshConfig,
33
+ allowBackendChange: options.allowBackendChange,
34
+ allowAgentInstructions: options.allowAgentInstructions,
35
+ noAgentInstructions: options.agentInstructions === false,
36
+ waitSeconds,
37
+ };
38
+ }
39
+ export function sameCompanyClone(origin, identity) {
40
+ return remotesMatch(origin, identity);
41
+ }
42
+ export function companyFolder(org) {
43
+ return path.join(homedir(), 'Superpanel', org);
44
+ }
45
+ const INSTRUCTIONS_QUESTION = 'Setup can write a note in the agent instructions naming this folder. Ask the person, then rerun with --allow-agent-instructions "<their words>" or --no-agent-instructions.';
46
+ export function setupQuestionsForAgent(input) {
47
+ const lines = [];
48
+ if (input.protocol === 'ask-install')
49
+ lines.push(GLOBAL_INSTALL_AGENT_PROMPT);
50
+ if (input.backendChangePath) {
51
+ lines.push(`The backend address in ${input.backendChangePath} would change. Ask the person, then rerun with --allow-backend-change.`);
52
+ }
53
+ if (input.instructions)
54
+ lines.push(INSTRUCTIONS_QUESTION);
55
+ return lines;
56
+ }
57
+ export function setupConfigPlan(input) {
58
+ if (input.read.status === 'unreadable') {
59
+ return {
60
+ action: 'stop',
61
+ message: `${input.path} could not be read (${input.read.message}). Fix that file and run setup again. Setup will not replace it.`,
62
+ };
63
+ }
64
+ if (input.shellUrl && !sameBackend(input.shellUrl, input.backendUrl))
65
+ return { action: 'shell' };
66
+ const config = input.read.status === 'ok' ? input.read.config : null;
67
+ const change = configBackendChange(config, input.backendUrl, undefined);
68
+ if (change.kind !== 'write')
69
+ return { action: 'keep' };
70
+ const hasKey = config !== null && Object.prototype.hasOwnProperty.call(config, 'backendUrl');
71
+ return { action: 'write', text: change.text, confirm: hasKey && !input.allowBackendChange };
72
+ }
73
+ function readSetupBackendConfig(configPath) {
74
+ if (!existsSync(configPath))
75
+ return { status: 'absent' };
76
+ try {
77
+ const bytes = readFileSync(configPath);
78
+ if ((bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0xfe && bytes[1] === 0xff)) {
79
+ return { status: 'unreadable', message: 'saved as UTF-16' };
80
+ }
81
+ return { status: 'ok', config: parseBackendConfig(bytes.toString('utf8')).config };
82
+ }
83
+ catch (error) {
84
+ return { status: 'unreadable', message: error instanceof Error ? error.message : String(error) };
85
+ }
86
+ }
87
+ function backendChangePath(read, configPath, backendUrl, allow) {
88
+ const plan = setupConfigPlan({ path: configPath, read, backendUrl, allowBackendChange: allow });
89
+ return plan.action === 'write' && plan.confirm ? configPath : null;
90
+ }
91
+ function instructionsUnanswered(options, targets) {
92
+ if (options.noAgentInstructions || options.allowAgentInstructions)
93
+ return false;
94
+ return targets.length > 0;
95
+ }
96
+ export function instructionAgent(env = process.env) {
97
+ const named = env.AI_AGENT?.trim().toLowerCase();
98
+ if (named === 'claude' || named === 'claude-code')
99
+ return 'claude';
100
+ if (named === 'codex')
101
+ return 'codex';
102
+ if (named)
103
+ return null;
104
+ if (env.CLAUDECODE)
105
+ return 'claude';
106
+ if (env.CODEX_SANDBOX || env.CODEX_CI || env.CODEX_THREAD_ID)
107
+ return 'codex';
108
+ return null;
109
+ }
110
+ function instructionPath(home, agent) {
111
+ const [dir, name] = agent === 'claude' ? ['.claude', 'CLAUDE.md'] : ['.codex', 'AGENTS.md'];
112
+ return path.join(home, dir, name);
113
+ }
114
+ export function instructionFiles(input) {
115
+ if (input.runningAsAgent) {
116
+ const agent = instructionAgent(input.env);
117
+ return agent ? [instructionPath(input.home, agent)] : [];
118
+ }
119
+ return ['claude', 'codex']
120
+ .map((agent) => instructionPath(input.home, agent))
121
+ .filter((file) => input.directoryExists(path.dirname(file)));
122
+ }
123
+ export { orgFromCloneUrl } from '../auth/origin.js';
124
+ const MARK = (org) => ({
125
+ start: `<!-- >>> superpanel ${org} -->`,
126
+ end: `<!-- <<< superpanel ${org} -->`,
127
+ });
128
+ export function instructionBlock(existing, org, display, folder) {
129
+ const { start, end } = MARK(org);
130
+ const body = [
131
+ start,
132
+ `${display}'s contact center on Superpanel is set up in ${folder}. When asked to change how it works (calls, texts, emails, follow-ups, hours, rules), work in that folder and follow its AGENTS.md; if this session is elsewhere, say so and ask to open it there.`,
133
+ end,
134
+ '',
135
+ ].join('\n');
136
+ const pattern = new RegExp(`${start}[\\s\\S]*?${end}\\n?`);
137
+ if (pattern.test(existing))
138
+ return existing.replace(pattern, body);
139
+ return `${existing.trimEnd()}\n\n${body}`;
140
+ }
141
+ function run(command, args, cwd) {
142
+ const launched = command === 'npm' ? npmLaunch(args) : { command, args };
143
+ const result = spawnSync(launched.command, launched.args, {
144
+ cwd,
145
+ encoding: 'utf8',
146
+ windowsVerbatimArguments: 'verbatim' in launched && launched.verbatim === true,
147
+ });
148
+ return { ok: result.status === 0, text: `${result.stdout ?? ''}${result.stderr ?? ''}`.trim() };
149
+ }
150
+ function confirm(question) {
151
+ return confirmAnswer(question, runningAsAgent() || !hasTerminal());
152
+ }
153
+ export function configBackendChange(config, backendUrl, shellUrl) {
154
+ if (shellUrl && !sameBackend(shellUrl, backendUrl))
155
+ return { kind: 'shell' };
156
+ const wanted = isDefaultBackend(backendUrl) ? null : backendUrl;
157
+ const hasKey = config !== null && Object.prototype.hasOwnProperty.call(config, 'backendUrl');
158
+ const current = hasKey && typeof config.backendUrl === 'string' ? config.backendUrl : undefined;
159
+ if (wanted === null) {
160
+ if (!hasKey)
161
+ return { kind: 'keep' };
162
+ return { kind: 'write', text: writeBackendConfig(config, null) };
163
+ }
164
+ if (current !== undefined && sameBackend(current, wanted))
165
+ return { kind: 'keep' };
166
+ return { kind: 'write', text: writeBackendConfig(config, wanted) };
167
+ }
168
+ export function supportedSetupNode(version) {
169
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version.trim());
170
+ return !!match && (Number(match[1]) > 22 || (Number(match[1]) === 22 && Number(match[2]) >= 15));
171
+ }
172
+ export async function runSetup(options) {
173
+ const node = run('node', ['-p', 'process.versions.node']);
174
+ if (!node.ok || !supportedSetupNode(node.text))
175
+ throw new Error('Node.js 22.15 or newer is required.');
176
+ if (!run('git', ['--version']).ok)
177
+ throw new Error('git is required.');
178
+ const backendUrl = resolveBackendUrl(options.url);
179
+ const shellUrl = shellBackendUrl();
180
+ const cached = await getValidCliAuthorization(backendUrl).catch((error) => {
181
+ if (error instanceof CliLoginRejectedError)
182
+ return null;
183
+ throw error;
184
+ });
185
+ let authorization = cached;
186
+ let me = authorization ? await requestCliIdentity(backendUrl, authorization.accessToken) : null;
187
+ if (!me || me.response.status === 401) {
188
+ await runLogin({ url: backendUrl, waitSeconds: options.waitSeconds, open: true });
189
+ authorization = await getValidCliAuthorization(backendUrl);
190
+ if (!authorization)
191
+ throw new Error(`not logged in to ${backendUrl}; run \`${loginCommand(backendUrl)}\``);
192
+ me = await requestCliIdentity(backendUrl, authorization.accessToken);
193
+ }
194
+ if (!authorization || !me.response.ok)
195
+ throw new Error('Could not verify the company for this login. Retry setup when the backend is available.');
196
+ const slug = me.payload?.user?.companyName ?? null;
197
+ if (options.company && (!me.response.ok || !slug))
198
+ throw new Error('Could not verify the company for this login. Retry setup when the backend is available.');
199
+ const display = me.payload?.user?.companyDisplayName ?? slug ?? 'This company';
200
+ if (options.company && slug && options.company !== slug) {
201
+ throw new Error(`This login is for ${slug}. To set up ${options.company}, run \`${cliCommand('logout', backendUrl)}\`, switch company in the web app, then \`${loginCommand(backendUrl)}\`.`);
202
+ }
203
+ const preferSsh = defaultCloneUsesSsh(me.payload.user?.role);
204
+ const asAgent = runningAsAgent();
205
+ const agent = asAgent || !hasTerminal();
206
+ const instructionTargets = instructionFiles({
207
+ home: homedir(),
208
+ runningAsAgent: asAgent,
209
+ directoryExists: (dir) => existsSync(dir),
210
+ });
211
+ const account = await getGitAccount(backendUrl, authorization.accessToken);
212
+ const previewUrl = account?.httpsCloneUrl ?? account?.sshCloneUrl ?? null;
213
+ if (!account || !previewUrl)
214
+ throw new Error('This login has no company repository to clone.');
215
+ const org = orgFromCloneUrl(previewUrl);
216
+ if (!org)
217
+ throw new Error('The clone address has no organization name.');
218
+ const folder = companyFolder(org);
219
+ const configPath = path.join(folder, BACKEND_CONFIG_FILE);
220
+ const backendConfig = readSetupBackendConfig(configPath);
221
+ const earlyConfig = setupConfigPlan({ path: configPath, read: backendConfig, backendUrl });
222
+ if (earlyConfig.action === 'stop')
223
+ throw new Error(earlyConfig.message);
224
+ const cloneStatus = existsSync(folder) ? await companyCloneStatus(folder, account) : 'missing';
225
+ if (cloneStatus === 'different') {
226
+ throw new Error(`${folder} is a different git repository. Setup will not change it. Move that directory aside and run setup again.`);
227
+ }
228
+ const names = existsSync(folder) ? readdirSync(folder) : [];
229
+ if (cloneStatus === 'missing' && names.length > 0) {
230
+ throw new Error(`${folder} already has other files. Setup will not replace them.`);
231
+ }
232
+ const reuse = cloneStatus === 'matches';
233
+ if (agent) {
234
+ const protocol = reuse
235
+ ? null
236
+ : chooseGitProtocol({
237
+ requested: options.gitProtocol,
238
+ preferSsh,
239
+ installCli: options.installCli,
240
+ });
241
+ const questions = setupQuestionsForAgent({
242
+ protocol,
243
+ backendChangePath: backendChangePath(backendConfig, configPath, backendUrl, options.allowBackendChange),
244
+ instructions: instructionsUnanswered(options, instructionTargets),
245
+ });
246
+ if (protocol === 'ssh' && account.sshCloneUrl && account.sshHost && account.sshPort)
247
+ questions.push(...(await sshSetupQuestions({ ...account, sshCloneUrl: account.sshCloneUrl, sshHost: account.sshHost, sshPort: account.sshPort }, Boolean(options.allowSshConfig))));
248
+ if (questions.length > 0)
249
+ throw new NeedsPersonError(questions.join('\n'));
250
+ }
251
+ await refreshInstalledSkill();
252
+ let method;
253
+ if (reuse) {
254
+ console.log(`Using the existing clone at ${folder} with its configured Git addresses.`);
255
+ }
256
+ else {
257
+ method = await prepareGitMethod({
258
+ command: 'setup',
259
+ onInstallAnswer: (answer) => {
260
+ options = { ...options, installCli: answer };
261
+ },
262
+ requested: options.gitProtocol,
263
+ preferSsh,
264
+ installCli: options.installCli,
265
+ backendUrl,
266
+ token: authorization.accessToken,
267
+ agent,
268
+ });
269
+ if (method === 'ssh' && !options.gitProtocol && !preferSsh && options.installCli === false) {
270
+ console.error('The global CLI will not be installed, so git uses SSH.');
271
+ }
272
+ if (method === 'ssh' && !run('ssh', ['-V']).ok)
273
+ throw new Error('ssh is required for --git-protocol ssh.');
274
+ const cloneUrl = method === 'ssh' ? account.sshCloneUrl : account.httpsCloneUrl;
275
+ if (!cloneUrl)
276
+ throw new Error('This login has no company repository to clone.');
277
+ const git = await setUpGit({
278
+ backendUrl,
279
+ token: authorization.accessToken,
280
+ method,
281
+ allowSshConfig: Boolean(options.allowSshConfig),
282
+ });
283
+ const refusal = gitSetupRefusal(git, {
284
+ allowSshConfig: Boolean(options.allowSshConfig),
285
+ command: 'setup',
286
+ backendUrl,
287
+ });
288
+ if (refusal)
289
+ throw refusal;
290
+ if (!existsSync(folder))
291
+ mkdirSync(folder, { recursive: true });
292
+ const cloned = await isolatedGit(['clone', '--', cloneUrl, folder]);
293
+ if (cloned.code !== 0)
294
+ throw new Error(cloned.stderr || `Could not clone into ${folder}`);
295
+ }
296
+ const configNow = readSetupBackendConfig(configPath);
297
+ const plan = setupConfigPlan({
298
+ path: configPath,
299
+ read: configNow,
300
+ backendUrl,
301
+ shellUrl,
302
+ allowBackendChange: options.allowBackendChange,
303
+ });
304
+ if (plan.action === 'stop')
305
+ throw new Error(plan.message);
306
+ if (plan.action === 'shell') {
307
+ console.error('SUPERPANEL_SDK_BACKEND_URL is set in the shell. Clear it, or pass --url every time.');
308
+ }
309
+ else if (plan.action === 'write') {
310
+ if (plan.confirm && !(await confirm(`Update ${configPath} so this repo uses ${backendUrl}?`))) {
311
+ throw new NeedsPersonError(`The backend address in ${configPath} would change. Ask the person, then rerun with --allow-backend-change.`);
312
+ }
313
+ if (plan.text === null)
314
+ unlinkSync(configPath);
315
+ else {
316
+ mkdirSync(path.dirname(configPath), { recursive: true });
317
+ writeFileSync(configPath, plan.text);
318
+ }
319
+ }
320
+ const installed = run('npm', ['install'], folder);
321
+ if (!installed.ok)
322
+ throw new Error(installed.text || 'npm install failed');
323
+ const checked = run('npm', ['run', 'typecheck'], folder);
324
+ if (!checked.ok)
325
+ throw new Error(checked.text || 'npm run typecheck failed');
326
+ if (!options.noAgentInstructions && instructionTargets.length > 0) {
327
+ if (!options.allowAgentInstructions) {
328
+ const yes = await confirm('Write a short note to your agent about this company folder?');
329
+ if (!yes) {
330
+ if (agent) {
331
+ throw new NeedsPersonError('Setup can write a note in the agent instructions naming this folder. Ask the person, then rerun with --allow-agent-instructions "<their words>" or --no-agent-instructions.');
332
+ }
333
+ }
334
+ else {
335
+ options = { ...options, allowAgentInstructions: 'yes' };
336
+ }
337
+ }
338
+ if (options.allowAgentInstructions) {
339
+ for (const file of instructionTargets) {
340
+ mkdirSync(path.dirname(file), { recursive: true });
341
+ const previous = existsSync(file) ? readFileSync(file, 'utf8') : '';
342
+ writeFileSync(file, instructionBlock(previous, org, display, folder));
343
+ }
344
+ }
345
+ }
346
+ if (reuse || method === 'ssh') {
347
+ await offerGlobalCli({ installCli: options.installCli, backendUrl, token: authorization.accessToken, agent });
348
+ }
349
+ await offerSkill(options);
350
+ console.log(`Setup complete. The company repo is at ${folder}.`);
351
+ console.log("Read this repo's AGENTS.md and brief/brief.yaml. If the brief records previous rounds, continue from the latest progress. If there are no rounds yet, start the first one by asking what matters most to the company.");
352
+ console.log('Start the next chat in that folder before editing the repo.');
353
+ }
354
+ export async function offerSkill(options, deps = {}) {
355
+ if (options.installSkill === false || !(deps.globalCli ?? globalCliInstalled)())
356
+ return;
357
+ const install = runSkillInstall({ skipForeign: options.installSkill !== true }, deps.homes);
358
+ if (options.installSkill === true)
359
+ return install;
360
+ try {
361
+ await install;
362
+ }
363
+ catch (error) {
364
+ console.error(`Could not install the Superpanel skill: ${error instanceof Error ? error.message : error}`);
365
+ }
366
+ }
@@ -0,0 +1,29 @@
1
+ export type SkillCopy = 'missing' | 'current' | 'outdated' | 'foreign';
2
+ export declare const MANAGED_SKILL_MARK = "managed-by: superpanel-cli";
3
+ export declare function skillCopyKind(copy: string | null, text: string): SkillCopy;
4
+ export declare function skillText(): string;
5
+ export declare function runningFromCache(entry?: string): boolean;
6
+ export declare function isGlobalPathCli(input: {
7
+ entry: string;
8
+ pathValue: string;
9
+ find?: (command: string, pathValue: string) => string | null;
10
+ cliEntry?: (found: string) => string;
11
+ sameFile?: (left: string, right: string) => boolean;
12
+ }): boolean;
13
+ export declare function refreshInstalledSkill(input?: {
14
+ entry?: string;
15
+ pathValue?: string;
16
+ find?: (command: string, pathValue: string) => string | null;
17
+ cliEntry?: (found: string) => string;
18
+ sameFile?: (left: string, right: string) => boolean;
19
+ text?: string;
20
+ homes?: string[];
21
+ read?: (file: string) => Promise<string | null>;
22
+ write?: (dir: string, text: string) => Promise<void>;
23
+ warn?: (message: string) => void;
24
+ }): Promise<void>;
25
+ export declare function runSkillInstall(options?: {
26
+ allowOverwrite?: boolean;
27
+ skipForeign?: boolean;
28
+ }, homes?: string[], confirmOverwrite?: ((question: string) => Promise<boolean>) | undefined): Promise<void>;
29
+ //# sourceMappingURL=skill.d.ts.map
@@ -0,0 +1,169 @@
1
+ import { readFileSync, realpathSync } from 'node:fs';
2
+ import { lstat, mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { credentialCliEntry, findOnPath, shellPath } from '../git/setup.js';
7
+ import { hasTerminal, runningAsAgent } from '../ops/agent.js';
8
+ import { confirm } from './git-method.js';
9
+ import { NeedsPersonError } from '../ops/types.js';
10
+ import { cliVersion } from '../version.js';
11
+ export const MANAGED_SKILL_MARK = 'managed-by: superpanel-cli';
12
+ export function skillCopyKind(copy, text) {
13
+ if (copy === null)
14
+ return 'missing';
15
+ if (!copy.includes(MANAGED_SKILL_MARK))
16
+ return 'foreign';
17
+ return copy === text ? 'current' : 'outdated';
18
+ }
19
+ const SKILL_HOMES = [
20
+ path.join(homedir(), '.claude', 'skills', 'superpanel'),
21
+ path.join(homedir(), '.agents', 'skills', 'superpanel'),
22
+ ];
23
+ export function skillText() {
24
+ const file = fileURLToPath(new URL('../../skill/SKILL.md', import.meta.url));
25
+ return readFileSync(file, 'utf8').replace(/cli-version: [\w.-]+/, `cli-version: ${cliVersion()}`);
26
+ }
27
+ export function runningFromCache(entry = process.argv[1] ?? '') {
28
+ return entry.includes(`${path.sep}_npx${path.sep}`) || entry.includes(`${path.sep}.npm${path.sep}`);
29
+ }
30
+ function sameFile(left, right) {
31
+ const resolved = (file) => {
32
+ try {
33
+ return realpathSync(file);
34
+ }
35
+ catch {
36
+ return path.resolve(file);
37
+ }
38
+ };
39
+ return resolved(left) === resolved(right);
40
+ }
41
+ export function isGlobalPathCli(input) {
42
+ if (!input.entry || runningFromCache(input.entry))
43
+ return false;
44
+ const found = (input.find ?? findOnPath)('superpanel', shellPath(input.pathValue));
45
+ if (!found)
46
+ return false;
47
+ const resolved = (input.cliEntry ?? credentialCliEntry)(found);
48
+ return (input.sameFile ?? sameFile)(resolved, input.entry);
49
+ }
50
+ async function readSkillCopy(dir) {
51
+ try {
52
+ return await readFile(path.join(dir, 'SKILL.md'), 'utf8');
53
+ }
54
+ catch (error) {
55
+ if (error.code !== 'ENOENT')
56
+ throw error;
57
+ }
58
+ try {
59
+ await lstat(dir);
60
+ return '';
61
+ }
62
+ catch (error) {
63
+ if (error.code === 'ENOENT')
64
+ return null;
65
+ throw error;
66
+ }
67
+ }
68
+ export async function refreshInstalledSkill(input = {}) {
69
+ const warn = input.warn ?? ((message) => console.error(message));
70
+ try {
71
+ if (!isGlobalPathCli({
72
+ entry: input.entry ?? process.argv[1] ?? '',
73
+ pathValue: input.pathValue ?? process.env.PATH ?? '',
74
+ find: input.find,
75
+ cliEntry: input.cliEntry,
76
+ sameFile: input.sameFile,
77
+ })) {
78
+ return;
79
+ }
80
+ const text = input.text ?? skillText();
81
+ const homes = input.homes ?? SKILL_HOMES;
82
+ const read = input.read ??
83
+ (async (file) => {
84
+ try {
85
+ return await readFile(file, 'utf8');
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ });
91
+ const write = input.write ??
92
+ (async (dir, body) => {
93
+ await mkdir(dir, { recursive: true });
94
+ await writeFile(path.join(dir, 'SKILL.md'), body);
95
+ });
96
+ for (const dir of homes) {
97
+ let current;
98
+ try {
99
+ current = await read(path.join(dir, 'SKILL.md'));
100
+ }
101
+ catch (error) {
102
+ warn(`Could not read the Superpanel skill in ${dir} (${error instanceof Error ? error.message : error}).`);
103
+ continue;
104
+ }
105
+ if (skillCopyKind(current, text) !== 'outdated')
106
+ continue;
107
+ try {
108
+ await write(dir, text);
109
+ warn(`Updated the Superpanel skill in ${dir}`);
110
+ }
111
+ catch (error) {
112
+ warn(`Could not update the Superpanel skill in ${dir} (${error instanceof Error ? error.message : error}).`);
113
+ }
114
+ }
115
+ }
116
+ catch (error) {
117
+ warn(`Could not update the Superpanel skill (${error instanceof Error ? error.message : error}).`);
118
+ }
119
+ }
120
+ export async function runSkillInstall(options = {}, homes = SKILL_HOMES, confirmOverwrite = hasTerminal() && !runningAsAgent() ? (question) => confirm(question, false) : undefined) {
121
+ const text = skillText();
122
+ const failures = [];
123
+ for (const dir of homes) {
124
+ const file = path.join(dir, 'SKILL.md');
125
+ let current;
126
+ try {
127
+ current = await readSkillCopy(dir);
128
+ }
129
+ catch (error) {
130
+ failures.push(`Could not read the Superpanel skill in ${dir} (${error instanceof Error ? error.message : error}).`);
131
+ continue;
132
+ }
133
+ const kind = skillCopyKind(current, text);
134
+ if (kind === 'foreign' && !options.allowOverwrite) {
135
+ if (options.skipForeign) {
136
+ console.error(`Left ${dir} as it is: Superpanel did not write it. If the person wants the skill there, ask them first, then run superpanel skill install --allow-overwrite.`);
137
+ continue;
138
+ }
139
+ if (confirmOverwrite) {
140
+ const yes = await confirmOverwrite(`Install Superpanel's SKILL.md in the existing folder ${dir}? Any existing SKILL.md there will be replaced; other files will be kept.`);
141
+ if (!yes) {
142
+ console.error(`Skipped the Superpanel skill in ${dir}.`);
143
+ continue;
144
+ }
145
+ }
146
+ else
147
+ throw new NeedsPersonError([
148
+ `${dir} already exists and was not written by Superpanel.`,
149
+ 'Stop and ask the person. If they agree, run superpanel skill install --allow-overwrite.',
150
+ ].join('\n'));
151
+ }
152
+ if (kind === 'current')
153
+ continue;
154
+ if (kind === 'outdated' && runningFromCache()) {
155
+ console.error(`The Superpanel skill in ${dir} was written by another CLI version. A global install rewrites it; this copy does not.`);
156
+ continue;
157
+ }
158
+ try {
159
+ await mkdir(dir, { recursive: true });
160
+ await writeFile(file, text);
161
+ console.error(`Installed the Superpanel skill in ${dir}`);
162
+ }
163
+ catch (error) {
164
+ failures.push(`Could not write the Superpanel skill in ${dir} (${error instanceof Error ? error.message : error}).`);
165
+ }
166
+ }
167
+ if (failures.length)
168
+ throw new Error(failures.join('\n'));
169
+ }
@@ -0,0 +1,13 @@
1
+ export declare function runSshKeyList(options: {
2
+ url?: string;
3
+ }): Promise<void>;
4
+ export declare function runSshKeyAdd(options: {
5
+ url?: string;
6
+ publicKey?: string;
7
+ title?: string;
8
+ }): Promise<void>;
9
+ export declare function runSshKeyRemove(id: string, options: {
10
+ url?: string;
11
+ allowRemove?: string;
12
+ }): Promise<void>;
13
+ //# sourceMappingURL=ssh-key.d.ts.map
@@ -0,0 +1,83 @@
1
+ import { CliLoginRejectedError, getValidCliAuthorization, loginCommand, resolveBackendUrl } from '../auth/auth.js';
2
+ import { guardNetworkedClone } from '../auth/origin-guard.js';
3
+ import { listSshKeys, addSshKey } from '../api/platform.js';
4
+ import { apiUrl, sendJson } from '../auth/http.js';
5
+ import { hasTerminal, runningAsAgent } from '../ops/agent.js';
6
+ import { NeedsPersonError } from '../ops/types.js';
7
+ async function tokenFor(url) {
8
+ const backendUrl = resolveBackendUrl(url);
9
+ try {
10
+ const authorization = await getValidCliAuthorization(backendUrl);
11
+ if (!authorization)
12
+ throw new Error(`Not logged in. Run \`${loginCommand(backendUrl)}\`.`);
13
+ return { backendUrl, token: authorization.accessToken };
14
+ }
15
+ catch (error) {
16
+ if (error instanceof CliLoginRejectedError)
17
+ throw new Error(`The login ended. Run \`${loginCommand(backendUrl)}\`.`);
18
+ throw error;
19
+ }
20
+ }
21
+ function printKey(key) {
22
+ console.log(`${key.id}\t${key.fingerprint}\t${key.title}`);
23
+ }
24
+ export async function runSshKeyList(options) {
25
+ const { backendUrl, token } = await tokenFor(options.url);
26
+ await guardNetworkedClone(process.cwd(), backendUrl, token);
27
+ const keys = await listSshKeys(backendUrl, token);
28
+ if (keys.length === 0)
29
+ console.log('No SSH keys on this Git account.');
30
+ for (const key of keys)
31
+ printKey(key);
32
+ }
33
+ export async function runSshKeyAdd(options) {
34
+ const publicKey = options.publicKey?.trim();
35
+ if (!publicKey)
36
+ throw new Error('--public-key is required');
37
+ const { backendUrl, token } = await tokenFor(options.url);
38
+ await guardNetworkedClone(process.cwd(), backendUrl, token);
39
+ const added = await addSshKey(backendUrl, token, {
40
+ title: options.title?.trim() || 'superpanel',
41
+ publicKey,
42
+ });
43
+ console.log(added.created ? `Added SSH key ${added.key.id}.` : `SSH key ${added.key.id} was already on the account.`);
44
+ }
45
+ async function confirmRemove(key, quote) {
46
+ if (quote?.trim())
47
+ return;
48
+ const message = [
49
+ `This deletes SSH key ${key.id} (${key.title}, ${key.fingerprint}).`,
50
+ 'Another computer that uses this key will not be able to reach git.',
51
+ 'Stop and ask the person. If they agree, rerun with --allow-remove "<their words>".',
52
+ 'A vague answer is not agreement: ask again.',
53
+ ].join('\n');
54
+ if (runningAsAgent() || !hasTerminal())
55
+ throw new NeedsPersonError(message);
56
+ const { createInterface } = await import('node:readline/promises');
57
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
58
+ try {
59
+ const answer = await rl.question(`${message}\nProceed? [y/N] `);
60
+ if (!/^y(es)?$/i.test(answer.trim()))
61
+ throw new Error('Not changed.');
62
+ }
63
+ finally {
64
+ rl.close();
65
+ }
66
+ }
67
+ export async function runSshKeyRemove(id, options) {
68
+ const keyId = Number(id);
69
+ if (!Number.isInteger(keyId))
70
+ throw new Error('the key id is a number from `superpanel ssh-key list`');
71
+ const { backendUrl, token } = await tokenFor(options.url);
72
+ await guardNetworkedClone(process.cwd(), backendUrl, token);
73
+ const keys = await listSshKeys(backendUrl, token);
74
+ const key = keys.find((item) => item.id === keyId);
75
+ if (!key)
76
+ throw new Error(`No SSH key ${id} on this Git account.`);
77
+ await confirmRemove(key, options.allowRemove);
78
+ const { response, payload } = await sendJson('DELETE', apiUrl(backendUrl, `me/gitea/ssh-keys/${keyId}`), token);
79
+ if (!response.ok && response.status !== 204) {
80
+ throw new Error(payload.error ?? `removing the key failed (${response.status})`);
81
+ }
82
+ console.log(`Removed SSH key ${key.id} (${key.title}).`);
83
+ }
@@ -0,0 +1,7 @@
1
+ export type CredentialIo = {
2
+ stdin: NodeJS.ReadableStream;
3
+ stdout: NodeJS.WritableStream;
4
+ stderr: NodeJS.WritableStream;
5
+ };
6
+ export declare function runGitCredential(action: string, backendUrl: string, io: CredentialIo): Promise<void>;
7
+ //# sourceMappingURL=credential.d.ts.map