@skrr-ai/cli 0.1.162 → 0.1.163

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 (82) hide show
  1. package/dist/base-command.d.ts +5 -2
  2. package/dist/base-command.js +96 -39
  3. package/dist/commands/activity/list.d.ts +7 -0
  4. package/dist/commands/activity/list.js +17 -0
  5. package/dist/commands/activity/scan-older.d.ts +2 -2
  6. package/dist/commands/activity/scan-older.js +6 -5
  7. package/dist/commands/activity/show.d.ts +0 -2
  8. package/dist/commands/activity/show.js +21 -42
  9. package/dist/commands/agents/always-on/release-run.d.ts +3 -3
  10. package/dist/commands/agents/always-on/release-run.js +5 -6
  11. package/dist/commands/agents/mini-computer/app/reset.d.ts +1 -0
  12. package/dist/commands/agents/mini-computer/app/reset.js +5 -2
  13. package/dist/commands/agents/mini-computer/app/set.js +1 -1
  14. package/dist/commands/agents/mini-computer/show.js +4 -2
  15. package/dist/commands/agents/mini-computer/tasks-view.js +2 -2
  16. package/dist/commands/agents/triggers/replay.js +1 -1
  17. package/dist/commands/agents/triggers/runs.d.ts +2 -3
  18. package/dist/commands/agents/triggers/runs.js +4 -5
  19. package/dist/commands/apps/auto-apply.js +31 -10
  20. package/dist/commands/apps/check.js +8 -0
  21. package/dist/commands/apps/data/batch.js +16 -5
  22. package/dist/commands/apps/data/collections.js +1 -1
  23. package/dist/commands/apps/data/delete.js +12 -4
  24. package/dist/commands/apps/data/patch.js +11 -4
  25. package/dist/commands/apps/data/put.js +13 -6
  26. package/dist/commands/apps/data/query.js +3 -3
  27. package/dist/commands/apps/install.js +24 -7
  28. package/dist/commands/apps/installations/events.d.ts +1 -0
  29. package/dist/commands/apps/installations/events.js +63 -10
  30. package/dist/commands/apps/installations/show.js +26 -5
  31. package/dist/commands/apps/installations/snapshot.js +1 -1
  32. package/dist/commands/apps/installations/versions.js +25 -9
  33. package/dist/commands/apps/logs.js +4 -1
  34. package/dist/commands/apps/push.js +10 -2
  35. package/dist/commands/apps/reconsent.js +7 -1
  36. package/dist/commands/apps/rollback.js +2 -2
  37. package/dist/commands/apps/settings/set.js +81 -4
  38. package/dist/commands/apps/settings/show.js +38 -7
  39. package/dist/commands/duties/status.js +20 -15
  40. package/dist/commands/outbox/drop.js +21 -15
  41. package/dist/commands/outbox/list.d.ts +2 -1
  42. package/dist/commands/outbox/list.js +20 -11
  43. package/dist/commands/outbox/retry.d.ts +8 -11
  44. package/dist/commands/outbox/retry.js +135 -92
  45. package/dist/commands/spaces/create.js +1 -1
  46. package/dist/commands/tasks/comments/add.js +1 -1
  47. package/dist/commands/triggers/audit.js +3 -5
  48. package/dist/commands/triggers/fire-detail.js +7 -1
  49. package/dist/commands/triggers/replay.js +1 -1
  50. package/dist/commands/triggers/runs.d.ts +2 -4
  51. package/dist/commands/triggers/runs.js +3 -5
  52. package/dist/generated/agent-guides.json +19 -19
  53. package/dist/lib/agent-activity.d.ts +21 -1
  54. package/dist/lib/agent-activity.js +98 -29
  55. package/dist/lib/api-fetch.d.ts +2 -0
  56. package/dist/lib/api-fetch.js +5 -5
  57. package/dist/lib/appData.d.ts +43 -5
  58. package/dist/lib/appData.js +117 -25
  59. package/dist/lib/appInstallations.d.ts +5 -5
  60. package/dist/lib/appInstallations.js +211 -74
  61. package/dist/lib/appSettings.d.ts +2 -0
  62. package/dist/lib/appSettings.js +36 -3
  63. package/dist/lib/apps-command.d.ts +9 -0
  64. package/dist/lib/apps-command.js +191 -7
  65. package/dist/lib/appsCheck.js +29 -3
  66. package/dist/lib/appsFs.d.ts +1 -1
  67. package/dist/lib/json-output.d.ts +4 -0
  68. package/dist/lib/json-output.js +38 -0
  69. package/dist/lib/miniComputer.js +9 -2
  70. package/dist/lib/node-adapter.js +35 -2
  71. package/dist/lib/outbox.d.ts +20 -5
  72. package/dist/lib/outbox.js +233 -76
  73. package/dist/lib/rate-limit-retry.d.ts +3 -2
  74. package/dist/lib/rate-limit-retry.js +3 -2
  75. package/dist/lib/roles.d.ts +1 -1
  76. package/dist/lib/triggers.d.ts +3 -0
  77. package/dist/lib/triggers.js +10 -0
  78. package/dist/lib/widgetStaticScan.d.ts +3 -1
  79. package/dist/lib/widgetStaticScan.js +182 -47
  80. package/dist/node_modules/@skrr-ai/data-provider/index.js +10416 -9520
  81. package/oclif.manifest.json +137 -44
  82. package/package.json +4 -3
