@skrr-ai/cli 0.1.164 → 0.1.165

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 (88) hide show
  1. package/README.md +13 -0
  2. package/dist/base-command.d.ts +14 -1
  3. package/dist/base-command.js +166 -46
  4. package/dist/commands/agent/message/send.d.ts +1 -0
  5. package/dist/commands/agent/message/send.js +3 -0
  6. package/dist/commands/agents/mini-computer/app/set.js +1 -1
  7. package/dist/commands/agents/mini-computer/tasks-view.js +1 -1
  8. package/dist/commands/apps/check.js +3 -8
  9. package/dist/commands/apps/data/batch.d.ts +1 -0
  10. package/dist/commands/apps/data/batch.js +19 -2
  11. package/dist/commands/apps/data/delete.d.ts +1 -0
  12. package/dist/commands/apps/data/delete.js +14 -2
  13. package/dist/commands/apps/data/patch.d.ts +1 -0
  14. package/dist/commands/apps/data/patch.js +11 -2
  15. package/dist/commands/apps/data/put.d.ts +1 -0
  16. package/dist/commands/apps/data/put.js +17 -3
  17. package/dist/commands/apps/install.js +7 -2
  18. package/dist/commands/apps/installations/compatibility.d.ts +13 -0
  19. package/dist/commands/apps/installations/compatibility.js +60 -0
  20. package/dist/commands/apps/installations/show.js +9 -3
  21. package/dist/commands/apps/installations/snapshot.js +5 -2
  22. package/dist/commands/apps/operations/check.d.ts +16 -0
  23. package/dist/commands/apps/operations/check.js +127 -0
  24. package/dist/commands/apps/publish/propose.js +33 -4
  25. package/dist/commands/apps/reconsent.js +7 -1
  26. package/dist/commands/apps/reference.d.ts +4 -2
  27. package/dist/commands/apps/reference.js +7 -4
  28. package/dist/commands/apps/rollback.d.ts +9 -0
  29. package/dist/commands/apps/rollback.js +81 -2
  30. package/dist/commands/apps/upgrade.d.ts +8 -0
  31. package/dist/commands/apps/upgrade.js +67 -2
  32. package/dist/commands/apps/version/cat.d.ts +22 -0
  33. package/dist/commands/apps/version/cat.js +220 -0
  34. package/dist/commands/apps/version/show.js +3 -1
  35. package/dist/commands/commerce/incidents/release.d.ts +24 -0
  36. package/dist/commands/commerce/incidents/release.js +46 -0
  37. package/dist/commands/duties/cases.js +12 -1
  38. package/dist/commands/duties/hypotheses.js +10 -3
  39. package/dist/commands/duties/observations.d.ts +4 -0
  40. package/dist/commands/duties/observations.js +14 -3
  41. package/dist/commands/outbox/list.d.ts +11 -4
  42. package/dist/commands/outbox/list.js +56 -9
  43. package/dist/commands/outbox/retry.d.ts +8 -2
  44. package/dist/commands/outbox/retry.js +76 -16
  45. package/dist/commands/outbox/show.d.ts +20 -0
  46. package/dist/commands/outbox/show.js +83 -0
  47. package/dist/commands/proposals/list.js +13 -9
  48. package/dist/commands/requests/show.d.ts +12 -0
  49. package/dist/commands/requests/show.js +42 -23
  50. package/dist/commands/spaces/deletion/cancel.d.ts +21 -0
  51. package/dist/commands/spaces/deletion/cancel.js +70 -0
  52. package/dist/commands/spaces/workflows/run.js +12 -0
  53. package/dist/commands/widgets/check.d.ts +9 -0
  54. package/dist/commands/widgets/check.js +16 -3
  55. package/dist/generated/agent-guides.json +17 -17
  56. package/dist/lib/api-fetch.d.ts +5 -0
  57. package/dist/lib/api-fetch.js +53 -21
  58. package/dist/lib/appCompatibility.d.ts +31 -0
  59. package/dist/lib/appCompatibility.js +66 -0
  60. package/dist/lib/appData.d.ts +46 -4
  61. package/dist/lib/appData.js +156 -31
  62. package/dist/lib/appInstallations.d.ts +32 -5
  63. package/dist/lib/appInstallations.js +197 -34
  64. package/dist/lib/appVersionFile.d.ts +82 -0
  65. package/dist/lib/appVersionFile.js +195 -0
  66. package/dist/lib/apps-command.d.ts +14 -3
  67. package/dist/lib/apps-command.js +68 -60
  68. package/dist/lib/appsCheck.js +16 -2
  69. package/dist/lib/commerce.d.ts +6 -0
  70. package/dist/lib/commerce.js +9 -0
  71. package/dist/lib/duties.d.ts +15 -1
  72. package/dist/lib/duties.js +21 -3
  73. package/dist/lib/json-output.d.ts +2 -0
  74. package/dist/lib/json-output.js +8 -4
  75. package/dist/lib/node-adapter.d.ts +2 -0
  76. package/dist/lib/node-adapter.js +35 -8
  77. package/dist/lib/outbox.d.ts +110 -1
  78. package/dist/lib/outbox.js +261 -35
  79. package/dist/lib/space-deletion-cancel.d.ts +47 -0
  80. package/dist/lib/space-deletion-cancel.js +141 -0
  81. package/dist/lib/widgetCheck.js +1 -1
  82. package/dist/lib/widgetStaticScan.d.ts +11 -5
  83. package/dist/lib/widgetStaticScan.js +73 -165
  84. package/dist/lib/write-outcome.d.ts +74 -0
  85. package/dist/lib/write-outcome.js +176 -0
  86. package/dist/node_modules/@skrr-ai/data-provider/index.js +11839 -11318
  87. package/oclif.manifest.json +1940 -16
  88. package/package.json +9 -3
@@ -146,8 +146,43 @@ const STORE_WRITER_WORDS = {
146
146
  agent: "only agents acting for people with edit access can change it; the app's own code can only read it",
147
147
  person: "only people can change it; the app's own code can only read it",
148
148
  };
