@skrr-ai/cli 0.1.165 → 0.1.167

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 (97) hide show
  1. package/dist/base-command.js +0 -1
  2. package/dist/commands/activity/scan-older.d.ts +1 -1
  3. package/dist/commands/activity/scan-older.js +5 -4
  4. package/dist/commands/agent/message/approve.d.ts +1 -0
  5. package/dist/commands/agent/message/approve.js +6 -2
  6. package/dist/commands/agent/message/decline.d.ts +1 -0
  7. package/dist/commands/agent/message/decline.js +6 -2
  8. package/dist/commands/agent/message/pending.js +5 -2
  9. package/dist/commands/agent/message/review.d.ts +13 -0
  10. package/dist/commands/agent/message/review.js +68 -0
  11. package/dist/commands/agents/always-on/recovery-close.d.ts +28 -0
  12. package/dist/commands/agents/always-on/recovery-close.js +60 -0
  13. package/dist/commands/agents/always-on/recovery-review.d.ts +22 -0
  14. package/dist/commands/agents/always-on/recovery-review.js +190 -0
  15. package/dist/commands/apps/installations/compatibility.js +1 -1
  16. package/dist/commands/apps/installations/list.js +3 -0
  17. package/dist/commands/apps/installations/migrate/abort.d.ts +13 -0
  18. package/dist/commands/apps/installations/migrate/abort.js +45 -0
  19. package/dist/commands/apps/installations/migrate/cutover.d.ts +15 -0
  20. package/dist/commands/apps/installations/migrate/cutover.js +102 -0
  21. package/dist/commands/apps/installations/migrate/plan.d.ts +13 -0
  22. package/dist/commands/apps/installations/migrate/plan.js +51 -0
  23. package/dist/commands/apps/installations/migrate/rollback.d.ts +16 -0
  24. package/dist/commands/apps/installations/migrate/rollback.js +103 -0
  25. package/dist/commands/apps/installations/migrate/stage.d.ts +15 -0
  26. package/dist/commands/apps/installations/migrate/stage.js +96 -0
  27. package/dist/commands/apps/installations/migrate/status.d.ts +12 -0
  28. package/dist/commands/apps/installations/migrate/status.js +52 -0
  29. package/dist/commands/apps/installations/migrate/validate.d.ts +14 -0
  30. package/dist/commands/apps/installations/migrate/validate.js +58 -0
  31. package/dist/commands/apps/installations/show.js +8 -6
  32. package/dist/commands/apps/operations/check.js +1 -1
  33. package/dist/commands/apps/resume.js +1 -1
  34. package/dist/commands/apps/settings/set.js +22 -10
  35. package/dist/commands/duties/show.js +10 -0
  36. package/dist/commands/goals/key-results/assess.d.ts +2 -3
  37. package/dist/commands/goals/key-results/assess.js +5 -12
  38. package/dist/commands/harnesses/removal-references.d.ts +16 -0
  39. package/dist/commands/harnesses/removal-references.js +61 -0
  40. package/dist/commands/tasks/actionability.js +8 -3
  41. package/dist/commands/tasks/complete.js +35 -17
  42. package/dist/commands/tasks/expectations/assess.d.ts +1 -0
  43. package/dist/commands/tasks/expectations/assess.js +50 -21
  44. package/dist/commands/tasks/expectations.js +5 -2
  45. package/dist/commands/tasks/judge.d.ts +1 -0
  46. package/dist/commands/tasks/judge.js +17 -2
  47. package/dist/commands/tasks/result/submit.js +26 -17
  48. package/dist/commands/tasks/review-queue.js +2 -1
  49. package/dist/commands/tasks/review.d.ts +1 -0
  50. package/dist/commands/tasks/review.js +24 -3
  51. package/dist/commands/tasks/show.d.ts +13 -0
  52. package/dist/commands/tasks/show.js +41 -3
  53. package/dist/commands/tasks/updates/add.d.ts +1 -0
  54. package/dist/commands/tasks/updates/add.js +71 -21
  55. package/dist/commands/tasks/updates/list.d.ts +4 -0
  56. package/dist/commands/tasks/updates/list.js +3 -1
  57. package/dist/commands/tasks/waive.d.ts +1 -0
  58. package/dist/commands/tasks/waive.js +17 -2
  59. package/dist/generated/agent-guides.json +20 -20
  60. package/dist/lib/agent-activity.d.ts +3 -1
  61. package/dist/lib/agent-activity.js +50 -11
  62. package/dist/lib/api-fetch.js +32 -5
  63. package/dist/lib/appCompatibility.js +1 -1
  64. package/dist/lib/appData.d.ts +1 -1
  65. package/dist/lib/appData.js +6 -2
  66. package/dist/lib/appDataMigration.d.ts +204 -0
  67. package/dist/lib/appDataMigration.js +753 -0
  68. package/dist/lib/appDataMigrationCommand.d.ts +39 -0
  69. package/dist/lib/appDataMigrationCommand.js +90 -0
  70. package/dist/lib/appInstallations.d.ts +8 -0
  71. package/dist/lib/appInstallations.js +55 -2
  72. package/dist/lib/apps-command.js +17 -10
  73. package/dist/lib/harnesses.d.ts +24 -0
  74. package/dist/lib/harnesses.js +4 -0
  75. package/dist/lib/node-adapter.d.ts +0 -2
  76. package/dist/lib/node-adapter.js +46 -42
  77. package/dist/lib/rate-limit-retry.d.ts +4 -5
  78. package/dist/lib/rate-limit-retry.js +6 -10
  79. package/dist/lib/reference-syntax.d.ts +28 -0
  80. package/dist/lib/reference-syntax.js +91 -0
  81. package/dist/lib/refresh.d.ts +2 -0
  82. package/dist/lib/refresh.js +6 -0
  83. package/dist/lib/runtime-context.js +6 -0
  84. package/dist/lib/task-closure.d.ts +1 -1
  85. package/dist/lib/task-closure.js +1 -1
  86. package/dist/lib/task-operations.d.ts +28 -6
  87. package/dist/lib/task-operations.js +77 -4
  88. package/dist/lib/task-preflight.js +8 -3
  89. package/dist/lib/task-write-attribution.d.ts +183 -19
  90. package/dist/lib/task-write-attribution.js +270 -39
  91. package/dist/lib/write-outcome.d.ts +2 -0
  92. package/dist/lib/write-outcome.js +14 -0
  93. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/daemonWire.js +63 -0
  94. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/daemonWire.js +71 -0
  95. package/dist/node_modules/@skrr-ai/data-provider/index.js +11635 -11306
  96. package/oclif.manifest.json +1387 -412
  97. package/package.json +5 -2
