@uru-intelligence/app 2.1.4 → 2.1.6

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.d.ts CHANGED
@@ -44,6 +44,17 @@ export declare const computeRateLimitBackoffMs: (args: {
44
44
  baseDelayMs: number;
45
45
  maxDelayMs: number;
46
46
  }) => number;
47
+ /**
48
+ * Compute a rate-limit wait. A server Retry-After is authoritative, so this
49
+ * path does not shorten it to the normal fallback backoff cap. The shared
50
+ * request signal still bounds the wait.
51
+ */
52
+ export declare const computeRateLimitRetryDelayMs: (args: {
53
+ attempt: number;
54
+ retryAfterSeconds: number | null | undefined;
55
+ baseDelayMs: number;
56
+ maxDelayMs: number;
57
+ }) => number;
47
58
  /**
48
59
  * Parse a retry-after hint (seconds) from a 429 response's `Retry-After` header
49
60
  * and/or a `retryAfterSeconds` field in the parsed owned HTTP body. Prefers the header
@@ -54,6 +65,8 @@ export declare const parseRetryAfterSeconds: (args: {
54
65
  header: string | null | undefined;
55
66
  body: unknown;
56
67
  }) => number | null;
68
+ /** Read the owned retry decision without inspecting provider-authored text. */
69
+ export declare const parseRetryable: (body: unknown) => boolean | undefined;
57
70
  /**
58
71
  * Per-client mutable state for the forceRefresh throttle: the last epoch-ms at
59
72
  * which a forceRefresh was HONORED for each capability key. Created once per
package/dist/dampers.js CHANGED
@@ -1,5 +1,17 @@
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;
4
16
  const DEFAULT_RATE_LIMIT_BASE_DELAY_MS = 500;
5
17
  const DEFAULT_RATE_LIMIT_MAX_DELAY_MS = 10_000;
@@ -11,6 +23,9 @@ const nonNegativeOr = (value, fallback) => typeof value === "number" && Number.i
11
23
  ? value
12
24
  : fallback;
13
25
  const defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
26
+ let remaining = Number.isFinite(ms)
27
+ ? Math.max(0, Math.min(ms, Number.MAX_SAFE_INTEGER - 1))
28
+ : 0;
14
29
  let timeout;
15
30
  const abort = () => {
16
31
  cleanup();
@@ -18,22 +33,34 @@ const defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
18
33
  new DOMException("The operation was aborted.", "AbortError"));
19
34
  };
20
35
  const cleanup = () => {
21
- clearTimeout(timeout);
36
+ if (timeout !== undefined)
37
+ clearTimeout(timeout);
22
38
  signal?.removeEventListener("abort", abort);
23
39
  };
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;
40
+ const schedule = () => {
41
+ if (remaining <= 0) {
42
+ cleanup();
43
+ resolve();
44
+ return;
45
+ }
46
+ const chunk = Math.min(remaining, MAX_TIMER_DELAY_MS);
47
+ timeout = setTimeout(() => {
48
+ remaining -= chunk;
49
+ schedule();
50
+ }, chunk);
51
+ };
52
+ if (signal !== undefined) {
53
+ if (signal.aborted) {
54
+ abort();
55
+ return;
56
+ }
57
+ signal.addEventListener("abort", abort, { once: true });
58
+ if (signal.aborted) {
59
+ abort();
60
+ return;
61
+ }
33
62
  }
34
- signal.addEventListener("abort", abort, { once: true });
35
- if (signal.aborted)
36
- abort();
63
+ schedule();
37
64
  });
38
65
  /** Fold caller overrides into a fully-defaulted {@link ResolvedDamperConfig}. */
