@uru-intelligence/app 2.1.5 → 2.2.1

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.
package/dist/dampers.js CHANGED
@@ -1,6 +1,19 @@
1
1
  /** Client retry delays and force-refresh limits. */
2
2
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
+ const safeRecordValue = (record, field) => {
4
+ if (record === null)
5
+ return undefined;
6
+ try {
7
+ return record[field];
8
+ }
9
+ catch {
10
+ return undefined;
11
+ }
12
+ };
13
+ const MAX_RETRY_AFTER_SECONDS = (Number.MAX_SAFE_INTEGER - 1) / 1000;
14
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
3
15
  const DEFAULT_MAX_RATE_LIMIT_RETRIES = 3;
16
+ const DEFAULT_MAX_TRANSPORT_RETRIES = 7;
4
17
  const DEFAULT_RATE_LIMIT_BASE_DELAY_MS = 500;
5
18
  const DEFAULT_RATE_LIMIT_MAX_DELAY_MS = 10_000;
6
19
  const DEFAULT_FORCE_REFRESH_MIN_INTERVAL_MS = 5000;
@@ -11,6 +24,9 @@ const nonNegativeOr = (value, fallback) => typeof value === "number" && Number.i
11
24
  ? value
12
25
  : fallback;
13
26
  const defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
27
+ let remaining = Number.isFinite(ms)
28
+ ? Math.max(0, Math.min(ms, Number.MAX_SAFE_INTEGER - 1))
29
+ : 0;
14
30
  let timeout;
15
31
  const abort = () => {
16
32
  cleanup();
@@ -18,22 +34,34 @@ const defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
18
34
  new DOMException("The operation was aborted.", "AbortError"));
19
35
  };
20
36
  const cleanup = () => {
21
- clearTimeout(timeout);
37
+ if (timeout !== undefined)
38
+ clearTimeout(timeout);
22
39
  signal?.removeEventListener("abort", abort);
23
40
  };
24
- timeout = setTimeout(() => {
25
- cleanup();
26
- resolve();
27
- }, Math.max(0, ms));
28
- if (signal === undefined)
29
- return;
30
- if (signal.aborted) {
31
- abort();
32
- return;
41
+ const schedule = () => {
42
+ if (remaining <= 0) {
43
+ cleanup();
44
+ resolve();
45
+ return;
46
+ }
47
+ const chunk = Math.min(remaining, MAX_TIMER_DELAY_MS);
48
+ timeout = setTimeout(() => {
49
+ remaining -= chunk;
50
+ schedule();
51
+ }, chunk);
52
+ };
53
+ if (signal !== undefined) {
54
+ if (signal.aborted) {
55
+ abort();
56
+ return;
57
+ }
58
+ signal.addEventListener("abort", abort, { once: true });
59
+ if (signal.aborted) {
60
+ abort();
61
+ return;
62
+ }
33
63
  }
34
- signal.addEventListener("abort", abort, { once: true });
35
- if (signal.aborted)
36
- abort();
64
+ schedule();
37
65
  });
38
66
  /** Fold caller overrides into a fully-defaulted {@link ResolvedDamperConfig}. */