@@ -17,6 +17,18 @@ const appData_1 = require("./appData");
17
17
  * know (forbidden, not found, the server being down) are the base command's to say.
18
18
  */
19
19
  class AppsCommand extends base_command_1.BaseCommand {
20
+ /** A successful response was already received; do not turn a synchronous output failure into a request failure. */
21
+ failConfirmedDataOutput() {
22
+ try {
23
+ process.stderr.write('The server returned a success response, but the CLI could not finish printing it. Do not resend blindly; inspect the current data before taking further action.\n');
24
+ }
25
+ catch {
26
+ // stderr may be unavailable too; the exit status still reports failure.
27
+ }
28
+ // Output may already contain a partial JSON success. Do not append another JSON error or expose
29
+ // an arbitrary output exception. BaseCommand drains pending stdio before handling this exit.
30
+ return this.exit(1);
31
+ }
20
32
  /** The id of the app the person named (an id or a slug). */
21
33
  async appId(ref) {
22
34
  try {
@@ -43,7 +55,7 @@ class AppsCommand extends base_command_1.BaseCommand {
43
55
  failInstallation(error, { subject } = {}) {
44
56
  const refusal = (0, apps_1.readAppsRefusal)(error);
45
57
  if (refusal && (0, data_provider_1.isAppInstallationConflict)(refusal.error)) {
46
- const words = (0, appInstallations_1.describeInstallationConflict)(refusal, this.config.bin);
58
+ const words = (0, appInstallations_1.describeInstallationConflict)(refusal, this.config.bin, subject);
47
59
  if (words !== null) {
48
60
  return this.failWithCliError({
49
61
  message: words,
@@ -71,6 +83,11 @@ class AppsCommand extends base_command_1.BaseCommand {
71
83
  * the channel does not say (the server being down, a sign-in that expired) is the base command's. Never returns.
72
84
  */
73
85
  failPersonData(error, target) {
86
+ if (error instanceof Error &&
87
+ ((0, base_command_1.isOclifExitError)(error) ||
88
+ typeof error.oclif?.exit === 'number')) {
89
+ throw error;
90
+ }
74
91
  if (error instanceof appData_1.AppDataInputError) {
75
92
  return this.failWithCliError({
76
93
  message: error.message,
@@ -82,9 +99,150 @@ class AppsCommand extends base_command_1.BaseCommand {
82
99
  if (error instanceof appsFs_1.AppsFsError) {
83
100
  return this.failApps(error);
84
101
  }
85
- const failure = (0, appData_1.readPersonDataFailure)(error);
86
- if (failure === null) {
87
- return this.failApps(error);
102
+ // A redirect or a write's 401 is not a confirmed app-data refusal, even
103
+ // if an intermediary supplies a body that happens to resemble one.
104
+ const responseStatus = error?.status;
105
+ const responseCode = error?.code;
106
+ const parsedFailure = (0, appData_1.readPersonDataFailure)(error);
107
+ const paused = parsedFailure?.kind === 'refusal' &&
108
+ parsedFailure.code === 'unavailable' &&
109
+ parsedFailure.reason === 'installation_suspended';
110
+ const confirmedPause = paused && (responseStatus === 403 || responseStatus === 503);
111
+ const knownForbidden = parsedFailure?.kind === 'refusal' &&
112
+ ['human_only', 'not_granted', 'forbidden_by_viewer'].includes(parsedFailure.code);
113
+ // The route's per-operation limit refuses before any write runs, so a 429 carrying the contract's
114
+ // `rate` body is a definite "not applied". Any other 429 proves nothing and stays unknown.
115
+ const confirmedRate = parsedFailure?.kind === 'refusal' && parsedFailure.code === 'rate' && responseStatus === 429;
116
+ const sentWrite = Boolean(target.verb) && target.requestStarted;
117
+ // An unrecognized body or a recognizable body with a different HTTP status is not a confirmed app-data response.
118
+ // Both sides use the shared contract. A conflict is an answer, not a refusal, and uses 409.
119
+ const expectedStatus = parsedFailure?.kind === 'conflict'
120
+ ? 409
121
+ : parsedFailure?.kind === 'refusal'
122
+ ? data_provider_1.APP_PERSON_DATA_REFUSAL_STATUS[parsedFailure.code]
123
+ : undefined;
124
+ const mismatchedFailure = sentWrite &&
125
+ typeof responseStatus === 'number' &&
126
+ responseStatus >= 400 &&
127
+ responseStatus <= 599 &&
128
+ !confirmedPause &&
129
+ expectedStatus !== responseStatus;
130
+ // A batch conflict identifies one submitted operation. An absent or out-of-range index cannot
131
+ // establish which request the response describes, so do not claim that nothing was written.
132
+ const invalidBatchConflict = sentWrite &&
133
+ target.verb === 'batch' &&
134
+ parsedFailure?.kind === 'conflict' &&
135
+ (!Array.isArray(target.batchTargets) ||
136
+ !Number.isSafeInteger(parsedFailure.index) ||
137
+ parsedFailure.index < 0 ||
138
+ parsedFailure.index >= target.batchTargets.length);
139
+ const unconfirmedResponse = invalidBatchConflict ||
140
+ (sentWrite && (responseStatus === undefined || responseStatus === 0)) ||
141
+ (typeof responseStatus === 'number' &&
142
+ ((responseStatus >= 300 && responseStatus <= 399) ||
143
+ mismatchedFailure ||
144
+ (sentWrite &&
145
+ (responseStatus === 401 ||
146
+ responseStatus === 408 ||
147
+ responseStatus === 425 ||
148
+ (responseStatus === 429 && !confirmedRate) ||
149
+ (!confirmedPause &&
150
+ ((responseStatus >= 500 && responseStatus <= 599) ||
151
+ (responseStatus === 403 && !knownForbidden))))) ||
152
+ (responseStatus >= 200 &&
153
+ responseStatus <= 299 &&
154
+ responseCode === 'NON_JSON_RESPONSE')));
155
+ const failure = unconfirmedResponse ? null : parsedFailure;
156
+ if (failure === null ||
157
+ (failure.kind === 'refusal' && (failure.code === 'unavailable' || failure.code === 'rate'))) {
158
+ const e = error;
159
+ const status = typeof e?.status === 'number' ? e.status : undefined;
160
+ const code = typeof e?.code === 'string' ? e.code : '';
161
+ const message = typeof e?.message === 'string' ? e.message : '';
162
+ let body;
163
+ try {
164
+ const parsed = typeof e?.body === 'string' ? JSON.parse(e.body) : undefined;
165
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
166
+ body = parsed;
167
+ }
168
+ catch {
169
+ /* Non-JSON responses have no structured diagnostic. */
170
+ }
171
+ const safe = (value) => typeof value === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(value) ? value : undefined;
172
+ const requestId = safe(e?.requestId) ?? safe(body?.requestId);
173
+ if (target.verb &&
174
+ target.requestStarted &&
175
+ failure?.kind === 'refusal' &&
176
+ failure.code === 'unavailable' &&
177
+ failure.reason === 'installation_suspended') {
178
+ return this.failWithCliError({
179
+ code: appData_1.PERSON_DATA_REFUSAL_CODES.unavailable,
180
+ message: (0, appData_1.describePersonDataRefusal)(failure, this.config.bin),
181
+ ...(status === undefined ? {} : { status }),
182
+ ...(requestId ? { requestId } : {}),
183
+ exit: 1,
184
+ retryable: false,
185
+ details: {
186
+ reason: failure.reason,
187
+ retryability: 'after_state_change',
188
+ outcome: 'not_applied',
189
+ },
190
+ });
191
+ }
192
+ const uncertain = unconfirmedResponse ||
193
+ status === 0 ||
194
+ status === 401 ||
195
+ status === 408 ||
196
+ status === 425 ||
197
+ (status === 429 && !confirmedRate) ||
198
+ (status !== undefined && status >= 300 && status <= 399) ||
199
+ (status === 403 &&
200
+ (failure === null ||
201
+ (failure.kind === 'refusal' &&
202
+ (failure.code === 'rate' || failure.code === 'unavailable')))) ||
203
+ (status !== undefined && status >= 500 && status <= 599) ||
204
+ code === 'APP_DATA_UNCONFIRMED_RESPONSE' ||
205
+ code === 'NON_JSON_RESPONSE' ||
206
+ e?.name === 'SyntaxError' ||
207
+ (status === undefined &&
208
+ (e?.name === 'AbortError' ||
209
+ /^(ECONN|EPIPE|ETIMEDOUT|UND_ERR_)/.test(code) ||
210
+ /fetch failed|network error/i.test(message)));
211
+ if (target.verb && target.requestStarted && uncertain) {
212
+ const originalCode = safe(code) ?? safe(body?.code);
213
+ const retryAfterMs = parsedFailure?.kind === 'refusal' &&
214
+ parsedFailure.retryAfterMs !== undefined &&
215
+ Number.isFinite(parsedFailure.retryAfterMs) &&
216
+ parsedFailure.retryAfterMs >= 0
217
+ ? parsedFailure.retryAfterMs
218
+ : typeof e?.retryAfterMs === 'number' &&
219
+ Number.isFinite(e.retryAfterMs) &&
220
+ e.retryAfterMs >= 0
221
+ ? e.retryAfterMs
222
+ : undefined;
223
+ return this.failWithCliError({
224
+ code: 'APP_DATA_WRITE_OUTCOME_UNKNOWN',
225
+ message: (target.verb === 'batch' && target.batchHasGeneratedIds
226
+ ? 'The batch may have reached the server, but its outcome is unknown. One or more puts had no ID; if applied, their server-generated IDs may be impossible to identify from this response. Matching document content alone does not prove which write happened. Do not resend blindly; reconcile the batch and any concurrent changes before deciding what to do.'
227
+ : 'The write may have reached the server, but its outcome is unknown. Read the affected data and revisions before deciding what to do; for a batch, check each affected document. Reconcile concurrent changes before writing again.') +
228
+ (status === 401 ? ' A 401 response was received; check your sign-in separately.' : ''),
229
+ ...(status === undefined || status === 0 ? {} : { status }),
230
+ ...(requestId ? { requestId } : {}),
231
+ exit: 5,
232
+ retryable: false,
233
+ details: {
234
+ outcome: 'unknown',
235
+ operation: target.verb,
236
+ ...(target.verb === 'batch' && target.batchHasGeneratedIds
237
+ ? { generatedIdsMayBeUnknown: true }
238
+ : {}),
239
+ ...(retryAfterMs === undefined ? {} : { retryAfterMs }),
240
+ ...(originalCode ? { originalCode } : {}),
241
+ },
242
+ });
243
+ }
244
+ if (failure === null)
245
+ return this.failApps(error);
88
246
  }
89
247
  if (failure.kind === 'conflict') {
90
248
  return this.failWithCliError({
@@ -96,18 +254,44 @@ class AppsCommand extends base_command_1.BaseCommand {
96
254
  details: {
97
255
  conflict: failure.conflict,
98
256
  ...(failure.currentRev === undefined ? {} : { currentRev: failure.currentRev }),
257
+ ...(target.verb === 'batch' && failure.index !== undefined
258
+ ? { index: failure.index }
259
+ : {}),
99
260
  },
100
261
  });
101
262
  }
102
263
  return this.failWithCliError({
103
- message: (0, appData_1.describePersonDataRefusal)(failure, this.config.bin),
264
+ message: (0, appData_1.describePersonDataRefusal)(failure, this.config.bin, target.operation),
104
265
  code: appData_1.PERSON_DATA_REFUSAL_CODES[failure.code],
105
266
  ...(failure.status === undefined ? {} : { status: failure.status }),
106
267
  exit: (0, appData_1.personDataFailureExit)(failure),
107
268
  retryable: (0, appData_1.personDataFailureRetryable)(failure),
108
- ...(failure.retryAfterMs === undefined
269
+ ...(failure.retryAfterMs === undefined &&
270
+ failure.index === undefined &&
271
+ failure.code !== 'unavailable' &&
272
+ !(target.operation === 'query' &&
273
+ typeof data_provider_1.APP_STORE_CURSOR_INVALID_REASON === 'string' &&
274
+ failure.reason === data_provider_1.APP_STORE_CURSOR_INVALID_REASON)
109
275
  ? {}
110
- : { details: { retryAfterMs: failure.retryAfterMs } }),
276
+ : {
277
+ details: {
278
+ ...(failure.retryAfterMs === undefined ? {} : { retryAfterMs: failure.retryAfterMs }),
279
+ ...(failure.index === undefined ? {} : { index: failure.index }),
280
+ ...(target.operation === 'query' &&
281
+ typeof data_provider_1.APP_STORE_CURSOR_INVALID_REASON === 'string' &&
282
+ failure.reason === data_provider_1.APP_STORE_CURSOR_INVALID_REASON
283
+ ? { reason: data_provider_1.APP_STORE_CURSOR_INVALID_REASON }
284
+ : {}),
285
+ ...(failure.code !== 'unavailable'
286
+ ? {}
287
+ : {
288
+ retryability: failure.reason === 'installation_suspended'
289
+ ? 'after_state_change'
290
+ : 'unknown',
291
+ ...(failure.reason ? { reason: failure.reason } : {}),
292
+ }),
293
+ },
294
+ }),
111
295
  });
112
296
  }
113
297
  /**
@@ -71,8 +71,8 @@ function compileScript(source) {
71
71
  };
72
72
  }
73
73
  }
74
- function scanSandbox(sections) {
75
- const scan = (0, widgetStaticScan_1.scanWidgetSource)(sections);
74
+ function scanSandbox(sections, options) {
75
+ const scan = (0, widgetStaticScan_1.scanWidgetSource)(sections, options);
76
76
  return {
77
77
  findings: scan.findings.map((found) => ({
78
78
  severity: found.severity,
@@ -120,6 +120,14 @@ function placeOf(issue) {
120
120
  return '';
121
121
  return issue.line ? `${issue.path}:${issue.line}` : issue.path;
122
122
  }
123
+ // Only collapse warnings with the same meaning and file. Lines remain distinct
124
+ // in the full JSON report; errors are always shown individually.
125
+ function warningDisplayKey(issue) {
126
+ return JSON.stringify([
127
+ issue.source, issue.code, issue.path, issue.at, issue.message, issue.fix,
128
+ issue.heuristic, issue.tier, issue.unanalyzable, issue.evidence,
129
+ ]);
130
+ }
123
131
  /** The report as lines for a terminal: the verdict, then each finding with where it is and what to do. */
124
132
  function formatAppCheckReport(report) {
125
133
  const lines = [];
@@ -150,7 +158,22 @@ function formatAppCheckReport(report) {
150
158
  }
151
159
  }
152
160
  const explained = {};
161
+ const warningCounts = new Map();
162
+ const warningsShown = new Map();
163
+ for (const issue of report.issues) {
164
+ if (issue.severity !== 'warn')
165
+ continue;
166
+ const key = warningDisplayKey(issue);
167
+ warningCounts.set(key, (warningCounts.get(key) ?? 0) + 1);
168
+ }
153
169
  for (const issue of report.issues) {
170
+ const key = issue.severity === 'warn' ? warningDisplayKey(issue) : undefined;
171
+ const count = key === undefined ? 0 : warningCounts.get(key) ?? 0;
172
+ const shown = key === undefined ? 0 : warningsShown.get(key) ?? 0;
173
+ if (count > 5 && shown >= 3)
174
+ continue;
175
+ if (key !== undefined)
176
+ warningsShown.set(key, shown + 1);
154
177
  const place = placeOf(issue);
155
178
  const tag = issue.tier ? ` [${TIER_TAG[issue.tier]}]` : '';
156
179
  lines.push(`${issue.severity === 'error' ? 'error' : 'warn '} ${issue.code}${place ? ` ${place}` : ''}${issue.at ? ` (${issue.at})` : ''}${issue.heuristic ? ' [heuristic]' : ''}${tag}`);
@@ -164,11 +187,14 @@ function formatAppCheckReport(report) {
164
187
  }
165
188
  if (issue.fix)
166
189
  lines.push(` fix: ${issue.fix}`);
190
+ if (count > 5 && shown === 2) {
191
+ lines.push(` ${count - 3} more matching warning${count - 3 === 1 ? '' : 's'}. Run with --json to see every occurrence.`);
192
+ }
167
193
  }
168
194
  if (security) {
169
195
  lines.push('', security.limitations.headline);
170
196
  for (const point of security.limitations.points)
171
- lines.push(` - ${point}`);
197
+ lines.push(` - ${(0, data_provider_1.clarifyAppCheckLimitation)(point)}`);
172
198
  }
173
199
  lines.push('', report.heuristic);
174
200
  return lines;
@@ -1,6 +1,6 @@
1
1
  import type { AppDraftFile, AppPathProblem } from '@skrr-ai/data-provider';
2
2
  /** Why a read or a write of a package was refused. */
3
- export type AppsFsErrorCode = 'symlink' | 'not_regular' | 'too_large' | 'too_many' | 'not_text' | 'bad_path' | 'outside_root' | 'exists' | 'not_directory' | 'unreadable';
3
+ export type AppsFsErrorCode = 'symlink' | 'not_regular' | 'too_large' | 'too_many' | 'not_text' | 'invalid_asset' | 'bad_path' | 'outside_root' | 'exists' | 'not_directory' | 'unreadable';
4
4
  export declare class AppsFsError extends Error {
5
5
  readonly code: AppsFsErrorCode;
6
6
  /** The path (relative to the package, or as typed) the refusal is about. */
@@ -17,11 +17,15 @@
17
17
  * identifier would turn a cosmetic cleanup into data loss.
18
18
  */
19
19
  type Json = unknown;
20
+ /** Escape terminal controls in serialized JSON without changing its parsed value. */
21
+ export declare function escapeJsonForTerminal(text: string): string;
20
22
  /**
21
23
  * Returns the SAME reference when nothing needed stripping, so a caller can tell
22
24
  * "unchanged" apart from "rebuilt" and leave the original text alone.
23
25
  */
24
26
  export declare function stripStorageFields(value: Json): Json;
27
+ /** Strip query envelope metadata without interpreting app-owned `docs[].data` as platform metadata. */
28
+ export declare function stripAppDataQueryMetadata(value: Json): Json;
25
29
  /**
26
30
  * Apply {@link stripStorageFields} to one line of CLI output. Anything that is
27
31
  * not a JSON object/array (prose, a bare string, malformed text) is returned
@@ -18,10 +18,28 @@
18
18
  * identifier would turn a cosmetic cleanup into data loss.
19
19
  */
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.escapeJsonForTerminal = escapeJsonForTerminal;
21
22
  exports.stripStorageFields = stripStorageFields;
23
+ exports.stripAppDataQueryMetadata = stripAppDataQueryMetadata;
22
24
  exports.stripStorageFieldsFromText = stripStorageFieldsFromText;
23
25
  exports.withOk = withOk;
24
26
  exports.withCliOperation = withCliOperation;
27
+ const JSON_TERMINAL_CONTROLS = /[\u007f-\u009f\u00ad\u034f\u061c\u115f\u1160\u17b4\u17b5\u180b-\u180e\u200b-\u200f\u2028-\u202e\u2060-\u206f\u2800\u3164\ufe00-\ufe0f\ufeff\uffa0\ufff9-\ufffb\u{1d173}-\u{1d17a}\u{e0000}-\u{e03ff}]/gu;
28
+ /** Escape terminal controls in serialized JSON without changing its parsed value. */
29
+ function escapeJsonForTerminal(text) {
30
+ const head = text.trimStart()[0];
31
+ if ((head !== '{' && head !== '[' && head !== '"') || text.search(JSON_TERMINAL_CONTROLS) === -1)
32
+ return text;
33
+ // Prose printed by a command in JSON mode is not necessarily a JSON document.
34
+ try {
35
+ JSON.parse(text);
36
+ }
37
+ catch {
38
+ return text;
39
+ }
40
+ // Do not escape C0: a serialized JSON string has already escaped it, while indentation uses newlines.
41
+ return text.replace(JSON_TERMINAL_CONTROLS, (char) => Array.from({ length: char.length }, (_, index) => `\\u${char.charCodeAt(index).toString(16).padStart(4, '0')}`).join(''));
42
+ }
25
43
  function usableId(value) {
26
44
  return (typeof value === 'string' && value.length > 0) || typeof value === 'number';
27
45
  }
@@ -57,6 +75,26 @@ function stripStorageFields(value) {
57
75
  }
58
76
  return changed ? next : value;
59
77
  }
78
+ /** Strip query envelope metadata without interpreting app-owned `docs[].data` as platform metadata. */
79
+ function stripAppDataQueryMetadata(value) {
80
+ if (!value || typeof value !== 'object' || Array.isArray(value))
81
+ return stripStorageFields(value);
82
+ const source = value;
83
+ if (!Array.isArray(source.docs))
84
+ return stripStorageFields(value);
85
+ const { docs, ...envelope } = source;
86
+ const cleanedEnvelope = stripStorageFields(envelope);
87
+ const cleanedDocs = docs.map((doc) => {
88
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc))
89
+ return stripStorageFields(doc);
90
+ const row = doc;
91
+ if (!Object.prototype.hasOwnProperty.call(row, 'data'))
92
+ return stripStorageFields(row);
93
+ const { data, ...metadata } = row;
94
+ return { ...stripStorageFields(metadata), data };
95
+ });
96
+ return { ...cleanedEnvelope, docs: cleanedDocs };
97
+ }
60
98
  /**
61
99
  * Apply {@link stripStorageFields} to one line of CLI output. Anything that is
62
100
  * not a JSON object/array (prose, a bare string, malformed text) is returned
@@ -70,6 +70,12 @@ const REFUSAL_WORDS = {
70
70
  exit: 1,
71
71
  retryable: false,
72
72
  }),
73
+ revision_exhausted: () => ({
74
+ message: 'This app configuration has reached its revision limit. Nothing was changed; contact support.',
75
+ code: 'MINI_COMPUTER_REVISION_EXHAUSTED',
76
+ exit: 1,
77
+ retryable: false,
78
+ }),
73
79
  busy: () => ({
74
80
  message: 'Other changes kept landing at the same moment. Nothing was lost; run the command again.',
75
81
  code: 'MINI_COMPUTER_BUSY',
@@ -165,8 +171,9 @@ function formatMiniAppConfig(raw) {
165
171
  const entry = (0, data_provider_1.parseMiniAppConfigEntry)(raw);
166
172
  if (entry === null)
167
173
  return ['This configuration is not in a form this version of the CLI understands.'];
168
- if (entry.config === null)
169
- return [`${entry.appId}: default (nothing set)`];
174
+ if (entry.config === null) {
175
+ return [`${entry.appId}: default (nothing set), revision ${entry.rev}`];
176
+ }
170
177
  const view = entry.config.view;
171
178
  const lines = [
172
179
  `${entry.appId}: revision ${entry.rev}${entry.via ? `, set by ${entry.via}` : ''}`,
@@ -22,6 +22,12 @@ require("./auth-core-init");
22
22
  const rate_limit_retry_1 = require("./rate-limit-retry");
23
23
  const RESOLVE_URL_RE = /^https?:\/\//i;
24
24
  const RESOLVE_URL_RE_2 = /\/+$/;
25
+ // These routes do not yet have a server-side idempotency receipt. A generated
26
+ // request key alone cannot make an arbitrary gateway response safe to replay.
27
+ // A deployment can mount the API beneath a path prefix; a match at any
28
+ // segment is deliberately conservative even for a different origin.
29
+ const APP_DATA_PATH_RE = /\/api\/apps\/installations\/[^/]+\/data(?:\/|$)/;
30
+ const APP_SETTINGS_PATH_RE = /\/api\/apps\/installations\/[^/]+\/settings\/?$/;
25
31
  // ---------------------------------------------------------------------
26
32
  // Per-process credential override — set by BaseCommand.init().
27
33
  // Pulled out of the closure so test harnesses or long-lived callers
@@ -163,6 +169,26 @@ function createNodeAdapter(opts = {}) {
163
169
  }
164
170
  return u.toString();
165
171
  }
172
+ function isAppDataWrite(method, url) {
173
+ if (method === 'GET')
174
+ return false;
175
+ try {
176
+ return APP_DATA_PATH_RE.test(new URL(url).pathname);
177
+ }
178
+ catch {
179
+ return false;
180
+ }
181
+ }
182
+ function isAppSettingsWrite(method, url) {
183
+ if (method !== 'PUT')
184
+ return false;
185
+ try {
186
+ return APP_SETTINGS_PATH_RE.test(new URL(url).pathname);
187
+ }
188
+ catch {
189
+ return false;
190
+ }
191
+ }
166
192
  /** The last 429's `Retry-After`, read off the response of the most recent attempt. */
167
193
  let lastRetryAfterMs;
168
194
  async function rawRequest(method, url, body, options, isFormData) {
@@ -191,7 +217,12 @@ function createNodeAdapter(opts = {}) {
191
217
  const signal = timeoutSignal && callerSignal
192
218
  ? AbortSignal.any([timeoutSignal, callerSignal])
193
219
  : timeoutSignal || callerSignal;
194
- const { response, retryAfterMs } = await (0, rate_limit_retry_1.fetchWithRateLimitRetry)(() => fetch(finalUrl, { method, headers, body: finalBody, ...(signal ? { signal } : {}), ...(0, task_runtime_headers_1.taskRuntimeRedirectOptions)(headers) }), { method, headers });
220
+ const appDataWrite = isAppDataWrite(method, finalUrl);
221
+ const appSettingsWrite = isAppSettingsWrite(method, finalUrl);
222
+ const noReplay = options?._disableAuthReplay === true;
223
+ const { response, retryAfterMs } = await (0, rate_limit_retry_1.fetchWithRateLimitRetry)(() => fetch(finalUrl, { method, headers, body: finalBody, ...(signal ? { signal } : {}),
224
+ ...(appDataWrite || appSettingsWrite || noReplay ? { redirect: 'manual' } : (0, task_runtime_headers_1.taskRuntimeRedirectOptions)(headers)) }), { method, headers, ...(appDataWrite || appSettingsWrite || noReplay
225
+ ? { maxRetries: 0 } : {}) });
195
226
  lastRetryAfterMs = retryAfterMs;
196
227
  return response;
197
228
  }
@@ -344,10 +375,12 @@ function createNodeAdapter(opts = {}) {
344
375
  headers: (0, data_provider_1.withIdempotencyKey)(options?.headers, { method, url, body }),
345
376
  };
346
377
  }
378
+ const appDataWrite = isAppDataWrite(method, resolveUrl(url));
379
+ const appSettingsWrite = isAppSettingsWrite(method, resolveUrl(url));
347
380
  let res = await rawRequest(method, url, body, options, isFormData);
348
381
  // Never retry auth endpoints themselves — prevents refresh recursion
349
382
  // and lets login/logout/refresh surface their real errors.
350
- if (res.status === 401 && !url.includes('/api/auth/')) {
383
+ if (res.status === 401 && !appDataWrite && !appSettingsWrite && options?._disableAuthReplay !== true && !url.includes('/api/auth/')) {
351
384
  const refreshed = await refresh();
352
385
  if (refreshed) {
353
386
  res = await rawRequest(method, url, body, options, isFormData);
@@ -27,6 +27,14 @@ export interface OutboxEntry {
27
27
  /** ISO timestamp of the most recent failed replay, when there has been one. */
28
28
  lastAttemptAt?: string;
29
29
  lastError?: string;
30
+ /** A replay was started; a result ID is a response shape, not proof of the original target or effect. */
31
+ replay?: {
32
+ state: 'sending' | 'result_recorded';
33
+ attemptId: string;
34
+ startedAt: string;
35
+ fingerprint: string;
36
+ resultId?: string;
37
+ };
30
38
  }
31
39
  /**
32
40
  * A replay that keeps failing is either a permanent server-side refusal or a
@@ -38,13 +46,16 @@ export interface OutboxEntry {
38
46
  export declare const MAX_REPLAY_ATTEMPTS = 10;
39
47
  export declare function isOutageFailure(err: unknown): boolean;
40
48
  export declare function isRetryableWrite(err: unknown): boolean;
49
+ /** One replay at a time; unlike the short queue lock, this spans network calls. */
50
+ export declare function lockOutboxReplay(profile?: string): Promise<() => Promise<void>>;
51
+ export declare class OutboxFullError extends Error {
52
+ constructor();
53
+ }
41
54
  export declare function enqueueWrite(input: Omit<OutboxEntry, 'id' | 'queuedAt' | 'attempts'>, profile?: string): OutboxEntry;
42
- /**
43
- * Read every intact entry. A truncated trailing line — the shape a crash
44
- * mid-append leaves — is skipped, because losing the one entry that was still
45
- * being written is strictly better than failing to read the ones that landed.
46
- */
55
+ /** Fail visibly when the queue is unreadable; never present damage as an empty queue. */
47
56
  export declare function listWrites(profile?: string): OutboxEntry[];
57
+ /** Replay must fail before sending if the queue cannot be read intact. */
58
+ export declare function listReplayWrites(profile?: string): OutboxEntry[];
48
59
  /**
49
60
  * Rewrite the log with `entries`, atomically (tmp + rename).
50
61
  *
@@ -52,6 +63,10 @@ export declare function listWrites(profile?: string): OutboxEntry[];
52
63
  * append: it could lose entries that were never attempted.
53
64
  */
54
65
  export declare function replaceWrites(entries: OutboxEntry[], profile?: string): void;
66
+ /** Persist a one-attempt claim before sending. Existing claims are never taken over. */
67
+ export declare function claimOutboxReplay(id: string, profile?: string): OutboxEntry | null;
68
+ /** Retain the content while recording the result of the exact claimed request. */
69
+ export declare function acknowledgeOutboxReplay(claim: OutboxEntry, resultId: string, profile?: string): void;
55
70
  export declare function dropWrite(id: string, profile?: string): boolean;
56
71
  export interface IncidentState {
57
72
  /** ISO timestamp when the control plane was last observed failing. */