@@ -0,0 +1,39 @@
1
+ import type { AppDataMigrationView } from '@skrr-ai/data-provider';
2
+ import { AppsCommand } from './apps-command';
3
+ import { MigrationLoopError } from './appDataMigration';
4
+ import type { MigrationFailureContext, MigrationStep } from './appDataMigration';
5
+ /**
6
+ * What the five `apps installations migrate` commands share: saying what a failed request means in the exit table's terms
7
+ * (`appDataMigration.ts`), saying that an answer is unreadable (exit 5, never a success), and printing a migration, in text or as
8
+ * `--json`, under the exit its state has. It declares no static `args` or `flags`: oclif reads those from the concrete command's own
9
+ * class, and one inherited from here would be lost (see `command-inherited-statics.spec.ts`).
10
+ */
11
+ export declare abstract class AppsMigrationCommand extends AppsCommand {
12
+ /**
13
+ * Say what a failed request means. A refusal, a stranger, a bad request, a switched-off feature and a write whose outcome is unknown get
14
+ * the migration's own words and exit code; what it does not know (a sign-in that expired, a rate limit, the server being down on a read) is
15
+ * the CLI's ordinary failure. Never returns.
16
+ */
17
+ protected failMigration(error: unknown, ctx: Omit<MigrationFailureContext, 'bin'>, write: boolean): never;
18
+ /** A call of a loop failed or was unreadable. Never returns. */
19
+ protected failLoop(error: MigrationLoopError, ctx: Omit<MigrationFailureContext, 'bin'>): never;
20
+ /** The server answered, but not with a migration this client understands. Exit 5, never a success. Never returns. */
21
+ protected failUnreadable(step: MigrationStep, installation: string): never;
22
+ /**
23
+ * The server answered with a migration this client reads, but not in the state the step says it leaves it in (a plan that is not
24
+ * `planned`, an abort that is not `aborted`). Exit 5: the step did not provably do what it says. Never returns.
25
+ */
26
+ protected failUnexpectedState(step: MigrationStep, view: AppDataMigrationView, expected: string): never;
27
+ /**
28
+ * Print a migration under the exit its state has. Text: the lines of `formatMigration`, then any `notes` on STDERR (why a loop stopped).
29
+ * `--json`: the one document on stdout (`json` is what to print, `ok` only for exit 0), the notes still on stderr. A non-zero exit is
30
+ * taken after the output has been handed to the operating system.
31
+ */
32
+ protected report(view: AppDataMigrationView, options: {
33
+ json: boolean;
34
+ exit: number;
35
+ /** What `--json` prints; defaults to the migration itself. */
36
+ jsonValue?: unknown;
37
+ notes?: Array<string | null>;
38
+ }): Promise<void>;
39
+ }
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AppsMigrationCommand = void 0;
4
+ const apps_command_1 = require("./apps-command");
5
+ const drain_stdio_1 = require("./drain-stdio");
6
+ const appDataMigration_1 = require("./appDataMigration");
7
+ /**
8
+ * What the five `apps installations migrate` commands share: saying what a failed request means in the exit table's terms
9
+ * (`appDataMigration.ts`), saying that an answer is unreadable (exit 5, never a success), and printing a migration, in text or as
10
+ * `--json`, under the exit its state has. It declares no static `args` or `flags`: oclif reads those from the concrete command's own
11
+ * class, and one inherited from here would be lost (see `command-inherited-statics.spec.ts`).
12
+ */
13
+ class AppsMigrationCommand extends apps_command_1.AppsCommand {
14
+ /**
15
+ * Say what a failed request means. A refusal, a stranger, a bad request, a switched-off feature and a write whose outcome is unknown get
16
+ * the migration's own words and exit code; what it does not know (a sign-in that expired, a rate limit, the server being down on a read) is
17
+ * the CLI's ordinary failure. Never returns.
18
+ */
19
+ failMigration(error, ctx, write) {
20
+ const failure = (0, appDataMigration_1.describeMigrationFailure)(error, { ...ctx, bin: this.config.bin }, write);
21
+ if (failure === null) {
22
+ return this.failInstallation(error, {
23
+ subject: ctx.installation,
24
+ ...(ctx.versionId === undefined ? {} : { versionId: ctx.versionId }),
25
+ });
26
+ }
27
+ return this.failWithCliError(failure);
28
+ }
29
+ /** A call of a loop failed or was unreadable. Never returns. */
30
+ failLoop(error, ctx) {
31
+ if (error.unreadable) {
32
+ return this.failWithCliError({
33
+ message: `${(0, appDataMigration_1.migrationUnreadableMessage)(ctx.step, ctx.installation)}${error.calls > 1
34
+ ? ` ${error.calls - 1} earlier call${error.calls - 1 === 1 ? '' : 's'} in this run ${error.calls - 1 === 1 ? 'was' : 'were'} answered${error.last ? ` (the migration was ${error.last.state} then)` : ''}.`
35
+ : ''}`,
36
+ code: appDataMigration_1.APPS_MIGRATION_CODES.unreadable,
37
+ exit: appDataMigration_1.APPS_MIGRATION_EXIT.unknown,
38
+ retryable: false,
39
+ details: { outcome: 'unknown', step: ctx.step, calls: error.calls },
40
+ });
41
+ }
42
+ return this.failMigration(error.error, { ...ctx, calls: error.calls, last: error.last }, true);
43
+ }
44
+ /** The server answered, but not with a migration this client understands. Exit 5, never a success. Never returns. */
45
+ failUnreadable(step, installation) {
46
+ return this.failWithCliError({
47
+ message: (0, appDataMigration_1.migrationUnreadableMessage)(step, installation),
48
+ code: appDataMigration_1.APPS_MIGRATION_CODES.unreadable,
49
+ exit: appDataMigration_1.APPS_MIGRATION_EXIT.unknown,
50
+ retryable: false,
51
+ details: { outcome: 'unknown', step },
52
+ });
53
+ }
54
+ /**
55
+ * The server answered with a migration this client reads, but not in the state the step says it leaves it in (a plan that is not
56
+ * `planned`, an abort that is not `aborted`). Exit 5: the step did not provably do what it says. Never returns.
57
+ */
58
+ failUnexpectedState(step, view, expected) {
59
+ const inst = (0, appDataMigration_1.installationRef)(view.installationId);
60
+ return this.failWithCliError({
61
+ message: `The server answered with a migration that is ${view.state}, not ${expected}, so it is not known that the ${step} did what it says. This is not a success.\n→ Read where it stands with: ${this.config.bin} apps installations migrate status ${inst}`,
62
+ code: appDataMigration_1.APPS_MIGRATION_CODES.unreadable,
63
+ exit: appDataMigration_1.APPS_MIGRATION_EXIT.unknown,
64
+ retryable: false,
65
+ details: { outcome: 'unknown', step, state: view.state },
66
+ });
67
+ }
68
+ /**
69
+ * Print a migration under the exit its state has. Text: the lines of `formatMigration`, then any `notes` on STDERR (why a loop stopped).
70
+ * `--json`: the one document on stdout (`json` is what to print, `ok` only for exit 0), the notes still on stderr. A non-zero exit is
71
+ * taken after the output has been handed to the operating system.
72
+ */
73
+ async report(view, options) {
74
+ if (options.json) {
75
+ this.printJsonResult(options.jsonValue ?? view, { ok: options.exit === 0 });
76
+ }
77
+ else {
78
+ for (const line of (0, appDataMigration_1.formatMigration)(view, this.config.bin))
79
+ this.log(line);
80
+ }
81
+ for (const note of options.notes ?? []) {
82
+ if (note)
83
+ this.logToStderr(note);
84
+ }
85
+ await (0, drain_stdio_1.drainStdio)();
86
+ if (options.exit !== 0)
87
+ this.exit(options.exit);
88
+ }
89
+ }
90
+ exports.AppsMigrationCommand = AppsMigrationCommand;
@@ -84,6 +84,14 @@ export declare function resolveInstallTarget(input: {
84
84
  appId: string;
85
85
  versionId?: string;
86
86
  }): Promise<InstallTarget>;