149
+ /** Names as a sentence lists them, each in quotes: "a", "a" and "b", "a", "b" and "c". */
150
+ function quotedList(names) {
151
+ const quoted = names.map((name) => `"${name}"`);
152
+ const last = quoted.pop();
153
+ if (last === undefined) {
154
+ return '';
155
+ }
156
+ return quoted.length === 0 ? last : `${quoted.join(', ')} and ${last}`;
157
+ }
158
+ /**
159
+ * What can wake a job declared as `on@change:<collection>`, said from the writers THE COLLECTION DECLARES (`appChangeWakeFacts`),
160
+ * so the line cannot name a source the "keep its own data" line above it says is impossible (OSK-23757: "an app-window write"
161
+ * over a collection the app's own code could only read). `declared` is `undefined` when this disclosure does not list the
162
+ * collection's writers (an older server, or a collection the app cannot read), and the line then says it does not know.
163
+ */
164
+ function describeChangeWake(name, declared) {
165
+ const target = `"${name}"`;
166
+ const never = 'agent writes and webhook deliveries never wake it this way';
167
+ const facts = (0, data_provider_1.appChangeWakeFacts)(declared);
168
+ if (!facts.known) {
169
+ return `can wake on a permitted write by a person or the app's own code to ${target} (who may write it is not shown here; ${never}; not on a clock)`;
170
+ }
171
+ const person = facts.sources.includes('person');
172
+ const app = facts.sources.includes('app');
173
+ if (person && app) {
174
+ return `can wake when a person or the app's own code changes ${target} (${never}; not on a clock)`;
175
+ }
176
+ if (person) {
177
+ return `can wake when a person changes ${target} (the app's own code cannot write it; ${never}; not on a clock)`;
178
+ }
179
+ if (app) {
180
+ return `can wake when the app's own code changes ${target} (people cannot write it; ${never}; not on a clock)`;
181
+ }
182
+ return `cannot be woken by a change to ${target} (no writer it declares can start a wake: an agent's writes never do; not on a clock)`;
183
+ }
149
184
  /** A job's schedule in words, beside the text the author wrote (which is always still shown). */