39
67
  export const resolveDamperConfig = (options) => ({
@@ -42,7 +70,9 @@ export const resolveDamperConfig = (options) => ({
42
70
  forceRefreshMinIntervalMs: nonNegativeOr(options?.forceRefreshMinIntervalMs, DEFAULT_FORCE_REFRESH_MIN_INTERVAL_MS),
43
71
  // `<= 0` disables backoff — clamped to 0 (no retries) rather than negative.
44
72
  maxRateLimitRetries: nonNegativeOr(options?.maxRateLimitRetries, DEFAULT_MAX_RATE_LIMIT_RETRIES),
73
+ maxTransportRetries: nonNegativeOr(options?.maxTransportRetries, DEFAULT_MAX_TRANSPORT_RETRIES),
45
74
  now: options?.now ?? (() => Date.now()),
75
+ random: options?.random ?? (() => Math.random()),
46
76
  rateLimitBaseDelayMs: positiveOr(options?.rateLimitBaseDelayMs, DEFAULT_RATE_LIMIT_BASE_DELAY_MS),
47
77
  rateLimitMaxDelayMs: positiveOr(options?.rateLimitMaxDelayMs, DEFAULT_RATE_LIMIT_MAX_DELAY_MS),
48
78
  sleep: options?.sleep ?? defaultSleep,
@@ -67,6 +97,24 @@ export const computeRateLimitBackoffMs = (args) => {
67
97
  const exponential = baseDelayMs * 2 ** Math.max(0, attempt);
68
98
  return Math.min(maxDelayMs, exponential);
69
99
  };
100
+ /**
101
+ * Compute a rate-limit wait. A server Retry-After is authoritative, so this
102
+ * path does not shorten it to the normal fallback backoff cap. The shared
103
+ * request signal still bounds the wait.
104
+ */
105
+ export const computeRateLimitRetryDelayMs = (args) => {
106
+ if (typeof args.retryAfterSeconds === "number" &&
107
+ Number.isFinite(args.retryAfterSeconds) &&
108
+ args.retryAfterSeconds > 0) {
109
+ return Math.ceil(args.retryAfterSeconds * 1000);
110
+ }
111
+ return computeRateLimitBackoffMs({
112
+ attempt: args.attempt,
113
+ baseDelayMs: args.baseDelayMs,
114
+ maxDelayMs: args.maxDelayMs,
115
+ retryAfterSeconds: null,
116
+ });
117
+ };
70
118
  /**
71
119
  * Parse a retry-after hint (seconds) from a 429 response's `Retry-After` header
72
120
  * and/or a `retryAfterSeconds` field in the parsed owned HTTP body. Prefers the header
@@ -77,19 +125,72 @@ export const parseRetryAfterSeconds = (args) => {
77
125
  const headerRaw = (args.header ?? "").trim();
78
126
  if (headerRaw !== "") {
79
127
  const headerSeconds = Number(headerRaw);
80
- if (Number.isFinite(headerSeconds) && headerSeconds > 0) {
128
+ if (Number.isFinite(headerSeconds) &&
129
+ headerSeconds > 0 &&
130
+ headerSeconds <= MAX_RETRY_AFTER_SECONDS) {
81
131
  return headerSeconds;
82
132
  }
83
133
  }
134
+ const positiveSeconds = (value) => {
135
+ const seconds = typeof value === "number"
136
+ ? value
137
+ : typeof value === "string" && value.trim() !== ""
138
+ ? Number(value)
139
+ : NaN;
140
+ return Number.isFinite(seconds) && seconds > 0 && seconds <= MAX_RETRY_AFTER_SECONDS
141
+ ? seconds
142
+ : null;
143
+ };
144
+ const fromRecord = (record) => {
145
+ const direct = positiveSeconds(safeRecordValue(record, "retryAfterSeconds") ??
146
+ safeRecordValue(record, "retry_after_seconds"));
147
+ if (direct !== null)
148
+ return direct;
149
+ const retryAfterMs = positiveSeconds(safeRecordValue(record, "retryAfterMs") ??
150
+ safeRecordValue(record, "retry_after_ms"));
151
+ if (retryAfterMs !== null)
152
+ return retryAfterMs / 1000;
153
+ const detailsValue = safeRecordValue(record, "details");
154
+ const details = isRecord(detailsValue) ? detailsValue : null;
155
+ if (details !== null) {
156
+ const detailSeconds = positiveSeconds(safeRecordValue(details, "retryAfterSeconds") ??
157
+ safeRecordValue(details, "retry_after_seconds"));
158
+ if (detailSeconds !== null)
159
+ return detailSeconds;
160
+ const detailMs = positiveSeconds(safeRecordValue(details, "retryAfterMs") ??
161
+ safeRecordValue(details, "retry_after_ms"));
162
+ if (detailMs !== null)
163
+ return detailMs / 1000;
164
+ }
165
+ return null;
166
+ };
84
167
  if (isRecord(args.body)) {
85
- const candidate = args.body.retryAfterSeconds;
86
- const seconds = Number(candidate);
87
- if (Number.isFinite(seconds) && seconds > 0) {
168
+ const seconds = fromRecord(args.body);
169
+ if (seconds !== null) {
88
170
  return seconds;
89
171
  }
172
+ const errorValue = safeRecordValue(args.body, "error");
173
+ const error = isRecord(errorValue) ? errorValue : null;
174
+ if (error !== null)
175
+ return fromRecord(error);
90
176
  }
91
177
  return null;
92
178
  };
179
+ /** Read the owned retry decision without inspecting provider-authored text. */
180
+ export const parseRetryable = (body) => {
181
+ if (!isRecord(body))
182
+ return undefined;
183
+ const errorValue = safeRecordValue(body, "error");
184
+ const error = isRecord(errorValue) ? errorValue : null;
185
+ const errorDetailsValue = safeRecordValue(error, "details");
186
+ const errorDetails = isRecord(errorDetailsValue) ? errorDetailsValue : null;
187
+ for (const record of [error, body, errorDetails]) {
188
+ const retryable = safeRecordValue(record, "retryable");
189
+ if (typeof retryable === "boolean")
190
+ return retryable;
191
+ }
192
+ return undefined;
193
+ };
93
194
  /**
94
195
  * Per-client mutable state for the forceRefresh throttle: the last epoch-ms at
95
196
  * which a forceRefresh was HONORED for each capability key. Created once per
@@ -155,7 +155,44 @@ export const decodeDatasetRowsResult = (value, decodeRow) => {
155
155
  export const decodeDefaultDatasetRowsResult = (value) => {
156
156
  const label = "Uru Dataset query";
157
157
  const body = responseObject(value, label);
158
- return rowsResultFields(body, [...requiredRows(body.rows, label)], label);
158
+ const rows = requiredRows(body.rows, label).map((row, index) => {
159
+ if (typeof row.id !== "string" || !isRuntimeJsonObject(row.fields)) {
160
+ return invalidResponse(label, body.rows, `rows[${index}]`);
161
+ }
162
+ const rowVersion = row.rowVersion;
163
+ const createdAt = row.createdAt;
164
+ const updatedAt = row.updatedAt;
165
+ const deleted = row.deleted;
166
+ if (hasOwn(row, "rowVersion")) {
167
+ if (typeof rowVersion !== "string") {
168
+ return invalidResponse(label, body.rows, `rows[${index}].rowVersion`);
169
+ }
170
+ }
171
+ if (hasOwn(row, "createdAt")) {
172
+ if (typeof createdAt !== "string") {
173
+ return invalidResponse(label, body.rows, `rows[${index}].createdAt`);
174
+ }
175
+ }
176
+ if (hasOwn(row, "updatedAt")) {
177
+ if (typeof updatedAt !== "string") {
178
+ return invalidResponse(label, body.rows, `rows[${index}].updatedAt`);
179
+ }
180
+ }
181
+ if (hasOwn(row, "deleted")) {
182
+ if (typeof deleted !== "boolean") {
183
+ return invalidResponse(label, body.rows, `rows[${index}].deleted`);
184
+ }
185
+ }
186
+ return {
187
+ id: row.id,
188
+ fields: row.fields,
189
+ ...(typeof rowVersion === "string" ? { rowVersion } : {}),
190
+ ...(typeof createdAt === "string" ? { createdAt } : {}),
191
+ ...(typeof updatedAt === "string" ? { updatedAt } : {}),
192
+ ...(typeof deleted === "boolean" ? { deleted } : {}),
193
+ };
194
+ });
195
+ return rowsResultFields(body, rows, label);
159
196
  };
160
197
  const requiredBoolean = (body, field, label) => {
161
198
  const value = body[field];
@@ -0,0 +1,9 @@
1
+ import type { UruDatasetRowMutationInput, UruDatasetRowView } from "./types.js";
2
+ import type { RuntimeJsonObject } from "./transport-json.js";
3
+ /**
4
+ * Convert a native Dataset row view into a lossless row update.
5
+ *
6
+ * Keep row identity separate from customer fields. A flat row cannot represent
7
+ * a customer field named `id` because that key names the row in an upsert.
8
+ */
9
+ export declare const datasetRowForMutation: <TFields extends RuntimeJsonObject>(row: UruDatasetRowView<TFields>) => UruDatasetRowMutationInput<TFields>;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Convert a native Dataset row view into a lossless row update.
3
+ *
4
+ * Keep row identity separate from customer fields. A flat row cannot represent
5
+ * a customer field named `id` because that key names the row in an upsert.
6
+ */
7
+ export const datasetRowForMutation = (row) => ({
8
+ expectedRowVersion: row.rowVersion ?? null,
9
+ fields: { ...row.fields },
10
+ rowId: row.id,
11
+ });
@@ -6,6 +6,7 @@
6
6
  * The HTTP boundary lives in `dataset-boundary.ts` so this module only assembles
7
7
  * the current Dataset request paths and overloads.
8
8
  */
9
+ import type { CallKeys } from "./job-run.js";
9
10
  import type { CreateUruAppRuntimeClientOptions, UruAppRuntimeClient, UruDatasetsContext } from "./types.js";
10
11
  /** Build the Dataset surface hung off a server context. */
11
- export declare const createDatasetsContext: (app: UruAppRuntimeClient, clientOptions: CreateUruAppRuntimeClientOptions) => UruDatasetsContext;
12
+ export declare const createDatasetsContext: (app: UruAppRuntimeClient, clientOptions: CreateUruAppRuntimeClientOptions, keys?: CallKeys) => UruDatasetsContext;
package/dist/datasets.js CHANGED
@@ -7,9 +7,12 @@
7
7
  * the current Dataset request paths and overloads.
8
8
  */
9
9
  import { datasetIdsForRequest, datasetRowIdsForRequest, datasetRowsForRequest, decodeDatasetMutationResult, decodeDatasetRowsResult, decodeDefaultDatasetMutationResult, decodeDefaultDatasetRowsResult, datasetWriteErrorMessage, serializeDatasetRequest, } from "./dataset-boundary.js";
10
+ import { resolveDamperConfig } from "./dampers.js";
10
11
  import { UruAppRuntimeError } from "./errors.js";
12
+ import { RANDOM_CALL_KEYS } from "./job-run.js";
11
13
  import { requireCompletedRuntimeResponse, resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
12
- const fetchDatasetWrite = async (options, subpath, body) => {
14
+ import { postWithResends } from "./transport-retry.js";
15
+ const fetchDatasetWrite = async (options, subpath, body, send) => {
13
16
  const runtimeFetch = resolveRuntimeFetch(options);
14
17
  const deploymentId = typeof options.deploymentId === "string" ? options.deploymentId.trim() : "";
15
18
  if (!deploymentId) {
@@ -25,13 +28,15 @@ const fetchDatasetWrite = async (options, subpath, body) => {
25
28
  const url = `${baseUrl}${basePath}/apps/${encodeURIComponent(deploymentId)}/${subpath}`;
26
29
  const headers = new Headers(await resolveHeaders(options.headers));
27
30
  headers.set("content-type", "application/json");
28
- const response = await runtimeFetch(url, {
31
+ const { body: parsed, response } = await postWithResends({
29
32
  body: serializedBody,
33
+ config: send.config,
30
34
  headers,
31
- method: "POST",
32
- signal: AbortSignal.timeout(30_000),
35
+ resendLost: send.resendLost,
36
+ runtimeFetch,
37
+ sendTimeoutMs: 30_000,
38
+ url,
33
39
  });
34
- const parsed = await response.json().catch(() => null);
35
40
  if (!response.ok) {
36
41
  const message = datasetWriteErrorMessage(parsed, response.status);
37
42
  throw new UruAppRuntimeError(message, {
@@ -41,8 +46,29 @@ const fetchDatasetWrite = async (options, subpath, body) => {
41
46
  }
42
47
  return parsed;
43
48
  };
44
- const postProviderDatasetWrite = async (options, subpath, body) => decodeDefaultDatasetMutationResult(await fetchDatasetWrite(options, subpath, body));
45
- const postProviderDatasetWriteDecoded = async (options, subpath, body, decodeResult) => decodeDatasetMutationResult(await fetchDatasetWrite(options, subpath, body), decodeResult);
49
+ const postProviderDatasetWrite = async (options, subpath, body, send) => decodeDefaultDatasetMutationResult(await fetchDatasetWrite(options, subpath, body, send));
50
+ const postProviderDatasetWriteDecoded = async (options, subpath, body, send, decodeResult) => decodeDatasetMutationResult(await fetchDatasetWrite(options, subpath, body, send), decodeResult);
51
+ /**
52
+ * One row write's body with its key. Each call gets its own key, and every
53
+ * send of that call carries it, so a resend after a lost response is a replay
54
+ * of the stored command rather than a second write.
55
+ */
56
+ const keyedMutationBody = (body, mutationOptions, config, keys, datasetRef) => {
57
+ const callerKey = mutationOptions?.idempotencyKey;
58
+ const idempotencyKey = callerKey !== undefined && callerKey !== ""
59
+ ? callerKey
60
+ : config.defaultIdempotencyKeys
61
+ ? keys.next("dataset", datasetRef.trim())
62
+ : undefined;
63
+ return {
64
+ body: {
65
+ ...body,
66
+ ...mutationOptions,
67
+ ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
68
+ },
69
+ send: { config, resendLost: idempotencyKey !== undefined },
70
+ };
71
+ };
46
72
  const datasetMutationPath = (datasetRef) => {
47
73
  const slug = datasetRef.trim();
48
74
  if (!slug) {
@@ -61,7 +87,7 @@ const idMutationBody = (operation, rowIds) => ({
61
87
  operation,
62
88
  row_ids: datasetRowIdsForRequest(rowIds),
63
89
  });
64
- const sqlBody = (sql, options) => {
90
+ const sqlBody = (sql, options, config, keys) => {
65
91
  if (typeof sql !== "string" || sql.trim() === "") {
66
92
  throw new UruAppRuntimeError("SQL statement is required.", {
67
93
  body: sql,
@@ -89,6 +115,14 @@ const sqlBody = (sql, options) => {
89
115
  if (options.timeoutMs !== undefined) {
90
116
  body.timeout_ms = options.timeoutMs;
91
117
  }
118
+ const idempotencyKey = options.idempotencyKey !== undefined && options.idempotencyKey !== ""
119
+ ? options.idempotencyKey
120
+ : config.defaultIdempotencyKeys
121
+ ? keys.next("dataset-sql", "")
122
+ : undefined;
123
+ if (idempotencyKey !== undefined) {
124
+ body.idempotency_key = idempotencyKey;
125
+ }
92
126
  return body;
93
127
  };
94
128
  const createQueryRowsInvoker = (app) => {
@@ -101,44 +135,63 @@ const createQueryRowsInvoker = (app) => {
101
135
  }
102
136
  return queryRows;
103
137
  };
104
- const createRowMutationInvoker = (options) => {
138
+ const createRowMutationInvoker = (options, config, keys) => {
105
139
  async function mutate(datasetRef, rows, decodeResult, mutationOptions) {
106
- const body = { ...upsertBody(rows), ...mutationOptions };
107
140
  const path = datasetMutationPath(datasetRef);
141
+ const { body, send } = keyedMutationBody(upsertBody(rows), mutationOptions, config, keys, datasetRef);
108
142
  if (decodeResult === undefined) {
109
- return await postProviderDatasetWrite(options, path, body);
143
+ return await postProviderDatasetWrite(options, path, body, send);
110
144
  }
111
- return await postProviderDatasetWriteDecoded(options, path, body, decodeResult);
145
+ return await postProviderDatasetWriteDecoded(options, path, body, send, decodeResult);
112
146
  }
113
147
  return mutate;
114
148
  };
115
- const createIdMutationInvoker = (options, operation) => {
149
+ const createRowViewMutationInvoker = (options, config, keys) => {
150
+ async function mutate(datasetRef, rows, decodeResult, mutationOptions) {
151
+ const path = datasetMutationPath(datasetRef);
152
+ const { body, send } = keyedMutationBody({ operation: "upsertFields", rows: datasetRowsForRequest(rows) }, mutationOptions, config, keys, datasetRef);
153
+ if (decodeResult === undefined) {
154
+ return await postProviderDatasetWrite(options, path, body, send);
155
+ }
156
+ return await postProviderDatasetWriteDecoded(options, path, body, send, decodeResult);
157
+ }
158
+ return mutate;
159
+ };
160
+ const createIdMutationInvoker = (options, config, keys, operation) => {
116
161
  async function mutate(datasetRef, rowIds, decodeResult, mutationOptions) {
117
- const body = { ...idMutationBody(operation, rowIds), ...mutationOptions };
118
162
  const path = datasetMutationPath(datasetRef);
163
+ const { body, send } = keyedMutationBody(idMutationBody(operation, rowIds), mutationOptions, config, keys, datasetRef);
119
164
  if (decodeResult === undefined) {
120
- return await postProviderDatasetWrite(options, path, body);
165
+ return await postProviderDatasetWrite(options, path, body, send);
121
166
  }
122
- return await postProviderDatasetWriteDecoded(options, path, body, decodeResult);
167
+ return await postProviderDatasetWriteDecoded(options, path, body, send, decodeResult);
123
168
  }
124
169
  return mutate;
125
170
  };
126
- const createSqlWriteInvoker = (options) => {
171
+ const createSqlWriteInvoker = (options, config, keys) => {
172
+ // A SQL statement has no stored command to replay, so it is never sent
173
+ // again here. Its key lets the server answer a caller's own second send of
174
+ // the same call with the first result instead of running it twice.
175
+ const send = { config, resendLost: false };
127
176
  async function write(sql, writeOptions, decodeResult) {
128
- const body = sqlBody(sql, writeOptions);
177
+ const body = sqlBody(sql, writeOptions, config, keys);
129
178
  if (decodeResult === undefined) {
130
- return await postProviderDatasetWrite(options, "dataset-sql", body);
179
+ return await postProviderDatasetWrite(options, "dataset-sql", body, send);
131
180
  }
132
- return await postProviderDatasetWriteDecoded(options, "dataset-sql", body, decodeResult);
181
+ return await postProviderDatasetWriteDecoded(options, "dataset-sql", body, send, decodeResult);
133
182
  }
134
183
  return write;
135
184
  };
136
185
  /** Build the Dataset surface hung off a server context. */
137
- export const createDatasetsContext = (app, clientOptions) => ({
138
- deleteRows: createIdMutationInvoker(clientOptions, "delete"),
139
- insertRows: createRowMutationInvoker(clientOptions),
140
- queryRows: createQueryRowsInvoker(app),
141
- restoreRows: createIdMutationInvoker(clientOptions, "restore"),
142
- sqlWrite: createSqlWriteInvoker(clientOptions),
143
- upsertRows: createRowMutationInvoker(clientOptions),
144
- });
186
+ export const createDatasetsContext = (app, clientOptions, keys = RANDOM_CALL_KEYS) => {
187
+ const config = resolveDamperConfig(clientOptions.dampers);
188
+ return {
189
+ deleteRows: createIdMutationInvoker(clientOptions, config, keys, "delete"),
190
+ insertRows: createRowMutationInvoker(clientOptions, config, keys),
191
+ queryRows: createQueryRowsInvoker(app),
192
+ restoreRows: createIdMutationInvoker(clientOptions, config, keys, "restore"),
193
+ sqlWrite: createSqlWriteInvoker(clientOptions, config, keys),
194
+ upsertRows: createRowMutationInvoker(clientOptions, config, keys),
195
+ upsertRowViews: createRowViewMutationInvoker(clientOptions, config, keys),
196
+ };
197
+ };
package/dist/errors.d.ts CHANGED
@@ -5,14 +5,21 @@
5
5
  * the public barrel. `index.ts` re-exports it, because it is part of the
6
6
  * published API: a caller has to be able to `instanceof` it.
7
7
  */
8
+ export declare const approvedRuntimeFailureCode: (value: unknown) => string | null;
8
9
  /** Thrown for every Uru app runtime failure: transport, protocol and binding. */
9
10
  export declare class UruAppRuntimeError extends Error {
10
11
  /** HTTP status of the failed call, or `0` when the failure was local. */
11
12
  readonly status: number;
12
13
  /** Parsed response body when the server sent one, otherwise `null`. */
13
14
  readonly body: unknown;
15
+ /** A platform-owned failure code, when the server approved it. */
16
+ readonly code: string | null;
17
+ /** A safe server retry hint, in seconds, when one was supplied. */
18
+ readonly retryAfterSeconds: number | null;
14
19
  constructor(message: string, details: {
15
20
  status: number;
16
21
  body: unknown;
22
+ code?: unknown;
23
+ retryAfterSeconds?: unknown;
17
24
  });
18
25
  }
package/dist/errors.js CHANGED
@@ -5,16 +5,207 @@
5
5
  * the public barrel. `index.ts` re-exports it, because it is part of the
6
6
  * published API: a caller has to be able to `instanceof` it.
7
7
  */
8
+ /** Only platform-owned codes may cross the SDK error boundary. */
9
+ const SAFE_RUNTIME_FAILURE_CODES = new Set([
10
+ "artifact_tool_caller_identity_required",
11
+ "invalid_wrapper_tool_name",
12
+ "runtime_identity_missing",
13
+ "policy_receipt_handoff_invalid",
14
+ "mcp_proxy_not_configured",
15
+ "missing_api_key",
16
+ "dataset_frozen_gem_release_unverified",
17
+ "dataset_frozen_gem_compatibility_disabled",
18
+ "timeout",
19
+ "transport_error",
20
+ "connection_unavailable",
21
+ "artifact_tool_receipt_unavailable",
22
+ "artifact_tool_attempt_unavailable",
23
+ "tool_result_content_unavailable",
24
+ "tool_parameters_content_unavailable",
25
+ "artifact_tool_refresh_failed",
26
+ "tool_admission_unavailable",
27
+ "tool_gateway_denied",
28
+ "app_runtime_failed",
29
+ "artifact_proxy_failed",
30
+ "artifact_rate_limited",
31
+ "rate_limited",
32
+ "artifact_tool_access_invalid",
33
+ "artifact_tool_admission_identity_invalid",
34
+ "artifact_tool_admission_limited",
35
+ "artifact_tool_admission_unavailable",
36
+ "artifact_tool_authority_identity_invalid",
37
+ "artifact_tool_binding_identity_mismatch",
38
+ "artifact_tool_binding_not_visible",
39
+ "artifact_tool_cache_refresh_in_progress",
40
+ "artifact_tool_circuit_open",
41
+ "artifact_tool_execution_cancelled",
42
+ "artifact_tool_execution_failed",
43
+ "artifact_tool_execution_pending",
44
+ "artifact_tool_pre_dispatch_failed",
45
+ "artifact_tool_provider_outcome_unknown",
46
+ "artifact_tool_terminalization_unavailable",
47
+ "job_provider_gateway_unavailable",
48
+ "job_machine_admission_invalid",
49
+ "job_runtime_image_base_unavailable",
50
+ "job_runtime_image_pin_unavailable",
51
+ "job_runtime_image_pin_mismatch",
52
+ "job_machine_image_mismatch",
53
+ "job_machine_capacity_unavailable",
54
+ "job_machine_app_unavailable",
55
+ "job_machine_network_unavailable",
56
+ "job_machine_proxy_unavailable",
57
+ "job_machine_revocation_state_unavailable",
58
+ "job_runtime_image_delivery_failed",
59
+ "job_machine_isolation_unavailable",
60
+ "job_secret_environment_invalid",
61
+ "job_secret_environment_incomplete",
62
+ "job_machine_lease_expired",
63
+ "job_machine_request_failed",
64
+ "job_machine_list_invalid",
65
+ "job_machine_identity_ambiguous",
66
+ "job_machine_identity_mismatch",
67
+ "job_machine_launch_fence_lost",
68
+ "execution_failed",
69
+ "execution_outcome_unknown",
70
+ "historical_result_unavailable",
71
+ "job_canceled",
72
+ "job_cleanup_failed",
73
+ "job_completion_not_accepted",
74
+ "job_handler_failed",
75
+ "job_hard_deadline",
76
+ "job_machine_start_failed",
77
+ "job_machine_stopped",
78
+ "job_output_invalid",
79
+ "job_prepare_failed",
80
+ "job_report_failed",
81
+ "job_revoked",
82
+ "job_runtime_failed",
83
+ "legacy_tool_contract_disabled",
84
+ "program_job_attach_rejected",
85
+ "program_job_capacity_exceeded",
86
+ "program_job_owner_missing",
87
+ "program_job_spending_check_failed",
88
+ "program_job_spending_limit",
89
+ "provider_credential_rejected",
90
+ "provider_failed",
91
+ "provider_invalid",
92
+ "provider_not_connected",
93
+ "provider_rate_limited",
94
+ "provider_rejected",
95
+ "provider_required",
96
+ "provider_timeout",
97
+ "provider_transport_failed",
98
+ "provider_unavailable",
99
+ "public_tool_budget_limited",
100
+ "public_tool_budget_unavailable",
101
+ "result_limit",
102
+ "runtime_capability_unsupported",
103
+ "runtime_unavailable",
104
+ "tool_execution_failed",
105
+ "tool_timeout",
106
+ "tool_transport_failed",
107
+ "usage_limit_reached",
108
+ "usage_limit_unavailable",
109
+ ]);
110
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
111
+ const safeRecordValue = (record, field) => {
112
+ if (record === null)
113
+ return undefined;
114
+ try {
115
+ return record[field];
116
+ }
117
+ catch {
118
+ return undefined;
119
+ }
120
+ };
121
+ const MAX_RETRY_AFTER_SECONDS = (Number.MAX_SAFE_INTEGER - 1) / 1000;
122
+ export const approvedRuntimeFailureCode = (value) => typeof value === "string" && SAFE_RUNTIME_FAILURE_CODES.has(value)
123
+ ? value
124
+ : null;
125
+ const codeFromBody = (body) => {
126
+ if (!isRecord(body))
127
+ return null;
128
+ const errorValue = safeRecordValue(body, "error");
129
+ const error = isRecord(errorValue) ? errorValue : null;
130
+ const bodyDetailsValue = safeRecordValue(body, "details");
131
+ const bodyDetails = isRecord(bodyDetailsValue) ? bodyDetailsValue : null;
132
+ const errorDetailsValue = safeRecordValue(error, "details");
133
+ const errorDetails = isRecord(errorDetailsValue) ? errorDetailsValue : null;
134
+ return (approvedRuntimeFailureCode(safeRecordValue(error, "code")) ??
135
+ approvedRuntimeFailureCode(safeRecordValue(body, "code")) ??
136
+ approvedRuntimeFailureCode(safeRecordValue(errorDetails, "code")) ??
137
+ approvedRuntimeFailureCode(safeRecordValue(bodyDetails, "code")));
138
+ };
139
+ const positiveRetryAfterSeconds = (value) => {
140
+ const seconds = typeof value === "number"
141
+ ? value
142
+ : typeof value === "string" && value.trim() !== ""
143
+ ? Number(value)
144
+ : NaN;
145
+ return Number.isFinite(seconds) && seconds > 0 && seconds <= MAX_RETRY_AFTER_SECONDS
146
+ ? seconds
147
+ : null;
148
+ };
149
+ const retryAfterFromBody = (body) => {
150
+ if (!isRecord(body))
151
+ return null;
152
+ const errorValue = safeRecordValue(body, "error");
153
+ const error = isRecord(errorValue) ? errorValue : null;
154
+ const bodyDetailsValue = safeRecordValue(body, "details");
155
+ const bodyDetails = isRecord(bodyDetailsValue) ? bodyDetailsValue : null;
156
+ const errorDetailsValue = safeRecordValue(error, "details");
157
+ const errorDetails = isRecord(errorDetailsValue) ? errorDetailsValue : null;
158
+ const candidates = [
159
+ safeRecordValue(body, "retryAfterSeconds"),
160
+ safeRecordValue(body, "retry_after_seconds"),
161
+ safeRecordValue(error, "retryAfterSeconds"),
162
+ safeRecordValue(error, "retry_after_seconds"),
163
+ safeRecordValue(errorDetails, "retryAfterSeconds"),
164
+ safeRecordValue(errorDetails, "retry_after_seconds"),
165
+ safeRecordValue(bodyDetails, "retryAfterSeconds"),
166
+ safeRecordValue(bodyDetails, "retry_after_seconds"),
167
+ ];
168
+ for (const candidate of candidates) {
169
+ const seconds = positiveRetryAfterSeconds(candidate);
170
+ if (seconds !== null)
171
+ return seconds;
172
+ }
173
+ const millisecondCandidates = [
174
+ safeRecordValue(body, "retryAfterMs"),
175
+ safeRecordValue(body, "retry_after_ms"),
176
+ safeRecordValue(error, "retryAfterMs"),
177
+ safeRecordValue(error, "retry_after_ms"),
178
+ safeRecordValue(errorDetails, "retryAfterMs"),
179
+ safeRecordValue(errorDetails, "retry_after_ms"),
180
+ safeRecordValue(bodyDetails, "retryAfterMs"),
181
+ safeRecordValue(bodyDetails, "retry_after_ms"),
182
+ ];
183
+ for (const candidate of millisecondCandidates) {
184
+ const milliseconds = positiveRetryAfterSeconds(candidate);
185
+ if (milliseconds !== null)
186
+ return milliseconds / 1000;
187
+ }
188
+ return null;
189
+ };
8
190
  /** Thrown for every Uru app runtime failure: transport, protocol and binding. */
9
191
  export class UruAppRuntimeError extends Error {
10
192
  /** HTTP status of the failed call, or `0` when the failure was local. */
11
193
  status;
12
194
  /** Parsed response body when the server sent one, otherwise `null`. */
13
195
  body;
196
+ /** A platform-owned failure code, when the server approved it. */
197
+ code;
198
+ /** A safe server retry hint, in seconds, when one was supplied. */
199
+ retryAfterSeconds;
14
200
  constructor(message, details) {
15
201
  super(message);
16
202
  this.name = "UruAppRuntimeError";
17
203
  this.status = details.status;
18
204
  this.body = details.body;
205
+ this.code =
206
+ approvedRuntimeFailureCode(details.code) ?? codeFromBody(details.body);
207
+ this.retryAfterSeconds =
208
+ positiveRetryAfterSeconds(details.retryAfterSeconds) ??
209
+ retryAfterFromBody(details.body);
19
210
  }
20
211
  }