@uru-intelligence/app 1.0.0 → 2.0.0

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/transport.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * neither exceeds the repo's 1000-line clean-code budget).
7
7
  *
8
8
  * The P2 runaway dampers (default idempotency key, 429 backoff, forceRefresh
9
- * throttle — `docs/plans/gem-runtime-cost-safety-audit.md`) live inline in
9
+ * throttle — the 2026-08 Gem runtime cost-safety audit) live inline in
10
10
  * `invokeAppRuntime` here, composing the pure helpers from `./dampers`.
11
11
  *
12
12
  * Imports the shared URL/error primitives from `./runtime.js` and the
@@ -15,611 +15,664 @@
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 { computeRateLimitBackoffMs, defaultIdempotencyKey, parseRetryAfterSeconds, } from './dampers.js';
19
- import { runtimeErrorMessage } from './errorResponse.js';
20
- import { UruAppRuntimeError } from './errors.js';
21
- import { resolveHeaders, runtimeBasePath, trimTrailingSlash } from './runtime.js';
22
- function isRecord(value) {
23
- return typeof value === 'object' && value !== null && !Array.isArray(value);
24
- }
25
- function httpRecord(value, label) {
18
+ import { computeRateLimitBackoffMs, parseRetryAfterSeconds, } from "./dampers.js";
19
+ import { runtimeErrorMessage } from "./error-response.js";
20
+ import { UruAppRuntimeError } from "./errors.js";
21
+ import { resolveHeaders, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
22
+ import { isRuntimeJsonObject } from "./transport-json.js";
23
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
24
+ const httpRecord = (value, label) => {
26
25
  if (!isRecord(value)) {
27
26
  throw new UruAppRuntimeError(`Invalid ${label} response.`, {
28
- status: 0,
29
27
  body: value,
28
+ status: 0,
30
29
  });
31
30
  }
32
31
  return value;
33
- }
34
- function invalidOwnedField(label, body, field) {
32
+ };
33
+ const invalidOwnedField = (label, body, field) => {
35
34
  throw new UruAppRuntimeError(`Invalid ${label} response field: ${field}.`, {
36
- status: 0,
37
35
  body,
36
+ status: 0,
38
37
  });
39
- }
40
- function requiredString(body, field, label) {
38
+ };
39
+ const requiredString = (body, field, label) => {
41
40
  const value = body[field];
42
- return typeof value === 'string' ? value : invalidOwnedField(label, body, field);
43
- }
44
- function requiredBoolean(body, field, label) {
41
+ return typeof value === "string"
42
+ ? value
43
+ : invalidOwnedField(label, body, field);
44
+ };
45
+ const requiredBoolean = (body, field, label) => {
45
46
  const value = body[field];
46
- return typeof value === 'boolean' ? value : invalidOwnedField(label, body, field);
47
- }
48
- function optionalString(value) {
49
- return typeof value === 'string' ? value : undefined;
50
- }
51
- function optionalNullableString(value) {
52
- return value === null || typeof value === 'string' ? value : undefined;
53
- }
54
- function optionalNullableNumber(value) {
55
- return value === null || (typeof value === 'number' && Number.isFinite(value))
47
+ return typeof value === "boolean"
56
48
  ? value
57
- : undefined;
58
- }
59
- function optionalBoolean(value) {
60
- return typeof value === 'boolean' ? value : undefined;
61
- }
62
- function optionalRecord(value) {
63
- return isRecord(value) ? value : undefined;
64
- }
49
+ : invalidOwnedField(label, body, field);
50
+ };
51
+ const optionalString = (value) => typeof value === "string" ? value : undefined;
52
+ const optionalNullableString = (value) => value === null || typeof value === "string" ? value : undefined;
53
+ const optionalNullableNumber = (value) => value === null || (typeof value === "number" && Number.isFinite(value))
54
+ ? value
55
+ : undefined;
56
+ const optionalBoolean = (value) => typeof value === "boolean" ? value : undefined;
65
57
  /** Map the owned camelCase HTTP envelope without copying unknown fields. */
66
- export function appRuntimeInvocationResponseFromHttp(value) {
67
- const label = 'app runtime invocation';
58
+ export const appRuntimeInvocationResponseFromHttp = (value, decodeResult) => {
59
+ const label = "app runtime invocation";
68
60
  const body = httpRecord(value, label);
69
61
  const output = {
70
- ok: requiredBoolean(body, 'ok', label),
71
- status: requiredString(body, 'status', label),
72
- state: requiredString(body, 'state', label),
73
- deploymentId: requiredString(body, 'deploymentId', label),
74
- capabilityType: requiredString(body, 'capabilityType', label),
75
- capabilityName: requiredString(body, 'capabilityName', label),
76
- pending: requiredBoolean(body, 'pending', label),
62
+ capabilityName: requiredString(body, "capabilityName", label),
63
+ capabilityType: requiredString(body, "capabilityType", label),
64
+ deploymentId: requiredString(body, "deploymentId", label),
65
+ ok: requiredBoolean(body, "ok", label),
66
+ pending: requiredBoolean(body, "pending", label),
67
+ state: requiredString(body, "state", label),
68
+ status: requiredString(body, "status", label),
77
69
  };
78
- if (Object.prototype.hasOwnProperty.call(body, 'result')) {
79
- output.result = body['result'];
80
- }
81
- const executionId = optionalNullableString(body['executionId']);
82
- if (executionId !== undefined)
70
+ if (Object.hasOwn(body, "result")) {
71
+ const { result } = body;
72
+ output.result =
73
+ result === null || decodeResult === undefined
74
+ ? result
75
+ : decodeResult(result);
76
+ }
77
+ const executionId = optionalNullableString(body.executionId);
78
+ if (executionId !== undefined) {
83
79
  output.executionId = executionId;
84
- const diagnostics = optionalRecord(body['diagnostics']);
85
- if (diagnostics !== undefined)
86
- output.diagnostics = diagnostics;
80
+ }
81
+ if (Object.hasOwn(body, "diagnostics")) {
82
+ const { diagnostics } = body;
83
+ if (isRuntimeJsonObject(diagnostics)) {
84
+ output.diagnostics = diagnostics;
85
+ }
86
+ else {
87
+ invalidOwnedField(label, body, "diagnostics");
88
+ }
89
+ }
87
90
  return output;
88
- }
91
+ };
89
92
  /** Map the owned camelCase job-status envelope without copying unknown fields. */
90
- export function appRuntimeExecutionStatusFromHttp(value) {
91
- const label = 'app runtime job status';
93
+ export const appRuntimeExecutionStatusFromHttp = (value, decodeResult) => {
94
+ const label = "app runtime job status";
92
95
  const body = httpRecord(value, label);
93
96
  const output = {
94
- success: requiredBoolean(body, 'success', label),
95
- executionId: requiredString(body, 'executionId', label),
97
+ executionId: requiredString(body, "executionId", label),
98
+ success: requiredBoolean(body, "success", label),
96
99
  };
97
- const pending = optionalBoolean(body['pending']);
98
- if (pending !== undefined)
100
+ const pending = optionalBoolean(body.pending);
101
+ if (pending !== undefined) {
99
102
  output.pending = pending;
100
- if (Object.prototype.hasOwnProperty.call(body, 'result')) {
101
- output.result = body['result'];
102
103
  }
103
- const error = optionalNullableString(body['error']);
104
- if (error !== undefined)
104
+ if (Object.hasOwn(body, "result")) {
105
+ const { result } = body;
106
+ output.result =
107
+ result === null || decodeResult === undefined
108
+ ? result
109
+ : decodeResult(result);
110
+ }
111
+ const error = optionalNullableString(body.error);
112
+ if (error !== undefined) {
105
113
  output.error = error;
106
- const state = optionalString(body['state']);
107
- if (state !== undefined)
114
+ }
115
+ const state = optionalString(body.state);
116
+ if (state !== undefined) {
108
117
  output.state = state;
109
- const status = optionalNullableString(body['status']);
110
- if (status !== undefined)
118
+ }
119
+ const status = optionalNullableString(body.status);
120
+ if (status !== undefined) {
111
121
  output.status = status;
112
- const statusUrl = optionalNullableString(body['statusUrl']);
113
- if (statusUrl !== undefined)
122
+ }
123
+ const statusUrl = optionalNullableString(body.statusUrl);
124
+ if (statusUrl !== undefined) {
114
125
  output.statusUrl = statusUrl;
115
- const retryAfterSeconds = optionalNullableNumber(body['retryAfterSeconds']);
116
- if (retryAfterSeconds !== undefined)
126
+ }
127
+ const retryAfterSeconds = optionalNullableNumber(body.retryAfterSeconds);
128
+ if (retryAfterSeconds !== undefined) {
117
129
  output.retryAfterSeconds = retryAfterSeconds;
118
- const cacheStatus = optionalNullableString(body['cacheStatus']);
119
- if (cacheStatus !== undefined)
130
+ }
131
+ const cacheStatus = optionalNullableString(body.cacheStatus);
132
+ if (cacheStatus !== undefined) {
120
133
  output.cacheStatus = cacheStatus;
121
- const executor = optionalNullableString(body['executor']);
122
- if (executor !== undefined)
134
+ }
135
+ const executor = optionalNullableString(body.executor);
136
+ if (executor !== undefined) {
123
137
  output.executor = executor;
124
- const executorKind = optionalNullableString(body['executorKind']);
125
- if (executorKind !== undefined)
138
+ }
139
+ const executorKind = optionalNullableString(body.executorKind);
140
+ if (executorKind !== undefined) {
126
141
  output.executorKind = executorKind;
142
+ }
127
143
  return output;
128
- }
129
- function routeSegmentForCapabilityType(capabilityType) {
130
- if (capabilityType === 'server_function') {
131
- return 'server-functions';
144
+ };
145
+ const routeSegmentForCapabilityType = (capabilityType) => {
146
+ if (capabilityType === "server_function") {
147
+ return "server-functions";
132
148
  }
133
- if (capabilityType === 'endpoint') {
134
- return 'endpoints';
149
+ if (capabilityType === "endpoint") {
150
+ return "endpoints";
135
151
  }
136
- if (capabilityType === 'job') {
137
- return 'jobs';
152
+ if (capabilityType === "job") {
153
+ return "jobs";
138
154
  }
139
155
  return capabilityType;
140
- }
141
- function encodeCapabilityPath(capabilityType, capabilityName) {
142
- if (capabilityType !== 'endpoint') {
156
+ };
157
+ const encodeCapabilityPath = (capabilityType, capabilityName) => {
158
+ if (capabilityType !== "endpoint") {
143
159
  return encodeURIComponent(capabilityName);
144
160
  }
145
161
  return capabilityName
146
- .split('/')
147
- .filter(segment => segment.trim().length > 0)
148
- .map(segment => encodeURIComponent(segment))
149
- .join('/');
150
- }
151
- function makeRuntimeRequestId() {
152
- return `uru_app_${Math.random().toString(36).slice(2)}`;
153
- }
154
- function runtimeHttpRequestOptions(options) {
162
+ .split("/")
163
+ .filter((segment) => segment.trim().length > 0)
164
+ .map((segment) => encodeURIComponent(segment))
165
+ .join("/");
166
+ };
167
+ const makeRuntimeRequestId = () => `uru_app_${Math.random().toString(36).slice(2)}`;
168
+ const runtimeHttpRequestOptions = (options) => {
155
169
  const transport = {};
156
- if (options?.idempotencyKey) {
157
- transport.idempotencyKey = options.idempotencyKey;
158
- }
159
- if (typeof options?.timeoutMs === 'number') {
160
- transport.timeoutMs = options.timeoutMs;
170
+ const idempotencyKey = options?.idempotencyKey;
171
+ if (idempotencyKey !== undefined && idempotencyKey !== "") {
172
+ transport.idempotencyKey = idempotencyKey;
173
+ }
174
+ const timeoutMs = options?.timeoutMs;
175
+ if (timeoutMs !== undefined) {
176
+ if (!Number.isInteger(timeoutMs) ||
177
+ timeoutMs < 1000 ||
178
+ timeoutMs > 60_000) {
179
+ throw new UruAppRuntimeError("Invalid app runtime timeoutMs.", {
180
+ body: timeoutMs,
181
+ status: 0,
182
+ });
183
+ }
184
+ transport.timeoutMs = timeoutMs;
161
185
  }
162
186
  if (options?.forceRefresh === true) {
163
187
  transport.forceRefresh = true;
164
188
  }
165
189
  return transport;
166
- }
167
- function normalizeRuntimeState(input) {
168
- const explicitState = String(input.state ?? '')
169
- .trim()
170
- .toLowerCase();
171
- if (explicitState) {
190
+ };
191
+ const RUNTIME_STATE_BY_CACHE_STATUS = {
192
+ coalesced: "cached",
193
+ fresh: "cached",
194
+ refreshed: "refreshed",
195
+ refreshing: "refreshing",
196
+ stale: "stale",
197
+ };
198
+ const RUNTIME_STATE_BY_STATUS = {
199
+ budget_blocked: "budget_blocked",
200
+ canceled: "canceled",
201
+ cancelled: "canceled",
202
+ completed: "succeeded",
203
+ error: "failed",
204
+ failed: "failed",
205
+ polling: "polling",
206
+ queued: "queued",
207
+ rate_limited: "rate_limited",
208
+ service_unavailable: "service_unavailable",
209
+ succeeded: "succeeded",
210
+ success: "succeeded",
211
+ };
212
+ const normalizedStateText = (value) => (value ?? "").trim().toLowerCase();
213
+ const runtimeStateFromMap = (states, key) => (Object.hasOwn(states, key) ? states[key] : undefined);
214
+ const stateFromStatus = (status, forceRefresh) => {
215
+ if (status === "running") {
216
+ return forceRefresh === true ? "refreshing" : "running";
217
+ }
218
+ return runtimeStateFromMap(RUNTIME_STATE_BY_STATUS, status);
219
+ };
220
+ const stateFromHttpStatus = (status) => {
221
+ if (status === 429) {
222
+ return "rate_limited";
223
+ }
224
+ if (status === 402) {
225
+ return "budget_blocked";
226
+ }
227
+ if (status === 503) {
228
+ return "service_unavailable";
229
+ }
230
+ return undefined;
231
+ };
232
+ const hasRuntimeError = (error) => error !== undefined && error !== null && error !== "";
233
+ const normalizeRuntimeState = (input) => {
234
+ const explicitState = normalizedStateText(input.state);
235
+ if (explicitState !== "") {
172
236
  return explicitState;
173
237
  }
174
- const cacheStatus = String(input.cacheStatus ?? '')
175
- .trim()
176
- .toLowerCase();
177
- if (cacheStatus === 'refreshing') {
178
- return 'refreshing';
179
- }
180
- if (cacheStatus === 'stale') {
181
- return 'stale';
182
- }
183
- if (cacheStatus === 'fresh' || cacheStatus === 'coalesced') {
184
- return 'cached';
185
- }
186
- if (cacheStatus === 'refreshed') {
187
- return 'refreshed';
188
- }
189
- const status = String(input.status ?? '')
190
- .trim()
191
- .toLowerCase();
192
- if (status === 'queued') {
193
- return 'queued';
194
- }
195
- if (status === 'running') {
196
- return input.forceRefresh ? 'refreshing' : 'running';
197
- }
198
- if (status === 'polling') {
199
- return 'polling';
238
+ const cacheState = runtimeStateFromMap(RUNTIME_STATE_BY_CACHE_STATUS, normalizedStateText(input.cacheStatus));
239
+ if (cacheState !== undefined) {
240
+ return cacheState;
200
241
  }
201
- if (status === 'canceled' || status === 'cancelled') {
202
- return 'canceled';
242
+ const statusState = stateFromStatus(normalizedStateText(input.status), input.forceRefresh);
243
+ if (statusState !== undefined) {
244
+ return statusState;
203
245
  }
204
- if (status === 'rate_limited') {
205
- return 'rate_limited';
206
- }
207
- if (status === 'budget_blocked') {
208
- return 'budget_blocked';
209
- }
210
- if (status === 'service_unavailable') {
211
- return 'service_unavailable';
212
- }
213
- if (status === 'failed' || status === 'error') {
214
- return 'failed';
215
- }
216
- if (status === 'succeeded' || status === 'success' || status === 'completed') {
217
- return 'succeeded';
218
- }
219
- if (input.httpStatus === 429) {
220
- return 'rate_limited';
221
- }
222
- if (input.httpStatus === 402) {
223
- return 'budget_blocked';
224
- }
225
- if (input.httpStatus === 503) {
226
- return 'service_unavailable';
246
+ const httpState = stateFromHttpStatus(input.httpStatus);
247
+ if (httpState !== undefined) {
248
+ return httpState;
227
249
  }
228
250
  if (input.pending === true) {
229
- return input.forceRefresh ? 'refreshing' : 'running';
251
+ return input.forceRefresh === true ? "refreshing" : "running";
230
252
  }
231
253
  if (input.ok === true || input.success === true) {
232
- return 'succeeded';
233
- }
234
- if (input.ok === false || input.success === false || input.error) {
235
- return 'failed';
236
- }
237
- return 'idle';
238
- }
239
- function runtimeEventTypeForState(state, pending) {
240
- if (state === 'canceled') {
241
- return 'canceled';
242
- }
243
- if (state === 'failed' ||
244
- state === 'rate_limited' ||
245
- state === 'budget_blocked' ||
246
- state === 'service_unavailable') {
247
- return 'failed';
248
- }
249
- if (pending ||
250
- state === 'queued' ||
251
- state === 'running' ||
252
- state === 'refreshing') {
253
- return 'status';
254
- }
255
- return 'completed';
256
- }
257
- function emitRuntimeEvent(options, event) {
258
- if (typeof options?.onEvent === 'function') {
254
+ return "succeeded";
255
+ }
256
+ if (input.ok === false ||
257
+ input.success === false ||
258
+ hasRuntimeError(input.error)) {
259
+ return "failed";
260
+ }
261
+ return "idle";
262
+ };
263
+ const runtimeEventTypeForState = (state, pending) => {
264
+ if (state === "canceled") {
265
+ return "canceled";
266
+ }
267
+ if (state === "failed" ||
268
+ state === "rate_limited" ||
269
+ state === "budget_blocked" ||
270
+ state === "service_unavailable") {
271
+ return "failed";
272
+ }
273
+ if (pending === true ||
274
+ state === "queued" ||
275
+ state === "running" ||
276
+ state === "refreshing") {
277
+ return "status";
278
+ }
279
+ return "completed";
280
+ };
281
+ const emitRuntimeEvent = (options, event) => {
282
+ if (typeof options?.onEvent === "function") {
259
283
  options.onEvent(event);
260
284
  }
261
- if (typeof options?.onStatus === 'function') {
285
+ if (typeof options?.onStatus === "function") {
262
286
  options.onStatus(event);
263
287
  }
264
- }
265
- export async function invokeAppRuntime(options, damper, capabilityType, name, input, invocationOptions) {
266
- const runtimeFetch = options.fetch ?? globalThis.fetch;
267
- if (!runtimeFetch) {
268
- throw new UruAppRuntimeError('Uru app runtime fetch is not available.', {
269
- status: 0,
288
+ };
289
+ const resolveRuntimeFetch = (options) => {
290
+ if (options.fetch !== undefined) {
291
+ return options.fetch;
292
+ }
293
+ if (typeof globalThis.fetch !== "function") {
294
+ throw new UruAppRuntimeError("Uru app runtime fetch is not available.", {
270
295
  body: null,
296
+ status: 0,
271
297
  });
272
298
  }
273
- const deploymentId = options.deploymentId.trim();
299
+ return globalThis.fetch;
300
+ };
301
+ const invocationIdentity = (options, name) => {
274
302
  const capabilityName = name.trim();
275
- if (!deploymentId) {
276
- throw new UruAppRuntimeError('Uru app runtime deployment id is required.', {
303
+ const deploymentId = options.deploymentId.trim();
304
+ if (deploymentId === "") {
305
+ throw new UruAppRuntimeError("Uru app runtime deployment id is required.", {
306
+ body: null,
277
307
  status: 0,
308
+ });
309
+ }
310
+ if (capabilityName === "") {
311
+ throw new UruAppRuntimeError("Uru app runtime capability name is required.", {
278
312
  body: null,
313
+ status: 0,
279
314
  });
280
315
  }
281
- if (!capabilityName) {
282
- throw new UruAppRuntimeError('Uru app runtime capability name is required.', {
316
+ return { capabilityName, deploymentId };
317
+ };
318
+ const invocationInput = (input) => {
319
+ const runtimeInput = input === undefined ? {} : input;
320
+ if (isRuntimeJsonObject(runtimeInput)) {
321
+ return runtimeInput;
322
+ }
323
+ throw new UruAppRuntimeError("Invalid app runtime input.", {
324
+ body: input,
325
+ status: 0,
326
+ });
327
+ };
328
+ const invocationUrl = (options, deploymentId, capabilityType, capabilityName) => {
329
+ const baseUrl = options.baseUrl === undefined || options.baseUrl === ""
330
+ ? ""
331
+ : trimTrailingSlash(options.baseUrl);
332
+ const basePath = runtimeBasePath(options);
333
+ const encodedCapabilityName = encodeCapabilityPath(capabilityType, capabilityName);
334
+ const routeSegment = routeSegmentForCapabilityType(capabilityType);
335
+ return `${baseUrl}${basePath}/apps/${encodeURIComponent(deploymentId)}/${routeSegment}/${encodedCapabilityName}`;
336
+ };
337
+ const invocationRequestBody = (transport, runtimeInput, effectiveForce, damper, originalInput) => {
338
+ if (effectiveForce) {
339
+ transport.forceRefresh = true;
340
+ }
341
+ else {
342
+ delete transport.forceRefresh;
343
+ }
344
+ try {
345
+ if (transport.idempotencyKey === undefined &&
346
+ damper.config.defaultIdempotencyKeys) {
347
+ transport.idempotencyKey = `uru-app:${crypto.randomUUID()}`;
348
+ }
349
+ const requestBody = JSON.stringify({
350
+ input: runtimeInput,
351
+ ...transport,
352
+ });
353
+ if (requestBody === undefined) {
354
+ throw new TypeError("App runtime input could not be serialized.");
355
+ }
356
+ return requestBody;
357
+ }
358
+ catch {
359
+ throw new UruAppRuntimeError("Invalid app runtime input.", {
360
+ body: originalInput,
283
361
  status: 0,
284
- body: null,
285
362
  });
286
363
  }
364
+ };
365
+ const responseBody = async (response) => await response.json().catch(() => null);
366
+ const fetchInvocation = async (args, attempt = 0) => {
367
+ const response = await args.runtimeFetch(args.url, {
368
+ body: args.requestBody,
369
+ headers: args.headers,
370
+ method: "POST",
371
+ });
372
+ const body = await responseBody(response);
373
+ const shouldRetry = response.status === 429 && attempt < args.damper.config.maxRateLimitRetries;
374
+ if (!shouldRetry) {
375
+ return { body, response };
376
+ }
377
+ const delayMs = computeRateLimitBackoffMs({
378
+ attempt,
379
+ baseDelayMs: args.damper.config.rateLimitBaseDelayMs,
380
+ maxDelayMs: args.damper.config.rateLimitMaxDelayMs,
381
+ retryAfterSeconds: parseRetryAfterSeconds({
382
+ body,
383
+ header: response.headers.get("retry-after"),
384
+ }),
385
+ });
386
+ emitRuntimeEvent(args.invocationOptions, {
387
+ capabilityName: args.capabilityName,
388
+ capabilityType: args.capabilityType,
389
+ deploymentId: args.deploymentId,
390
+ requestId: args.requestId,
391
+ retryAfterSeconds: Math.ceil(delayMs / 1000),
392
+ state: "rate_limited",
393
+ type: "status",
394
+ });
395
+ await args.damper.config.sleep(delayMs);
396
+ return await fetchInvocation(args, attempt + 1);
397
+ };
398
+ const normalizedInvocationResponse = (runtimeResponse, fallbackIdentity, fallbackCapabilityType, state, diagnostics) => ({
399
+ capabilityName: runtimeResponse.capabilityName === ""
400
+ ? fallbackIdentity.capabilityName
401
+ : runtimeResponse.capabilityName,
402
+ capabilityType: runtimeResponse.capabilityType === ""
403
+ ? fallbackCapabilityType
404
+ : runtimeResponse.capabilityType,
405
+ deploymentId: runtimeResponse.deploymentId === ""
406
+ ? fallbackIdentity.deploymentId
407
+ : runtimeResponse.deploymentId,
408
+ diagnostics,
409
+ ...(runtimeResponse.executionId === undefined
410
+ ? {}
411
+ : { executionId: runtimeResponse.executionId }),
412
+ ok: runtimeResponse.ok,
413
+ pending: runtimeResponse.pending,
414
+ ...(Object.hasOwn(runtimeResponse, "result")
415
+ ? { result: runtimeResponse.result }
416
+ : {}),
417
+ state,
418
+ status: runtimeResponse.status,
419
+ });
420
+ export const invokeAppRuntime = async (options, damper, capabilityType, name, input, invocationOptions) => {
421
+ const runtimeFetch = resolveRuntimeFetch(options);
422
+ const identity = invocationIdentity(options, name);
423
+ const { capabilityName, deploymentId } = identity;
424
+ const runtimeInput = invocationInput(input);
425
+ const transport = runtimeHttpRequestOptions(invocationOptions);
287
426
  // P2 damper: a requested forceRefresh is honored only if it clears the
288
427
  // per-capability throttle; otherwise the call is sent WITHOUT force_refresh so
289
428
  // it can be served from cache instead of hammering past it.
290
429
  const requestedForce = invocationOptions?.forceRefresh === true;
291
430
  const effectiveForce = damper.throttle.shouldForceRefresh({
292
431
  key: `${deploymentId}:${capabilityType}:${capabilityName}`,
293
- requested: requestedForce,
294
- nowMs: damper.config.now(),
295
432
  minIntervalMs: damper.config.forceRefreshMinIntervalMs,
433
+ nowMs: damper.config.now(),
434
+ requested: requestedForce,
296
435
  });
297
436
  const requestId = invocationOptions?.requestId ?? makeRuntimeRequestId();
437
+ const url = invocationUrl(options, deploymentId, capabilityType, capabilityName);
438
+ // Create the key once per invocation. Transport retries reuse this body,
439
+ // while a later call remains a separate operation even when its input matches.
440
+ const requestBody = invocationRequestBody(transport, runtimeInput, effectiveForce, damper, input);
298
441
  emitRuntimeEvent(invocationOptions, {
299
- type: 'started',
300
- state: effectiveForce ? 'refreshing' : 'queued',
301
- deploymentId,
302
- capabilityType,
303
442
  capabilityName,
443
+ capabilityType,
444
+ deploymentId,
304
445
  requestId,
446
+ state: effectiveForce ? "refreshing" : "queued",
447
+ type: "started",
305
448
  });
306
- const baseUrl = options.baseUrl ? trimTrailingSlash(options.baseUrl) : '';
307
- const basePath = runtimeBasePath(options);
308
- const routeSegment = routeSegmentForCapabilityType(capabilityType);
309
- const encodedCapabilityName = encodeCapabilityPath(capabilityType, capabilityName);
310
- const url = `${baseUrl}${basePath}/apps/${encodeURIComponent(deploymentId)}/${routeSegment}/${encodedCapabilityName}`;
311
449
  const headers = new Headers(await resolveHeaders(options.headers));
312
- headers.set('content-type', 'application/json');
313
- // Build the transport envelope: the caller's normalized options, but with the
314
- // throttled forceRefresh decision and — when the caller supplied none — a
315
- // default idempotency_key so identical accidental re-fires collapse to one
316
- // Temporal workflow (REJECT_DUPLICATE) instead of thousands.
317
- const transport = runtimeHttpRequestOptions(invocationOptions);
318
- if (effectiveForce) {
319
- transport.forceRefresh = true;
320
- }
321
- else {
322
- delete transport.forceRefresh;
323
- }
324
- if (transport.idempotencyKey === undefined &&
325
- damper.config.defaultIdempotencyKeys) {
326
- transport.idempotencyKey = defaultIdempotencyKey({
327
- deploymentId,
328
- capabilityType,
329
- capabilityName,
330
- input: input ?? {},
331
- nowMs: damper.config.now(),
332
- windowMs: damper.config.idempotencyWindowMs,
333
- });
334
- }
335
- const requestBody = JSON.stringify({ input: input ?? {}, ...transport });
450
+ headers.set("content-type", "application/json");
336
451
  // P2 damper: bounded backoff-and-retry on 429 / rate_limited. `attempt` counts
337
452
  // retries beyond the first send; the loop performs at most
338
453
  // `maxRateLimitRetries` extra sends, honoring Retry-After / retry_after_seconds
339
454
  // (capped) before falling through to the normal failure path.
340
- let response;
341
- let body;
342
- for (let attempt = 0;; attempt += 1) {
343
- response = await runtimeFetch(url, {
344
- method: 'POST',
345
- headers,
346
- body: requestBody,
347
- });
348
- body = (await response.json().catch(() => null));
349
- if (response.status !== 429 || attempt >= damper.config.maxRateLimitRetries) {
350
- break;
351
- }
352
- const delayMs = computeRateLimitBackoffMs({
353
- attempt,
354
- retryAfterSeconds: parseRetryAfterSeconds({
355
- header: response.headers.get('retry-after'),
356
- body,
357
- }),
358
- baseDelayMs: damper.config.rateLimitBaseDelayMs,
359
- maxDelayMs: damper.config.rateLimitMaxDelayMs,
360
- });
361
- emitRuntimeEvent(invocationOptions, {
362
- type: 'status',
363
- state: 'rate_limited',
364
- deploymentId,
365
- capabilityType,
366
- capabilityName,
367
- requestId,
368
- retryAfterSeconds: Math.ceil(delayMs / 1000),
369
- });
370
- await damper.config.sleep(delayMs);
371
- }
455
+ const { body, response } = await fetchInvocation({
456
+ capabilityName,
457
+ capabilityType,
458
+ damper,
459
+ deploymentId,
460
+ headers,
461
+ ...(invocationOptions === undefined ? {} : { invocationOptions }),
462
+ requestBody,
463
+ requestId,
464
+ runtimeFetch,
465
+ url,
466
+ });
372
467
  if (!response.ok) {
373
468
  const message = runtimeErrorMessage(body, `Uru app runtime call failed with HTTP ${response.status}`);
374
469
  emitRuntimeEvent(invocationOptions, {
375
- type: 'failed',
470
+ capabilityName,
471
+ capabilityType,
472
+ deploymentId,
473
+ diagnostics: isRuntimeJsonObject(body) ? body : {},
474
+ error: message,
475
+ requestId,
376
476
  state: normalizeRuntimeState({
377
- httpStatus: response.status,
378
477
  error: message,
478
+ httpStatus: response.status,
379
479
  }),
380
- deploymentId,
381
- capabilityType,
382
- capabilityName,
383
- requestId,
384
- error: message,
385
- diagnostics: typeof body === 'object' && body !== null
386
- ? body
387
- : {},
480
+ type: "failed",
388
481
  });
389
482
  throw new UruAppRuntimeError(message, {
390
- status: response.status,
391
483
  body,
484
+ status: response.status,
392
485
  });
393
486
  }
394
- const runtimeResponse = appRuntimeInvocationResponseFromHttp(body);
487
+ const runtimeResponse = appRuntimeInvocationResponseFromHttp(body, invocationOptions?.decodeResult);
395
488
  const diagnostics = runtimeResponse.diagnostics ?? {};
396
- const cacheStatus = typeof diagnostics['cache_status'] === 'string'
397
- ? diagnostics['cache_status']
489
+ const cacheStatus = typeof diagnostics.cache_status === "string"
490
+ ? diagnostics.cache_status
398
491
  : null;
399
492
  const state = normalizeRuntimeState({
400
- ok: runtimeResponse.ok,
401
- pending: runtimeResponse.pending,
402
- status: runtimeResponse.status,
403
- state: runtimeResponse.state,
404
493
  cacheStatus,
405
494
  forceRefresh: effectiveForce,
406
- });
407
- const normalizedResponse = {
408
495
  ok: runtimeResponse.ok,
409
- status: runtimeResponse.status,
410
- state,
411
- deploymentId: runtimeResponse.deploymentId || deploymentId,
412
- capabilityType: runtimeResponse.capabilityType || capabilityType,
413
- capabilityName: runtimeResponse.capabilityName || capabilityName,
414
- ...(Object.prototype.hasOwnProperty.call(runtimeResponse, 'result')
415
- ? { result: runtimeResponse.result }
416
- : {}),
417
- ...(runtimeResponse.executionId === undefined
418
- ? {}
419
- : { executionId: runtimeResponse.executionId }),
420
496
  pending: runtimeResponse.pending,
421
- diagnostics,
422
- };
497
+ state: runtimeResponse.state,
498
+ status: runtimeResponse.status,
499
+ });
500
+ const normalizedResponse = normalizedInvocationResponse(runtimeResponse, identity, capabilityType, state, diagnostics);
423
501
  emitRuntimeEvent(invocationOptions, {
424
- type: runtimeEventTypeForState(state, normalizedResponse.pending),
425
- state,
426
- deploymentId: normalizedResponse.deploymentId,
427
- capabilityType: normalizedResponse.capabilityType,
502
+ cacheStatus,
428
503
  capabilityName: normalizedResponse.capabilityName,
504
+ capabilityType: normalizedResponse.capabilityType,
505
+ deploymentId: normalizedResponse.deploymentId,
506
+ diagnostics,
429
507
  executionId: normalizedResponse.executionId,
430
508
  requestId,
431
509
  result: normalizedResponse.result,
432
- cacheStatus,
433
- diagnostics,
510
+ state,
511
+ type: runtimeEventTypeForState(state, normalizedResponse.pending),
434
512
  });
435
513
  return normalizedResponse;
436
- }
437
- export async function getAppRuntimeJobStatus(options, executionId, invocationOptions) {
438
- const runtimeFetch = options.fetch ?? globalThis.fetch;
439
- if (!runtimeFetch) {
440
- throw new UruAppRuntimeError('Uru app runtime fetch is not available.', {
441
- status: 0,
442
- body: null,
443
- });
444
- }
514
+ };
515
+ const jobIdentity = (options, executionId) => {
445
516
  const deploymentId = options.deploymentId.trim();
446
517
  const normalizedExecutionId = executionId.trim();
447
- if (!deploymentId || !normalizedExecutionId) {
448
- throw new UruAppRuntimeError('Uru app runtime deployment id and execution id are required.', {
449
- status: 0,
518
+ if (deploymentId === "" || normalizedExecutionId === "") {
519
+ throw new UruAppRuntimeError("Uru app runtime deployment id and execution id are required.", {
450
520
  body: null,
521
+ status: 0,
451
522
  });
452
523
  }
524
+ return { deploymentId, executionId: normalizedExecutionId };
525
+ };
526
+ const jobExecutionUrl = (options, identity, cancel = false) => {
527
+ const baseUrl = options.baseUrl === undefined || options.baseUrl === ""
528
+ ? ""
529
+ : trimTrailingSlash(options.baseUrl);
530
+ const suffix = cancel ? "/cancel" : "";
531
+ return `${baseUrl}${runtimeBasePath(options)}/apps/${encodeURIComponent(identity.deploymentId)}/jobs/executions/${encodeURIComponent(identity.executionId)}${suffix}`;
532
+ };
533
+ const executionState = (status) => normalizeRuntimeState({
534
+ ...(status.cacheStatus === undefined
535
+ ? {}
536
+ : { cacheStatus: status.cacheStatus }),
537
+ ...(status.error === undefined ? {} : { error: status.error }),
538
+ ...(status.pending === undefined ? {} : { pending: status.pending }),
539
+ ...(status.state === undefined ? {} : { state: status.state }),
540
+ ...(status.status === undefined ? {} : { status: status.status }),
541
+ ...(status.success === undefined ? {} : { success: status.success }),
542
+ });
543
+ const normalizedExecutionStatus = (status, state) => ({
544
+ ...(status.cacheStatus === undefined
545
+ ? {}
546
+ : { cacheStatus: status.cacheStatus }),
547
+ ...(status.error === undefined ? {} : { error: status.error }),
548
+ ...(status.executionId === undefined
549
+ ? {}
550
+ : { executionId: status.executionId }),
551
+ ...(status.executor === undefined ? {} : { executor: status.executor }),
552
+ ...(status.executorKind === undefined
553
+ ? {}
554
+ : { executorKind: status.executorKind }),
555
+ ...(status.pending === undefined ? {} : { pending: status.pending }),
556
+ ...(Object.hasOwn(status, "result") ? { result: status.result } : {}),
557
+ ...(status.retryAfterSeconds === undefined
558
+ ? {}
559
+ : { retryAfterSeconds: status.retryAfterSeconds }),
560
+ state,
561
+ ...(status.status === undefined ? {} : { status: status.status }),
562
+ ...(status.statusUrl === undefined ? {} : { statusUrl: status.statusUrl }),
563
+ ...(status.success === undefined ? {} : { success: status.success }),
564
+ });
565
+ export const getAppRuntimeJobStatus = async (options, executionId, invocationOptions) => {
566
+ const runtimeFetch = resolveRuntimeFetch(options);
567
+ const identity = jobIdentity(options, executionId);
568
+ const { deploymentId, executionId: normalizedExecutionId } = identity;
453
569
  const requestId = invocationOptions?.requestId ?? makeRuntimeRequestId();
454
570
  emitRuntimeEvent(invocationOptions, {
455
- type: 'status',
456
- state: 'polling',
571
+ capabilityName: "",
572
+ capabilityType: "job",
457
573
  deploymentId,
458
- capabilityType: 'job',
459
- capabilityName: '',
460
574
  executionId: normalizedExecutionId,
461
575
  requestId,
576
+ state: "polling",
577
+ type: "status",
462
578
  });
463
- const baseUrl = options.baseUrl ? trimTrailingSlash(options.baseUrl) : '';
464
- const basePath = runtimeBasePath(options);
465
- const url = `${baseUrl}${basePath}/apps/${encodeURIComponent(deploymentId)}/jobs/executions/${encodeURIComponent(normalizedExecutionId)}`;
579
+ const url = jobExecutionUrl(options, identity);
466
580
  const headers = new Headers(await resolveHeaders(options.headers));
467
- const response = await runtimeFetch(url, { method: 'GET', headers });
468
- const body = (await response.json().catch(() => null));
581
+ const response = await runtimeFetch(url, { headers, method: "GET" });
582
+ const body = await responseBody(response);
469
583
  if (!response.ok && response.status !== 202) {
470
584
  const message = runtimeErrorMessage(body, `Uru app runtime job status failed with HTTP ${response.status}`);
471
585
  emitRuntimeEvent(invocationOptions, {
472
- type: 'failed',
473
- state: normalizeRuntimeState({
474
- httpStatus: response.status,
475
- error: message,
476
- }),
586
+ capabilityName: "",
587
+ capabilityType: "job",
477
588
  deploymentId,
478
- capabilityType: 'job',
479
- capabilityName: '',
589
+ diagnostics: isRuntimeJsonObject(body) ? body : {},
590
+ error: message,
480
591
  executionId: normalizedExecutionId,
481
592
  requestId,
482
- error: message,
483
- diagnostics: typeof body === 'object' && body !== null
484
- ? body
485
- : {},
593
+ state: normalizeRuntimeState({
594
+ error: message,
595
+ httpStatus: response.status,
596
+ }),
597
+ type: "failed",
486
598
  });
487
599
  throw new UruAppRuntimeError(message, {
488
- status: response.status,
489
600
  body,
601
+ status: response.status,
490
602
  });
491
603
  }
492
- const statusBody = appRuntimeExecutionStatusFromHttp(body);
493
- const state = normalizeRuntimeState({
494
- success: statusBody.success,
495
- pending: statusBody.pending,
496
- status: statusBody.status,
497
- state: statusBody.state,
498
- cacheStatus: statusBody.cacheStatus,
499
- error: statusBody.error,
500
- });
501
- const normalizedStatus = {
502
- ...(statusBody.success === undefined ? {} : { success: statusBody.success }),
503
- ...(statusBody.pending === undefined ? {} : { pending: statusBody.pending }),
504
- ...(Object.prototype.hasOwnProperty.call(statusBody, 'result')
505
- ? { result: statusBody.result }
506
- : {}),
507
- ...(statusBody.error === undefined ? {} : { error: statusBody.error }),
508
- state,
509
- ...(statusBody.status === undefined ? {} : { status: statusBody.status }),
510
- ...(statusBody.executionId === undefined
511
- ? {}
512
- : { executionId: statusBody.executionId }),
513
- ...(statusBody.statusUrl === undefined
514
- ? {}
515
- : { statusUrl: statusBody.statusUrl }),
516
- ...(statusBody.retryAfterSeconds === undefined
517
- ? {}
518
- : { retryAfterSeconds: statusBody.retryAfterSeconds }),
519
- ...(statusBody.cacheStatus === undefined
520
- ? {}
521
- : { cacheStatus: statusBody.cacheStatus }),
522
- ...(statusBody.executor === undefined ? {} : { executor: statusBody.executor }),
523
- ...(statusBody.executorKind === undefined
524
- ? {}
525
- : { executorKind: statusBody.executorKind }),
526
- };
604
+ const statusBody = appRuntimeExecutionStatusFromHttp(body, invocationOptions?.decodeResult);
605
+ const state = executionState(statusBody);
606
+ const normalizedStatus = normalizedExecutionStatus(statusBody, state);
527
607
  emitRuntimeEvent(invocationOptions, {
528
- type: runtimeEventTypeForState(state, normalizedStatus.pending),
529
- state,
608
+ cacheStatus: normalizedStatus.cacheStatus,
609
+ capabilityName: "",
610
+ capabilityType: "job",
530
611
  deploymentId,
531
- capabilityType: 'job',
532
- capabilityName: '',
612
+ error: normalizedStatus.error,
533
613
  executionId: normalizedExecutionId,
534
614
  requestId,
535
615
  result: normalizedStatus.result,
536
- error: normalizedStatus.error,
537
616
  retryAfterSeconds: normalizedStatus.retryAfterSeconds,
538
- cacheStatus: normalizedStatus.cacheStatus,
617
+ state,
618
+ type: runtimeEventTypeForState(state, normalizedStatus.pending),
539
619
  });
540
620
  return normalizedStatus;
541
- }
542
- export async function cancelAppRuntimeJob(options, executionId, invocationOptions) {
543
- const runtimeFetch = options.fetch ?? globalThis.fetch;
544
- if (!runtimeFetch) {
545
- throw new UruAppRuntimeError('Uru app runtime fetch is not available.', {
546
- status: 0,
547
- body: null,
548
- });
549
- }
550
- const deploymentId = options.deploymentId.trim();
551
- const normalizedExecutionId = executionId.trim();
552
- if (!deploymentId || !normalizedExecutionId) {
553
- throw new UruAppRuntimeError('Uru app runtime deployment id and execution id are required.', {
554
- status: 0,
555
- body: null,
556
- });
557
- }
621
+ };
622
+ export const cancelAppRuntimeJob = async (options, executionId, invocationOptions) => {
623
+ const runtimeFetch = resolveRuntimeFetch(options);
624
+ const identity = jobIdentity(options, executionId);
625
+ const { deploymentId, executionId: normalizedExecutionId } = identity;
558
626
  const requestId = invocationOptions?.requestId ?? makeRuntimeRequestId();
559
- const baseUrl = options.baseUrl ? trimTrailingSlash(options.baseUrl) : '';
560
- const basePath = runtimeBasePath(options);
561
- const url = `${baseUrl}${basePath}/apps/${encodeURIComponent(deploymentId)}/jobs/executions/${encodeURIComponent(normalizedExecutionId)}/cancel`;
627
+ const url = jobExecutionUrl(options, identity, true);
562
628
  const headers = new Headers(await resolveHeaders(options.headers));
563
- const response = await runtimeFetch(url, { method: 'POST', headers });
564
- const body = (await response.json().catch(() => null));
629
+ const response = await runtimeFetch(url, { headers, method: "POST" });
630
+ const body = await responseBody(response);
565
631
  if (!response.ok) {
566
632
  const message = runtimeErrorMessage(body, `Uru app runtime job cancel failed with HTTP ${response.status}`);
567
633
  emitRuntimeEvent(invocationOptions, {
568
- type: 'failed',
569
- state: normalizeRuntimeState({
570
- httpStatus: response.status,
571
- error: message,
572
- }),
634
+ capabilityName: "",
635
+ capabilityType: "job",
573
636
  deploymentId,
574
- capabilityType: 'job',
575
- capabilityName: '',
637
+ diagnostics: isRuntimeJsonObject(body) ? body : {},
638
+ error: message,
576
639
  executionId: normalizedExecutionId,
577
640
  requestId,
578
- error: message,
579
- diagnostics: typeof body === 'object' && body !== null
580
- ? body
581
- : {},
641
+ state: normalizeRuntimeState({
642
+ error: message,
643
+ httpStatus: response.status,
644
+ }),
645
+ type: "failed",
582
646
  });
583
647
  throw new UruAppRuntimeError(message, {
584
- status: response.status,
585
648
  body,
649
+ status: response.status,
586
650
  });
587
651
  }
588
- const runtimeResponse = appRuntimeInvocationResponseFromHttp(body);
652
+ const runtimeResponse = appRuntimeInvocationResponseFromHttp(body, invocationOptions?.decodeResult);
589
653
  const diagnostics = runtimeResponse.diagnostics ?? {};
590
- const normalizedResponse = {
654
+ const state = normalizeRuntimeState({
655
+ cacheStatus: typeof diagnostics.cache_status === "string"
656
+ ? diagnostics.cache_status
657
+ : null,
591
658
  ok: runtimeResponse.ok,
659
+ pending: runtimeResponse.pending,
660
+ state: runtimeResponse.state,
592
661
  status: runtimeResponse.status,
593
- state: normalizeRuntimeState({
594
- ok: runtimeResponse.ok,
595
- pending: runtimeResponse.pending,
596
- status: runtimeResponse.status,
597
- state: runtimeResponse.state,
598
- cacheStatus: typeof diagnostics['cache_status'] === 'string'
599
- ? diagnostics['cache_status']
600
- : null,
601
- }),
602
- deploymentId: runtimeResponse.deploymentId || deploymentId,
603
- capabilityType: runtimeResponse.capabilityType || 'job',
662
+ });
663
+ const normalizedResponse = normalizedInvocationResponse(runtimeResponse, {
604
664
  capabilityName: runtimeResponse.capabilityName,
605
- ...(Object.prototype.hasOwnProperty.call(runtimeResponse, 'result')
606
- ? { result: runtimeResponse.result }
607
- : {}),
608
- ...(runtimeResponse.executionId === undefined
609
- ? {}
610
- : { executionId: runtimeResponse.executionId }),
611
- pending: runtimeResponse.pending,
612
- diagnostics,
613
- };
665
+ deploymentId,
666
+ }, "job", state, diagnostics);
614
667
  emitRuntimeEvent(invocationOptions, {
615
- type: 'canceled',
616
- state: 'canceled',
617
- deploymentId: normalizedResponse.deploymentId,
618
- capabilityType: 'job',
619
668
  capabilityName: normalizedResponse.capabilityName,
669
+ capabilityType: "job",
670
+ deploymentId: normalizedResponse.deploymentId,
671
+ diagnostics,
620
672
  executionId: normalizedExecutionId,
621
673
  requestId,
622
- diagnostics,
674
+ state: "canceled",
675
+ type: "canceled",
623
676
  });
624
677
  return normalizedResponse;
625
- }
678
+ };