@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/transport.js CHANGED
@@ -15,115 +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
- import { abortReason, awaitWithAbort, readRuntimeResponseBody, validateRuntimeInvocationOptions, withRuntimeRequestSignal, } from "./transport-deadline.js";
22
- import { fetchInvocation } from "./transport-invocation.js";
22
+ import { abortReason, validateRuntimeInvocationOptions, withRuntimeRequestSignal, } from "./transport-deadline.js";
23
+ import { fetchInvocation, fetchJobCancel, 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
- "job_provider_gateway_unavailable",
66
- "job_machine_admission_invalid",
67
- "job_runtime_image_base_unavailable",
68
- "job_runtime_image_pin_unavailable",
69
- "job_runtime_image_pin_mismatch",
70
- "job_machine_image_mismatch",
71
- "job_machine_capacity_unavailable",
72
- "job_machine_app_unavailable",
73
- "job_machine_network_unavailable",
74
- "job_machine_proxy_unavailable",
75
- "job_machine_revocation_state_unavailable",
76
- "job_runtime_image_delivery_failed",
77
- "job_machine_isolation_unavailable",
78
- "job_secret_environment_invalid",
79
- "job_secret_environment_incomplete",
80
- "job_machine_lease_expired",
81
- "job_machine_request_failed",
82
- "job_machine_list_invalid",
83
- "job_machine_identity_ambiguous",
84
- "job_machine_identity_mismatch",
85
- "job_machine_launch_fence_lost",
86
- "execution_failed",
87
- "execution_outcome_unknown",
88
- "historical_result_unavailable",
89
- "job_canceled",
90
- "job_cleanup_failed",
91
- "job_completion_not_accepted",
92
- "job_handler_failed",
93
- "job_hard_deadline",
94
- "job_machine_start_failed",
95
- "job_machine_stopped",
96
- "job_output_invalid",
97
- "job_prepare_failed",
98
- "job_report_failed",
99
- "job_revoked",
100
- "job_runtime_failed",
101
- "legacy_tool_contract_disabled",
102
- "program_job_attach_rejected",
103
- "program_job_capacity_exceeded",
104
- "program_job_owner_missing",
105
- "program_job_spending_check_failed",
106
- "program_job_spending_limit",
107
- "provider_credential_rejected",
108
- "provider_failed",
109
- "provider_invalid",
110
- "provider_not_connected",
111
- "provider_rate_limited",
112
- "provider_rejected",
113
- "provider_required",
114
- "provider_timeout",
115
- "provider_transport_failed",
116
- "provider_unavailable",
117
- "public_tool_budget_limited",
118
- "public_tool_budget_unavailable",
119
- "runtime_capability_unsupported",
120
- "runtime_unavailable",
121
- "tool_execution_failed",
122
- "tool_timeout",
123
- "tool_transport_failed",
124
- "usage_limit_reached",
125
- "usage_limit_unavailable",
126
- ]);
127
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;
128
26
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
129
27
  const httpRecord = (value, label) => {
@@ -172,9 +70,7 @@ const safeRecordValue = (record, field) => {
172
70
  const optionalApprovedFailureCode = (value) => {
173
71
  if (value === null)
174
72
  return null;
175
- return typeof value === "string" && SAFE_RUNTIME_FAILURE_CODES.has(value)
176
- ? value
177
- : undefined;
73
+ return approvedRuntimeFailureCode(value) ?? undefined;
178
74
  };
179
75
  const optionalRuntimeUuid = (value) => {
180
76
  if (typeof value !== "string")
@@ -486,26 +382,42 @@ const invocationUrl = (options, deploymentId, capabilityType, capabilityName) =>
486
382
  const routeSegment = routeSegmentForCapabilityType(capabilityType);
487
383
  return `${baseUrl}${basePath}/apps/${encodeURIComponent(deploymentId)}/${routeSegment}/${encodedCapabilityName}`;
488
384
  };
489
- const invocationRequestBody = (transport, runtimeInput, effectiveForce, damper, originalInput) => {
385
+ const queryIdempotencyKey = () => `uru-app:${crypto.randomUUID()}`;
386
+ const invocationRequestBodies = (transport, runtimeInput, effectiveForce, damper, originalInput, capabilityType, capabilityName) => {
490
387
  if (effectiveForce) {
491
388
  transport.forceRefresh = true;
492
389
  }
493
390
  else {
494
391
  delete transport.forceRefresh;
495
392
  }
496
- try {
497
- if (transport.idempotencyKey === undefined &&
498
- damper.config.defaultIdempotencyKeys) {
499
- transport.idempotencyKey = `uru-app:${crypto.randomUUID()}`;
500
- }
393
+ const serialize = (idempotencyKey) => {
501
394
  const requestBody = JSON.stringify({
502
395
  input: runtimeInput,
503
396
  ...transport,
397
+ ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
504
398
  });
505
399
  if (requestBody === undefined) {
506
400
  throw new TypeError("App runtime input could not be serialized.");
507
401
  }
508
402
  return requestBody;
403
+ };
404
+ try {
405
+ if (transport.idempotencyKey === undefined &&
406
+ damper.config.defaultIdempotencyKeys) {
407
+ transport.idempotencyKey =
408
+ capabilityType === "query"
409
+ ? queryIdempotencyKey()
410
+ : damper.keys.next(capabilityType, capabilityName);
411
+ }
412
+ const { idempotencyKey } = transport;
413
+ const firstBody = serialize(idempotencyKey);
414
+ const freshKeyPerResend = capabilityType === "query" && idempotencyKey !== undefined;
415
+ return {
416
+ bodyFor: resend => resend === 0 || !freshKeyPerResend
417
+ ? firstBody
418
+ : serialize(queryIdempotencyKey()),
419
+ keyed: idempotencyKey !== undefined,
420
+ };
509
421
  }
510
422
  catch {
511
423
  throw new UruAppRuntimeError("Invalid app runtime input.", {
@@ -514,6 +426,14 @@ const invocationRequestBody = (transport, runtimeInput, effectiveForce, damper,
514
426
  });
515
427
  }
516
428
  };
429
+ /**
430
+ * Whether a lost response may be sent again. A query only reads. An action or
431
+ * a job is safe only under its key, which makes the server replay the first
432
+ * run. An endpoint or a server function has no stored-result replay, so a
433
+ * lost response could hide a completed side effect.
434
+ */
435
+ const invocationResendsLost = (capabilityType, keyed) => capabilityType === "query" ||
436
+ (keyed && (capabilityType === "action" || capabilityType === "job"));
517
437
  const normalizedInvocationResponse = (runtimeResponse, fallbackIdentity, fallbackCapabilityType, state, diagnostics) => ({
518
438
  capabilityName: runtimeResponse.capabilityName === ""
519
439
  ? fallbackIdentity.capabilityName
@@ -559,7 +479,7 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
559
479
  const url = invocationUrl(options, deploymentId, capabilityType, capabilityName);
560
480
  // Create the key once per invocation. Transport retries reuse this body,
561
481
  // while a later call remains a separate operation even when its input matches.
562
- const requestBody = invocationRequestBody(transport, runtimeInput, effectiveForce, damper, input);
482
+ const requestBodies = invocationRequestBodies(transport, runtimeInput, effectiveForce, damper, input, capabilityType, capabilityName);
563
483
  emitRuntimeEvent(invocationOptions, {
564
484
  capabilityName,
565
485
  capabilityType,
@@ -570,10 +490,11 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
570
490
  });
571
491
  const headers = new Headers(await resolveHeaders(options.headers));
572
492
  headers.set("content-type", "application/json");
573
- // P2 damper: bounded backoff-and-retry on 429 / rate_limited. `attempt` counts
574
- // retries beyond the first send; the loop performs at most
493
+ // P2 damper: bounded backoff-and-retry on 429 / rate_limited, at most
575
494
  // `maxRateLimitRetries` extra sends, honoring Retry-After / retry_after_seconds
576
- // (capped) before falling through to the normal failure path.
495
+ // (capped) before falling through to the normal failure path. A response the
496
+ // platform never gave (a restarting replica) is sent again separately, at
497
+ // most `maxTransportRetries` times, when the call is safe to send again.
577
498
  const { body, response } = await withRuntimeRequestSignal(invocationOptions, async (requestSignal) => await fetchInvocation({
578
499
  capabilityName,
579
500
  capabilityType,
@@ -581,8 +502,9 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
581
502
  deploymentId,
582
503
  emit: event => emitRuntimeEvent(invocationOptions, event),
583
504
  headers,
584
- requestBody,
505
+ requestBody: requestBodies.bodyFor,
585
506
  requestId,
507
+ resendLost: invocationResendsLost(capabilityType, requestBodies.keyed),
586
508
  runtimeFetch,
587
509
  ...(requestSignal === undefined ? {} : { signal: requestSignal }),
588
510
  url,
@@ -605,6 +527,10 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
605
527
  throw new UruAppRuntimeError(message, {
606
528
  body,
607
529
  status: response.status,
530
+ retryAfterSeconds: parseRetryAfterSeconds({
531
+ body,
532
+ header: response.headers.get("retry-after"),
533
+ }),
608
534
  });
609
535
  }
610
536
  const runtimeResponse = appRuntimeInvocationResponseFromHttp(body, invocationOptions?.decodeResult);
@@ -689,7 +615,7 @@ const normalizedExecutionStatus = (status, state) => ({
689
615
  ...(status.statusUrl === undefined ? {} : { statusUrl: status.statusUrl }),
690
616
  ...(status.success === undefined ? {} : { success: status.success }),
691
617
  });
692
- export const getAppRuntimeJobStatus = async (options, executionId, invocationOptions) => {
618
+ export const getAppRuntimeJobStatus = async (options, executionId, invocationOptions, damper) => {
693
619
  const runtimeFetch = resolveRuntimeFetch(options);
694
620
  const identity = jobIdentity(options, executionId);
695
621
  const { deploymentId, executionId: normalizedExecutionId } = identity;
@@ -707,22 +633,17 @@ export const getAppRuntimeJobStatus = async (options, executionId, invocationOpt
707
633
  });
708
634
  const url = jobExecutionUrl(options, identity);
709
635
  const headers = new Headers(await resolveHeaders(options.headers));
710
- const { response, body } = await withRuntimeRequestSignal(invocationOptions, async (signal) => {
711
- if (signal?.aborted === true) {
712
- throw abortReason(signal);
713
- }
714
- const response = await awaitWithAbort(Promise.resolve().then(() => {
715
- if (signal?.aborted === true) {
716
- throw abortReason(signal);
717
- }
718
- return runtimeFetch(url, {
719
- headers,
720
- method: "GET",
721
- ...(signal === undefined ? {} : { signal }),
722
- });
723
- }), signal);
724
- return { body: await readRuntimeResponseBody(response, signal), response };
725
- });
636
+ const { response, body } = await withRuntimeRequestSignal(invocationOptions, async (signal) => await fetchJobStatus({
637
+ damper,
638
+ deploymentId,
639
+ emit: event => emitRuntimeEvent(invocationOptions, event),
640
+ executionId: normalizedExecutionId,
641
+ headers,
642
+ requestId,
643
+ runtimeFetch,
644
+ ...(signal === undefined ? {} : { signal }),
645
+ url,
646
+ }));
726
647
  if (!response.ok && response.status !== 202) {
727
648
  const message = runtimeErrorMessage(body, `Uru app runtime job status failed with HTTP ${response.status}`);
728
649
  emitRuntimeEvent(invocationOptions, {
@@ -742,6 +663,10 @@ export const getAppRuntimeJobStatus = async (options, executionId, invocationOpt
742
663
  throw new UruAppRuntimeError(message, {
743
664
  body,
744
665
  status: response.status,
666
+ retryAfterSeconds: parseRetryAfterSeconds({
667
+ body,
668
+ header: response.headers.get("retry-after"),
669
+ }),
745
670
  });
746
671
  }
747
672
  const statusBody = appRuntimeExecutionStatusFromHttp(body, invocationOptions?.decodeResult);
@@ -762,7 +687,7 @@ export const getAppRuntimeJobStatus = async (options, executionId, invocationOpt
762
687
  });
763
688
  return normalizedStatus;
764
689
  };
765
- export const cancelAppRuntimeJob = async (options, executionId, invocationOptions) => {
690
+ export const cancelAppRuntimeJob = async (options, executionId, invocationOptions, damper) => {
766
691
  const runtimeFetch = resolveRuntimeFetch(options);
767
692
  const identity = jobIdentity(options, executionId);
768
693
  const { deploymentId, executionId: normalizedExecutionId } = identity;
@@ -771,22 +696,17 @@ export const cancelAppRuntimeJob = async (options, executionId, invocationOption
771
696
  const requestId = invocationOptions?.requestId ?? makeRuntimeRequestId();
772
697
  const url = jobExecutionUrl(options, identity, true);
773
698
  const headers = new Headers(await resolveHeaders(options.headers));
774
- const { response, body } = await withRuntimeRequestSignal(invocationOptions, async (signal) => {
775
- if (signal?.aborted === true) {
776
- throw abortReason(signal);
777
- }
778
- const response = await awaitWithAbort(Promise.resolve().then(() => {
779
- if (signal?.aborted === true) {
780
- throw abortReason(signal);
781
- }
782
- return runtimeFetch(url, {
783
- headers,
784
- method: "POST",
785
- ...(signal === undefined ? {} : { signal }),
786
- });
787
- }), signal);
788
- return { body: await readRuntimeResponseBody(response, signal), response };
789
- });
699
+ const { response, body } = await withRuntimeRequestSignal(invocationOptions, async (signal) => await fetchJobCancel({
700
+ damper,
701
+ deploymentId,
702
+ emit: event => emitRuntimeEvent(invocationOptions, event),
703
+ executionId: normalizedExecutionId,
704
+ headers,
705
+ requestId,
706
+ runtimeFetch,
707
+ ...(signal === undefined ? {} : { signal }),
708
+ url,
709
+ }));
790
710
  if (!response.ok) {
791
711
  const message = runtimeErrorMessage(body, `Uru app runtime job cancel failed with HTTP ${response.status}`);
792
712
  emitRuntimeEvent(invocationOptions, {
@@ -806,6 +726,10 @@ export const cancelAppRuntimeJob = async (options, executionId, invocationOption
806
726
  throw new UruAppRuntimeError(message, {
807
727
  body,
808
728
  status: response.status,
729
+ retryAfterSeconds: parseRetryAfterSeconds({
730
+ body,
731
+ header: response.headers.get("retry-after"),
732
+ }),
809
733
  });
810
734
  }
811
735
  const runtimeResponse = appRuntimeInvocationResponseFromHttp(body, invocationOptions?.decodeResult);
@@ -830,8 +754,8 @@ export const cancelAppRuntimeJob = async (options, executionId, invocationOption
830
754
  diagnostics,
831
755
  executionId: normalizedExecutionId,
832
756
  requestId,
833
- state: "canceled",
834
- type: "canceled",
757
+ state,
758
+ type: runtimeEventTypeForState(state, normalizedResponse.pending),
835
759
  });
836
760
  return normalizedResponse;
837
761
  };
package/dist/types.d.ts CHANGED
@@ -27,7 +27,7 @@ export type UruAppRuntimeCapabilityType = "query" | "action" | "job" | "endpoint
27
27
  * may add a state before this package knows about it, and a client that threw
28
28
  * on an unrecognised state would break on a backend deploy.
29
29
  */
30
- export type UruAppRuntimeState = "idle" | "queued" | "running" | "polling" | "cached" | "stale" | "refreshing" | "refreshed" | "succeeded" | "failed" | "rate_limited" | "budget_blocked" | "service_unavailable" | "canceled";
30
+ export type UruAppRuntimeState = "idle" | "queued" | "running" | "cancel_requested" | "polling" | "cached" | "stale" | "refreshing" | "refreshed" | "succeeded" | "failed" | "rate_limited" | "reconnecting" | "budget_blocked" | "service_unavailable" | "canceled";
31
31
  /** Lifecycle transitions reported to `onEvent` / `onStatus`. */
32
32
  export type UruAppRuntimeEventType = "started" | "status" | "completed" | "failed" | "canceled";
33
33
  /** One lifecycle notification for an in-flight invocation. */
@@ -117,6 +117,8 @@ export interface UruActionInvoker {
117
117
  }
118
118
  /** The capability-invocation client returned by `createUruAppRuntimeClient`. */
119
119
  export interface UruAppRuntimeClient {
120
+ /** Deployment identity used by every operation on this client. */
121
+ readonly deploymentId: string;
120
122
  query: UruCapabilityInvoker;
121
123
  action: UruCapabilityInvoker;
122
124
  job: UruCapabilityInvoker;
@@ -125,6 +127,111 @@ export interface UruAppRuntimeClient {
125
127
  jobStatus: UruJobStatusInvoker;
126
128
  cancelJob: UruCancelJobInvoker;
127
129
  }
130
+ /** A saved caller request used to recover one background job. */
131
+ export interface UruBackgroundJobRecord {
132
+ readonly version: 1;
133
+ readonly idempotencyKey: string;
134
+ readonly deploymentId: string;
135
+ readonly capabilityName: string;
136
+ readonly input: Readonly<Record<string, unknown>>;
137
+ /** Absolute Unix time in milliseconds. This value never changes on resume. */
138
+ readonly deadlineAt: number;
139
+ /** The exact invocation timeout sent on every start replay. */
140
+ readonly timeoutMs?: number;
141
+ readonly executionId: string | null;
142
+ /** A saved user intent. It does not mean the job has stopped. */
143
+ readonly cancelRequested: boolean;
144
+ /** The server acknowledged a cancel request. It does not prove final cancel. */
145
+ readonly cancelAcknowledged: boolean;
146
+ }
147
+ /**
148
+ * Atomic caller-owned persistence for resumable background job requests.
149
+ * `create` must insert only when the key is absent. Each update must change
150
+ * only its named field, keep immutable request fields fixed, and never change
151
+ * a saved `true` control flag back to `false`.
152
+ */
153
+ export interface UruBackgroundJobStore {
154
+ /** Read one record by its logical request key. */
155
+ load(idempotencyKey: string): Promise<unknown | null>;
156
+ /** Insert only when absent; return the stored record when the key exists. */
157
+ create(record: UruBackgroundJobRecord): Promise<{
158
+ created: boolean;
159
+ record: unknown;
160
+ }>;
161
+ /** Set the server execution id once, or confirm that it is already equal. */
162
+ setExecutionId(idempotencyKey: string, executionId: string): Promise<unknown>;
163
+ /** Set cancel intent to true without changing immutable request fields. */
164
+ requestCancel(idempotencyKey: string): Promise<unknown>;
165
+ /** Set cancel acknowledgement to true without changing other fields. */
166
+ acknowledgeCancel(idempotencyKey: string): Promise<unknown>;
167
+ }
168
+ /** The fixed request data a Gem persists before starting background work. */
169
+ export interface UruBackgroundJobRequest {
170
+ idempotencyKey: string;
171
+ capabilityName: string;
172
+ input?: Readonly<Record<string, unknown>>;
173
+ deadlineAt: number;
174
+ timeoutMs?: number;
175
+ }
176
+ /** Local callbacks and cancellation for one helper call. */
177
+ export type UruBackgroundJobCallOptions = Pick<UruAppRuntimeInvocationOptions, "signal" | "onEvent" | "onStatus">;
178
+ /** Dependencies for the shared start/observe/wait/cancel/resume helper. */
179
+ export interface CreateUruBackgroundJobCoordinatorOptions {
180
+ app: UruAppRuntimeClient;
181
+ deploymentId: string;
182
+ store: UruBackgroundJobStore;
183
+ pollIntervalMs?: number;
184
+ now?: () => number;
185
+ sleep?: (milliseconds: number, signal: AbortSignal) => Promise<void>;
186
+ }
187
+ /** One read of the server-owned job state. */
188
+ export type UruBackgroundJobObservation = {
189
+ kind: "unknown";
190
+ reason: "execution_id_missing";
191
+ record: UruBackgroundJobRecord;
192
+ } | {
193
+ kind: "pending";
194
+ record: UruBackgroundJobRecord;
195
+ executionId: string;
196
+ status: UruAppRuntimeExecutionStatus;
197
+ } | {
198
+ kind: "complete";
199
+ record: UruBackgroundJobRecord;
200
+ executionId: string;
201
+ status: UruAppRuntimeExecutionStatus;
202
+ };
203
+ /** Resume may replay a saved start to recover an execution id after a lost response. */
204
+ export type UruBackgroundJobResumeResult = {
205
+ kind: "unknown";
206
+ reason: "execution_id_missing" | "deadline_expired";
207
+ record: UruBackgroundJobRecord;
208
+ startResponse?: UruAppRuntimeInvocationResponse;
209
+ } | {
210
+ kind: "pending" | "complete";
211
+ record: UruBackgroundJobRecord;
212
+ executionId: string;
213
+ status: UruAppRuntimeExecutionStatus;
214
+ startResponse?: UruAppRuntimeInvocationResponse;
215
+ cancelResponse?: UruAppRuntimeInvocationResponse;
216
+ };
217
+ /** wait returns the last server state when the original deadline expires. */
218
+ export type UruBackgroundJobWaitResult = UruBackgroundJobResumeResult | {
219
+ kind: "deadline_exceeded";
220
+ record: UruBackgroundJobRecord;
221
+ executionId?: string;
222
+ status?: UruAppRuntimeExecutionStatus;
223
+ };
224
+ /** Typed operations over the existing app-runtime job endpoints. */
225
+ export interface UruBackgroundJobCoordinator {
226
+ start(request: UruBackgroundJobRequest, options?: UruBackgroundJobCallOptions): Promise<{
227
+ record: UruBackgroundJobRecord;
228
+ response: UruAppRuntimeInvocationResponse;
229
+ }>;
230
+ observe(idempotencyKey: string, options?: UruBackgroundJobCallOptions): Promise<UruBackgroundJobObservation>;
231
+ wait(idempotencyKey: string, options?: UruBackgroundJobCallOptions): Promise<UruBackgroundJobWaitResult>;
232
+ cancel(idempotencyKey: string, options?: UruBackgroundJobCallOptions): Promise<UruBackgroundJobResumeResult>;
233
+ resume(idempotencyKey: string, options?: UruBackgroundJobCallOptions): Promise<UruBackgroundJobResumeResult>;
234
+ }
128
235
  /** Comparison operators accepted by a Dataset `where` clause. */
129
236
  export type UruDatasetWhereOperator = "eq" | "neq" | "ne" | "gt" | "gte" | "lt" | "lte" | "ilike" | "in" | "nin" | "not_in" | "is_null";
130
237
  /** One server-side filter condition. */
@@ -174,8 +281,30 @@ export interface UruDatasetRowsResult<TRow = UruDatasetRow> {
174
281
  nextCursor?: string | null;
175
282
  sourceMeta?: RuntimeJsonObject | null;
176
283
  }
177
- /** One validated wire row. A caller can decode it into a domain model. */
178
- export type UruDatasetRow = RuntimeJsonObject;
284
+ /** Metadata owned by Uru for one native Dataset row. */
285
+ export interface UruDatasetRowMetadata {
286
+ readonly id: string;
287
+ readonly rowVersion?: string;
288
+ readonly createdAt?: string;
289
+ readonly updatedAt?: string;
290
+ readonly deleted?: boolean;
291
+ }
292
+ /** Native Dataset V2 row view with customer fields kept below `fields`. */
293
+ export interface UruDatasetRowView<TFields extends RuntimeJsonObject = RuntimeJsonObject> extends UruDatasetRowMetadata {
294
+ readonly fields: TFields;
295
+ }
296
+ /** One validated native Dataset row returned by `queryRows`. */
297
+ export type UruDatasetRow = UruDatasetRowView;
298
+ /** A lossless row update: identity and customer fields use separate keys. */
299
+ export interface UruDatasetRowMutationInput<TFields extends RuntimeJsonObject = RuntimeJsonObject> {
300
+ readonly rowId: string | null;
301
+ readonly expectedRowVersion: string | null;
302
+ readonly fields: TFields;
303
+ }
304
+ /** Flat row input accepted by a Dataset upsert. */
305
+ export type UruDatasetRowInput<TFields extends RuntimeJsonObject = RuntimeJsonObject> = TFields & {
306
+ readonly id?: string;
307
+ };
179
308
  /** The envelope every Dataset write resolves to. */
180
309
  export interface UruDatasetMutationResult<TResult = unknown> {
181
310
  ok: boolean;
@@ -197,6 +326,12 @@ export interface UruDatasetSqlWriteOptions {
197
326
  maxRows?: number;
198
327
  maxAffected?: number;
199
328
  timeoutMs?: number;
329
+ /**
330
+ * Names this one statement. A second send with the same key and statement
331
+ * gets the first result instead of a second run. Each call gets its own key
332
+ * when this is omitted.
333
+ */
334
+ idempotencyKey?: string;
200
335
  }
201
336
  export interface UruDatasetQueryRows {
202
337
  <TRow>(datasetRef: string, query: UruDatasetQuery | undefined, decodeRow: UruResultDecoder<TRow>): Promise<UruDatasetRowsResult<TRow>>;
@@ -205,12 +340,21 @@ export interface UruDatasetQueryRows {
205
340
  /** Public wire contract: kept local because this package has no private workspace dependencies. */
206
341
  export interface UruDatasetMutationOptions {
207
342
  expectedDatasetRevision?: string;
343
+ /**
344
+ * Names this one write. A second send with the same key and rows gets the
345
+ * first result instead of a second write. Each call gets its own key when
346
+ * this is omitted.
347
+ */
208
348
  idempotencyKey?: string;
209
349
  }
210
350
  export interface UruDatasetRowMutation {
211
351
  <TResult>(datasetRef: string, rows: readonly unknown[], decodeResult: UruResultDecoder<TResult>, options?: UruDatasetMutationOptions): Promise<UruDatasetMutationResult<TResult>>;
212
352
  (datasetRef: string, rows: readonly unknown[], decodeResult?: undefined, options?: UruDatasetMutationOptions): Promise<UruDatasetMutationResult>;
213
353
  }
354
+ export interface UruDatasetRowViewMutation {
355
+ <TFields extends RuntimeJsonObject, TResult>(datasetRef: string, rows: readonly UruDatasetRowMutationInput<TFields>[], decodeResult: UruResultDecoder<TResult>, options?: UruDatasetMutationOptions): Promise<UruDatasetMutationResult<TResult>>;
356
+ <TFields extends RuntimeJsonObject>(datasetRef: string, rows: readonly UruDatasetRowMutationInput<TFields>[], decodeResult?: undefined, options?: UruDatasetMutationOptions): Promise<UruDatasetMutationResult>;
357
+ }
214
358
  export interface UruDatasetIdMutation {
215
359
  <TResult>(datasetRef: string, rowIds: readonly string[], decodeResult: UruResultDecoder<TResult>, options?: UruDatasetMutationOptions): Promise<UruDatasetMutationResult<TResult>>;
216
360
  (datasetRef: string, rowIds: readonly string[], decodeResult?: undefined, options?: UruDatasetMutationOptions): Promise<UruDatasetMutationResult>;
@@ -224,6 +368,7 @@ export interface UruDatasetsContext {
224
368
  queryRows: UruDatasetQueryRows;
225
369
  insertRows: UruDatasetRowMutation;
226
370
  upsertRows: UruDatasetRowMutation;
371
+ upsertRowViews: UruDatasetRowViewMutation;
227
372
  deleteRows: UruDatasetIdMutation;
228
373
  restoreRows: UruDatasetIdMutation;
229
374
  sqlWrite: UruDatasetSqlWrite;
@@ -238,8 +383,14 @@ export interface UruFileMetadata {
238
383
  export interface UruFileContent extends UruFileMetadata {
239
384
  readonly content: Uint8Array;
240
385
  }
386
+ /**
387
+ * One file the Gem wrote. `fileDeleted` is `true` once a person deleted that
388
+ * Library file forever: the output stays listed with the `fileId` it had, and
389
+ * `readOutput` answers 410.
390
+ */
241
391
  export interface UruFileOutput extends UruFileMetadata {
242
392
  readonly outputId: string;
393
+ readonly fileDeleted: boolean;
243
394
  readonly createdAt: string;
244
395
  }
245
396
  export interface UruFileOutputSummary extends UruFileOutput {
@@ -337,6 +488,19 @@ export interface UruJobProgress {
337
488
  readonly message?: string;
338
489
  }
339
490
  export type UruJobCheckpoint = RuntimeJsonObject;
491
+ /** The step a job is running, as its work receives it. */
492
+ export interface UruJobStep {
493
+ /** The step's name. */
494
+ readonly name: string;
495
+ /**
496
+ * A key this job run owns for the step's own write. It is the same on
497
+ * every attempt of the run. Pass it as a file output's `idempotencyKey`, or
498
+ * to an external API that takes an idempotency key.
499
+ */
500
+ readonly idempotencyKey: string;
501
+ }
502
+ /** What a job step may return. It is saved as JSON in the job checkpoint. */
503
+ export type UruJobStepResult = RuntimeJsonValue | undefined | void;
340
504
  /** Everything a Uru server runtime hands an app. */
341
505
  export interface UruServerContext {
342
506
  files: UruFilesContext;
@@ -348,7 +512,23 @@ export interface UruServerContext {
348
512
  jobs: {
349
513
  start: UruCapabilityInvoker;
350
514
  progress: (progress: UruJobProgress) => Promise<void>;
515
+ /**
516
+ * Save the job's own resume data. It replaces the data saved before;
517
+ * saved step results stay, also when the value carries a copy of them
518
+ * under `$uruSteps`. It is refused while a job step runs.
519
+ */
351
520
  checkpoint: (value: UruJobCheckpoint) => Promise<void>;
521
+ /**
522
+ * Run one named step of a program job once per job run.
523
+ *
524
+ * The first time, `run` runs and its result is saved in the job
525
+ * checkpoint. When a lost attempt runs the job again, the step returns
526
+ * the saved result and `run` does not run. A step that was cut short runs
527
+ * again, and its calls send the same keys, so each call's first answer
528
+ * comes back instead of a second write. Steps run one at a time, each
529
+ * name runs once per job run, and results must be small JSON.
530
+ */
531
+ step: <T extends UruJobStepResult>(name: string, run: (step: UruJobStep) => Promise<T> | T) => Promise<T>;
352
532
  };
353
533
  secrets: {
354
534
  has: (name: string) => boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uru-intelligence/app",
3
- "version": "2.1.5",
3
+ "version": "2.2.1",
4
4
  "private": false,
5
5
  "description": "Runtime client for Uru Gems: capability calls, Datasets, jobs and secrets",
6
6
  "keywords": [
@@ -53,12 +53,12 @@
53
53
  },
54
54
  "devDependencies": {
55
55
  "@types/node": "24.13.3",
56
- "bun-types": "1.3.13",
56
+ "bun-types": "1.3.14",
57
57
  "publint": "0.3.24",
58
58
  "typescript": "7.0.2"
59
59
  },
60
60
  "engines": {
61
61
  "node": ">=22.12.0"
62
62
  },
63
- "packageManager": "bun@1.3.13"
63
+ "packageManager": "bun@1.3.14"
64
64
  }