87
+ /**
88
+ * What `apps installations show` says about WHY an installation is suspended, and what the person can do about it, by who suspended it
89
+ * (`suspension.by`: `moderation` or `migration`; absent for a pause the person chose and from a server that does not say). The two
90
+ * sources must never be worded as each other: a moderation is the platform's decision and only the platform lifts it, while a migration
91
+ * is the installer's own and is closed by `apps installations migrate abort`. A source this client does not know, or none given, gets
92
+ * the words that are true of all of them.
93
+ */
94
+ export declare function describeSuspensionNote(installationId: string, source: unknown, bin: string): string[];
87
95
  /**
88
96
  * What the command that was refused knows, for the words of its refusal. Every field is optional: a command that knows
89
97
  * less gets words that name less (a placeholder in angle brackets where an argument is unknown), never a command printed
@@ -16,6 +16,7 @@ exports.formatHosting = formatHosting;
16
16
  exports.describeBindingRefusal = describeBindingRefusal;
17
17
  exports.describeDisclosureCheck = describeDisclosureCheck;
18
18
  exports.resolveInstallTarget = resolveInstallTarget;
19
+ exports.describeSuspensionNote = describeSuspensionNote;
19
20
  exports.describeInstallationConflict = describeInstallationConflict;
20
21
  exports.formatScopeIssues = formatScopeIssues;
21
22
  exports.resolveInstallPrincipal = resolveInstallPrincipal;
@@ -983,7 +984,53 @@ const FORBIDDEN_REASON_WORDS = {
983
984
  unknown_actor: 'The platform could not tell who is asking.',
984
985
  // the installation was suspended by the platform, not by the person: resuming it is not theirs to do
985
986
  suspended_by_moderation: 'The platform suspended this app, not you, and only the platform can lift that. There is nothing to resume from here.',
987
+ // a data migration (step 6b-1) runs under the installer's own approval; another editor starts one only by approving the app again
988
+ installer_only: 'Only the installer (the person whose approval this installation runs under) can do this. Another editor has to approve the app again first.',
986
989
  };
990
+ /**
991
+ * The words of a `forbidden` that name a command, so they need the binary's name and the installation asked about. The installation is
992
+ * frozen by its OWN data migration (step 6b-1): that is not a moderation, nobody at the platform lifts it, and the way out is the
993
+ * migration's own `abort`. A resume, a move and a settings write are refused with this reason until it is closed.
994
+ */
995
+ const FORBIDDEN_REASON_COMMAND_WORDS = {
996
+ suspended_by_migration: (bin, context) => {
997
+ const installation = idOf(INSTALLATION_ID_PATTERN, context.subject) ?? '<installation>';
998
+ return `This app is frozen while its data is being migrated to another version, so it cannot be resumed, moved or changed until that migration is closed. Nothing was changed. \`${bin} apps installations migrate status ${installation}\` says where the migration stands; \`${bin} apps installations migrate abort ${installation}\` ends it and puts the app back as it was.`;
999
+ },
1000
+ };
1001
+ /** The words of a `forbidden` refusal, by its reason. */
1002
+ function describeForbiddenReason(reason, bin, context, fallback) {
1003
+ const named = FORBIDDEN_REASON_COMMAND_WORDS[reason ?? ''];
1004
+ return named ? named(bin, context) : (FORBIDDEN_REASON_WORDS[reason ?? ''] ?? fallback);
1005
+ }
1006
+ /**
1007
+ * What `apps installations show` says about WHY an installation is suspended, and what the person can do about it, by who suspended it
1008
+ * (`suspension.by`: `moderation` or `migration`; absent for a pause the person chose and from a server that does not say). The two
1009
+ * sources must never be worded as each other: a moderation is the platform's decision and only the platform lifts it, while a migration
1010
+ * is the installer's own and is closed by `apps installations migrate abort`. A source this client does not know, or none given, gets
1011
+ * the words that are true of all of them.
1012
+ */
1013
+ function describeSuspensionNote(installationId, source, bin) {
1014
+ const valid = INSTALLATION_ID_PATTERN.test(installationId);
1015
+ const inst = valid ? installationId : '<installation>';
1016
+ if (source === 'migration') {
1017
+ return [
1018
+ 'Its data is being migrated to another version, which freezes it. It cannot be resumed, moved or changed until that migration is closed, and nothing live has changed.',
1019
+ `\`${bin} apps installations migrate status ${inst}\` says where the migration stands; \`${bin} apps installations migrate abort ${inst}\` ends it and puts the app back as it was.`,
1020
+ ];
1021
+ }
1022
+ if (source === 'moderation') {
1023
+ return [
1024
+ 'The platform suspended this app, not you, and only the platform can lift that. There is nothing to resume from here.',
1025
+ ];
1026
+ }
1027
+ return [
1028
+ valid
1029
+ ? `If you can manage this installation, you can try \`${bin} apps resume ${installationId}\` using the same account, deployment, profile and workspace as this command. Resuming may enable its jobs.`
1030
+ : 'If you can manage this installation, find its valid installation ID before trying to resume it. Resuming may enable its jobs.',
1031
+ `Otherwise ask someone who can manage it. A suspension the platform made (moderation) must be lifted by the platform, and a freeze held by a data migration is refused a resume until that migration is closed: \`${bin} apps installations migrate status ${inst}\` says whether one is open.`,
1032
+ ];
1033
+ }
987
1034
  const INSTALLATION_ID_PATTERN = /^appi_[A-Za-z0-9_-]{1,60}(?![\s\S])/;
