@skrr-ai/cli 0.1.163 → 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 (102) hide show
  1. package/README.md +13 -0
  2. package/dist/base-command.d.ts +14 -1
  3. package/dist/base-command.js +190 -58
  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/show.js +7 -1
  8. package/dist/commands/agents/mini-computer/tasks-view.js +1 -1
  9. package/dist/commands/agents/supervision.d.ts +25 -0
  10. package/dist/commands/agents/supervision.js +129 -0
  11. package/dist/commands/apps/check.js +3 -8
  12. package/dist/commands/apps/data/batch.d.ts +1 -0
  13. package/dist/commands/apps/data/batch.js +19 -2
  14. package/dist/commands/apps/data/delete.d.ts +1 -0
  15. package/dist/commands/apps/data/delete.js +14 -2
  16. package/dist/commands/apps/data/patch.d.ts +1 -0
  17. package/dist/commands/apps/data/patch.js +11 -2
  18. package/dist/commands/apps/data/put.d.ts +1 -0
  19. package/dist/commands/apps/data/put.js +17 -3
  20. package/dist/commands/apps/install.js +7 -2
  21. package/dist/commands/apps/installations/compatibility.d.ts +13 -0
  22. package/dist/commands/apps/installations/compatibility.js +60 -0
  23. package/dist/commands/apps/installations/show.js +9 -3
  24. package/dist/commands/apps/installations/snapshot.js +5 -2
  25. package/dist/commands/apps/operations/check.d.ts +16 -0
  26. package/dist/commands/apps/operations/check.js +127 -0
  27. package/dist/commands/apps/publish/propose.js +33 -4
  28. package/dist/commands/apps/reconsent.js +7 -1
  29. package/dist/commands/apps/reference.d.ts +4 -2
  30. package/dist/commands/apps/reference.js +7 -4
  31. package/dist/commands/apps/rollback.d.ts +9 -0
  32. package/dist/commands/apps/rollback.js +81 -2
  33. package/dist/commands/apps/upgrade.d.ts +8 -0
  34. package/dist/commands/apps/upgrade.js +67 -2
  35. package/dist/commands/apps/version/cat.d.ts +22 -0
  36. package/dist/commands/apps/version/cat.js +220 -0
  37. package/dist/commands/apps/version/show.js +3 -1
  38. package/dist/commands/commerce/incidents/release.d.ts +24 -0
  39. package/dist/commands/commerce/incidents/release.js +46 -0
  40. package/dist/commands/duties/action-proposal.js +19 -11
  41. package/dist/commands/duties/cadence-decisions.js +7 -0
  42. package/dist/commands/duties/cases.js +12 -1
  43. package/dist/commands/duties/hypotheses.js +10 -3
  44. package/dist/commands/duties/observations.d.ts +4 -0
  45. package/dist/commands/duties/observations.js +14 -3
  46. package/dist/commands/duties/trigger-status.js +2 -2
  47. package/dist/commands/duties/wake-capabilities.js +12 -6
  48. package/dist/commands/outbox/list.d.ts +11 -4
  49. package/dist/commands/outbox/list.js +56 -9
  50. package/dist/commands/outbox/retry.d.ts +8 -2
  51. package/dist/commands/outbox/retry.js +76 -16
  52. package/dist/commands/outbox/show.d.ts +20 -0
  53. package/dist/commands/outbox/show.js +83 -0
  54. package/dist/commands/proposals/list.js +13 -9
  55. package/dist/commands/requests/show.d.ts +12 -0
  56. package/dist/commands/requests/show.js +42 -23
  57. package/dist/commands/spaces/deletion/cancel.d.ts +21 -0
  58. package/dist/commands/spaces/deletion/cancel.js +70 -0
  59. package/dist/commands/spaces/workflows/run.js +12 -0
  60. package/dist/commands/widgets/check.d.ts +9 -0
  61. package/dist/commands/widgets/check.js +16 -3
  62. package/dist/generated/agent-guides.json +17 -17
  63. package/dist/lib/api-fetch.d.ts +5 -0
  64. package/dist/lib/api-fetch.js +53 -21
  65. package/dist/lib/appCompatibility.d.ts +31 -0
  66. package/dist/lib/appCompatibility.js +66 -0
  67. package/dist/lib/appData.d.ts +46 -4
  68. package/dist/lib/appData.js +156 -31
  69. package/dist/lib/appInstallations.d.ts +32 -5
  70. package/dist/lib/appInstallations.js +218 -34
  71. package/dist/lib/appVersionFile.d.ts +82 -0
  72. package/dist/lib/appVersionFile.js +195 -0
  73. package/dist/lib/apps-command.d.ts +14 -3
  74. package/dist/lib/apps-command.js +68 -60
  75. package/dist/lib/appsCheck.js +31 -6
  76. package/dist/lib/chat-supervision.d.ts +21 -0
  77. package/dist/lib/chat-supervision.js +37 -0
  78. package/dist/lib/commerce.d.ts +6 -0
  79. package/dist/lib/commerce.js +9 -0
  80. package/dist/lib/duties.d.ts +19 -1
  81. package/dist/lib/duties.js +21 -3
  82. package/dist/lib/json-output.d.ts +2 -0
  83. package/dist/lib/json-output.js +8 -4
  84. package/dist/lib/miniComputer.d.ts +1 -0
  85. package/dist/lib/miniComputer.js +7 -2
  86. package/dist/lib/miniComputerCommand.js +4 -1
  87. package/dist/lib/node-adapter.d.ts +2 -0
  88. package/dist/lib/node-adapter.js +35 -8
  89. package/dist/lib/outbox.d.ts +110 -1
  90. package/dist/lib/outbox.js +261 -35
  91. package/dist/lib/roles.d.ts +1 -1
  92. package/dist/lib/space-deletion-cancel.d.ts +47 -0
  93. package/dist/lib/space-deletion-cancel.js +141 -0
  94. package/dist/lib/widgetCheck.js +30 -4
  95. package/dist/lib/widgetStaticScan.d.ts +24 -9
  96. package/dist/lib/widgetStaticScan.js +207 -192
  97. package/dist/lib/write-outcome.d.ts +74 -0
  98. package/dist/lib/write-outcome.js +176 -0
  99. package/dist/node_modules/@skrr-ai/data-provider/APP_HTML_PARSER_LICENSES.txt +36 -0
  100. package/dist/node_modules/@skrr-ai/data-provider/index.js +20204 -15169
  101. package/oclif.manifest.json +2143 -25
  102. package/package.json +10 -3