150
- function describeSchedule(schedule) {
185
+ function describeSchedule(schedule, collectionWriters) {
151
186
  const reading = (0, data_provider_1.readAppJobSchedule)(schedule);
152
187
  switch (reading.kind) {
153
188
  case 'daily':
@@ -157,7 +192,7 @@ function describeSchedule(schedule) {
157
192
  case 'event':
158
193
  return reading.source === 'webhook'
159
194
  ? `can wake when the app's "${reading.name}" webhook delivers an event (not on a clock)`
160
- : `can wake on a permitted person or app-window write to "${reading.name}" (see collection permissions; agent and webhook writes do not trigger this change wake; not on a clock)`;
195
+ : describeChangeWake(reading.name, collectionWriters?.get(reading.name));
161
196
  case 'configured':
162
197
  return "on a schedule set in the app's settings";
163
198
  default:
@@ -390,7 +425,7 @@ function jobNextLine(job) {
390
425
  }
391
426
  return [` next: ${stateReason.next.replace(FORMAT_JOB_STATES_RE, '<installation id>')}`];
392
427
  }
393
- function itemLines(item) {
428
+ function itemLines(item, collectionWriters) {
394
429
  switch (item.kind) {
395
430
  case 'store':
396
431
  return item.collections.map((collection) => {
@@ -438,17 +473,16 @@ function itemLines(item) {
438
473
  return [
439
474
  `run these jobs automatically, unattended. ${item.statement} That is accepted when you install it, and each job is listed so you can weigh it:`,
440
475
  ...item.jobs.flatMap((job) => [
441
- ` - ${(0, data_provider_1.plainAppLabel)(job.title)} (${job.schedule}): ${describeSchedule(job.schedule)}${job.guide ? `, following ${job.guide}` : ''}${mark(job.consent)}${describeJobState(job)}`,
476
+ ` - ${(0, data_provider_1.plainAppLabel)(job.title)} (${job.schedule}): ${describeSchedule(job.schedule, collectionWriters)}${job.guide ? `, following ${job.guide}` : ''}${mark(job.consent)}${describeJobState(job)}`,
442
477
  ...jobNextLine(job),
443
478
  ]),
444
- ...(item.jobs.some((job) => {
445
- const kind = (0, data_provider_1.readAppJobSchedule)(job.schedule).kind;
446
- return kind === 'event' || kind === 'configured';
447
- })
448
- ? [' If a job is event-triggered, limits or delivery failures can cause it to miss events. A recorded change or webhook delivery does not guarantee a run.']
449
- : []),
479
+ // how a wake is delivered, said once and only for an app with a job an event can start (OSK-23917); the sentence is the
480
+ // contract's, the same one the web draws and the reference prints
481
+ ...((0, data_provider_1.appDisclosureHasEventWake)(item.jobs) ? [` ${data_provider_1.APP_EVENT_WAKE_BEST_EFFORT}`] : []),
450
482
  ...(item.jobs.some((job) => (0, data_provider_1.readAppJobSchedule)(job.schedule).kind === 'configured')
451
- ? [' If a settings-based schedule resolves to an event, the job may not wake at all. A scheduled status does not confirm it can wake.']
483
+ ? [
484
+ ' If a settings-based schedule resolves to an event, the job may not wake at all. A scheduled status does not confirm it can wake.',
485
+ ]
452
486
  : []),
453
487
  ...(item.notices?.some((notice) => notice.kind === 'trigger_detached')
454
488
  ? [
@@ -466,12 +500,52 @@ const REASON_WORDS = {
466
500
  capability_expanded: 'this version asks for more than was approved',
467
501
  egress_code_changed: `the app changed, and what it may send out of ${data_provider_1.BRAND.displayName} is approved only for the code you saw`,
468
502
  jobs_changed: 'a job was added or changed',
469
- store_writers_expanded: "this version lets something new change the data the app keeps, such as the app's own code",
503
+ // The fallback for a reason that names no writer (`items` absent or unreadable): it names none either. It used to say
504
+ // "such as the app's own code" over every version, including one that added only an Agent writer (OSK-23751).
505
+ store_writers_expanded: 'this version lets a kind of writer you have not approved change data the app already keeps',
470
506
  };
471
- /** The words for each reason a grant stopped covering a version; a kind it does not know is said as it came. */
472
- function describeGrantReasons(kinds) {
507
+ /**
508
+ * Who a version newly lets change a collection, as a noun phrase a sentence can take. A `Record` over the contract's writers, so
509
+ * a writer added there does not compile here until it has words. The same three phrases as the web's
510
+ * `com_app_reason_store_writers_added_*` sentences, which read the same facts (`appStoreWritersAdded`).
511
+ */
512
+ const STORE_WRITER_ADDED_WORDS = {
513
+ app: "the app's own code",
514
+ agent: 'agents acting for people with edit access',
515
+ person: 'people with edit access',
516
+ };
517
+ /** One line of the new writers a version adds, for one kind of writer: which collections it can now change. */
518
+ function storeWritersAddedLine(added) {
519
+ const who = added.known
520
+ ? STORE_WRITER_ADDED_WORDS[added.writer]
521
+ : `a kind of writer this CLI does not know ("${(0, data_provider_1.plainAppLabel)(added.writer, 40)}")`;
522
+ return `this version lets ${who} change ${quotedList(added.collections)} (you have not approved that)`;
523
+ }
524
+ /**
525
+ * The words for each reason a grant stopped covering a version; a kind it does not know is said as it came. A reason that
526
+ * carries facts says them: `store_writers_expanded` lists, for each kind of writer a version adds, the collections it can now
527
+ * change (`digest:app` is "the app's own code ... "digest""), from the `items` the server sent, and says the neutral
528
+ * sentence when it sent none. All the store-writer reasons of a list are said together, once.
529
+ */
530
+ function describeGrantReasons(reasons) {
473
531
  const words = REASON_WORDS;
474
- return kinds.map((kind) => words[kind] ?? kind);
532
+ const lines = [];
533
+ let writersSaid = false;
534
+ for (const reason of reasons) {
535
+ if (reason.kind === 'store_writers_expanded') {
536
+ if (writersSaid) {
537
+ continue;
538
+ }
539
+ writersSaid = true;
540
+ const added = (0, data_provider_1.appStoreWritersAdded)(reasons);
541
+ if (added.length > 0) {
542
+ lines.push(...added.map(storeWritersAddedLine));
543
+ continue;
544
+ }
545
+ }
546
+ lines.push(words[reason.kind] ?? reason.kind);
547
+ }
548
+ return lines;
475
549
  }
476
550
  /**
477
551
  * The sentences of the note on an app installed on a PERSON that are true of this app, and none of the others (OSK-23975).
@@ -547,13 +621,15 @@ function formatDisclosure(raw, facts) {
547
621
  lines.push(`For an installation on ${disclosure.scope.principal.kind} ${disclosure.scope.principal.id}.`);
548
622
  }
549
623
  }
624
+ // a job woken by a change to a collection is said from who that collection lets write (OSK-23757)
625
+ const collectionWriters = (0, data_provider_1.appDisclosureCollectionWriters)(disclosure.can);
550
626
  if (disclosure.can.length === 0) {
551
627
  lines.push('It asks for nothing: it can only draw itself.');
552
628
  }
553
629
  else {
554
630
  lines.push('It can:');
555
631
  for (const item of disclosure.can) {
556
- const [first, ...rest] = itemLines(item);
632
+ const [first, ...rest] = itemLines(item, collectionWriters);
557
633
  if (first !== undefined) {
558
634
  lines.push(` - ${first}`);
559
635
  lines.push(...rest.map((line) => ` ${line.replace(FORMAT_DISCLOSURE_RE, '')}`.replace(FORMAT_DISCLOSURE_RE_2, ' ')));
@@ -562,7 +638,7 @@ function formatDisclosure(raw, facts) {
562
638
  }
563
639
  if (disclosure.consent.status === 'needs_reconsent') {
564
640
  lines.push('Why it needs approving again:');
565
- for (const reason of describeGrantReasons(disclosure.consent.reasons.map((r) => r.kind))) {
641
+ for (const reason of describeGrantReasons(disclosure.consent.reasons)) {
566
642
  lines.push(` - ${reason}`);
567
643
  }
568
644
  }
@@ -908,6 +984,47 @@ const FORBIDDEN_REASON_WORDS = {
908
984
  // the installation was suspended by the platform, not by the person: resuming it is not theirs to do
909
985
  suspended_by_moderation: 'The platform suspended this app, not you, and only the platform can lift that. There is nothing to resume from here.',
910
986
  };
987
+ const INSTALLATION_ID_PATTERN = /^appi_[A-Za-z0-9_-]{1,60}(?![\s\S])/;
988
+ const VERSION_ID_PATTERN = /^appv_[A-Za-z0-9_-]{1,60}(?![\s\S])/;
989
+ const AGENT_ID_PATTERN = /^agent_[A-Za-z0-9_-]{1,60}(?![\s\S])/;
990
+ /** An id of the shape a command takes, or null. A refusal's ids come from the server, and none goes into a command unread. */
991
+ function idOf(pattern, value) {
992
+ return typeof value === 'string' && pattern.test(value) ? value : null;
993
+ }
994
+ /** What did not happen, by what the command was doing. A refusal is made before anything is written, so "changed" is true of every command. */
995
+ function nothingWas(context) {
996
+ switch (context.action) {
997
+ case 'install':
998
+ return 'Nothing was installed.';
999
+ case 'reconsent':
1000
+ return 'Nothing was approved.';
1001
+ default:
1002
+ return 'Nothing was changed.';
1003
+ }
1004
+ }
1005
+ /**
1006
+ * The command that shows a version's disclosure, with the argument it requires (the version) and the option that makes
1007
+ * its answer about the place in question: the installation being approved again or moved, or who an install is for.
1008
+ */
1009
+ function disclosureCommand(bin, context, versionId) {
1010
+ const version = idOf(VERSION_ID_PATTERN, versionId) ?? '<version>';
1011
+ const installation = idOf(INSTALLATION_ID_PATTERN, context.subject);
1012
+ if (installation) {
1013
+ return `${bin} apps disclosure ${version} --installation ${installation}`;
1014
+ }
1015
+ if (context.principal?.kind === 'user') {
1016
+ return `${bin} apps disclosure ${version} --me`;
1017
+ }
1018
+ const agent = idOf(AGENT_ID_PATTERN, context.principal?.id);
1019
+ if (context.principal?.kind === 'agent' && agent) {
1020
+ return `${bin} apps disclosure ${version} --agent ${agent}`;
1021
+ }
1022
+ return `${bin} apps disclosure ${version}`;
1023
+ }
1024
+ /** The version a refusal says an installation runs now (`current.versionId`), or null. */
1025
+ function currentVersionOf(refusal) {
1026
+ return idOf(VERSION_ID_PATTERN, refusal.current?.versionId);
1027
+ }
911
1028
  /**
912
1029
  * Every reason an installation call is refused, with the sentence and the next step. A `Record` over the
913
1030
  * contract's list, so a reason added there does not compile here until it has words.
@@ -921,19 +1038,32 @@ const CONFLICT_WORDS = {
921
1038
  version_not_found: () => 'There is no such version of that app that you can use.',
922
1039
  version_not_installable: () => 'That version is not available for this action. If an install or version change was attempted, check the installation list for the same account and destination, then inspect its current state and data before deciding what to do next; do not retry blindly.',
923
1040
  manifest_invalid: () => "That version's manifest is not one this platform will run, so it was not installed.",
924
- consent_mismatch: (_refusal, bin) => `The bundle you were shown is not the one on record for that version. Nothing was installed. Run \`${bin} apps disclosure\` again and approve what it shows.`,
925
- version_changed: (refusal, bin) => `The installation moved to another version while you were deciding${refusal.current ? ` (now ${refusal.current.versionId})` : ''}. Nothing was changed. Read \`${bin} apps disclosure\` again and approve what it shows.`,
1041
+ consent_mismatch: (_refusal, bin, context) => `The bundle you were shown is not the one on record for that version. ${nothingWas(context)} Run \`${disclosureCommand(bin, context, context.versionId)}\` again and approve what it shows.`,
1042
+ version_changed: (refusal, bin, context) => {
1043
+ const installation = idOf(INSTALLATION_ID_PATTERN, context.subject);
1044
+ const now = currentVersionOf(refusal);
1045
+ return `The installation moved to another version while you were deciding${refusal.current ? ` (now ${refusal.current.versionId})` : ''}. Nothing was changed. Read \`${disclosureCommand(bin, context, now ?? context.versionId)}\` again and approve what it shows${installation ? ` with \`${bin} apps reconsent ${installation} --yes\`` : ''}.`;
1046
+ },
926
1047
  invalid_update_policy: () => 'That update policy is not one of manual, auto_minor or beta.',
927
1048
  binding_required: (refusal) => describeBindingRefusal(refusal),
928
- already_installed: (refusal, bin) => `That app is already installed on this agent${refusal.installationId ? ` (${refusal.installationId})` : ''}. Move it to a newer version with \`${bin} apps upgrade\`.`,
1049
+ already_installed: (refusal, bin, context) => {
1050
+ const where = context.principal === undefined
1051
+ ? ''
1052
+ : context.principal.kind === 'user'
1053
+ ? ' on you'
1054
+ : ' on this agent';
1055
+ const prior = idOf(INSTALLATION_ID_PATTERN, refusal.installationId);
1056
+ const wanted = idOf(VERSION_ID_PATTERN, context.versionId);
1057
+ return `That app is already installed${where}${refusal.installationId ? ` (${refusal.installationId})` : ''}. To ${wanted ? `run the version you asked for (${wanted}) instead` : 'move it to another version'}, use \`${bin} apps upgrade ${prior ?? '<installation>'} --version ${wanted ?? '<version>'}\`${prior ? `; \`${bin} apps installations show ${prior}\` says which version it runs now` : ''}.`;
1058
+ },
929
1059
  not_found: () => 'There is no such installation that you can see.',
930
1060
  changed: () => 'The installation changed while this was running. Read its current state before deciding what to do next.',
931
1061
  not_auto_updatable: () => 'That installation does not update on its own.',
932
1062
  data_deletion_not_confirmed: (refusal) => `Removing this app also deletes its data (${refusal.docCount ?? 'some'} document${refusal.docCount === 1 ? '' : 's'}), which is yours to confirm. Nothing was removed. Say it, with --delete-data, if you mean it.`,
933
1063
  installation_incomplete: () => 'This installation points at a version that can no longer be read. It can be removed, not run.',
934
- principal_scope_unserved: (refusal) => `This app asks for ${describeScopeIssues(refusal.unserved)}, which cannot work for the place it would be installed (an app installed on a person reaches that person's own data, never an agent's or a space's, and has no agent to run it yet).${needsOperator(refusal.unserved)
1064
+ principal_scope_unserved: (refusal, _bin, context) => `This app asks for ${describeScopeIssues(refusal.unserved)}, which cannot work for the place it would be installed (an app installed on a person reaches that person's own data, never an agent's or a space's, and has no agent to run it yet).${needsOperator(refusal.unserved)
935
1065
  ? ' An app that needs an agent to run it can, for now, only be installed on one of your agents.'
936
- : ''} Nothing was installed.`,
1066
+ : ''} ${nothingWas(context)}`,
937
1067
  no_previous_version: () => 'This installation has never been moved onto the version it runs, so there is no earlier version to go back to. Nothing was changed.',
938
1068
  job_schedule_invalid: (refusal, bin) => {
939
1069
  const issues = Array.isArray(refusal.issues)
@@ -942,15 +1072,25 @@ const CONFLICT_WORDS = {
942
1072
  return `${issues > 0 ? `${issues} of this app's scheduled jobs have` : 'A scheduled job has'} a schedule or event target that cannot be used. Review the selected settings and declared targets; \`${bin} apps check\` checks the app package.`;
943
1073
  },
944
1074
  };
945
- /** The sentence for a refusal the server made on an installation call, or null for one that is not. */
946
- function describeInstallationConflict(refusal, bin, subject) {
1075
+ /**
1076
+ * The sentence for a refusal the server made on an installation call, or null for one that is not. `context` is what the
1077
+ * command knows (the installation it was about, the version, what it was doing); a bare string is the installation, as
1078
+ * the callers that only ever had that pass it.
1079
+ */
1080
+ function describeInstallationConflict(refusal, bin, context) {
947
1081
  if (!(0, data_provider_1.isAppInstallationConflict)(refusal.error)) {
948
1082
  return null;
949
1083
  }
950
- if (refusal.error === 'changed' && subject && /^appi_[A-Za-z0-9_-]{1,60}(?![\s\S])/.test(subject)) {
951
- return `The installation changed while this was running. Read its current state with \`${bin} apps installations show ${subject}\` using the same account, deployment, profile and workspace before deciding what to do next.`;
1084
+ const known = typeof context === 'string' ? { subject: context } : (context ?? {});
1085
+ if (refusal.error === 'changed' && refusal.reason === 'rollback_target_changed') {
1086
+ // refused before anything was written: the server compares the target first, so this one can say nothing was moved
1087
+ const named = known.subject && /^appi_[A-Za-z0-9_-]{1,60}(?![\s\S])/.test(known.subject);
1088
+ return `The version this rollback would go back to is no longer the one you expected, so nothing was moved. Read the installation's versions again${named ? ` with \`${bin} apps installations versions ${known.subject}\`` : ''} before deciding what to do next.`;
1089
+ }
1090
+ if (refusal.error === 'changed' && idOf(INSTALLATION_ID_PATTERN, known.subject)) {
1091
+ return `The installation changed while this was running. Read its current state with \`${bin} apps installations show ${known.subject}\` using the same account, deployment, profile and workspace before deciding what to do next.`;
952
1092
  }
953
- return CONFLICT_WORDS[refusal.error](refusal, bin);
1093
+ return CONFLICT_WORDS[refusal.error](refusal, bin, known);
954
1094
  }
955
1095
  /** The machine code of every installation refusal: `APP_<REASON>`. */
956
1096
  exports.ALL_INSTALLATION_REFUSAL_CODES = Object.fromEntries(Object.keys(CONFLICT_WORDS).map((conflict) => [conflict, `APP_${conflict.toUpperCase()}`]));
@@ -1100,9 +1240,11 @@ function installationRefusalExit(conflict) {
1100
1240
  /** Why a version that needs no new approval was still not applied by the opt-in, in a clause. */
1101
1241
  const AUTO_APPLY_HOLD_WORDS = {
1102
1242
  installation_suspended: 'the installation is paused',
1103
- cut_by_another_person: "it was not made by the person who enabled automatic updates or their own agents (apply it yourself if you trust it)",
1243
+ cut_by_another_person: 'it was not made by the person who enabled automatic updates or their own agents (apply it yourself if you trust it)',
1104
1244
  version_not_installable: 'the version was rejected or withdrawn',
1105
1245
  principal_scope_unserved: 'it declares something this installation cannot serve',
1246
+ data_incompatible: 'the installation holds data that version’s schemas do not fit (see `apps installations compatibility`)',
1247
+ data_unproven: 'it could not be proven that the installation’s stored data fits that version’s schemas (see `apps installations compatibility`); unknown is not a pass',
1106
1248
  };
1107
1249
  /** Names come from an app's version; show a bounded summary and keep the full disclosure as the review step. */
1108
1250
  function pendingReasonDetails(reason) {
@@ -1124,6 +1266,17 @@ function pendingReasonDetails(reason) {
1124
1266
  }
1125
1267
  return lines;
1126
1268
  }
1269
+ /**
1270
+ * A pending notice (`pending.notices`), in a line. It is worth reading before the version is applied and it is NOT a reason
1271
+ * for approving again: the version's `status` and the instructions beside it are exactly what they were, and nothing here reads
1272
+ * a document (OSK-23684).
1273
+ */
1274
+ function describePendingNotice(notice) {
1275
+ switch (notice.kind) {
1276
+ case 'interface_major_changed':
1277
+ return `note: this version changes the app's data interface from major ${notice.from} to major ${notice.to}, so its collections may have a new shape. Applying it does not check or migrate documents the installation already holds, and some may not satisfy the new schema. This is a notice, not a block.`;
1278
+ }
1279
+ }
1127
1280
  /**
1128
1281
  * What the versions view says, as lines a person reads: which version is installed, what is waiting and what it needs,
1129
1282
  * the opt-in and the currently observed rollback target. `needs_reconsent` is said as "asks for more than you approved", never as a verdict on the
@@ -1134,10 +1287,16 @@ function formatInstallationVersions(view, bin, requestedInstallationId) {
1134
1287
  // commands unless they match the requested installation and are safe as unquoted arguments.
1135
1288
  const safeId = (value) => typeof value === 'string' && /^[A-Za-z0-9_][A-Za-z0-9_-]{0,63}(?![\s\S])/.test(value);
1136
1289
  const safeVersion = (value) => Number.isSafeInteger(value) && Number(value) > 0;
1137
- if (!view || !safeId(requestedInstallationId) || view.installationId !== requestedInstallationId ||
1138
- !safeId(view.installationId) || !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}(?![\s\S])/.test(bin) ||
1139
- !view.current || !safeId(view.current.versionId) || !safeVersion(view.current.version) ||
1140
- typeof view.viewer?.canManage !== 'boolean' || typeof view.autoApply?.enabled !== 'boolean' ||
1290
+ if (!view ||
1291
+ !safeId(requestedInstallationId) ||
1292
+ view.installationId !== requestedInstallationId ||
1293
+ !safeId(view.installationId) ||
1294
+ !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}(?![\s\S])/.test(bin) ||
1295
+ !view.current ||
1296
+ !safeId(view.current.versionId) ||
1297
+ !safeVersion(view.current.version) ||
1298
+ typeof view.viewer?.canManage !== 'boolean' ||
1299
+ typeof view.autoApply?.enabled !== 'boolean' ||
1141
1300
  !Array.isArray(view.history) ||
1142
1301
  (view.pending && (!safeId(view.pending.versionId) || !safeVersion(view.pending.version))) ||
1143
1302
  (view.rollback && (!safeId(view.rollback.versionId) || !safeVersion(view.rollback.version)))) {
@@ -1156,10 +1315,14 @@ function formatInstallationVersions(view, bin, requestedInstallationId) {
1156
1315
  if (view.pending) {
1157
1316
  const pending = view.pending;
1158
1317
  lines.push(`waiting: v${pending.version} (${pending.versionId})${pending.changelog ? ` - ${(0, data_provider_1.plainAppLabel)(pending.changelog, 120)}` : ''}`);
1318
+ // said whatever its status: a version that asks for nothing new can still change what the installation's documents must be
1319
+ for (const notice of (0, data_provider_1.readAppPendingNotices)(pending.notices)) {
1320
+ lines.push(` ${describePendingNotice(notice)}`);
1321
+ }
1159
1322
  if (pending.status === 'needs_reconsent') {
1160
1323
  lines.push(' it asks for more than you approved, so it does not run until you approve it:');
1161
1324
  for (const reason of pending.reasons) {
1162
- for (const line of describeGrantReasons([reason.kind]))
1325
+ for (const line of describeGrantReasons([reason]))
1163
1326
  lines.push(` ${line}`);
1164
1327
  for (const line of pendingReasonDetails(reason))
1165
1328
  lines.push(` ${line}`);
@@ -1181,7 +1344,7 @@ function formatInstallationVersions(view, bin, requestedInstallationId) {
1181
1344
  lines.push('waiting: no newer version is shown as waiting; the installed version may still need approval.');
1182
1345
  }
1183
1346
  lines.push(view.rollback
1184
- ? `going back: the currently observed previous version is v${view.rollback.version} (${view.rollback.versionId}). Run \`${bin} apps rollback ${view.installationId} --expected-version ${view.current.versionId}\` to request a rollback. The server selects the target from its history when it handles the request; --expected-version checks the current version, not the target or history.`
1347
+ ? `going back: the currently observed previous version is v${view.rollback.version} (${view.rollback.versionId}). Run \`${bin} apps rollback ${view.installationId} --expected-version ${view.current.versionId} --expected-target ${view.rollback.versionId}\` to request a rollback to that version only. The server selects the target from its history when it handles the request; --expected-version checks the current version, not the target or history, and --expected-target refuses the rollback, moving nothing, if the target is a different version by then.`
1185
1348
  : 'going back: no rollback option is available right now');
1186
1349
  for (const move of view.history.slice(-5)) {
1187
1350
  lines.push(` ${move.at} ${move.cause}${move.by === 'policy' ? ' (by the platform, on your opt-in)' : ` (${move.by})`} ${move.from} -> ${move.to}`);
@@ -0,0 +1,82 @@
1
+ import type { AppVersionDetail, AppVersionFileChunk } from '@skrr-ai/data-provider';
2
+ /** The most a read will hold. A package file is far smaller (`APP_DRAFT_LIMITS`); a server that says otherwise is not believed. */
3
+ export declare const VERSION_FILE_READ_MAX_BYTES: number;
4
+ /** The machine code and exit under which a mismatch is reported. A distinct exit: a harness must not read "6" as an ordinary failure. */
5
+ export declare const VERSION_FILE_INTEGRITY_CODE = "APP_VERSION_FILE_INTEGRITY";
6
+ export declare const VERSION_FILE_INTEGRITY_EXIT = 6;
7
+ /** What disagreed, in a closed set a harness can switch on. */
8
+ export type VersionFileProblemKind =
9
+ /** the version's file list does not hash to its `bundleHash` */
10
+ 'bundle_hash'
11
+ /** the server says the bytes it holds are not the bytes the version recorded */
12
+ | 'server_integrity'
13
+ /** a slice names another version, bundle, path, digest or size than the version's record */
14
+ | 'record'
15
+ /** a slice does not start where the last one ended, or is not the length asked for */
16
+ | 'continuity'
17
+ /** a slice's bytes are not valid base64, or do not hash to the digest it states */
18
+ | 'chunk_digest'
19
+ /** the slices joined are not the size, or do not hash to the digest, the version recorded */
20
+ | 'file_digest';
21
+ /** The bytes are not provably the version's. Carries what disagreed; never the bytes. */
22
+ export declare class VersionFileIntegrityError extends Error {
23
+ readonly kind: VersionFileProblemKind;
24
+ readonly details: Record<string, unknown>;
25
+ constructor(kind: VersionFileProblemKind, message: string, details?: Record<string, unknown>);
26
+ }
27
+ /** The path is not one the version lists. Carries a bounded sample of the ones it does. */
28
+ export declare class VersionFileNotListedError extends Error {
29
+ readonly path: string;
30
+ readonly listed: string[];
31
+ constructor(path: string, listed: string[]);
32
+ }
33
+ /** The caller asked for something that cannot be read (an offset past the end, a file past what the CLI will hold). */
34
+ export declare class VersionFileInputError extends Error {
35
+ readonly code: string;
36
+ constructor(code: string, message: string);
37
+ }
38
+ /** The two calls a read makes. `dataService` is the real one; a spec hands in its own. */
39
+ export interface VersionFileReader {
40
+ getVersion(versionId: string): Promise<AppVersionDetail>;
41
+ readChunk(versionId: string, params: {
42
+ path: string;
43
+ offset: number;
44
+ limit: number;
45
+ }): Promise<AppVersionFileChunk>;
46
+ }
47
+ export interface VersionFileRead {
48
+ versionId: string;
49
+ bundleHash: string;
50
+ path: string;
51
+ /** Where the bytes start, and how many there are. */
52
+ offset: number;
53
+ length: number;
54
+ /** The file's size, as the version recorded it. */
55
+ total: number;
56
+ /** The file's digest, as the version recorded it. */
57
+ fileSha256: string;
58
+ /** Slices asked for. */
59
+ chunks: number;
60
+ /** True when the whole file was read and its size and digest matched the record. False is a partial read, not a failure. */
61
+ wholeFileVerified: boolean;
62
+ bytes: Buffer;
63
+ }
64
+ /**
65
+ * Read `path` of `versionId` from `offset` for at most `limit` bytes (to the end when absent), checking everything the file
66
+ * header lists, and return the bytes only if all of it held. Throws {@link VersionFileIntegrityError},
67
+ * {@link VersionFileNotListedError} or {@link VersionFileInputError}; anything else is the API's own failure and is the
68
+ * caller's to say.
69
+ */
70
+ export declare function readVersionFile(reader: VersionFileReader, input: {
71
+ versionId: string;
72
+ path: string;
73
+ offset?: number;
74
+ limit?: number;
75
+ }): Promise<VersionFileRead>;
76
+ /** True when these bytes cannot be shown as text: a NUL, or not valid UTF-8. */
77
+ export declare function isBinary(bytes: Uint8Array): boolean;
78
+ /** The text with every unsafe character shown as `\u{hex}`, and how many there were. The bytes are not changed by `--raw` or `--out`. */
79
+ export declare function escapeForTerminal(text: string): {
80
+ text: string;
81
+ escaped: number;
82
+ };
@@ -0,0 +1,195 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VersionFileInputError = exports.VersionFileNotListedError = exports.VersionFileIntegrityError = exports.VERSION_FILE_INTEGRITY_EXIT = exports.VERSION_FILE_INTEGRITY_CODE = exports.VERSION_FILE_READ_MAX_BYTES = void 0;
4
+ exports.readVersionFile = readVersionFile;
5
+ exports.isBinary = isBinary;
6
+ exports.escapeForTerminal = escapeForTerminal;
7
+ /**
8
+ * `skrr apps version cat`: read the full text of a file of a FROZEN version, and prove it is the file the version's hash covers.
9
+ *
10
+ * A reviewer is asked to approve a version by its `bundleHash`. `apps version show` lists the files with their sizes and
11
+ * digests, but a digest is not something a person can read; `apps file cat` reads the MUTABLE draft, which may have moved
12
+ * since. This reads the version, a slice at a time, and refuses to hand over anything it has not checked itself:
13
+ *
14
+ * 1. the version's file list must hash to its `bundleHash` (`appBundlePreimage`), so the digests below are the ones the
15
+ * version's identity, and any consent bound to it, rests on;
16
+ * 2. the path must be one of those files, exactly;
17
+ * 3. every slice must name the same version, bundle, path, digest and size as that record, start where the last one ended,
18
+ * be exactly as long as was asked for (or what is left), and hash to the `chunkSha256` it states;
19
+ * 4. when the whole file was read, all the slices joined must hash to the record's `sha256` and be `size` bytes long.
20
+ *
21
+ * The server verifies the stored bytes against the same record before it serves a slice (`AppAuthoring/versionFile.js`); this
22
+ * does not take its word for it. Nothing here writes: the caller gets the bytes only after every check has passed, because a
23
+ * file that fails on its last slice has already been half printed by anything that streams. The bytes are bounded (a package
24
+ * file is at most a few hundred KB), so holding them costs nothing, and the bound is enforced so that a server that claims
25
+ * more cannot make a terminal command hold it.
26
+ *
27
+ * A read that starts after byte 0, or stops before the end (`--offset`, `--limit`), cannot check the file's digest; it says so
28
+ * (`wholeFileVerified: false`) and still checks every slice it did read.
29
+ */
30
+ const node_crypto_1 = require("node:crypto");
31
+ const data_provider_1 = require("@skrr-ai/data-provider");
32
+ const json_output_1 = require("./json-output");
33
+ /** The most a read will hold. A package file is far smaller (`APP_DRAFT_LIMITS`); a server that says otherwise is not believed. */
34
+ exports.VERSION_FILE_READ_MAX_BYTES = 8 * 1024 * 1024;
35
+ /** The machine code and exit under which a mismatch is reported. A distinct exit: a harness must not read "6" as an ordinary failure. */
36
+ exports.VERSION_FILE_INTEGRITY_CODE = 'APP_VERSION_FILE_INTEGRITY';
37
+ exports.VERSION_FILE_INTEGRITY_EXIT = 6;
38
+ /** The bytes are not provably the version's. Carries what disagreed; never the bytes. */
39
+ class VersionFileIntegrityError extends Error {
40
+ kind;
41
+ details;
42
+ constructor(kind, message, details = {}) {
43
+ super(message);
44
+ this.kind = kind;
45
+ this.details = details;
46
+ this.name = 'VersionFileIntegrityError';
47
+ }
48
+ }
49
+ exports.VersionFileIntegrityError = VersionFileIntegrityError;
50
+ /** The path is not one the version lists. Carries a bounded sample of the ones it does. */
51
+ class VersionFileNotListedError extends Error {
52
+ path;
53
+ listed;
54
+ constructor(path, listed) {
55
+ super(`This version lists no file at "${path}".`);
56
+ this.path = path;
57
+ this.listed = listed;
58
+ this.name = 'VersionFileNotListedError';
59
+ }
60
+ }
61
+ exports.VersionFileNotListedError = VersionFileNotListedError;
62
+ /** The caller asked for something that cannot be read (an offset past the end, a file past what the CLI will hold). */
63
+ class VersionFileInputError extends Error {
64
+ code;
65
+ constructor(code, message) {
66
+ super(message);
67
+ this.code = code;
68
+ this.name = 'VersionFileInputError';
69
+ }
70
+ }
71
+ exports.VersionFileInputError = VersionFileInputError;
72
+ const sha256Hex = (bytes) => (0, node_crypto_1.createHash)('sha256').update(bytes).digest('hex');
73
+ /** Base64 as `Buffer.from` would decode it, or null when the text is not canonical base64 (`Buffer` skips what it does not know). */
74
+ function strictBase64(text) {
75
+ if (typeof text !== 'string')
76
+ return null;
77
+ const bytes = Buffer.from(text, 'base64');
78
+ return bytes.toString('base64') === text ? bytes : null;
79
+ }
80
+ /**
81
+ * Read `path` of `versionId` from `offset` for at most `limit` bytes (to the end when absent), checking everything the file
82
+ * header lists, and return the bytes only if all of it held. Throws {@link VersionFileIntegrityError},
83
+ * {@link VersionFileNotListedError} or {@link VersionFileInputError}; anything else is the API's own failure and is the
84
+ * caller's to say.
85
+ */
86
+ async function readVersionFile(reader, input) {
87
+ const { versionId, path } = input;
88
+ const offset = input.offset ?? 0;
89
+ const { version } = await reader.getVersion(versionId);
90
+ // 1. the list the digests come from is the list the version's identity covers
91
+ let preimage;
92
+ try {
93
+ preimage = (0, data_provider_1.appBundlePreimage)(version.files);
94
+ }
95
+ catch {
96
+ throw new VersionFileIntegrityError('bundle_hash', "The version's file list cannot be hashed, so its digests cannot be tied to its bundle hash.");
97
+ }
98
+ if (sha256Hex(Buffer.from(preimage, 'utf8')) !== version.bundleHash) {
99
+ throw new VersionFileIntegrityError('bundle_hash', "The version's file list does not hash to its bundle hash, so its file digests are not the ones the version is identified by.", { bundleHash: version.bundleHash });
100
+ }
101
+ // 2. exactly one of those files
102
+ const record = version.files.find((file) => file.path === path);
103
+ if (!record) {
104
+ throw new VersionFileNotListedError(path, version.files.map((file) => file.path).slice(0, 50));
105
+ }
106
+ const total = record.size;
107
+ if (total > exports.VERSION_FILE_READ_MAX_BYTES) {
108
+ throw new VersionFileInputError('APP_VERSION_FILE_TOO_LARGE', `"${path}" is ${total} bytes; this command holds at most ${exports.VERSION_FILE_READ_MAX_BYTES} bytes of a file. A package file is far smaller, so the version's record is not believed.`);
109
+ }
110
+ if (offset > total) {
111
+ throw new VersionFileInputError('APP_VERSION_FILE_OFFSET', `--offset ${offset} is past the end of "${path}", which is ${total} bytes.`);
112
+ }
113
+ const end = input.limit === undefined ? total : Math.min(total, offset + input.limit);
114
+ // 3. every slice, against the record
115
+ const parts = [];
116
+ const whole = offset === 0 ? (0, node_crypto_1.createHash)('sha256') : null;
117
+ let at = offset;
118
+ let chunks = 0;
119
+ for (;;) {
120
+ // an empty window (an empty file, or an offset at the end) still asks once, so the server vouches for the file it is empty of
121
+ const want = Math.max(1, Math.min(data_provider_1.APP_VERSION_FILE_LIMITS.chunkBytesMax, end - at));
122
+ const expectedLength = Math.min(want, total - at);
123
+ const chunk = await reader.readChunk(versionId, { path, offset: at, limit: want });
124
+ chunks += 1;
125
+ if (chunk.versionId !== versionId ||
126
+ chunk.bundleHash !== version.bundleHash ||
127
+ chunk.path !== path ||
128
+ chunk.fileSha256 !== record.sha256 ||
129
+ chunk.total !== record.size) {
130
+ throw new VersionFileIntegrityError('record', `A slice of "${path}" does not name the version, path, digest and size the version recorded.`, { at });
131
+ }
132
+ const reachesEnd = at + expectedLength >= total;
133
+ if (chunk.offset !== at ||
134
+ chunk.length !== expectedLength ||
135
+ chunk.done !== reachesEnd ||
136
+ chunk.nextOffset !== (reachesEnd ? null : at + expectedLength)) {
137
+ throw new VersionFileIntegrityError('continuity', `A slice of "${path}" is not the one asked for at byte ${at}.`, { at });
138
+ }
139
+ const bytes = strictBase64(chunk.contentBase64);
140
+ if (bytes === null || bytes.length !== chunk.length || sha256Hex(bytes) !== chunk.chunkSha256) {
141
+ throw new VersionFileIntegrityError('chunk_digest', `The slice of "${path}" at byte ${at} is not the bytes its digest names.`, { at });
142
+ }
143
+ parts.push(bytes);
144
+ whole?.update(bytes);
145
+ at += bytes.length;
146
+ if (at >= end)
147
+ break;
148
+ }
149
+ // 4. the whole file, when the whole file was read
150
+ const joined = Buffer.concat(parts);
151
+ const wholeFile = offset === 0 && at === total;
152
+ if (wholeFile && (joined.length !== record.size || whole?.digest('hex') !== record.sha256)) {
153
+ throw new VersionFileIntegrityError('file_digest', `The slices of "${path}" joined are not the ${record.size} bytes with the digest this version recorded.`, { expectedBytes: record.size, readBytes: joined.length });
154
+ }
155
+ return {
156
+ versionId,
157
+ bundleHash: version.bundleHash,
158
+ path,
159
+ offset,
160
+ length: joined.length,
161
+ total,
162
+ fileSha256: record.sha256,
163
+ chunks,
164
+ wholeFileVerified: wholeFile,
165
+ bytes: joined,
166
+ };
167
+ }
168
+ /** True when these bytes cannot be shown as text: a NUL, or not valid UTF-8. */
169
+ function isBinary(bytes) {
170
+ if (bytes.includes(0))
171
+ return true;
172
+ try {
173
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes);
174
+ return false;
175
+ }
176
+ catch {
177
+ return true;
178
+ }
179
+ }
180
+ /**
181
+ * What a terminal would act on rather than show: C0 controls other than newline, tab and a carriage return that belongs to
182
+ * a CRLF; DEL and C1; and the invisible and direction-changing characters (zero-width, bidi overrides and isolates, line and
183
+ * paragraph separators, the byte-order mark, tag characters). The last group is what makes reviewed code differ from the
184
+ * code a compiler reads ("Trojan Source"), and an escape sequence is what lets a file repaint a reviewer's screen.
185
+ */
186
+ const TERMINAL_UNSAFE = new RegExp(`[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f]|\\r(?!\\n)|${json_output_1.JSON_TERMINAL_CONTROLS.source}`, 'gu');
187
+ /** The text with every unsafe character shown as `\u{hex}`, and how many there were. The bytes are not changed by `--raw` or `--out`. */
188
+ function escapeForTerminal(text) {
189
+ let escaped = 0;
190
+ const out = text.replace(TERMINAL_UNSAFE, (char) => {
191
+ escaped += 1;
192
+ return `\\u{${char.codePointAt(0).toString(16)}}`;
193
+ });
194
+ return { text: out, escaped };
195
+ }