988
1035
  const VERSION_ID_PATTERN = /^appv_[A-Za-z0-9_-]{1,60}(?![\s\S])/;
989
1036
  const AGENT_ID_PATTERN = /^agent_[A-Za-z0-9_-]{1,60}(?![\s\S])/;
@@ -1033,7 +1080,7 @@ const CONFLICT_WORDS = {
1033
1080
  invalid_input: () => 'The request was not understood. Check the ids and try again.',
1034
1081
  principal_kind_not_enabled: () => 'Apps can be installed on an agent or on yourself today; installing on a space is not available yet.',
1035
1082
  principal_not_found: () => 'There is no such agent that you can see (and an app on a person can be put there only by that person). Check the id (and that you have access to it).',
1036
- forbidden: (refusal) => FORBIDDEN_REASON_WORDS[refusal.reason ?? ''] ?? 'You may not do this.',
1083
+ forbidden: (refusal, bin, context) => describeForbiddenReason(refusal.reason, bin, context, 'You may not do this.'),
1037
1084
  app_not_found: () => 'There is no such app that you can use. Check the id, or ask its owner to share it.',
1038
1085
  version_not_found: () => 'There is no such version of that app that you can use.',
1039
1086
  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.',
@@ -1060,11 +1107,16 @@ const CONFLICT_WORDS = {
1060
1107
  changed: () => 'The installation changed while this was running. Read its current state before deciding what to do next.',
1061
1108
  not_auto_updatable: () => 'That installation does not update on its own.',
1062
1109
  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.`,
1063
- installation_incomplete: () => 'This installation points at a version that can no longer be read. It can be removed, not run.',
1110
+ installation_incomplete: () => 'This installation is incomplete or its version cannot be read, so it cannot run. Check your installations again later; if it remains unavailable, contact support with the installation ID. Its data may still be present.',
1064
1111
  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)
1065
1112
  ? ' An app that needs an agent to run it can, for now, only be installed on one of your agents.'
1066
1113
  : ''} ${nothingWas(context)}`,
1067
1114
  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.',
1115
+ // the installer's data migration holds the app frozen (step 6b): nothing about the installation's lifecycle is written until it is closed
1116
+ installation_being_migrated: (_refusal, bin, context) => {
1117
+ const installation = idOf(INSTALLATION_ID_PATTERN, context.subject) ?? '<installation>';
1118
+ return `This app is frozen while its data is being migrated to another version, so its update channel, its settings, its approval, its version and its existence cannot be changed until that migration is closed. Nothing was changed. The person who started it can read where it stands with \`${bin} apps installations migrate status ${installation}\` and end it with \`${bin} apps installations migrate abort ${installation}\` (a cutover that has begun can only finish or be rolled back).`;
1119
+ },
1068
1120
  job_schedule_invalid: (refusal, bin) => {
1069
1121
  const issues = Array.isArray(refusal.issues)
1070
1122
  ? refusal.issues.length
@@ -1240,6 +1292,7 @@ function installationRefusalExit(conflict) {
1240
1292
  /** Why a version that needs no new approval was still not applied by the opt-in, in a clause. */
1241
1293
  const AUTO_APPLY_HOLD_WORDS = {
1242
1294
  installation_suspended: 'the installation is paused',
1295
+ installation_being_migrated: 'the installation is frozen while its data is migrated (see `apps installations migrate status`)',
1243
1296
  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)',
1244
1297
  version_not_installable: 'the version was rejected or withdrawn',
1245
1298
  principal_scope_unserved: 'it declares something this installation cannot serve',
@@ -10,8 +10,8 @@ const appsFs_1 = require("./appsFs");
10
10
  const appData_1 = require("./appData");
11
11
  /**
12
12
  * The refusals the person-data write route sends BEFORE it writes, with the status it sends each at: the route's own table,
13
- * plus the store's `conflict` answer. `unavailable` is left out on purpose: it proves nothing unless it also says the
14
- * installation is paused, so `failPersonData` adds it, at the statuses a pause is sent with, only for that body.
13
+ * plus the store's `conflict` answer. A generic `unavailable` proves nothing. A confirmed pause or a fence refusal
14
+ * can establish that the write was not applied when it arrives with its documented status.
15
15
  */
16
16
  const { unavailable: _notAContractRefusal, ...PERSON_DATA_CONTRACT_REFUSALS } = data_provider_1.APP_PERSON_DATA_REFUSAL_STATUS;
17
17
  const PERSON_DATA_WRITE_REFUSALS = {
@@ -131,23 +131,28 @@ class AppsCommand extends base_command_1.BaseCommand {
131
131
  const responseStatus = error?.status;
132
132
  const responseCode = error?.code;
133
133
  const parsedFailure = (0, appData_1.readPersonDataFailure)(error);
134
- const paused = parsedFailure?.kind === 'refusal' &&
135
- parsedFailure.code === 'unavailable' &&
136
- parsedFailure.reason === 'installation_suspended';
134
+ const unavailableReason = parsedFailure?.kind === 'refusal' && parsedFailure.code === 'unavailable'
135
+ ? parsedFailure.reason
136
+ : undefined;
137
+ const unavailableStatuses = unavailableReason === 'installation_suspended'
138
+ ? [403, 503]
139
+ : unavailableReason === 'installation_changed'
140
+ ? [data_provider_1.APP_PERSON_DATA_REFUSAL_STATUS.unavailable]
141
+ : undefined;
137
142
  const sentWrite = Boolean(target.verb) && target.requestStarted;
138
143
  // Which responses prove the write was NOT applied is the shared contract's table, not this method's: a typed refusal
139
144
  // counts only at the status its route promises, a 401, 408, 425, 5xx or bare 429 never does, and no answer at all is
140
145
  // unknown (`classifyWriteOutcome`, OSK-24076). What is this command's own is the route's list of refusals, below.
141
146
  // The route's per-operation limit refuses before any write runs, so a 429 carrying the `rate` body is a definite
142
- // "not applied". A pause is a definite "not applied" only when it says so, at the statuses the route sends it with.
147
+ // "not applied". The route also confirms a refusal when it names a pause or the generation fence explicitly.
143
148
  const sent = (0, write_outcome_1.requestOfError)(error);
144
149
  const outcome = (0, write_outcome_1.classifyRequestOutcome)({
145
150
  request: { method: sentWrite ? sent.method || 'PUT' : 'GET', path: sent.path },
146
151
  status: typeof responseStatus === 'number' ? responseStatus : undefined,
147
152
  body: error?.body,
148
153
  transportError: sentWrite && (responseStatus === undefined || responseStatus === 0),
149
- refusals: paused
150
- ? { ...PERSON_DATA_WRITE_REFUSALS, unavailable: [403, 503] }
154
+ refusals: unavailableStatuses
155
+ ? { ...PERSON_DATA_WRITE_REFUSALS, unavailable: unavailableStatuses }
151
156
  : PERSON_DATA_WRITE_REFUSALS,
152
157
  // A 2xx the transport could not read as JSON is not the confirmation it looks like.
153
158
  bodyConfirms: responseCode !== 'NON_JSON_RESPONSE',
@@ -188,7 +193,7 @@ class AppsCommand extends base_command_1.BaseCommand {
188
193
  target.requestStarted &&
189
194
  failure?.kind === 'refusal' &&
190
195
  failure.code === 'unavailable' &&
191
- failure.reason === 'installation_suspended') {
196
+ (failure.reason === 'installation_suspended' || failure.reason === 'installation_changed')) {
192
197
  return this.failWithCliError({
193
198
  code: appData_1.PERSON_DATA_REFUSAL_CODES.unavailable,
194
199
  message: (0, appData_1.describePersonDataRefusal)(failure, this.config.bin),
@@ -198,7 +203,9 @@ class AppsCommand extends base_command_1.BaseCommand {
198
203
  retryable: false,
199
204
  details: {
200
205
  reason: failure.reason,
201
- retryability: 'after_state_change',
206
+ ...(failure.reason === 'installation_suspended'
207
+ ? { retryability: 'after_state_change' }
208
+ : {}),
202
209
  outcome: 'not_applied',
203
210
  },
204
211
  });
@@ -184,6 +184,30 @@ export declare function getHarness(id: string): Promise<{
184
184
  harness?: Harness;
185
185
  }>;
186
186
  export declare function getHarnessModels(id: string): Promise<unknown>;
187
+ /**
188
+ * `GET /api/harnesses/:id/removal-references`: what still points at this
189
+ * machine. Partial, read-only evidence; the server never says removal is safe
190
+ * (`removalAuthorized` is always false).
191
+ */
192
+ export interface HarnessRemovalReferences {
193
+ harnessId: string;
194
+ observedAt: string;
195
+ coverage: 'partial';
196
+ removalAuthorized: false;
197
+ agents: {
198
+ total: number;
199
+ owned: number;
200
+ other: number;
201
+ ownedListed: Array<{
202
+ id: string | null;
203
+ name: string | null;
204
+ }>;
205
+ ownedTruncated: boolean;
206
+ };
207
+ /** `null` when the owner's inference policy could not be read. */
208
+ ownInferencePolicyReferencesMachine: boolean | null;
209
+ }
210
+ export declare function getHarnessRemovalReferences(id: string): Promise<HarnessRemovalReferences>;
187
211
  export declare function listHarnessProducts(): Promise<unknown>;
188
212
  export declare function getHarnessUsage(id: string): Promise<unknown>;
189
213
  /** The rollup across every harness. The web calls this key `fleetUsage`. */
@@ -5,6 +5,7 @@ exports.describeHealthReasonSentences = describeHealthReasonSentences;
5
5
  exports.listHarnesses = listHarnesses;
6
6
  exports.getHarness = getHarness;
7
7
  exports.getHarnessModels = getHarnessModels;
8
+ exports.getHarnessRemovalReferences = getHarnessRemovalReferences;
8
9
  exports.listHarnessProducts = listHarnessProducts;
9
10
  exports.getHarnessUsage = getHarnessUsage;
10
11
  exports.getAllHarnessUsage = getAllHarnessUsage;
@@ -97,6 +98,9 @@ async function getHarness(id) {
97
98
  async function getHarnessModels(id) {
98
99
  return (0, api_fetch_1.apiFetch)(`/api/harnesses/${encodeURIComponent(id)}/models`);
99
100
  }
101
+ async function getHarnessRemovalReferences(id) {
102
+ return (0, api_fetch_1.apiFetch)(`/api/harnesses/${encodeURIComponent(id)}/removal-references`);
103
+ }
100
104
  async function listHarnessProducts() {
101
105
  return (0, api_fetch_1.apiFetch)('/api/machines/products');
102
106
  }
@@ -1,8 +1,6 @@
1
1
  import { type HttpAdapter } from '@skrr-ai/data-provider';
2
2
  import { type ResolvedCredential } from '@skrr-ai/auth-core';
3
3
  import './auth-core-init';
4
- export declare const APP_DATA_PATH_RE: RegExp;
5
- export declare const APP_SETTINGS_PATH_RE: RegExp;
6
4
  /**
7
5
  * node-adapter.ts — Node-native HttpAdapter for @skrr-ai/data-provider.
8
6
  *
@@ -1,6 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.APP_SETTINGS_PATH_RE = exports.APP_DATA_PATH_RE = void 0;
4
3
  exports.setAdapterCredentialOverride = setAdapterCredentialOverride;
5
4
  exports.clearAdapterCredentialOverride = clearAdapterCredentialOverride;
6
5
  exports.getAdapterCredentialOverride = getAdapterCredentialOverride;
@@ -24,12 +23,6 @@ const rate_limit_retry_1 = require("./rate-limit-retry");
24
23
  const write_outcome_1 = require("./write-outcome");
25
24
  const RESOLVE_URL_RE = /^https?:\/\//i;
26
25
  const RESOLVE_URL_RE_2 = /\/+$/;
27
- // These routes do not yet have a server-side idempotency receipt. A generated
28
- // request key alone cannot make an arbitrary gateway response safe to replay.
29
- // A deployment can mount the API beneath a path prefix; a match at any
30
- // segment is deliberately conservative even for a different origin.
31
- exports.APP_DATA_PATH_RE = /\/api\/apps\/installations\/[^/]+\/data(?:\/|$)/;
32
- exports.APP_SETTINGS_PATH_RE = /\/api\/apps\/installations\/[^/]+\/settings\/?$/;
33
26
  // ---------------------------------------------------------------------
34
27
  // Per-process credential override — set by BaseCommand.init().
35
28
  // Pulled out of the closure so test harnesses or long-lived callers
@@ -171,26 +164,6 @@ function createNodeAdapter(opts = {}) {
171
164
  }
172
165
  return u.toString();
173
166
  }
174
- function isAppDataWrite(method, url) {
175
- if (method === 'GET')
176
- return false;
177
- try {
178
- return exports.APP_DATA_PATH_RE.test(new URL(url).pathname);
179
- }
180
- catch {
181
- return false;
182
- }
183
- }
184
- function isAppSettingsWrite(method, url) {
185
- if (method !== 'PUT')
186
- return false;
187
- try {
188
- return exports.APP_SETTINGS_PATH_RE.test(new URL(url).pathname);
189
- }
190
- catch {
191
- return false;
192
- }
193
- }
194
167
  /** The last 429's `Retry-After`, read off the response of the most recent attempt. */
195
168
  let lastRetryAfterMs;
196
169
  async function rawRequest(method, url, body, options, isFormData) {
@@ -219,9 +192,7 @@ function createNodeAdapter(opts = {}) {
219
192
  const signal = timeoutSignal && callerSignal
220
193
  ? AbortSignal.any([timeoutSignal, callerSignal])
221
194
  : timeoutSignal || callerSignal;
222
- const appDataWrite = isAppDataWrite(method, finalUrl);
223
- const appSettingsWrite = isAppSettingsWrite(method, finalUrl);
224
- const noReplay = options?._disableAuthReplay === true;
195
+ const replaySafe = options?._disableAuthReplay !== true && (0, write_outcome_1.isRequestReplaySafe)(method, finalUrl, headers);
225
196
  let fetched;
226
197
  try {
227
198
  fetched = await (0, rate_limit_retry_1.fetchWithRateLimitRetry)(() => fetch(finalUrl, {
@@ -229,13 +200,16 @@ function createNodeAdapter(opts = {}) {
229
200
  headers,
230
201
  body: finalBody,
231
202
  ...(signal ? { signal } : {}),
232
- ...(appDataWrite || appSettingsWrite || noReplay
203
+ // A receipt for this route cannot vouch for a redirect destination.
204
+ ...(!replaySafe || method !== 'GET'
233
205
  ? { redirect: 'manual' }
234
206
  : (0, task_runtime_headers_1.taskRuntimeRedirectOptions)(headers)),
235
207
  }), {
236
208
  method,
209
+ url: finalUrl,
237
210
  headers,
238
- ...(appDataWrite || appSettingsWrite || noReplay ? { maxRetries: 0 } : {}),
211
+ signal,
212
+ ...(!replaySafe ? { maxRetries: 0 } : {}),
239
213
  });
240
214
  }
241
215
  catch (transportError) {
@@ -386,6 +360,37 @@ function createNodeAdapter(opts = {}) {
386
360
  onTokenRefresh?.(accessToken, outcome.outcome.refreshToken);
387
361
  return true;
388
362
  }
363
+ async function refreshBeforeWrite() {
364
+ const { token, kind } = currentCredential();
365
+ if (!token ||
366
+ _credOverride?.source === 'flag' ||
367
+ (0, auth_core_1.isStaticTokenKind)(kind) ||
368
+ !(0, refresh_1.cliCredentialNeedsRefresh)(token))
369
+ return;
370
+ if ((0, delegated_cli_1.isDelegatedCliSession)()) {
371
+ await refresh();
372
+ return;
373
+ }
374
+ if ((0, credential_resolver_1.resolveTrustedAutonomousCredential)())
375
+ return;
376
+ if ((0, daemonBroker_1.isBrokeredHandoffToken)(token)) {
377
+ const fresh = await (0, daemonBroker_1.redeemBrokeredHandoffToken)(true);
378
+ if (fresh?.accessToken) {
379
+ setAdapterCredentialOverride({
380
+ token: fresh.accessToken,
381
+ source: 'env-token',
382
+ kind: (0, auth_core_1.classifyTokenKind)(fresh.accessToken),
383
+ });
384
+ onTokenRefresh?.(fresh.accessToken);
385
+ }
386
+ return;
387
+ }
388
+ const fresh = await (0, refresh_1.ensureFreshCliCredential)({ credential: _credOverride ?? undefined });
389
+ if (fresh.refreshed && fresh.credential.token) {
390
+ setAdapterCredentialOverride(fresh.credential);
391
+ onTokenRefresh?.(fresh.credential.token, fresh.pair?.refreshToken);
392
+ }
393
+ }
389
394
  async function request(method, url, body, options, isFormData = false) {
390
395
  // Writes that arrive through `request.ts` already carry a key. A direct
391
396
  // adapter call gets one by the same shared rule, chosen HERE, once, so the
@@ -396,16 +401,15 @@ function createNodeAdapter(opts = {}) {
396
401
  headers: (0, data_provider_1.withIdempotencyKey)(options?.headers, { method, url, body }),
397
402
  };
398
403
  }
399
- const appDataWrite = isAppDataWrite(method, resolveUrl(url));
400
- const appSettingsWrite = isAppSettingsWrite(method, resolveUrl(url));
404
+ if (method !== 'GET' && !url.includes('/api/auth/')) {
405
+ await refreshBeforeWrite();
406
+ }
407
+ const replaySafe = options?._disableAuthReplay !== true &&
408
+ (0, write_outcome_1.isRequestReplaySafe)(method, resolveUrl(url), options?.headers);
401
409
  let res = await rawRequest(method, url, body, options, isFormData);
402
410
  // Never retry auth endpoints themselves — prevents refresh recursion
403
411
  // and lets login/logout/refresh surface their real errors.
404
- if (res.status === 401 &&
405
- !appDataWrite &&
406
- !appSettingsWrite &&
407
- options?._disableAuthReplay !== true &&
408
- !url.includes('/api/auth/')) {
412
+ if (res.status === 401 && replaySafe && !url.includes('/api/auth/')) {
409
413
  const refreshed = await refresh();
410
414
  if (refreshed) {
411
415
  res = await rawRequest(method, url, body, options, isFormData);
@@ -420,11 +424,11 @@ function createNodeAdapter(opts = {}) {
420
424
  if (brokered) {
421
425
  res = await rawRequest(method, url, body, options, isFormData);
422
426
  }
423
- else {
424
- onAuthFailure?.();
425
- }
426
427
  }
427
428
  }
429
+ if (res.status === 401 && !url.includes('/api/auth/')) {
430
+ onAuthFailure?.();
431
+ }
428
432
  if (!res.ok) {
429
433
  // Attach the raw body to the error object so callers can inspect
430
434
  // it programmatically (e.g., --json mode, debug output), but keep
@@ -6,10 +6,8 @@
6
6
  * (`Retry-After`, `standardHeaders: true`). Until now both transports treated a
7
7
  * 429 as terminal, so a burst of keyed creates failed on the first refusal.
8
8
  *
9
- * Retried only when replay is provably safe: a GET, or a write that carries an
10
- * `X-Idempotency-Key` (every `request.ts` / adapter write does). Callers must
11
- * disable retries for routes without server-side replay protection: a client
12
- * header or a 429 from an intermediary does not prove the write did not run.
9
+ * Reads retry automatically. A write also needs a request key and a server-declared
10
+ * replay receipt. A response from an intermediary cannot establish that a write was refused.
13
11
  *
14
12
  * Never retried when the body says it cannot help: a 429 that declares
15
13
  * `retryable: false` (a follow-up budget refusal, which says the day resets at
@@ -31,9 +29,10 @@ export declare function parseRetryAfterMs(value: string | null | undefined, now?
31
29
  */
32
30
  export declare function rateLimitWaitMs(attempt: number, retryAfterMs: number | undefined, random?: () => number): number;
33
31
  export declare function maxRateLimitRetries(env?: NodeJS.ProcessEnv): number;
34
- export declare function isRateLimitRetrySafe(method: string, headers: Record<string, string> | undefined): boolean;
32
+ export declare function isRateLimitRetrySafe(method: string, headers?: Record<string, string>, url?: string): boolean;
35
33
  export interface RateLimitRetryOptions {
36
34
  method: string;
35
+ url?: string;
37
36
  headers?: Record<string, string>;
38
37
  signal?: AbortSignal;
39
38
  sleep?: (ms: number) => Promise<void>;
@@ -7,10 +7,8 @@
7
7
  * (`Retry-After`, `standardHeaders: true`). Until now both transports treated a
8
8
  * 429 as terminal, so a burst of keyed creates failed on the first refusal.
9
9
  *
10
- * Retried only when replay is provably safe: a GET, or a write that carries an
11
- * `X-Idempotency-Key` (every `request.ts` / adapter write does). Callers must
12
- * disable retries for routes without server-side replay protection: a client
13
- * header or a 429 from an intermediary does not prove the write did not run.
10
+ * Reads retry automatically. A write also needs a request key and a server-declared
11
+ * replay receipt. A response from an intermediary cannot establish that a write was refused.
14
12
  *
15
13
  * Never retried when the body says it cannot help: a 429 that declares
16
14
  * `retryable: false` (a follow-up budget refusal, which says the day resets at
@@ -28,6 +26,7 @@ exports.rateLimitWaitMs = rateLimitWaitMs;
28
26
  exports.maxRateLimitRetries = maxRateLimitRetries;
29
27
  exports.isRateLimitRetrySafe = isRateLimitRetrySafe;
30
28
  exports.fetchWithRateLimitRetry = fetchWithRateLimitRetry;
29
+ const write_outcome_1 = require("./write-outcome");
31
30
  const PARSE_RETRY_AFTER_MS_RE = /^\d+(\.\d+)?$/;
32
31
  exports.DEFAULT_MAX_RATE_LIMIT_RETRIES = 2;
33
32
  exports.MAX_RATE_LIMIT_WAIT_MS = 10_000;
@@ -61,11 +60,8 @@ function maxRateLimitRetries(env = process.env) {
61
60
  const n = Number(raw);
62
61
  return Number.isInteger(n) && n >= 0 ? Math.min(n, 5) : exports.DEFAULT_MAX_RATE_LIMIT_RETRIES;
63
62
  }
64
- function hasKey(headers) {
65
- return Object.keys(headers ?? {}).some((k) => k.toLowerCase() === 'x-idempotency-key');
66
- }
67
- function isRateLimitRetrySafe(method, headers) {
68
- return method.toUpperCase() === 'GET' || hasKey(headers);
63
+ function isRateLimitRetrySafe(method, headers, url) {
64
+ return (0, write_outcome_1.isRequestReplaySafe)(method, url, headers);
69
65
  }
70
66
  function retryAfterOf(response) {
71
67
  return response.status === 429
@@ -94,7 +90,7 @@ async function fetchWithRateLimitRetry(attemptFetch, options) {
94
90
  const max = options.maxRetries ?? maxRateLimitRetries();
95
91
  let response = await attemptFetch();
96
92
  let retryAfterMs = retryAfterOf(response);
97
- if (!isRateLimitRetrySafe(options.method, options.headers))
93
+ if (!(0, write_outcome_1.isRequestReplaySafe)(options.method, options.url, options.headers))
98
94
  return { response, retryAfterMs };
99
95
  for (let attempt = 0; attempt < max && response.status === 429; attempt++) {
100
96
  if (options.signal?.aborted)
@@ -0,0 +1,28 @@
1
+ import type { TaskReference } from '@skrr-ai/data-provider';
2
+ /** The accepted spellings, as error messages and help name them. */
3
+ export declare const REFERENCE_SYNTAX_EXAMPLES = "such as task:OSK-42, pr:https://github.com/acme/app/pull/482 or https://ci.example.com/runs/77";
4
+ export declare class ReferenceSyntaxError extends Error {
5
+ constructor(message: string);
6
+ }
7
+ /**
8
+ * Read one `<kind>:<id-or-uri>`, or a bare URL, into a reference. Throws a
9
+ * {@link ReferenceSyntaxError} naming `flag` when there is no kind or nothing after the colon.
10
+ *
11
+ * https://x/pr/1 → { kind: 'url', uri: 'https://x/pr/1' }
12
+ * pr:https://x/pr/1 → { kind: 'pr', uri: 'https://x/pr/1' }
13
+ * file:/tmp/report.txt → { kind: 'file', uri: '/tmp/report.txt' }
14
+ * task:OSK-42 → { kind: 'task', id: 'OSK-42' }
15
+ */
16
+ export declare function parseReference(raw: string, flag: string): TaskReference;
17
+ /** {@link parseReference} for every value of a repeatable flag; an absent flag is `[]`. */
18
+ export declare function parseReferences(raws: readonly string[] | undefined, flag: string): TaskReference[];
19
+ /**
20
+ * The entries of an `evidenceRefs` array written by hand in JSON, with each STRING entry turned
21
+ * into the object the server takes: a URL, or `<kind>:<id-or-uri>`. Anything that is not a string
22
+ * passes through untouched, because the server is the validator of the object form.
23
+ *
24
+ * A string that is neither is refused here, naming its index, so the first attempt does not
25
+ * travel to the server to learn the shape (`data.evidenceRefs.0: expected object, received
26
+ * string`).
27
+ */
28
+ export declare function liftReferenceEntries(entries: readonly unknown[], field: string): unknown[];