@@ -39,6 +39,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.OutboxFullError = exports.MAX_REPLAY_ATTEMPTS = void 0;
40
40
  exports.isOutageFailure = isOutageFailure;
41
41
  exports.isRetryableWrite = isRetryableWrite;
42
+ exports.normalizeOutboxOrigin = normalizeOutboxOrigin;
43
+ exports.outboxAccountFor = outboxAccountFor;
44
+ exports.outboxBindingFor = outboxBindingFor;
45
+ exports.isOutboxBound = isOutboxBound;
46
+ exports.currentReplayContext = currentReplayContext;
47
+ exports.assessReplayContext = assessReplayContext;
48
+ exports.printableOutboxField = printableOutboxField;
49
+ exports.describeReplayFindings = describeReplayFindings;
42
50
  exports.lockOutboxReplay = lockOutboxReplay;
43
51
  exports.enqueueWrite = enqueueWrite;
44
52
  exports.listWrites = listWrites;
@@ -91,6 +99,9 @@ const os = __importStar(require("node:os"));
91
99
  const path = __importStar(require("node:path"));
92
100
  const crypto = __importStar(require("node:crypto"));
93
101
  const proper_lockfile_1 = __importDefault(require("proper-lockfile"));
102
+ const auth_core_1 = require("@skrr-ai/auth-core");
103
+ const workspace_header_1 = require("./workspace-header");
104
+ const write_outcome_1 = require("./write-outcome");
94
105
  const IS_OUTAGE_FAILURE_RE = /fetch failed|ECONNREFUSED|ENOTFOUND|ETIMEDOUT|ECONNRESET|socket hang up|network/i;
95
106
  /**
96
107
  * A replay that keeps failing is either a permanent server-side refusal or a
@@ -202,7 +213,10 @@ function isOutageFailure(err) {
202
213
  * 408 the server timed out reading the request.
203
214
  * 425 too early — explicitly "try again".
204
215
  * 429 throttled. The one 4xx everybody agrees is temporary.
205
- * 5xx + dead transport: unchanged, the original rule.
216
+ * 5xx + dead transport: the original rule, and now 408 and 425 with them, for
217
+ * a route that keeps a server receipt only (see below): a write that may
218
+ * have been applied is not queued to be applied again unless the server
219
+ * will recognise it.
206
220
  *
207
221
  * Do NOT queue when the server knows who we are and the answer is no:
208
222
  *
@@ -214,21 +228,167 @@ function isOutageFailure(err) {
214
228
  * worse than one that fails visibly, because nobody looks at a queue that
215
229
  * never drains.
216
230
  */
