@quadient/skillshare 1.20.3 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@ import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { isAbsolute } from 'node:path';
3
3
  import { stat } from 'node:fs/promises';
4
4
  import { responseFingerprint } from './agents-response-hash.js';
5
+ import { agentEnvironmentSecrets, sanitizeAgentDiagnostics } from './agents-process.js';
5
6
  /** UI dimensions never change a native decision, scope or answer. Unencodable interactions stay visible and pending. */
6
7
  export function boundedSessionRequest(request) {
7
8
  const validKey = (key) => typeof key === 'string' && key.length > 0;
@@ -169,10 +170,12 @@ export class SessionRunner {
169
170
  now;
170
171
  opened = null;
171
172
  openSucceeded = false;
173
+ stopStartup;
172
174
  turnRunning = false;
173
175
  interruptRequested = false;
174
176
  idleTimer = null;
175
177
  closing = null;
178
+ driverClosing = null;
176
179
  closedReported = false;
177
180
  requests = new Set();
178
181
  responding = new Set();
@@ -200,16 +203,26 @@ export class SessionRunner {
200
203
  workdir: options.workdir,
201
204
  profile: options.profile,
202
205
  sandbox: options.sandbox,
203
- item: item => this.events.push({ type: 'item', ...item, text: item.text === undefined ? undefined : clip(item.text) }),
204
- thread: threadId => this.events.push({ type: 'thread', threadId }),
206
+ item: item => { if (!this.closing && !this.driverClosing)
207
+ this.events.push({ type: 'item', ...item, text: item.text === undefined ? undefined : clip(item.text) }); },
208
+ thread: threadId => { if (!this.closing && !this.driverClosing)
209
+ this.events.push({ type: 'thread', threadId }); },
205
210
  suggestion: text => {
206
211
  if (this.busy || this.closing || !text.trim())
207
212
  return;
208
213
  this.events.push({ type: 'suggestion', text: clip(text.trim(), MAX_SUGGESTION) });
209
214
  },
210
- exited: error => void this.finish(error ?? 'The agent stopped unexpectedly.'),
215
+ exited: error => {
216
+ if (this.driverClosing)
217
+ return;
218
+ const reason = error ?? 'The agent stopped unexpectedly.';
219
+ if (this.stopStartup)
220
+ this.stopStartup(reason);
221
+ else
222
+ void this.finish(reason);
223
+ },
211
224
  request: request => {
212
- if (this.closing || this.requests.has(request.id))
225
+ if (this.closing || this.driverClosing || this.requests.has(request.id))
213
226
  return;
214
227
  this.requests.add(request.id);
215
228
  this.timeoutChanged?.();
@@ -338,6 +351,10 @@ export class SessionRunner {
338
351
  if (!this.turnRunning || this.interruptRequested)
339
352
  return;
340
353
  this.interruptRequested = true;
354
+ if (this.stopStartup) {
355
+ this.stopStartup('The agent was stopped during startup.');
356
+ return;
357
+ }
341
358
  this.clearRequests();
342
359
  await this.driver.interrupt().catch(() => { });
343
360
  }
@@ -365,12 +382,15 @@ export class SessionRunner {
365
382
  const started = this.now();
366
383
  if (!this.openSucceeded) {
367
384
  try {
368
- this.opened ??= this.driver.open();
369
- await this.opened;
385
+ await this.openWithTimeout();
386
+ if (this.closing)
387
+ return;
370
388
  this.openSucceeded = true;
371
389
  }
372
390
  catch (error) {
373
- const reason = errorMessage(error);
391
+ if (this.closing)
392
+ return;
393
+ const reason = this.diagnosticError(errorMessage(error));
374
394
  // A failed resume uses up the message as a failed turn, so the server does not ask for the same start again.
375
395
  // A first start that fails has nothing to resume; the server fails the whole session.
376
396
  if (this.options.start.resumeThreadId) {
@@ -397,12 +417,47 @@ export class SessionRunner {
397
417
  this.clearRequests();
398
418
  if (this.interruptRequested && outcome.status === 'failed' && !outcome.error)
399
419
  outcome = { ...outcome, status: 'interrupted' };
400
- this.events.push({ type: 'turnCompleted', status: outcome.status, error: outcome.error,
420
+ this.events.push({ type: 'turnCompleted', status: outcome.status, error: outcome.error === undefined ? undefined : this.diagnosticError(outcome.error),
401
421
  stats: { ...outcome.stats, durationMs: this.now() - started } });
402
422
  this.turnRunning = false;
403
423
  void this.events.flush();
404
424
  void this.pump();
405
425
  }
426
+ /** Initialization can hang before a turn exists, so it needs its own deadline and cancellation. */
427
+ async openWithTimeout() {
428
+ const timeoutMs = this.options.startupTimeoutMs ?? 120_000;
429
+ let timer;
430
+ let expired = false;
431
+ const stopped = new Promise((resolve, reject) => {
432
+ this.stopStartup = error => {
433
+ if (expired && error)
434
+ return; // Killing the process must not replace the timeout with its exit error.
435
+ error ? reject(new Error(error)) : resolve();
436
+ };
437
+ // The backend can authorize native requests only after turnStarted, so startup must never pause for one.
438
+ timer = setTimeout(() => {
439
+ expired = true;
440
+ void this.closeDriver().then(() => {
441
+ const operation = this.options.start.resumeThreadId ? 'resume' : 'startup';
442
+ const diagnostics = this.driver.diagnostics?.();
443
+ reject(new Error(`The agent ${operation} did not finish within ${timeoutMs / 1000} seconds.`
444
+ + (diagnostics ? `\n${diagnostics}` : '')));
445
+ }).catch(reject);
446
+ }, timeoutMs);
447
+ });
448
+ try {
449
+ this.opened ??= this.driver.open();
450
+ await Promise.race([this.opened.then(() => expired ? stopped : undefined, error => {
451
+ if (expired)
452
+ return stopped;
453
+ throw error;
454
+ }), stopped]);
455
+ }
456
+ finally {
457
+ clearTimeout(timer);
458
+ this.stopStartup = undefined;
459
+ }
460
+ }
406
461
  /** Interrupts a turn that runs past its timeout, and gives up on an agent that does not stop when asked. */
407
462
  async withTimeout(turn) {
408
463
  const timeoutMs = Math.max(1, this.options.start.turnTimeoutSeconds) * 1000;
@@ -456,14 +511,34 @@ export class SessionRunner {
456
511
  clearTimeout(this.idleTimer);
457
512
  this.idleTimer = null;
458
513
  }
514
+ diagnosticError(error) {
515
+ return sanitizeAgentDiagnostics(error, [...agentEnvironmentSecrets(process.env), ...(this.options.start.mcpServers ?? []).map(server => server.bearerToken)]);
516
+ }
517
+ closeDriver() {
518
+ if (this.driverClosing)
519
+ return this.driverClosing;
520
+ let done;
521
+ this.driverClosing = new Promise(resolve => { done = resolve; });
522
+ try {
523
+ void this.driver.close().then(done, done);
524
+ }
525
+ catch {
526
+ done();
527
+ }
528
+ return this.driverClosing;
529
+ }
459
530
  finish(error) {
460
531
  this.closing ??= (async () => {
532
+ error = error === undefined ? undefined : this.diagnosticError(error);
533
+ if (error)
534
+ this.options.log?.(`Session ${this.sessionId} failed: ${oneLine(error, 2000)}`);
461
535
  this.clearIdle();
536
+ this.stopStartup?.();
462
537
  if (this.leaseTimer)
463
538
  clearTimeout(this.leaseTimer);
464
539
  this.leaseTimer = null;
465
540
  this.clearRequests();
466
- await this.driver.close().catch(() => { });
541
+ await this.closeDriver();
467
542
  if (this.turnRunning && !this.closedReported) {
468
543
  this.events.push({ type: 'turnCompleted', status: 'failed', error: error ?? 'The agent was stopped.' });
469
544
  this.turnRunning = false;
package/dist/agents.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { defaultServiceEnvironment, serviceLogs } from './service-manager.js';
1
2
  import { createHash, randomBytes } from 'node:crypto';
2
3
  import { mkdirSync } from 'node:fs';
3
4
  import { mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
@@ -5,7 +6,7 @@ import { hostname, homedir, platform, tmpdir } from 'node:os';
5
6
  import { dirname, isAbsolute, join } from 'node:path';
6
7
  import { setTimeout as delay } from 'node:timers/promises';
7
8
  import { createClaudeDriver } from './agents-claude.js';
8
- import { defaultServiceEnvironment, detectServiceAgents, installService, migrateServiceApprovalOptions, renderServiceStatus, serviceLogs, serviceStatus, uninstallService, } from './agents-service.js';
9
+ import { detectServiceAgents, installService, migrateServiceApprovalOptions, renderServiceStatus, serviceStatus, uninstallService, } from './agents-service.js';
9
10
  import { createCodexDriver } from './agents-codex.js';
10
11
  import { detectAgents, expandHome, profilesPath } from './agents-detect.js';
11
12
  import { loadAgentSettings, withoutLegacySandboxArgs } from './agents-settings.js';
@@ -376,7 +377,7 @@ export async function listen(options) {
376
377
  const runner = new SessionRunner({
377
378
  sessionId: command.sessionId, leaseToken: command.leaseToken, start: command.start, workdir: options.workdir, profile, sandbox: false,
378
379
  driver: driver(command.start), upload: uploader(command.sessionId, command.leaseToken), idleMs: options.idleMs, flushIntervalMs: options.flushIntervalMs,
379
- now,
380
+ now, log,
380
381
  leaseNow, leaseDeadline: polledAt + command.leaseRemainingMs,
381
382
  authorizeResponse: async (response) => {
382
383
  const result = await send(options.client, 'POST', `${root}/listeners/${options.listenerId}/sessions/${command.sessionId}/authorize-response`, {
package/dist/help.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  export const GLOBAL_FLAGS = ['token', 'server', 'help'];
3
- export const BOOLEAN_FLAGS = new Set(['all', 'digest', 'disabled', 'dry-run', 'force', 'headless', 'help', 'json', 'keep-unread', 'no-teams-watch', 'no-update', 'notify-again', 'original', 'external', 'internal', 'always-on', 'owners-only', 'resolved', 'review', 'sandbox', 'unread']);
3
+ export const BOOLEAN_FLAGS = new Set(['all', 'digest', 'disabled', 'dry-run', 'force', 'headless', 'help', 'json', 'keep-unread', 'no-teams-watch', 'no-update', 'no-wait', 'notify-again', 'original', 'always-on', 'owners-only', 'resolved', 'review', 'sandbox', 'unread']);
4
4
  export const COMMANDS = [
5
5
  {
6
6
  name: 'login',
@@ -86,8 +86,14 @@ export const COMMANDS = [
86
86
  'pages list [--json]',
87
87
  'pages show <slug> [--json]',
88
88
  'pages runtime <slug> [--json]',
89
- 'pages runtime set <slug> [--external|--internal] [--min <MiB>] [--max <MiB>] [--always-on true|false] [--json]',
89
+ 'pages runtime set <slug> [--min <MiB>] [--max <MiB>] [--always-on true|false] [--json]',
90
+ 'pages backups list <slug> [--json]',
91
+ 'pages backups create <slug> [--keep <days>] [--no-wait] [--json]',
92
+ 'pages backups restore <slug> <id> [--confirm <slug>] [--no-wait] [--json]',
93
+ 'pages backups delete <slug> <id> [--json]',
94
+ 'pages backups daily <slug> on|off [--json]',
90
95
  'pages upload <directory> [--slug <slug>] [--json]',
96
+ 'pages rename <slug> <new-slug> [--json]',
91
97
  'pages secrets list <slug> [--json]',
92
98
  'pages secrets set <slug> <name> [--json]',
93
99
  'pages secrets delete <slug> <name> [--json]',
@@ -99,9 +105,9 @@ export const COMMANDS = [
99
105
  'pages dev [directory] [--slug <slug>] [--port <port>] [--build <command> --watch-dir <sources>]',
100
106
  ' [--celld <executable>] [--user-id <id>] [--user-name <name>] [--user-email <email>]',
101
107
  ],
102
- description: 'An upload replaces all content of the page. Without --slug the directory name is used; build output folders such as dist need an explicit --slug. Pages owned by someone else are refused unless you are their co-owner or an admin. pages secrets manages the write-only secrets an app reads through SKILLSHARE_SECRETS (owner or admin only, at most 32 per page, 16 KiB each); set reads the value from piped stdin or a masked prompt, never from the command line. pages runtime set is for administrators: --external moves the app into its own pod (its data is copied, the app is briefly unavailable), --internal back into SkillShare; external apps get memory automatically between --min and --max MiB, and --always-on keeps an app running without traffic. pages comments reads and writes the annotations reviewers leave on a Page at /pa/<slug>/ (enable and disable decide whether the regular /p/<slug>/ address shows them too); add creates a page note, text without an argument (or -) is read from stdin, and list hides resolved threads unless --resolved is given.',
103
- examples: ['skillshare pages upload ./site --slug release-notes', 'skillshare pages dev . --slug my-app', 'skillshare pages secrets set my-app API_TOKEN', 'printf %s "$TOKEN" | skillshare pages secrets set my-app API_TOKEN', 'skillshare pages comments list my-app --author mine', 'skillshare pages comments reply my-app 12 "Fixed in revision 4"'],
104
- flags: ['slug', 'path', 'author', 'resolved', 'external', 'internal', 'min', 'max', 'always-on', 'json'],
108
+ description: 'An upload replaces all content of the page. Without --slug the directory name is used; build output folders such as dist need an explicit --slug. Pages owned by someone else are refused unless you are their co-owner or an admin. pages rename moves a page to a new slug with its versions, comments, secrets and app data (owner or admin only); the old address redirects to the new one and stays reserved. pages secrets manages the write-only secrets an app reads through SKILLSHARE_SECRETS (owner or admin only, at most 32 per page, 16 KiB each); set reads the value from piped stdin or a masked prompt, never from the command line. pages runtime set: each app runs in its own pod and gets memory automatically between --min and --max MiB, which the page owners or an admin set; only admins use --always-on to keep an app running without traffic. pages backups copies the data of a celld app (D1, KV, R2, Durable Objects, Workflows) for its owners or an admin; the app is stopped while a backup or restore runs and the command waits for it unless --no-wait. create keeps the backup for --keep days (default 30, at most 365), daily on takes a backup every day kept for 7 days, and every backup is deleted automatically when it expires. restore replaces all current data of the app: it asks twice, and without a terminal it needs --confirm <slug>. pages comments reads and writes the annotations reviewers leave on a Page at /pa/<slug>/ (enable and disable decide whether the regular /p/<slug>/ address shows them too); add creates a page note, text without an argument (or -) is read from stdin, and list hides resolved threads unless --resolved is given.',
109
+ examples: ['skillshare pages upload ./site --slug release-notes', 'skillshare pages dev . --slug my-app', 'skillshare pages backups create my-app --keep 7', 'skillshare pages backups restore my-app 3', 'skillshare pages secrets set my-app API_TOKEN', 'printf %s "$TOKEN" | skillshare pages secrets set my-app API_TOKEN', 'skillshare pages comments list my-app --author mine', 'skillshare pages comments reply my-app 12 "Fixed in revision 4"'],
110
+ flags: ['slug', 'path', 'author', 'resolved', 'min', 'max', 'always-on', 'keep', 'confirm', 'no-wait', 'json'],
105
111
  },
106
112
  {
107
113
  name: 'teams',
@@ -109,13 +115,17 @@ export const COMMANDS = [
109
115
  usage: [
110
116
  'teams login [local] [--browser chrome|msedge|chromium] [--headless] [--browser-profile <directory>]',
111
117
  'teams watch [local] [--browser chrome|msedge|chromium]',
118
+ 'teams service install [local] [--browser chrome|msedge|chromium] [--browser-profile <directory>] [--headless true|false]',
119
+ 'teams service status | uninstall',
120
+ 'teams service logs [--lines <count>]',
112
121
  'teams status | test [--json]',
113
122
  'teams logout',
114
123
  'teams access readOnly|limitedAccess|fullAccess',
115
124
  'teams upload <file>',
116
125
  'teams download <url> --output <new-file>',
117
126
  ],
118
- flags: ['browser', 'headless', 'browser-profile', 'output', 'json'],
127
+ description: 'After teams login, teams service install runs teams watch at every login for Teams renewal only. Manage the service with status, logs and uninstall.',
128
+ flags: ['browser', 'headless', 'browser-profile', 'output', 'json', 'lines'],
119
129
  },
120
130
  {
121
131
  name: 'salesforce',
package/dist/index.js CHANGED
@@ -4,7 +4,9 @@ import { runSalesforceCommand } from './salesforce.js';
4
4
  import { runNewsCommand } from './news.js';
5
5
  import { assertCredentialDestination, resolveTeamsObjectId, runTeamsCommand, watchTeamsInBackground } from './teams.js';
6
6
  import { runAgentsCommand, runServiceCommand } from './agents.js';
7
- import { SERVICE_ENV } from './agents-update.js';
7
+ import { runTeamsServiceCommand, TEAMS_SERVICE_ENV } from './teams-service.js';
8
+ import { defaultServiceEnvironment, servicePaths } from './service-manager.js';
9
+ import { fileLog, SERVICE_ENV } from './agents-update.js';
8
10
  import { formatUnknownCommand, parseCliArgs } from './cli-args.js';
9
11
  import { findCommand, readCliVersion, renderCommandHelp, renderUsage } from './help.js';
10
12
  import { inspectInstallTarget, installFilesAtomically } from './install-files.js';
@@ -15,6 +17,7 @@ import { runPageDev } from './pages-dev.js';
15
17
  import { runPageCommentsCommand } from './pages-comments.js';
16
18
  import { runPageSecretsCommand } from './pages-secrets.js';
17
19
  import { runPageRuntimeCommand } from './pages-runtime.js';
20
+ import { runPageBackupsCommand } from './pages-backups.js';
18
21
  import { waitForLoginCallback } from './login-callback.js';
19
22
  import { createHash, randomBytes } from 'node:crypto';
20
23
  import { spawn } from 'node:child_process';
@@ -139,19 +142,36 @@ async function main() {
139
142
  return;
140
143
  }
141
144
  case 'teams': {
142
- const baseUrl = options.flags.server ?? (options.positionals[1] === 'local' ? LOCAL_URL : await resolveActiveBaseUrl());
145
+ const [action, serviceAction] = options.positionals;
146
+ if (action === 'service' && serviceAction !== 'install') {
147
+ await runTeamsServiceCommand(defaultServiceEnvironment(APP_DIR), serviceAction, options.flags);
148
+ return;
149
+ }
150
+ const local = options.positionals[action === 'service' ? 2 : 1] === 'local';
151
+ const baseUrl = normalizeBaseUrl(options.flags.server ?? (local ? LOCAL_URL : await resolveActiveBaseUrl()));
143
152
  assertCredentialDestination(baseUrl);
144
- if (!options.token && !await loadSession(baseUrl))
153
+ const background = process.env[TEAMS_SERVICE_ENV] === '1';
154
+ // A service uses the saved, renewable CLI session. Never copy an install-time token into its launcher.
155
+ if (action === 'service' && options.flags.token)
156
+ throw new Error('teams service install uses your saved Skillshare login. Run it without --token.');
157
+ const token = action === 'service' || background ? undefined : options.token;
158
+ if (!token && !await loadSession(baseUrl)) {
159
+ if (background)
160
+ throw new Error(`Run skillshare login --server ${baseUrl} to sign in for the Teams service.`);
145
161
  await login(baseUrl);
146
- const teamsClient = await createClient(baseUrl, options.token);
147
- const action = options.positionals[0];
148
- if (!options.token && (action === 'login' || action === 'watch')
162
+ }
163
+ if (action === 'service') {
164
+ await runTeamsServiceCommand(defaultServiceEnvironment(APP_DIR), serviceAction, options.flags, baseUrl);
165
+ return;
166
+ }
167
+ const teamsClient = await createClient(baseUrl, token);
168
+ if (!background && !token && (action === 'login' || action === 'watch')
149
169
  && !resolveTeamsObjectId(await teamsClient.get('/api/auth/me'))) {
150
170
  // A browser sign-in lets the server record the Entra object id for this account.
151
171
  console.log('Linking your Microsoft account to Skillshare. Sign in once more in the browser.');
152
172
  await login(baseUrl);
153
173
  }
154
- await runTeamsCommand(teamsClient, options.positionals, options.flags, APP_DIR);
174
+ await runTeamsCommand(teamsClient, options.positionals, options.flags, APP_DIR, background ? fileLog(servicePaths(APP_DIR, 'teams').log) : undefined);
155
175
  return;
156
176
  }
157
177
  case 'salesforce': {
@@ -373,6 +393,16 @@ async function main() {
373
393
  await runPageRuntimeCommand(client, options.positionals.slice(1), options.flags, print);
374
394
  return;
375
395
  }
396
+ if (action === 'backups' || action === 'backup') {
397
+ const backupStatus = spinner({ indicator: 'timer', output: statusOutput });
398
+ await runPageBackupsCommand(client, options.positionals.slice(1), options.flags, {
399
+ print,
400
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
401
+ confirm: (message) => promptConfirm(message, false),
402
+ status: { start: (message) => backupStatus.start(message), stop: (message) => backupStatus.stop(message), clear: () => backupStatus.clear() },
403
+ });
404
+ return;
405
+ }
376
406
  if (action === 'show') {
377
407
  const slug = options.positionals[1];
378
408
  if (!slug)
@@ -402,6 +432,19 @@ async function main() {
402
432
  }
403
433
  return;
404
434
  }
435
+ if (action === 'rename') {
436
+ const [slug, newSlug] = options.positionals.slice(1);
437
+ if (!slug || !newSlug)
438
+ throw new Error('pages rename requires <slug> <new-slug>');
439
+ const current = await client.get(`/api/pages/${encodeURIComponent(slug)}`);
440
+ const detail = await parseJson(await client.request(`/api/pages/${encodeURIComponent(current.slug)}/rename`, {
441
+ method: 'POST',
442
+ headers: { 'Content-Type': 'application/json' },
443
+ body: JSON.stringify({ slug: newSlug, revision: current.contentRevision }),
444
+ }));
445
+ print(detail, () => `Renamed /p/${current.slug}/ to /p/${detail.slug}/. The old address redirects to it.\nOpen ${pageUrl(client.baseUrl, detail.slug)}`);
446
+ return;
447
+ }
405
448
  if (action === 'secrets') {
406
449
  await runPageSecretsCommand(client, options.positionals.slice(1), print);
407
450
  return;
@@ -410,7 +453,7 @@ async function main() {
410
453
  await runPageCommentsCommand(client, options.positionals.slice(1), options.flags, print);
411
454
  return;
412
455
  }
413
- throw new Error(`Unknown pages command '${action}'. Use list, show, runtime, upload, secrets, or comments.`);
456
+ throw new Error(`Unknown pages command '${action}'. Use list, show, runtime, upload, rename, secrets, or comments.`);
414
457
  }
415
458
  }
416
459
  return;
@@ -2245,5 +2288,8 @@ main().catch((error) => {
2245
2288
  const message = error instanceof Error
2246
2289
  ? error.message.trim() || 'Unexpected error.'
2247
2290
  : String(error).trim() || 'Unexpected error.';
2248
- process.stderr.write(`${message}\n`);
2291
+ if (process.env[TEAMS_SERVICE_ENV] === '1')
2292
+ fileLog(servicePaths(APP_DIR, 'teams').log)(message);
2293
+ else
2294
+ process.stderr.write(`${message}\n`);
2249
2295
  });
package/dist/output.js CHANGED
@@ -137,21 +137,19 @@ export function renderPageDetail(page, baseUrl, now = new Date()) {
137
137
  export function renderPageRuntime(slug, runtime, logLimit = 20) {
138
138
  const settings = runtime.settings;
139
139
  const lines = [
140
- `${slug}: ${runtime.state} · revision ${runtime.revision}${runtime.processId ? ` · pid ${runtime.processId}` : ''}${settings ? ` · ${settings.placement}` : ''}`,
140
+ `${slug}: ${runtime.state} · revision ${runtime.revision}${runtime.processId ? ` · pid ${runtime.processId}` : ''}`,
141
141
  ];
142
142
  if (runtime.error)
143
143
  lines.push(`Error: ${runtime.error}`);
144
144
  if (settings) {
145
145
  lines.push(`Always on: ${settings.alwaysOn ? 'yes' : 'no'}`);
146
- if (settings.placement === 'external') {
147
- const memory = runtime.memory;
148
- const usage = [
149
- memory?.currentMiB != null ? `using ${memory.currentMiB} MiB` : null,
150
- memory?.peakMiB != null ? `4-day peak ${memory.peakMiB} MiB` : null,
151
- memory?.outOfMemoryCount ? `${memory.outOfMemoryCount} out of memory` : null,
152
- ].filter(Boolean);
153
- lines.push(`Memory: ${settings.limitMiB} MiB, automatic within ${settings.minMiB}–${settings.maxMiB} MiB · CPU ${settings.cpuRequestMilli}m${usage.length ? ` · ${usage.join(' · ')}` : ''}`);
154
- }
146
+ const memory = runtime.memory;
147
+ const usage = [
148
+ memory?.currentMiB != null ? `using ${memory.currentMiB} MiB` : null,
149
+ memory?.peakMiB != null ? `4-day peak ${memory.peakMiB} MiB` : null,
150
+ memory?.outOfMemoryCount ? `${memory.outOfMemoryCount} out of memory` : null,
151
+ ].filter(Boolean);
152
+ lines.push(`Memory: ${settings.limitMiB} MiB, automatic within ${settings.minMiB}–${settings.maxMiB} MiB · CPU ${settings.cpuRequestMilli}m${usage.length ? ` · ${usage.join(' · ')}` : ''}`);
155
153
  }
156
154
  if (runtime.logsUrl)
157
155
  lines.push(`Pod logs: ${runtime.logsUrl}`);
@@ -0,0 +1,168 @@
1
+ import { formatByteSize, formatDateTime } from './output.js';
2
+ const POLL_MS = 2000;
3
+ /**
4
+ * `pages backups` lets the owners of a celld Page and administrators back up its data, keep daily backups and
5
+ * restore one. Backups and restores run on the server with the Page stopped; the command waits for them unless --no-wait.
6
+ */
7
+ export async function runPageBackupsCommand(client, positionals, flags, deps) {
8
+ const [action = 'list', slug, argument] = positionals;
9
+ if (!slug)
10
+ throw new Error(`pages backups ${action} requires <slug>`);
11
+ const base = `/api/pages/${encodeURIComponent(slug)}/backups`;
12
+ const wait = !isTrue(flags['no-wait']);
13
+ if (action === 'list') {
14
+ const view = await expect(slug, await client.request(base, { method: 'GET' }));
15
+ deps.print(view, () => renderPageBackups(slug, view));
16
+ return;
17
+ }
18
+ if (action === 'create') {
19
+ const body = flags.keep === undefined ? {} : { retentionDays: days(flags.keep) };
20
+ const started = await expect(slug, await client.request(base, json('POST', body)));
21
+ if (!wait) {
22
+ deps.print(started, () => `Backing up /p/${slug}/ as backup #${started.id}, kept until ${formatDateTime(started.expires)}. The Page is stopped until it finishes.`);
23
+ return;
24
+ }
25
+ deps.status.start(`Backing up /p/${slug}/ (the Page is stopped meanwhile)`);
26
+ const backup = await poll(client, slug, base, deps, (view) => {
27
+ const current = view.backups.find((candidate) => candidate.id === started.id);
28
+ return current && current.state !== 'creating' ? current : undefined;
29
+ });
30
+ if (backup.state === 'failed') {
31
+ deps.status.clear();
32
+ throw new Error(`Backup #${backup.id} of /p/${slug}/ failed: ${backup.error ?? 'unknown error'}`);
33
+ }
34
+ deps.status.stop(`Backed up /p/${slug}/ as backup #${backup.id} (${formatByteSize(backup.bytes)})`);
35
+ deps.print(backup, () => `Kept until ${formatDateTime(backup.expires)}.`);
36
+ return;
37
+ }
38
+ if (action === 'delete') {
39
+ const id = backupId(argument, 'delete');
40
+ await expect(slug, await client.request(`${base}/${id}`, { method: 'DELETE' }), id);
41
+ deps.print({ deleted: id }, () => `Deleted backup #${id} of /p/${slug}/.`);
42
+ return;
43
+ }
44
+ if (action === 'daily') {
45
+ if (argument !== 'on' && argument !== 'off')
46
+ throw new Error('pages backups daily requires <slug> on|off');
47
+ const view = await expect(slug, await client.request(`${base}/schedule`, json('PUT', { enabled: argument === 'on' })));
48
+ deps.print(view, () => `Daily backups of /p/${slug}/ are ${daily(view)}.`);
49
+ return;
50
+ }
51
+ if (action === 'restore') {
52
+ const id = backupId(argument, 'restore');
53
+ const view = await expect(slug, await client.request(base, { method: 'GET' }));
54
+ const backup = view.backups.find((candidate) => candidate.id === id);
55
+ if (!backup)
56
+ throw new Error(`Backup #${id} of /p/${slug}/ was not found.`);
57
+ if (backup.state !== 'ready')
58
+ throw new Error(`Backup #${id} of /p/${slug}/ is ${backup.state}; only a completed backup can be restored.`);
59
+ const created = formatDateTime(backup.created);
60
+ if (flags.confirm !== undefined) {
61
+ if (flags.confirm !== slug)
62
+ throw new Error(`--confirm must repeat the Page slug ${slug}.`);
63
+ }
64
+ else if (!deps.interactive) {
65
+ throw new Error(`Restoring replaces all data of /p/${slug}/. Repeat its slug with --confirm ${slug} to proceed.`);
66
+ }
67
+ else if (!await deps.confirm(`Restore /p/${slug}/ from backup #${id} of ${created}? All data written since then will be lost.`) ||
68
+ !await deps.confirm(`Are you absolutely sure? All current data of /p/${slug}/ will be permanently replaced by the backup of ${created}. This cannot be undone.`)) {
69
+ deps.print({ restored: false }, () => 'Restore cancelled; nothing was changed.');
70
+ return;
71
+ }
72
+ const started = await expect(slug, await client.request(`${base}/${id}/restore`, json('POST', { confirm: slug })), id);
73
+ if (!wait) {
74
+ deps.print(started, () => `Restoring /p/${slug}/ from backup #${id}. The Page is stopped until it finishes.`);
75
+ return;
76
+ }
77
+ deps.status.start(`Restoring /p/${slug}/ from backup #${id} (the Page is stopped meanwhile)`);
78
+ const restore = await poll(client, slug, base, deps, (current) => current.lastRestore && current.lastRestore.backupId === id && current.lastRestore.state !== 'running' && !current.operation
79
+ ? current.lastRestore : undefined);
80
+ if (restore.state === 'failed') {
81
+ deps.status.clear();
82
+ throw new Error(`Restoring /p/${slug}/ from backup #${id} failed: ${restore.error ?? 'unknown error'} The Page data may be incomplete; restore a backup again.`);
83
+ }
84
+ deps.status.stop(`Restored /p/${slug}/ from backup #${id} of ${created}`);
85
+ deps.print(restore, () => 'The Page starts again on its next request.');
86
+ return;
87
+ }
88
+ throw new Error(`Unknown pages backups action "${action}". Use list, create, delete, daily or restore.`);
89
+ }
90
+ export function renderPageBackups(slug, view) {
91
+ const lines = [`${slug}: daily backups ${daily(view)}`];
92
+ if (view.operation === 'backingUp')
93
+ lines.push('A backup is running; the Page is stopped until it finishes.');
94
+ if (view.operation === 'restoring')
95
+ lines.push('A restore is running; the Page is stopped until it finishes.');
96
+ const restore = view.lastRestore;
97
+ if (restore) {
98
+ const from = `backup #${restore.backupId} of ${formatDateTime(restore.backupCreated)}`;
99
+ lines.push(restore.state === 'done' ? `Last restore: ${from} by ${restore.requestedBy}, ${formatDateTime(restore.finished)}`
100
+ : restore.state === 'running' ? `Restoring ${from}…`
101
+ : `Last restore of ${from} failed: ${restore.error ?? 'unknown error'} The Page data may be incomplete.`);
102
+ }
103
+ if (view.backups.length === 0) {
104
+ lines.push('No backups yet.');
105
+ return lines.join('\n');
106
+ }
107
+ lines.push('');
108
+ for (const backup of view.backups) {
109
+ const by = backup.scheduled ? 'daily' : backup.createdBy;
110
+ const size = backup.state === 'ready' ? formatByteSize(backup.bytes) : backup.state;
111
+ lines.push(`#${backup.id} ${formatDateTime(backup.created)} ${size.padEnd(9)} expires ${formatDateTime(backup.expires)} ${by}`);
112
+ if (backup.error)
113
+ lines.push(` ${backup.error}`);
114
+ }
115
+ return lines.join('\n');
116
+ }
117
+ function daily(view) {
118
+ return view.dailyEnabled
119
+ ? `on at ${String(view.dailyHourUtc).padStart(2, '0')}:00 UTC, kept ${view.dailyRetentionDays} days${view.nextDailyRun ? ` (next ${formatDateTime(view.nextDailyRun)})` : ''}`
120
+ : 'off';
121
+ }
122
+ async function poll(client, slug, base, deps, done) {
123
+ const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
124
+ for (;;) {
125
+ await sleep(POLL_MS);
126
+ let view;
127
+ try {
128
+ view = await expect(slug, await client.request(base, { method: 'GET' }));
129
+ }
130
+ catch (error) {
131
+ deps.status.clear();
132
+ throw error;
133
+ }
134
+ const result = done(view);
135
+ if (result !== undefined)
136
+ return result;
137
+ }
138
+ }
139
+ function json(method, body) {
140
+ return { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) };
141
+ }
142
+ function backupId(value, action) {
143
+ if (!value || !/^\d+$/.test(value))
144
+ throw new Error(`pages backups ${action} requires <slug> <backup id>`);
145
+ return Number(value);
146
+ }
147
+ function days(value) {
148
+ if (!/^\d+$/.test(value) || Number(value) < 1)
149
+ throw new Error('--keep takes a whole number of days, for example --keep 30.');
150
+ return Number(value);
151
+ }
152
+ function isTrue(value) {
153
+ return value !== undefined && !['0', 'false', 'no', 'off'].includes(value.toLowerCase());
154
+ }
155
+ async function expect(slug, response, id) {
156
+ if (response.ok)
157
+ return (response.status === 204 ? undefined : await response.json());
158
+ if (response.status === 403)
159
+ throw new Error(`Only the owner or a co-owner of /p/${slug}/ or an administrator can manage its backups.`);
160
+ if (response.status === 404)
161
+ throw new Error(id === undefined ? `Page /p/${slug}/ was not found.` : `Page /p/${slug}/ or its backup #${id} was not found.`);
162
+ let error = {};
163
+ try {
164
+ error = await response.json();
165
+ }
166
+ catch { }
167
+ throw new Error(error.error ?? `Skillshare returned HTTP ${response.status} for the Page backups.`);
168
+ }
@@ -1,21 +1,21 @@
1
1
  import { renderPageRuntime } from './output.js';
2
2
  /**
3
3
  * `pages runtime <slug>` shows the runtime to its owner or an administrator; `pages runtime set <slug>`
4
- * lets an administrator move it between SkillShare and its own pod and set its automatic memory range.
4
+ * lets its owners set the automatic memory range of its pod and an administrator also keep it always on.
5
5
  */
6
6
  export async function runPageRuntimeCommand(client, positionals, flags, print) {
7
7
  if (positionals[0] === 'set' && positionals[1]) {
8
8
  const slug = positionals[1];
9
9
  const body = settingsRequest(flags);
10
10
  if (Object.keys(body).length === 0) {
11
- throw new Error('pages runtime set needs --external, --internal, --min <MiB>, --max <MiB> or --always-on true|false');
11
+ throw new Error('pages runtime set needs --min <MiB>, --max <MiB> or --always-on true|false');
12
12
  }
13
13
  const settings = await expect(slug, await client.request(`/api/pages/${encodeURIComponent(slug)}/runtime-settings`, {
14
14
  method: 'PUT',
15
15
  headers: { 'Content-Type': 'application/json' },
16
16
  body: JSON.stringify(body),
17
17
  }));
18
- print(settings, () => `Updated /p/${slug}/: ${settings.placement}, always on ${settings.alwaysOn ? 'yes' : 'no'}, memory ${settings.minMiB}–${settings.maxMiB} MiB (now ${settings.limitMiB} MiB).`);
18
+ print(settings, () => `Updated /p/${slug}/: always on ${settings.alwaysOn ? 'yes' : 'no'}, memory ${settings.minMiB}–${settings.maxMiB} MiB (now ${settings.limitMiB} MiB).`);
19
19
  return;
20
20
  }
21
21
  const slug = positionals[0];
@@ -26,14 +26,6 @@ export async function runPageRuntimeCommand(client, positionals, flags, print) {
26
26
  }
27
27
  export function settingsRequest(flags) {
28
28
  const body = {};
29
- const external = isTrue(flags.external);
30
- const internal = isTrue(flags.internal);
31
- if (external && internal)
32
- throw new Error('Use either --external or --internal.');
33
- if (external)
34
- body.placement = 'external';
35
- if (internal)
36
- body.placement = 'internal';
37
29
  if (flags.min !== undefined)
38
30
  body.minMiB = mebibytes('--min', flags.min);
39
31
  if (flags.max !== undefined)
@@ -54,7 +46,7 @@ async function expect(slug, response) {
54
46
  if (response.ok)
55
47
  return await response.json();
56
48
  if (response.status === 403)
57
- throw new Error(`Only an administrator can change the runtime of /p/${slug}/; its owner can view it.`);
49
+ throw new Error(`Only an administrator can change Always on of /p/${slug}/; its owners can set --min and --max.`);
58
50
  if (response.status === 404)
59
51
  throw new Error(`Page /p/${slug}/ was not found.`);
60
52
  let error = {};