39
66
  export const resolveDamperConfig = (options) => ({
@@ -67,6 +94,24 @@ export const computeRateLimitBackoffMs = (args) => {
67
94
  const exponential = baseDelayMs * 2 ** Math.max(0, attempt);
68
95
  return Math.min(maxDelayMs, exponential);
69
96
  };
97
+ /**
98
+ * Compute a rate-limit wait. A server Retry-After is authoritative, so this
99
+ * path does not shorten it to the normal fallback backoff cap. The shared
100
+ * request signal still bounds the wait.
101
+ */
102
+ export const computeRateLimitRetryDelayMs = (args) => {
103
+ if (typeof args.retryAfterSeconds === "number" &&
104
+ Number.isFinite(args.retryAfterSeconds) &&
105
+ args.retryAfterSeconds > 0) {
106
+ return Math.ceil(args.retryAfterSeconds * 1000);
107
+ }
108
+ return computeRateLimitBackoffMs({
109
+ attempt: args.attempt,
110
+ baseDelayMs: args.baseDelayMs,
111
+ maxDelayMs: args.maxDelayMs,
112
+ retryAfterSeconds: null,
113
+ });
114
+ };
70
115
  /**
71
116
  * Parse a retry-after hint (seconds) from a 429 response's `Retry-After` header
72
117
  * and/or a `retryAfterSeconds` field in the parsed owned HTTP body. Prefers the header
@@ -77,19 +122,72 @@ export const parseRetryAfterSeconds = (args) => {
77
122
  const headerRaw = (args.header ?? "").trim();
78
123
  if (headerRaw !== "") {
79
124
  const headerSeconds = Number(headerRaw);
80
- if (Number.isFinite(headerSeconds) && headerSeconds > 0) {
125
+ if (Number.isFinite(headerSeconds) &&
126
+ headerSeconds > 0 &&
127
+ headerSeconds <= MAX_RETRY_AFTER_SECONDS) {
81
128
  return headerSeconds;
82
129
  }
83
130
  }
131
+ const positiveSeconds = (value) => {
132
+ const seconds = typeof value === "number"
133
+ ? value
134
+ : typeof value === "string" && value.trim() !== ""
135
+ ? Number(value)
136
+ : NaN;
137
+ return Number.isFinite(seconds) && seconds > 0 && seconds <= MAX_RETRY_AFTER_SECONDS
138
+ ? seconds
139
+ : null;
140
+ };
141
+ const fromRecord = (record) => {
142
+ const direct = positiveSeconds(safeRecordValue(record, "retryAfterSeconds") ??
143
+ safeRecordValue(record, "retry_after_seconds"));
144
+ if (direct !== null)
145
+ return direct;
146
+ const retryAfterMs = positiveSeconds(safeRecordValue(record, "retryAfterMs") ??
147
+ safeRecordValue(record, "retry_after_ms"));
148
+ if (retryAfterMs !== null)
149
+ return retryAfterMs / 1000;
150
+ const detailsValue = safeRecordValue(record, "details");
151
+ const details = isRecord(detailsValue) ? detailsValue : null;
152
+ if (details !== null) {
153
+ const detailSeconds = positiveSeconds(safeRecordValue(details, "retryAfterSeconds") ??
154
+ safeRecordValue(details, "retry_after_seconds"));
155
+ if (detailSeconds !== null)
156
+ return detailSeconds;
157
+ const detailMs = positiveSeconds(safeRecordValue(details, "retryAfterMs") ??
158
+ safeRecordValue(details, "retry_after_ms"));
159
+ if (detailMs !== null)
160
+ return detailMs / 1000;
161
+ }
162
+ return null;
163
+ };
84
164
  if (isRecord(args.body)) {
85
- const candidate = args.body.retryAfterSeconds;
86
- const seconds = Number(candidate);
87
- if (Number.isFinite(seconds) && seconds > 0) {
165
+ const seconds = fromRecord(args.body);
166
+ if (seconds !== null) {
88
167
  return seconds;
89
168
  }
169
+ const errorValue = safeRecordValue(args.body, "error");
170
+ const error = isRecord(errorValue) ? errorValue : null;
171
+ if (error !== null)
172
+ return fromRecord(error);
90
173
  }
91
174
  return null;
92
175
  };
176
+ /** Read the owned retry decision without inspecting provider-authored text. */
177
+ export const parseRetryable = (body) => {
178
+ if (!isRecord(body))
179
+ return undefined;
180
+ const errorValue = safeRecordValue(body, "error");
181
+ const error = isRecord(errorValue) ? errorValue : null;
182
+ const errorDetailsValue = safeRecordValue(error, "details");
183
+ const errorDetails = isRecord(errorDetailsValue) ? errorDetailsValue : null;
184
+ for (const record of [error, body, errorDetails]) {
185
+ const retryable = safeRecordValue(record, "retryable");
186
+ if (typeof retryable === "boolean")
187
+ return retryable;
188
+ }
189
+ return undefined;
190
+ };
93
191
  /**
94
192
  * Per-client mutable state for the forceRefresh throttle: the last epoch-ms at
95
193
  * which a forceRefresh was HONORED for each capability key. Created once per
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,206 @@
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
+ "runtime_capability_unsupported",
102
+ "runtime_unavailable",
103
+ "tool_execution_failed",
104
+ "tool_timeout",
105
+ "tool_transport_failed",
106
+ "usage_limit_reached",
107
+ "usage_limit_unavailable",
108
+ ]);
109
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
110
+ const safeRecordValue = (record, field) => {
111
+ if (record === null)
112
+ return undefined;
113
+ try {
114
+ return record[field];
115
+ }
116
+ catch {
117
+ return undefined;
118
+ }
119
+ };
120
+ const MAX_RETRY_AFTER_SECONDS = (Number.MAX_SAFE_INTEGER - 1) / 1000;
121
+ export const approvedRuntimeFailureCode = (value) => typeof value === "string" && SAFE_RUNTIME_FAILURE_CODES.has(value)
122
+ ? value
123
+ : null;
124
+ const codeFromBody = (body) => {
125
+ if (!isRecord(body))
126
+ return null;
127
+ const errorValue = safeRecordValue(body, "error");
128
+ const error = isRecord(errorValue) ? errorValue : null;
129
+ const bodyDetailsValue = safeRecordValue(body, "details");
130
+ const bodyDetails = isRecord(bodyDetailsValue) ? bodyDetailsValue : null;
131
+ const errorDetailsValue = safeRecordValue(error, "details");
132
+ const errorDetails = isRecord(errorDetailsValue) ? errorDetailsValue : null;
133
+ return (approvedRuntimeFailureCode(safeRecordValue(error, "code")) ??
134
+ approvedRuntimeFailureCode(safeRecordValue(body, "code")) ??
135
+ approvedRuntimeFailureCode(safeRecordValue(errorDetails, "code")) ??
136
+ approvedRuntimeFailureCode(safeRecordValue(bodyDetails, "code")));
137
+ };
138
+ const positiveRetryAfterSeconds = (value) => {
139
+ const seconds = typeof value === "number"
140
+ ? value
141
+ : typeof value === "string" && value.trim() !== ""
142
+ ? Number(value)
143
+ : NaN;
144
+ return Number.isFinite(seconds) && seconds > 0 && seconds <= MAX_RETRY_AFTER_SECONDS
145
+ ? seconds
146
+ : null;
147
+ };
148
+ const retryAfterFromBody = (body) => {
149
+ if (!isRecord(body))
150
+ return null;
151
+ const errorValue = safeRecordValue(body, "error");
152
+ const error = isRecord(errorValue) ? errorValue : null;
153
+ const bodyDetailsValue = safeRecordValue(body, "details");
154
+ const bodyDetails = isRecord(bodyDetailsValue) ? bodyDetailsValue : null;
155
+ const errorDetailsValue = safeRecordValue(error, "details");
156
+ const errorDetails = isRecord(errorDetailsValue) ? errorDetailsValue : null;
157
+ const candidates = [
158
+ safeRecordValue(body, "retryAfterSeconds"),
159
+ safeRecordValue(body, "retry_after_seconds"),
160
+ safeRecordValue(error, "retryAfterSeconds"),
161
+ safeRecordValue(error, "retry_after_seconds"),
162
+ safeRecordValue(errorDetails, "retryAfterSeconds"),
163
+ safeRecordValue(errorDetails, "retry_after_seconds"),
164
+ safeRecordValue(bodyDetails, "retryAfterSeconds"),
165
+ safeRecordValue(bodyDetails, "retry_after_seconds"),
166
+ ];
167
+ for (const candidate of candidates) {
168
+ const seconds = positiveRetryAfterSeconds(candidate);
169
+ if (seconds !== null)
170
+ return seconds;
171
+ }
172
+ const millisecondCandidates = [
173
+ safeRecordValue(body, "retryAfterMs"),
174
+ safeRecordValue(body, "retry_after_ms"),
175
+ safeRecordValue(error, "retryAfterMs"),
176
+ safeRecordValue(error, "retry_after_ms"),
177
+ safeRecordValue(errorDetails, "retryAfterMs"),
178
+ safeRecordValue(errorDetails, "retry_after_ms"),
179
+ safeRecordValue(bodyDetails, "retryAfterMs"),
180
+ safeRecordValue(bodyDetails, "retry_after_ms"),
181
+ ];
182
+ for (const candidate of millisecondCandidates) {
183
+ const milliseconds = positiveRetryAfterSeconds(candidate);
184
+ if (milliseconds !== null)
185
+ return milliseconds / 1000;
186
+ }
187
+ return null;
188
+ };
8
189
  /** Thrown for every Uru app runtime failure: transport, protocol and binding. */
9
190
  export class UruAppRuntimeError extends Error {
10
191
  /** HTTP status of the failed call, or `0` when the failure was local. */
11
192
  status;
12
193
  /** Parsed response body when the server sent one, otherwise `null`. */
13
194
  body;
195
+ /** A platform-owned failure code, when the server approved it. */
196
+ code;
197
+ /** A safe server retry hint, in seconds, when one was supplied. */
198
+ retryAfterSeconds;
14
199
  constructor(message, details) {
15
200
  super(message);
16
201
  this.name = "UruAppRuntimeError";
17
202
  this.status = details.status;
18
203
  this.body = details.body;
204
+ this.code =
205
+ approvedRuntimeFailureCode(details.code) ?? codeFromBody(details.body);
206
+ this.retryAfterSeconds =
207
+ positiveRetryAfterSeconds(details.retryAfterSeconds) ??
208
+ retryAfterFromBody(details.body);
19
209
  }
20
210
  }
package/dist/index.js CHANGED
@@ -86,7 +86,7 @@ export const createUruAppRuntimeClient = (options) => {
86
86
  cancelJob: createCancelJobInvoker(options),
87
87
  endpoint: createCapabilityInvoker(options, damper, "endpoint"),
88
88
  job: createCapabilityInvoker(options, damper, "job"),
89
- jobStatus: createJobStatusInvoker(options),
89
+ jobStatus: createJobStatusInvoker(options, damper),
90
90
  query: createCapabilityInvoker(options, damper, "query"),
91
91
  serverFunction: createCapabilityInvoker(options, damper, "server_function"),
92
92
  };
@@ -2,6 +2,6 @@ import type { DamperRuntime } from "./transport.js";
2
2
  import type { CreateUruAppRuntimeClientOptions, UruActionInvoker, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruCapabilityInvoker, UruCancelJobInvoker, UruJobStatusInvoker } from "./types.js";
3
3
  /** Overloads expose a typed result only when the transport runs its decoder. */
4
4
  export declare const createCapabilityInvoker: (options: CreateUruAppRuntimeClientOptions, damper: DamperRuntime, capabilityType: UruAppRuntimeCapabilityType) => UruCapabilityInvoker;
5
- export declare const createJobStatusInvoker: (options: CreateUruAppRuntimeClientOptions) => UruJobStatusInvoker;
5
+ export declare const createJobStatusInvoker: (options: CreateUruAppRuntimeClientOptions, damper: DamperRuntime) => UruJobStatusInvoker;
6
6
  export declare const createCancelJobInvoker: (options: CreateUruAppRuntimeClientOptions) => UruCancelJobInvoker;
7
7
  export declare const createActionInvoker: (app: UruAppRuntimeClient) => UruActionInvoker;
@@ -7,9 +7,9 @@ export const createCapabilityInvoker = (options, damper, capabilityType) => {
7
7
  }
8
8
  return invoke;
9
9
  };
10
- export const createJobStatusInvoker = (options) => {
10
+ export const createJobStatusInvoker = (options, damper) => {
11
11
  async function status(executionId, invocationOptions) {
12
- return await getAppRuntimeJobStatus(options, executionId, invocationOptions);
12
+ return await getAppRuntimeJobStatus(options, executionId, invocationOptions, damper);
13
13
  }
14
14
  return status;
15
15
  };
@@ -19,3 +19,16 @@ export interface RuntimeFetchResult {
19
19
  response: Response;
20
20
  }
21
21
  export declare const fetchInvocation: (args: InvocationFetchArguments, attempt?: number) => Promise<RuntimeFetchResult>;
22
+ export interface JobStatusFetchArguments {
23
+ damper: DamperRuntime;
24
+ deploymentId: string;
25
+ emit: (event: UruAppRuntimeEvent) => void;
26
+ executionId: string;
27
+ headers: Headers;
28
+ requestId: string;
29
+ runtimeFetch: RuntimeFetch;
30
+ signal?: AbortSignal;
31
+ url: string;
32
+ }
33
+ /** Fetch one accepted execution's status with bounded, same-identity retries. */
34
+ export declare const fetchJobStatus: (args: JobStatusFetchArguments, attempt?: number) => Promise<RuntimeFetchResult>;
@@ -1,4 +1,4 @@
1
- import { computeRateLimitBackoffMs, parseRetryAfterSeconds, } from "./dampers.js";
1
+ import { computeRateLimitRetryDelayMs, parseRetryable, parseRetryAfterSeconds, } from "./dampers.js";
2
2
  import { awaitWithAbort, readRuntimeResponseBody, } from "./transport-deadline.js";
3
3
  export const fetchInvocation = async (args, attempt = 0) => {
4
4
  // Read out of `args` first. `args.runtimeFetch(...)` is a METHOD call, so it
@@ -16,11 +16,13 @@ export const fetchInvocation = async (args, attempt = 0) => {
16
16
  });
17
17
  }), args.signal);