217
- const RETRYABLE_STATUSES = new Set([401, 408, 425, 429]);
218
- function isRetryableWrite(err) {
231
+ const RETRYABLE_STATUSES = new Set([401, 429]);
232
+ /**
233
+ * ── What may be queued without knowing it did not happen (OSK-24076) ────────
234
+ *
235
+ * A write is queued to be sent again, and sending it again is only safe when the
236
+ * first attempt either did not happen or will be recognised. A 408, a 425, a 5xx
237
+ * and a dead connection prove neither: the server may have applied the write
238
+ * before it failed. Those are queued ONLY for a route the server keeps a replay
239
+ * receipt for (`request`, checked against the registry of routes that mount
240
+ * `requestIdempotency`); on any other route the outcome is unknown, and a repeat
241
+ * could apply it twice, so the write is not queued and the failure is reported.
242
+ *
243
+ * Three kinds of failure do not depend on the route and keep their answer:
244
+ * 401 and 429 as before: could not authenticate right now, throttled.
245
+ * a refused connection or a failed name lookup the request never left, so
246
+ * nothing happened and queueing it is safe.
247
+ *
248
+ * `request` is the write that failed. Left out, the route is unknown and so has
249
+ * no receipt: the default for a write is that nothing will recognise a repeat.
250
+ */
251
+ function isRetryableWrite(err, request) {
219
252
  const e = err;
220
253
  if (e && typeof e.status === 'number' && e.status > 0) {
221
254
  if (RETRYABLE_STATUSES.has(e.status))
222
255
  return true;
223
- if (e.status >= 500)
224
- return true;
256
+ if ((0, write_outcome_1.isAmbiguousStatus)(e.status)) {
257
+ return (0, write_outcome_1.classifyRequestOutcome)({ request: request ?? {}, status: e.status }).retryable;
258
+ }
225
259
  return false;
226
260
  }
227
261
  // No HTTP status means no response came back. `status: 0` is how some clients
228
262
  // spell that, which is why it falls through here rather than being read as a
229
263
  // sub-500 refusal — `isOutageFailure`'s own status check is narrower and is
230
264
  // left alone precisely because it feeds the incident prose.
231
- return isOutageFailure(err);
265
+ if (!isOutageFailure(err))
266
+ return false;
267
+ return ((0, write_outcome_1.requestNeverSent)(err) ||
268
+ (0, write_outcome_1.classifyRequestOutcome)({ request: request ?? {}, transportError: true }).retryable);
269
+ }
270
+ // ---------------------------------------------------------------------------
271
+ // Origin and account binding (OSK-23807)
272
+ // ---------------------------------------------------------------------------
273
+ //
274
+ // A queued write is a promise to do ONE thing to ONE deployment as ONE account.
275
+ // Replaying it against another server, or after signing in as someone else, is a
276
+ // different action that happens to carry the same payload. So the queue records
277
+ // where and as whom a write was authored, shows it, and refuses to replay it
278
+ // anywhere else.
279
+ //
280
+ // Nothing here is an authorisation control. The account label is read from a
281
+ // token claim nobody verified, so it guards against an honest mistake (the wrong
282
+ // profile, the wrong server, a different login) and not against someone who can
283
+ // already write this file. The server still authenticates and authorises every
284
+ // replay. Nothing recorded is a secret: no token, no refresh token, no email.
285
+ /**
286
+ * `scheme://host[:port]` of an API base URL, or null when it names no HTTP(S)
287
+ * server. Case, default ports, credentials, path, query and fragment are
288
+ * dropped, so `HTTPS://Skrr.AI:443/api/` and `https://skrr.ai` are one origin.
289
+ */
290
+ function normalizeOutboxOrigin(baseURL) {
291
+ if (typeof baseURL !== 'string' || !baseURL.trim())
292
+ return null;
293
+ let url;
294
+ try {
295
+ url = new URL(baseURL.trim());
296
+ }
297
+ catch {
298
+ return null;
299
+ }
300
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
301
+ return null;
302
+ return url.origin;
303
+ }
304
+ /** What a user id looks like. A claim outside this shape is not shown or stored. */
305
+ const ACCOUNT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
306
+ /**
307
+ * The account label for a credential: `user:<id>` from the access token's `id`
308
+ * claim, else `profile:<name>`, which is all an opaque credential (a personal
309
+ * access token, a CI token) lets the CLI know without asking the server.
310
+ */
311
+ function outboxAccountFor(token, profile) {
312
+ const payload = token ? (0, auth_core_1.decodeJwtPayload)(token) : null;
313
+ const id = payload && typeof payload === 'object' && !Array.isArray(payload)
314
+ ? payload.id
315
+ : undefined;
316
+ if (typeof id === 'string' && ACCOUNT_ID_RE.test(id))
317
+ return `user:${id}`;
318
+ return `profile:${profile || 'default'}`;
319
+ }
320
+ /**
321
+ * What to record on an entry being queued now, or null when the configured
322
+ * server is not an HTTP(S) origin. A null binding still queues the write so the
323
+ * content survives; it just stays paused as unverified, like an older entry.
324
+ */
325
+ function outboxBindingFor(input) {
326
+ const origin = normalizeOutboxOrigin(input.baseURL);
327
+ if (!origin)
328
+ return null;
329
+ return { origin, account: outboxAccountFor(input.token, input.profile) };
330
+ }
331
+ /** Does this entry record both where and as whom it was queued? */
332
+ function isOutboxBound(entry) {
333
+ return typeof entry.origin === 'string' && typeof entry.account === 'string';
334
+ }
335
+ const NOT_SIGNED_IN = 'not signed in';
336
+ function currentReplayContext(input) {
337
+ return {
338
+ origin: normalizeOutboxOrigin(input.baseURL),
339
+ // With no credential nothing can be replayed, and a `profile:` label would
340
+ // pass for an account the person is not signed in as.
341
+ account: input.token ? outboxAccountFor(input.token, input.profile) : NOT_SIGNED_IN,
342
+ };
343
+ }
344
+ /**
345
+ * May this entry be replayed from `current`?
346
+ *
347
+ * The workspace is not read from `current`: it is whatever `apiFetch` would put
348
+ * on the request, which is the entry's own header when it recorded one and the
349
+ * ambient workspace otherwise (an Agent session replaces even the recorded one).
350
+ * An entry queued with no workspace that is replayed while one is selected would
351
+ * land somewhere it was never authored for.
352
+ */
353
+ function assessReplayContext(entry, current, env = process.env) {
354
+ if (!isOutboxBound(entry))
355
+ return { state: 'unverified' };
356
+ const findings = [];
357
+ if (current.origin !== entry.origin) {
358
+ findings.push({
359
+ field: 'server',
360
+ recorded: entry.origin,
361
+ current: current.origin ?? 'unknown',
362
+ });
363
+ }
364
+ if (current.account !== entry.account) {
365
+ findings.push({ field: 'account', recorded: entry.account, current: current.account });
366
+ }
367
+ const recordedWorkspace = entry.workspaceId ?? null;
368
+ const effectiveWorkspace = (0, workspace_header_1.withWorkspaceHeader)(recordedWorkspace ? { 'X-Workspace-Id': recordedWorkspace } : {}, env)['X-Workspace-Id'] ?? null;
369
+ if (effectiveWorkspace !== recordedWorkspace) {
370
+ findings.push({
371
+ field: 'workspace',
372
+ recorded: recordedWorkspace ?? 'none',
373
+ current: effectiveWorkspace ?? 'none',
374
+ });
375
+ }
376
+ return findings.length > 0 ? { state: 'mismatch', findings } : { state: 'match' };
377
+ }
378
+ const OUTBOX_UNPRINTABLE_RE = /[\p{Cc}\p{Cf}\u2028\u2029]/gu;
379
+ /**
380
+ * A recorded value, safe to print. The file is the user's and can be edited or
381
+ * damaged, so a control or format character is shown as a visible `\uXXXX`
382
+ * rather than drawn.
383
+ */
384
+ function printableOutboxField(value) {
385
+ return value.replace(OUTBOX_UNPRINTABLE_RE, (c) => `\\u${(c.codePointAt(0) ?? 0).toString(16).padStart(4, '0')}`);
386
+ }
387
+ /** "recorded server https://a, current server https://b; recorded account ..." */
388
+ function describeReplayFindings(findings) {
389
+ return findings
390
+ .map((f) => `recorded ${f.field} ${printableOutboxField(f.recorded)}, current ${f.field} ${printableOutboxField(f.current)}`)
391
+ .join('; ');
232
392
  }
233
393
  function ensureDir(profile) {
234
394
  const dir = outboxDir(profile);
@@ -244,7 +404,11 @@ function withQueueLock(profile, work) {
244
404
  const until = Date.now() + 2_000;
245
405
  while (!release) {
246
406
  try {
247
- release = proper_lockfile_1.default.lockSync(lockKey, { lockfilePath: lockPath, realpath: false, stale: 120_000 });
407
+ release = proper_lockfile_1.default.lockSync(lockKey, {
408
+ lockfilePath: lockPath,
409
+ realpath: false,
410
+ stale: 120_000,
411
+ });
248
412
  }
249
413
  catch (error) {
250
414
  if (error.code !== 'ELOCKED' || Date.now() >= until)
@@ -263,13 +427,18 @@ function withQueueLock(profile, work) {
263
427
  async function lockOutboxReplay(profile) {
264
428
  const dir = ensureDir(profile);
265
429
  try {
266
- return await proper_lockfile_1.default.lock(path.join(dir, '.replay'), { lockfilePath: path.join(dir, '.replay.lock'), realpath: false, stale: 120_000 });
430
+ return await proper_lockfile_1.default.lock(path.join(dir, '.replay'), {
431
+ lockfilePath: path.join(dir, '.replay.lock'),
432
+ realpath: false,
433
+ stale: 120_000,
434
+ });
267
435
  }
268
436
  catch (error) {
269
437
  if (error.code !== 'ELOCKED')
270
438
  throw error;
271
439
  throw Object.assign(new Error('Another outbox retry or drop is in progress. Wait for it to finish, then inspect the queue and reconcile any uncertain result before deciding whether to retry.'), {
272
- code: 'OUTBOX_BUSY', retryable: false,
440
+ code: 'OUTBOX_BUSY',
441
+ retryable: false,
273
442
  });
274
443
  }
275
444
  }
@@ -293,7 +462,10 @@ function readWritesStrict(profile) {
293
462
  throw error;
294
463
  }
295
464
  const seen = new Set();
296
- return raw.split('\n').filter((line) => line.trim()).map((line) => {
465
+ return raw
466
+ .split('\n')
467
+ .filter((line) => line.trim())
468
+ .map((line) => {
297
469
  let value;
298
470
  try {
299
471
  value = JSON.parse(line);
@@ -302,20 +474,39 @@ function readWritesStrict(profile) {
302
474
  throw new OutboxCorruptError();
303
475
  }
304
476
  const entry = value;
305
- if (!entry || typeof entry !== 'object' || typeof entry.id !== 'string' || !entry.id ||
306
- seen.has(entry.id) || typeof entry.idempotencyKey !== 'string' || !entry.idempotencyKey ||
307
- typeof entry.command !== 'string' || typeof entry.summary !== 'string' ||
477
+ if (!entry ||
478
+ typeof entry !== 'object' ||
479
+ typeof entry.id !== 'string' ||
480
+ !entry.id ||
481
+ seen.has(entry.id) ||
482
+ typeof entry.idempotencyKey !== 'string' ||
483
+ !entry.idempotencyKey ||
484
+ typeof entry.command !== 'string' ||
485
+ typeof entry.summary !== 'string' ||
308
486
  !['post', 'put', 'patch', 'delete'].includes(entry.method) ||
309
487
  (entry.method !== 'delete' && !Object.prototype.hasOwnProperty.call(entry, 'body')) ||
310
- typeof entry.url !== 'string' || !entry.url || typeof entry.queuedAt !== 'string' ||
311
- !entry.reason || typeof entry.reason !== 'object' || typeof entry.reason.message !== 'string' ||
312
- !Number.isInteger(entry.attempts) || entry.attempts < 0 ||
313
- (entry.replay !== undefined && (!entry.replay || typeof entry.replay !== 'object' ||
314
- !['sending', 'result_recorded'].includes(entry.replay.state) ||
315
- typeof entry.replay.attemptId !== 'string' || !entry.replay.attemptId ||
316
- typeof entry.replay.startedAt !== 'string' || !entry.replay.startedAt ||
317
- typeof entry.replay.fingerprint !== 'string' || !/^[0-9a-f]{64}$/.test(entry.replay.fingerprint) ||
318
- (entry.replay.state === 'result_recorded' && (typeof entry.replay.resultId !== 'string' || !entry.replay.resultId))))) {
488
+ typeof entry.url !== 'string' ||
489
+ !entry.url ||
490
+ typeof entry.queuedAt !== 'string' ||
491
+ !entry.reason ||
492
+ typeof entry.reason !== 'object' ||
493
+ typeof entry.reason.message !== 'string' ||
494
+ !Number.isInteger(entry.attempts) ||
495
+ entry.attempts < 0 ||
496
+ (entry.origin !== undefined && (typeof entry.origin !== 'string' || !entry.origin)) ||
497
+ (entry.account !== undefined && (typeof entry.account !== 'string' || !entry.account)) ||
498
+ (entry.replay !== undefined &&
499
+ (!entry.replay ||
500
+ typeof entry.replay !== 'object' ||
501
+ !['sending', 'result_recorded'].includes(entry.replay.state) ||
502
+ typeof entry.replay.attemptId !== 'string' ||
503
+ !entry.replay.attemptId ||
504
+ typeof entry.replay.startedAt !== 'string' ||
505
+ !entry.replay.startedAt ||
506
+ typeof entry.replay.fingerprint !== 'string' ||
507
+ !/^[0-9a-f]{64}$/.test(entry.replay.fingerprint) ||
508
+ (entry.replay.state === 'result_recorded' &&
509
+ (typeof entry.replay.resultId !== 'string' || !entry.replay.resultId))))) {
319
510
  throw new OutboxCorruptError();
320
511
  }
321
512
  seen.add(entry.id);
@@ -323,10 +514,23 @@ function readWritesStrict(profile) {
323
514
  });
324
515
  }
325
516
  function replayFingerprint(entry) {
326
- return crypto.createHash('sha256').update(JSON.stringify({
327
- id: entry.id, key: entry.idempotencyKey, command: entry.command, method: entry.method,
328
- url: entry.url, body: entry.body, workspaceId: entry.workspaceId ?? null,
329
- })).digest('hex');
517
+ return crypto
518
+ .createHash('sha256')
519
+ .update(JSON.stringify({
520
+ id: entry.id,
521
+ key: entry.idempotencyKey,
522
+ command: entry.command,
523
+ method: entry.method,
524
+ url: entry.url,
525
+ body: entry.body,
526
+ workspaceId: entry.workspaceId ?? null,
527
+ // Only when recorded: an entry queued before origin binding must keep the
528
+ // fingerprint a replay claim stored for it, or that claim could not be
529
+ // acknowledged after an upgrade.
530
+ ...(entry.origin !== undefined ? { origin: entry.origin } : {}),
531
+ ...(entry.account !== undefined ? { account: entry.account } : {}),
532
+ }))
533
+ .digest('hex');
330
534
  }
331
535
  /**
332
536
  * Append one entry, fsynced before returning.
@@ -367,8 +571,16 @@ function enqueueWrite(input, profile) {
367
571
  // Matching on `idempotencyKey` is what makes this safe: it is caller-minted
368
572
  // and stable for the logical write (see `idempotencyKeyFor`), so two entries
369
573
  // sharing one are the same intent by construction, not by coincidence.
574
+ //
575
+ // The same key queued against another deployment, or as another account, is a
576
+ // different promise (OSK-23807): collapsing it would tell the caller their
577
+ // write is safe while the entry that exists can only ever be replayed
578
+ // somewhere else. Entries with no recorded binding compare equal to each
579
+ // other, so callers that record none behave exactly as before.
370
580
  if (input.idempotencyKey) {
371
- const existing = current.find((e) => e.idempotencyKey === input.idempotencyKey);
581
+ const existing = current.find((e) => e.idempotencyKey === input.idempotencyKey &&
582
+ e.origin === input.origin &&
583
+ e.account === input.account);
372
584
  if (existing)
373
585
  return existing;
374
586
  }
@@ -444,7 +656,8 @@ function durableReplayReplace(entries, profile) {
444
656
  }
445
657
  catch {
446
658
  throw Object.assign(new Error('The outbox could not confirm durable replay state. No further requests were sent; inspect the queue and reconcile any uncertain result.'), {
447
- code: 'OUTBOX_DURABILITY_UNAVAILABLE', retryable: false,
659
+ code: 'OUTBOX_DURABILITY_UNAVAILABLE',
660
+ retryable: false,
448
661
  });
449
662
  }
450
663
  finally {
@@ -461,8 +674,15 @@ function claimOutboxReplay(id, profile) {
461
674
  return null;
462
675
  const now = new Date().toISOString();
463
676
  const claimed = {
464
- ...entries[index], attempts: entries[index].attempts + 1, lastAttemptAt: now,
465
- replay: { state: 'sending', attemptId: crypto.randomUUID(), startedAt: now, fingerprint: replayFingerprint(entries[index]) },
677
+ ...entries[index],
678
+ attempts: entries[index].attempts + 1,
679
+ lastAttemptAt: now,
680
+ replay: {
681
+ state: 'sending',
682
+ attemptId: crypto.randomUUID(),
683
+ startedAt: now,
684
+ fingerprint: replayFingerprint(entries[index]),
685
+ },
466
686
  };
467
687
  entries[index] = claimed;
468
688
  durableReplayReplace(entries, profile);
@@ -474,15 +694,21 @@ function acknowledgeOutboxReplay(claim, resultId, profile) {
474
694
  withQueueLock(profile, () => {
475
695
  const entries = readWritesStrict(profile);
476
696
  const current = entries.find((entry) => entry.id === claim.id);
477
- if (!claim.replay || !current || current.replay?.attemptId !== claim.replay.attemptId ||
478
- current.replay.state !== 'sending' || current.replay.fingerprint !== replayFingerprint(current) ||
479
- current.replay.fingerprint !== claim.replay.fingerprint || !resultId) {
697
+ if (!claim.replay ||
698
+ !current ||
699
+ current.replay?.attemptId !== claim.replay.attemptId ||
700
+ current.replay.state !== 'sending' ||
701
+ current.replay.fingerprint !== replayFingerprint(current) ||
702
+ current.replay.fingerprint !== claim.replay.fingerprint ||
703
+ !resultId) {
480
704
  throw Object.assign(new Error('The outbox entry changed during replay; inspect and reconcile it before trying again.'), {
481
- code: 'OUTBOX_REPLAY_CHANGED', retryable: false,
705
+ code: 'OUTBOX_REPLAY_CHANGED',
706
+ retryable: false,
482
707
  });
483
708
  }
484
709
  const updated = entries.map((entry) => entry.id === claim.id
485
- ? { ...entry, replay: { ...claim.replay, state: 'result_recorded', resultId } } : entry);
710
+ ? { ...entry, replay: { ...claim.replay, state: 'result_recorded', resultId } }
711
+ : entry);
486
712
  durableReplayReplace(updated, profile);
487
713
  });
488
714
  }
@@ -53,7 +53,7 @@ export declare const roleApi: {
53
53
  config?: Record<string, unknown> | undefined;
54
54
  }[];
55
55
  sources: {
56
- source: "space" | "docs" | "tasks" | "memory" | "daemon" | "email" | "goal" | "files" | "local" | "browser" | "metrics" | "monitor" | "github" | "conversations" | "agent_initiatives" | "messages" | "documents" | "slack" | "calendar" | "product_metrics" | "business_metrics" | "state_monitor" | "agent_run";
56
+ source: "space" | "docs" | "tasks" | "memory" | "daemon" | "email" | "goal" | "files" | "local" | "browser" | "metrics" | "monitor" | "github" | "conversations" | "agent_initiatives" | "messages" | "documents" | "slack" | "calendar" | "product_metrics" | "business_metrics" | "state_monitor" | "agent_run" | "chat_execution";
57
57
  enabled: boolean;
58
58
  config?: Record<string, unknown> | undefined;
59
59
  }[];
@@ -0,0 +1,47 @@
1
+ /** The 503 code of a deployment that does not take deletion reservations. */
2
+ export declare const SPACE_DELETION_CANCELLATION_UNAVAILABLE = "SPACE_DELETION_CANCELLATION_UNAVAILABLE";
3
+ /** The server's reason a reservation can no longer be cancelled: memory clearing has begun. */
4
+ export declare const SPACE_MEMORY_DELETION_PENDING = "SPACE_MEMORY_DELETION_PENDING";
5
+ /** The server's reason a reservation cannot be cancelled yet: released loops are still being torn down. */
6
+ export declare const SPACE_LOOP_TEARDOWN_PENDING = "SPACE_LOOP_TEARDOWN_PENDING";
7
+ /** The code a not-for-PAT route answers a personal access token with. */
8
+ export declare const PAT_ROUTE_NOT_ALLOWED = "PAT_ROUTE_NOT_ALLOWED";
9
+ export type DeletionCancelOutcome = 'cancelled' | 'nothing_pending';
10
+ export interface DeletionCancelAnswer {
11
+ outcome: DeletionCancelOutcome;
12
+ cancelled: boolean;
13
+ /** Loops released by the deletion stay stopped either way: cancelling never recreates them. */
14
+ releasedLoopsRemainStopped: boolean;
15
+ }
16
+ /**
17
+ * Read the route's 200 body, or `null` when it is not the shape the route sends.
18
+ *
19
+ * `null` is deliberate and the caller must fail on it: a body that does not say
20
+ * `cancelled` either way cannot be read as "cancelled" or as "nothing pending",
21
+ * and guessing either would tell a person their Space is safe (or not) on no
22
+ * evidence.
23
+ */
24
+ export declare function readDeletionCancelAnswer(answer: unknown): DeletionCancelAnswer | null;
25
+ /** The lines printed for a 200, so the human output and the tests share one set of words. */
26
+ export declare function deletionCancelLines(answer: DeletionCancelAnswer, spaceRef: string, bin: string): string[];
27
+ export interface DeletionCancelRefusal {
28
+ message: string;
29
+ code: string;
30
+ exit: number;
31
+ retryable: boolean;
32
+ status?: number;
33
+ }
34
+ /**
35
+ * The refusal to print for a failed cancel, or `null` when the standard API error handler already
36
+ * says it well (404, 401, a plain permission 403, a real outage).
37
+ *
38
+ * The server's own 403 for a personal access token is accurate but stops at "Sign in to do this",
39
+ * and for a token held in `SKRR_TOKEN` that is not enough: the environment outranks the stored
40
+ * sign-in, so `skrr login` alone changes nothing until the variable is gone. The token is
41
+ * recognised by the server's `PAT_*` code, never by guessing from the credential: a PAT is judged
42
+ * by the route policy before anything else, so every 403 it meets here carries one.
43
+ */
44
+ export declare function describeDeletionCancelRefusal(err: unknown, context: {
45
+ spaceRef: string;
46
+ bin: string;
47
+ }): DeletionCancelRefusal | null;
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PAT_ROUTE_NOT_ALLOWED = exports.SPACE_LOOP_TEARDOWN_PENDING = exports.SPACE_MEMORY_DELETION_PENDING = exports.SPACE_DELETION_CANCELLATION_UNAVAILABLE = void 0;
4
+ exports.readDeletionCancelAnswer = readDeletionCancelAnswer;
5
+ exports.deletionCancelLines = deletionCancelLines;
6
+ exports.describeDeletionCancelRefusal = describeDeletionCancelRefusal;
7
+ /**
8
+ * `skrr spaces deletion cancel` (OSK-24060): the words for each answer of
9
+ * `POST /api/spaces/:spaceId/deletion-reservation/cancel`.
10
+ *
11
+ * The route is the Web's "stop deleting this Space" for a deletion that took a
12
+ * reservation. It is for a SIGNED-IN PERSON and nobody else: it is classified
13
+ * not-for-PAT in `personalAccessTokenRoutes.json`, so an automation token cannot
14
+ * undo a deletion a person ordered. The CLI's own credential after `skrr login`
15
+ * is a `scope: 'cli'` session JWT, which the route's `requireJwtAuth` accepts and
16
+ * `canAccessSpaceResource` then judges by the Space's DELETE permission.
17
+ *
18
+ * What the route answers, and what this module says for it:
19
+ *
20
+ * 200 { cancelled: true } the reservation was removed; the Space lives on
21
+ * 200 { cancelled: false } nothing was reserved; idempotent, NOT an error
22
+ * 403 PAT_* a personal access token was presented
23
+ * 403 no DELETE permission on the Space (relayed as is)
24
+ * 409 SPACE_MEMORY_DELETION_PENDING too late: memory clearing has begun
25
+ * 409 SPACE_LOOP_TEARDOWN_PENDING loop cleanup still running; retry
26
+ * 503 SPACE_DELETION_CANCELLATION_UNAVAILABLE the deployment has no reservations
27
+ *
28
+ * Kept out of the command so it can be tested without the command base class,
29
+ * and so the one wording for "nothing was pending" lives in one place.
30
+ */
31
+ const http_error_1 = require("./http-error");
32
+ /** The 503 code of a deployment that does not take deletion reservations. */
33
+ exports.SPACE_DELETION_CANCELLATION_UNAVAILABLE = 'SPACE_DELETION_CANCELLATION_UNAVAILABLE';
34
+ /** The server's reason a reservation can no longer be cancelled: memory clearing has begun. */
35
+ exports.SPACE_MEMORY_DELETION_PENDING = 'SPACE_MEMORY_DELETION_PENDING';
36
+ /** The server's reason a reservation cannot be cancelled yet: released loops are still being torn down. */
37
+ exports.SPACE_LOOP_TEARDOWN_PENDING = 'SPACE_LOOP_TEARDOWN_PENDING';
38
+ /** The code a not-for-PAT route answers a personal access token with. */
39
+ exports.PAT_ROUTE_NOT_ALLOWED = 'PAT_ROUTE_NOT_ALLOWED';
40
+ /**
41
+ * Read the route's 200 body, or `null` when it is not the shape the route sends.
42
+ *
43
+ * `null` is deliberate and the caller must fail on it: a body that does not say
44
+ * `cancelled` either way cannot be read as "cancelled" or as "nothing pending",
45
+ * and guessing either would tell a person their Space is safe (or not) on no
46
+ * evidence.
47
+ */
48
+ function readDeletionCancelAnswer(answer) {
49
+ if (!answer || typeof answer !== 'object')
50
+ return null;
51
+ const { cancelled, releasedLoopsRemainStopped } = answer;
52
+ if (typeof cancelled !== 'boolean')
53
+ return null;
54
+ return {
55
+ outcome: cancelled ? 'cancelled' : 'nothing_pending',
56
+ cancelled,
57
+ // The route always sends `true`. Absent is read as the route's own contract, not as "unknown":
58
+ // a released loop is never recreated by this call, so there is no state in which it is false.
59
+ releasedLoopsRemainStopped: releasedLoopsRemainStopped !== false,
60
+ };
61
+ }
62
+ /** The lines printed for a 200, so the human output and the tests share one set of words. */
63
+ function deletionCancelLines(answer, spaceRef, bin) {
64
+ if (!answer.cancelled) {
65
+ return [`No deletion is pending for space ${spaceRef}. Nothing was changed.`];
66
+ }
67
+ return [
68
+ `Cancelled the pending deletion of space ${spaceRef}. The space was not deleted.`,
69
+ 'Loops the deletion had already released stay stopped. Cancelling does not restart them; ' +
70
+ `resume each one you want running with \`${bin} duties resume <duty-id>\`.`,
71
+ ];
72
+ }
73
+ /** The code an error body carries, in either spelling the routes use (`code`, or upper-case `error`). */
74
+ function refusalCode(body) {
75
+ for (const key of ['code', 'error']) {
76
+ const value = body?.[key];
77
+ if (typeof value === 'string' && /^[A-Z][A-Z0-9_]+$/.test(value))
78
+ return value;
79
+ }
80
+ return undefined;
81
+ }
82
+ /**
83
+ * The refusal to print for a failed cancel, or `null` when the standard API error handler already
84
+ * says it well (404, 401, a plain permission 403, a real outage).
85
+ *
86
+ * The server's own 403 for a personal access token is accurate but stops at "Sign in to do this",
87
+ * and for a token held in `SKRR_TOKEN` that is not enough: the environment outranks the stored
88
+ * sign-in, so `skrr login` alone changes nothing until the variable is gone. The token is
89
+ * recognised by the server's `PAT_*` code, never by guessing from the credential: a PAT is judged
90
+ * by the route policy before anything else, so every 403 it meets here carries one.
91
+ */
92
+ function describeDeletionCancelRefusal(err, context) {
93
+ const status = (0, http_error_1.httpStatusOf)(err);
94
+ const code = refusalCode((0, http_error_1.httpBodyOf)(err));
95
+ const { spaceRef, bin } = context;
96
+ if (status === 503 && code === exports.SPACE_DELETION_CANCELLATION_UNAVAILABLE) {
97
+ return {
98
+ message: 'Cancelling a Space deletion is not enabled on this server, so there is no pending ' +
99
+ 'deletion to cancel and nothing was changed. This is a deployment setting rather than a ' +
100
+ 'fault, so retrying will not change it.',
101
+ code: exports.SPACE_DELETION_CANCELLATION_UNAVAILABLE,
102
+ status,
103
+ exit: 1,
104
+ retryable: false,
105
+ };
106
+ }
107
+ if (status === 403 && code?.startsWith('PAT_')) {
108
+ return {
109
+ message: 'An access token cannot cancel a Space deletion: only a signed-in person can undo a ' +
110
+ 'deletion. Nothing was changed.\n' +
111
+ `→ Unset SKRR_TOKEN and OVERSKY_TOKEN, then sign in with \`${bin} login\` and run this again.`,
112
+ code: code ?? exports.PAT_ROUTE_NOT_ALLOWED,
113
+ status,
114
+ exit: 3,
115
+ retryable: false,
116
+ };
117
+ }
118
+ if (status === 409 && code === exports.SPACE_MEMORY_DELETION_PENDING) {
119
+ return {
120
+ message: `Space ${spaceRef} can no longer be cancelled: its deletion has already started clearing ` +
121
+ 'the space’s memory. Nothing was changed.\n' +
122
+ `→ Finish the deletion with \`${bin} spaces delete ${spaceRef}\`.`,
123
+ code,
124
+ status,
125
+ exit: 1,
126
+ retryable: false,
127
+ };
128
+ }
129
+ if (status === 409 && code === exports.SPACE_LOOP_TEARDOWN_PENDING) {
130
+ return {
131
+ message: `Space ${spaceRef} cannot be cancelled yet: loops its deletion released are still being ` +
132
+ 'stopped. Nothing was changed.\n' +
133
+ `→ Run \`${bin} spaces deletion cancel ${spaceRef}\` again in a few minutes.`,
134
+ code,
135
+ status,
136
+ exit: 1,
137
+ retryable: true,
138
+ };
139
+ }
140
+ return null;
141
+ }
@@ -198,7 +198,7 @@ function errorMessage(err) {
198
198
  const message = err?.message;
199
199
  return typeof message === 'string' ? message : String(err);
200
200
  }
201
- function syntaxIssue(script, section, firstLine) {
201
+ function syntaxIssue(script, section, firstLine, sourceLines) {
202
202
  try {
203
203
  // Compile only. `vm.Script` parses and reports early errors; it never runs the code.
204
204
  new vm.Script(script, { filename: 'widget.js' });
@@ -215,7 +215,9 @@ function syntaxIssue(script, section, firstLine) {
215
215
  source: 'syntax',
216
216
  code: 'syntax/js',
217
217
  section,
218
- line: firstLine + (at ? Number(at[1]) - 1 : 0),
218
+ line: sourceLines === undefined
219
+ ? firstLine + (at ? Number(at[1]) - 1 : 0)
220
+ : sourceLines?.[(at ? Number(at[1]) : 1) - 1],
219
221
  message: `JavaScript syntax error: ${message}. The script would stop before running.`,
220
222
  ...(fix ? { fix } : {}),
221
223
  };
@@ -242,9 +244,33 @@ function contentIssues(parts) {
242
244
  issues.push(syntax);
243
245
  }
244
246
  }
245
- const scan = (0, widgetStaticScan_1.scanWidgetSource)(parts);
247
+ let scan;
248
+ try {
249
+ scan = (0, widgetStaticScan_1.scanWidgetSource)(parts);
250
+ }
251
+ catch {
252
+ issues.push({
253
+ severity: 'error',
254
+ source: 'static',
255
+ code: 'static/scanner-unavailable',
256
+ message: 'The static scan could not finish; static findings and inline script syntax checks may be incomplete.',
257
+ fix: 'Simplify the widget markup or try the check again.',
258
+ heuristic: true,
259
+ });
260
+ return issues;
261
+ }
262
+ if (scan.inlineCoverageComplete === false) {
263
+ issues.push({
264
+ severity: 'warn',
265
+ source: 'static',
266
+ code: 'static/template-script-unchecked',
267
+ section: 'html',
268
+ message: 'Scripts and event handlers in templates do not run at initial load; if widget code activates them later, their syntax and static findings have not been checked.',
269
+ heuristic: true,
270
+ });
271
+ }
246
272
  for (const script of scan.inlineScripts) {
247
- const syntax = syntaxIssue(script.content, 'html', script.line);
273
+ const syntax = syntaxIssue(script.content, 'html', script.line, script.sourceLines);
248
274
  if (syntax) {
249
275
  issues.push(syntax);
250
276
  }