18
18
  const body = await readRuntimeResponseBody(response, args.signal);
19
- const shouldRetry = response.status === 429 && attempt < args.damper.config.maxRateLimitRetries;
19
+ const shouldRetry = response.status === 429 &&
20
+ parseRetryable(body) !== false &&
21
+ attempt < args.damper.config.maxRateLimitRetries;
20
22
  if (!shouldRetry) {
21
23
  return { body, response };
22
24
  }
23
- const delayMs = computeRateLimitBackoffMs({
25
+ const delayMs = computeRateLimitRetryDelayMs({
24
26
  attempt,
25
27
  baseDelayMs: args.damper.config.rateLimitBaseDelayMs,
26
28
  maxDelayMs: args.damper.config.rateLimitMaxDelayMs,
@@ -46,3 +48,46 @@ export const fetchInvocation = async (args, attempt = 0) => {
46
48
  await awaitWithAbort(sleepPromise, args.signal);
47
49
  return await fetchInvocation(args, attempt + 1);
48
50
  };
51
+ /** Fetch one accepted execution's status with bounded, same-identity retries. */
52
+ export const fetchJobStatus = async (args, attempt = 0) => {
53
+ const { runtimeFetch } = args;
54
+ args.signal?.throwIfAborted();
55
+ const response = await awaitWithAbort(Promise.resolve().then(() => {
56
+ args.signal?.throwIfAborted();
57
+ return runtimeFetch(args.url, {
58
+ headers: args.headers,
59
+ method: "GET",
60
+ ...(args.signal === undefined ? {} : { signal: args.signal }),
61
+ });
62
+ }), args.signal);
63
+ const body = await readRuntimeResponseBody(response, args.signal);
64
+ const shouldRetry = response.status === 429 &&
65
+ parseRetryable(body) !== false &&
66
+ attempt < args.damper.config.maxRateLimitRetries;
67
+ if (!shouldRetry) {
68
+ return { body, response };
69
+ }
70
+ const retryAfterSeconds = parseRetryAfterSeconds({
71
+ body,
72
+ header: response.headers.get("retry-after"),
73
+ });
74
+ const delayMs = computeRateLimitRetryDelayMs({
75
+ attempt,
76
+ baseDelayMs: args.damper.config.rateLimitBaseDelayMs,
77
+ maxDelayMs: args.damper.config.rateLimitMaxDelayMs,
78
+ retryAfterSeconds,
79
+ });
80
+ args.signal?.throwIfAborted();
81
+ args.emit({
82
+ capabilityName: "",
83
+ capabilityType: "job",
84
+ deploymentId: args.deploymentId,
85
+ executionId: args.executionId,
86
+ requestId: args.requestId,
87
+ retryAfterSeconds: retryAfterSeconds ?? Math.ceil(delayMs / 1000),
88
+ state: "rate_limited",
89
+ type: "status",
90
+ });
91
+ await awaitWithAbort(args.damper.config.sleep(delayMs, args.signal), args.signal);
92
+ return await fetchJobStatus(args, attempt + 1);
93
+ };
@@ -56,6 +56,6 @@ export declare const appRuntimeInvocationResponseFromHttp: (value: unknown, deco
56
56
  /** Map the owned camelCase job-status envelope without copying unknown fields. */
57
57
  export declare const appRuntimeExecutionStatusFromHttp: (value: unknown, decodeResult?: UruResultDecoder<unknown>) => AppRuntimeExecutionHttpResponse;
58
58
  export declare const invokeAppRuntime: (options: CreateUruAppRuntimeClientOptions, damper: DamperRuntime, capabilityType: UruAppRuntimeCapabilityType, name: string, input?: unknown, invocationOptions?: UruAppRuntimeInvocationOptions) => Promise<UruAppRuntimeInvocationResponse>;
59
- export declare const getAppRuntimeJobStatus: (options: CreateUruAppRuntimeClientOptions, executionId: string, invocationOptions?: UruAppRuntimeInvocationOptions) => Promise<UruAppRuntimeExecutionStatus>;
59
+ export declare const getAppRuntimeJobStatus: (options: CreateUruAppRuntimeClientOptions, executionId: string, invocationOptions: UruAppRuntimeInvocationOptions | undefined, damper: DamperRuntime) => Promise<UruAppRuntimeExecutionStatus>;
60
60
  export declare const cancelAppRuntimeJob: (options: CreateUruAppRuntimeClientOptions, executionId: string, invocationOptions?: UruAppRuntimeInvocationOptions) => Promise<UruAppRuntimeInvocationResponse>;
61
61
  export {};
package/dist/transport.js CHANGED
@@ -15,94 +15,13 @@
15
15
  * for by exporting four internal helpers from it. Every edge here points at a
16
16
  * module that imports nothing back.
17
17
  */
18
+ import { parseRetryAfterSeconds, } from "./dampers.js";
18
19
  import { runtimeErrorMessage } from "./error-response.js";
19
- import { UruAppRuntimeError } from "./errors.js";
20
+ import { approvedRuntimeFailureCode, UruAppRuntimeError, } from "./errors.js";
20
21
  import { resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
21
22
  import { abortReason, awaitWithAbort, readRuntimeResponseBody, validateRuntimeInvocationOptions, withRuntimeRequestSignal, } from "./transport-deadline.js";
22
- import { fetchInvocation } from "./transport-invocation.js";
23
+ import { fetchInvocation, fetchJobStatus } from "./transport-invocation.js";
23
24
  import { isRuntimeJsonObject } from "./transport-json.js";
24
- /**
25
- * Only platform failure codes from the public Gem failure contract may cross
26
- * this boundary. Provider-defined details stay inside the HTTP response.
27
- */
28
- const SAFE_RUNTIME_FAILURE_CODES = new Set([
29
- "artifact_tool_caller_identity_required",
30
- "invalid_wrapper_tool_name",
31
- "runtime_identity_missing",
32
- "policy_receipt_handoff_invalid",
33
- "mcp_proxy_not_configured",
34
- "missing_api_key",
35
- "dataset_frozen_gem_release_unverified",
36
- "dataset_frozen_gem_compatibility_disabled",
37
- "timeout",
38
- "transport_error",
39
- "connection_unavailable",
40
- "artifact_tool_receipt_unavailable",
41
- "artifact_tool_attempt_unavailable",
42
- "tool_result_content_unavailable",
43
- "tool_parameters_content_unavailable",
44
- "artifact_tool_refresh_failed",
45
- "tool_admission_unavailable",
46
- "tool_gateway_denied",
47
- "app_runtime_failed",
48
- "artifact_proxy_failed",
49
- "artifact_rate_limited",
50
- "artifact_tool_access_invalid",
51
- "artifact_tool_admission_identity_invalid",
52
- "artifact_tool_admission_limited",
53
- "artifact_tool_admission_unavailable",
54
- "artifact_tool_authority_identity_invalid",
55
- "artifact_tool_binding_identity_mismatch",
56
- "artifact_tool_binding_not_visible",
57
- "artifact_tool_cache_refresh_in_progress",
58
- "artifact_tool_circuit_open",
59
- "artifact_tool_execution_cancelled",
60
- "artifact_tool_execution_failed",
61
- "artifact_tool_execution_pending",
62
- "artifact_tool_pre_dispatch_failed",
63
- "artifact_tool_provider_outcome_unknown",
64
- "artifact_tool_terminalization_unavailable",
65
- "execution_failed",
66
- "execution_outcome_unknown",
67
- "historical_result_unavailable",
68
- "job_canceled",
69
- "job_cleanup_failed",
70
- "job_completion_not_accepted",
71
- "job_handler_failed",
72
- "job_hard_deadline",
73
- "job_machine_start_failed",
74
- "job_machine_stopped",
75
- "job_output_invalid",
76
- "job_prepare_failed",
77
- "job_report_failed",
78
- "job_revoked",
79
- "job_runtime_failed",
80
- "legacy_tool_contract_disabled",
81
- "program_job_attach_rejected",
82
- "program_job_capacity_exceeded",
83
- "program_job_owner_missing",
84
- "program_job_spending_check_failed",
85
- "program_job_spending_limit",
86
- "provider_credential_rejected",
87
- "provider_failed",
88
- "provider_invalid",
89
- "provider_not_connected",
90
- "provider_rate_limited",
91
- "provider_rejected",
92
- "provider_required",
93
- "provider_timeout",
94
- "provider_transport_failed",
95
- "provider_unavailable",
96
- "public_tool_budget_limited",
97
- "public_tool_budget_unavailable",
98
- "runtime_capability_unsupported",
99
- "runtime_unavailable",
100
- "tool_execution_failed",
101
- "tool_timeout",
102
- "tool_transport_failed",
103
- "usage_limit_reached",
104
- "usage_limit_unavailable",
105
- ]);
106
25
  const RUNTIME_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
107
26
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
108
27
  const httpRecord = (value, label) => {
@@ -151,9 +70,7 @@ const safeRecordValue = (record, field) => {
151
70
  const optionalApprovedFailureCode = (value) => {
152
71
  if (value === null)
153
72
  return null;
154
- return typeof value === "string" && SAFE_RUNTIME_FAILURE_CODES.has(value)
155
- ? value
156
- : undefined;
73
+ return approvedRuntimeFailureCode(value) ?? undefined;
157
74
  };
158
75
  const optionalRuntimeUuid = (value) => {
159
76
  if (typeof value !== "string")
@@ -584,6 +501,10 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
584
501
  throw new UruAppRuntimeError(message, {
585
502
  body,
586
503
  status: response.status,
504
+ retryAfterSeconds: parseRetryAfterSeconds({
505
+ body,
506
+ header: response.headers.get("retry-after"),
507
+ }),
587
508
  });
588
509
  }
589
510
  const runtimeResponse = appRuntimeInvocationResponseFromHttp(body, invocationOptions?.decodeResult);
@@ -668,7 +589,7 @@ const normalizedExecutionStatus = (status, state) => ({
668
589
  ...(status.statusUrl === undefined ? {} : { statusUrl: status.statusUrl }),
669
590
  ...(status.success === undefined ? {} : { success: status.success }),
670
591
  });
671
- export const getAppRuntimeJobStatus = async (options, executionId, invocationOptions) => {
592
+ export const getAppRuntimeJobStatus = async (options, executionId, invocationOptions, damper) => {
672
593
  const runtimeFetch = resolveRuntimeFetch(options);
673
594
  const identity = jobIdentity(options, executionId);
674
595
  const { deploymentId, executionId: normalizedExecutionId } = identity;
@@ -686,22 +607,17 @@ export const getAppRuntimeJobStatus = async (options, executionId, invocationOpt
686
607
  });
687
608
  const url = jobExecutionUrl(options, identity);
688
609
  const headers = new Headers(await resolveHeaders(options.headers));
689
- const { response, body } = await withRuntimeRequestSignal(invocationOptions, async (signal) => {
690
- if (signal?.aborted === true) {
691
- throw abortReason(signal);
692
- }
693
- const response = await awaitWithAbort(Promise.resolve().then(() => {
694
- if (signal?.aborted === true) {
695
- throw abortReason(signal);
696
- }
697
- return runtimeFetch(url, {
698
- headers,
699
- method: "GET",
700
- ...(signal === undefined ? {} : { signal }),
701
- });
702
- }), signal);
703
- return { body: await readRuntimeResponseBody(response, signal), response };
704
- });
610
+ const { response, body } = await withRuntimeRequestSignal(invocationOptions, async (signal) => await fetchJobStatus({
611
+ damper,
612
+ deploymentId,
613
+ emit: event => emitRuntimeEvent(invocationOptions, event),
614
+ executionId: normalizedExecutionId,
615
+ headers,
616
+ requestId,
617
+ runtimeFetch,
618
+ ...(signal === undefined ? {} : { signal }),
619
+ url,
620
+ }));
705
621
  if (!response.ok && response.status !== 202) {
706
622
  const message = runtimeErrorMessage(body, `Uru app runtime job status failed with HTTP ${response.status}`);
707
623
  emitRuntimeEvent(invocationOptions, {
@@ -721,6 +637,10 @@ export const getAppRuntimeJobStatus = async (options, executionId, invocationOpt
721
637
  throw new UruAppRuntimeError(message, {
722
638
  body,
723
639
  status: response.status,
640
+ retryAfterSeconds: parseRetryAfterSeconds({
641
+ body,
642
+ header: response.headers.get("retry-after"),
643
+ }),
724
644
  });
725
645
  }
726
646
  const statusBody = appRuntimeExecutionStatusFromHttp(body, invocationOptions?.decodeResult);
@@ -785,6 +705,10 @@ export const cancelAppRuntimeJob = async (options, executionId, invocationOption
785
705
  throw new UruAppRuntimeError(message, {
786
706
  body,
787
707
  status: response.status,
708
+ retryAfterSeconds: parseRetryAfterSeconds({
709
+ body,
710
+ header: response.headers.get("retry-after"),
711
+ }),
788
712
  });
789
713
  }
790
714
  const runtimeResponse = appRuntimeInvocationResponseFromHttp(body, invocationOptions?.decodeResult);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uru-intelligence/app",
3
- "version": "2.1.4",
3
+ "version": "2.1.6",
4
4
  "private": false,
5
5
  "description": "Runtime client for Uru Gems: capability calls, Datasets, jobs and secrets",
6
6
  "keywords": [