@uru-intelligence/app 2.1.6 → 2.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +463 -14
  2. package/dist/background-jobs.d.ts +11 -0
  3. package/dist/background-jobs.js +571 -0
  4. package/dist/dampers.d.ts +24 -1
  5. package/dist/dampers.js +3 -0
  6. package/dist/dataset-boundary.js +38 -1
  7. package/dist/dataset-row.d.ts +9 -0
  8. package/dist/dataset-row.js +11 -0
  9. package/dist/datasets.d.ts +2 -1
  10. package/dist/datasets.js +82 -28
  11. package/dist/errors.js +5 -4
  12. package/dist/examples/customer-workflows/approved-external-write.d.ts +50 -0
  13. package/dist/examples/customer-workflows/approved-external-write.js +162 -0
  14. package/dist/examples/customer-workflows/file-processor.d.ts +46 -0
  15. package/dist/examples/customer-workflows/file-processor.js +53 -0
  16. package/dist/examples/customer-workflows/job-coordinator.d.ts +5 -0
  17. package/dist/examples/customer-workflows/job-coordinator.js +1 -0
  18. package/dist/examples/customer-workflows/review-only-draft.d.ts +38 -0
  19. package/dist/examples/customer-workflows/review-only-draft.js +48 -0
  20. package/dist/examples/customer-workflows/scheduled-collector.d.ts +46 -0
  21. package/dist/examples/customer-workflows/scheduled-collector.js +343 -0
  22. package/dist/files.js +4 -1
  23. package/dist/index.d.ts +6 -3
  24. package/dist/index.js +20 -7
  25. package/dist/invocations.d.ts +11 -1
  26. package/dist/invocations.js +72 -4
  27. package/dist/job-run.d.ts +90 -0
  28. package/dist/job-run.js +229 -0
  29. package/dist/jobs.d.ts +3 -3
  30. package/dist/jobs.js +39 -11
  31. package/dist/runtime.d.ts +8 -4
  32. package/dist/runtime.js +27 -7
  33. package/dist/transport-deadline.d.ts +0 -1
  34. package/dist/transport-deadline.js +0 -27
  35. package/dist/transport-invocation.d.ts +23 -4
  36. package/dist/transport-invocation.js +114 -29
  37. package/dist/transport-retry.d.ts +68 -0
  38. package/dist/transport-retry.js +245 -0
  39. package/dist/transport.d.ts +5 -20
  40. package/dist/transport.js +54 -33
  41. package/dist/types.d.ts +203 -4
  42. package/dist/uploads.js +158 -19
  43. package/package.json +34 -9
package/dist/transport.js CHANGED
@@ -19,8 +19,8 @@ import { parseRetryAfterSeconds, } from "./dampers.js";
19
19
  import { runtimeErrorMessage } from "./error-response.js";
20
20
  import { approvedRuntimeFailureCode, UruAppRuntimeError, } from "./errors.js";
21
21
  import { resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
22
- import { abortReason, awaitWithAbort, readRuntimeResponseBody, validateRuntimeInvocationOptions, withRuntimeRequestSignal, } from "./transport-deadline.js";
23
- import { fetchInvocation, fetchJobStatus } from "./transport-invocation.js";
22
+ import { abortReason, validateRuntimeInvocationOptions, withRuntimeRequestSignal, } from "./transport-deadline.js";
23
+ import { fetchInvocation, fetchJobCancel, fetchJobStatus, } from "./transport-invocation.js";
24
24
  import { isRuntimeJsonObject } from "./transport-json.js";
25
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;
26
26
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -149,7 +149,7 @@ export const appRuntimeInvocationResponseFromHttp = (value, decodeResult) => {
149
149
  return output;
150
150
  };
151
151
  /** Map the owned camelCase job-status envelope without copying unknown fields. */
152
- export const appRuntimeExecutionStatusFromHttp = (value, decodeResult) => {
152
+ const appRuntimeExecutionStatusFromHttp = (value, decodeResult) => {
153
153
  const label = "app runtime job status";
154
154
  const body = httpRecord(value, label);
155
155
  const output = {
@@ -382,26 +382,42 @@ const invocationUrl = (options, deploymentId, capabilityType, capabilityName) =>
382
382
  const routeSegment = routeSegmentForCapabilityType(capabilityType);
383
383
  return `${baseUrl}${basePath}/apps/${encodeURIComponent(deploymentId)}/${routeSegment}/${encodedCapabilityName}`;
384
384
  };
385
- const invocationRequestBody = (transport, runtimeInput, effectiveForce, damper, originalInput) => {
385
+ const queryIdempotencyKey = () => `uru-app:${crypto.randomUUID()}`;
386
+ const invocationRequestBodies = (transport, runtimeInput, effectiveForce, damper, originalInput, capabilityType, capabilityName) => {
386
387
  if (effectiveForce) {
387
388
  transport.forceRefresh = true;
388
389
  }
389
390
  else {
390
391
  delete transport.forceRefresh;
391
392
  }
392
- try {
393
- if (transport.idempotencyKey === undefined &&
394
- damper.config.defaultIdempotencyKeys) {
395
- transport.idempotencyKey = `uru-app:${crypto.randomUUID()}`;
396
- }
393
+ const serialize = (idempotencyKey) => {
397
394
  const requestBody = JSON.stringify({
398
395
  input: runtimeInput,
399
396
  ...transport,
397
+ ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
400
398
  });
401
399
  if (requestBody === undefined) {
402
400
  throw new TypeError("App runtime input could not be serialized.");
403
401
  }
404
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
+ };
405
421
  }
406
422
  catch {
407
423
  throw new UruAppRuntimeError("Invalid app runtime input.", {
@@ -410,6 +426,14 @@ const invocationRequestBody = (transport, runtimeInput, effectiveForce, damper,
410
426
  });
411
427
  }
412
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"));
413
437
  const normalizedInvocationResponse = (runtimeResponse, fallbackIdentity, fallbackCapabilityType, state, diagnostics) => ({
414
438
  capabilityName: runtimeResponse.capabilityName === ""
415
439
  ? fallbackIdentity.capabilityName
@@ -455,7 +479,7 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
455
479
  const url = invocationUrl(options, deploymentId, capabilityType, capabilityName);
456
480
  // Create the key once per invocation. Transport retries reuse this body,
457
481
  // while a later call remains a separate operation even when its input matches.
458
- const requestBody = invocationRequestBody(transport, runtimeInput, effectiveForce, damper, input);
482
+ const requestBodies = invocationRequestBodies(transport, runtimeInput, effectiveForce, damper, input, capabilityType, capabilityName);
459
483
  emitRuntimeEvent(invocationOptions, {
460
484
  capabilityName,
461
485
  capabilityType,
@@ -466,10 +490,11 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
466
490
  });
467
491
  const headers = new Headers(await resolveHeaders(options.headers));
468
492
  headers.set("content-type", "application/json");
469
- // P2 damper: bounded backoff-and-retry on 429 / rate_limited. `attempt` counts
470
- // retries beyond the first send; the loop performs at most
493
+ // P2 damper: bounded backoff-and-retry on 429 / rate_limited, at most
471
494
  // `maxRateLimitRetries` extra sends, honoring Retry-After / retry_after_seconds
472
- // (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.
473
498
  const { body, response } = await withRuntimeRequestSignal(invocationOptions, async (requestSignal) => await fetchInvocation({
474
499
  capabilityName,
475
500
  capabilityType,
@@ -477,8 +502,9 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
477
502
  deploymentId,
478
503
  emit: event => emitRuntimeEvent(invocationOptions, event),
479
504
  headers,
480
- requestBody,
505
+ requestBody: requestBodies.bodyFor,
481
506
  requestId,
507
+ resendLost: invocationResendsLost(capabilityType, requestBodies.keyed),
482
508
  runtimeFetch,
483
509
  ...(requestSignal === undefined ? {} : { signal: requestSignal }),
484
510
  url,
@@ -661,7 +687,7 @@ export const getAppRuntimeJobStatus = async (options, executionId, invocationOpt
661
687
  });
662
688
  return normalizedStatus;
663
689
  };
664
- export const cancelAppRuntimeJob = async (options, executionId, invocationOptions) => {
690
+ export const cancelAppRuntimeJob = async (options, executionId, invocationOptions, damper) => {
665
691
  const runtimeFetch = resolveRuntimeFetch(options);
666
692
  const identity = jobIdentity(options, executionId);
667
693
  const { deploymentId, executionId: normalizedExecutionId } = identity;
@@ -670,22 +696,17 @@ export const cancelAppRuntimeJob = async (options, executionId, invocationOption
670
696
  const requestId = invocationOptions?.requestId ?? makeRuntimeRequestId();
671
697
  const url = jobExecutionUrl(options, identity, true);
672
698
  const headers = new Headers(await resolveHeaders(options.headers));
673
- const { response, body } = await withRuntimeRequestSignal(invocationOptions, async (signal) => {
674
- if (signal?.aborted === true) {
675
- throw abortReason(signal);
676
- }
677
- const response = await awaitWithAbort(Promise.resolve().then(() => {
678
- if (signal?.aborted === true) {
679
- throw abortReason(signal);
680
- }
681
- return runtimeFetch(url, {
682
- headers,
683
- method: "POST",
684
- ...(signal === undefined ? {} : { signal }),
685
- });
686
- }), signal);
687
- return { body: await readRuntimeResponseBody(response, signal), response };
688
- });
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
+ }));
689
710
  if (!response.ok) {
690
711
  const message = runtimeErrorMessage(body, `Uru app runtime job cancel failed with HTTP ${response.status}`);
691
712
  emitRuntimeEvent(invocationOptions, {
@@ -733,8 +754,8 @@ export const cancelAppRuntimeJob = async (options, executionId, invocationOption
733
754
  diagnostics,
734
755
  executionId: normalizedExecutionId,
735
756
  requestId,
736
- state: "canceled",
737
- type: "canceled",
757
+ state,
758
+ type: runtimeEventTypeForState(state, normalizedResponse.pending),
738
759
  });
739
760
  return normalizedResponse;
740
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 {
@@ -276,7 +427,7 @@ export type UruUploadOutcome = "verified" | "pending" | "absent" | "expired" | "
276
427
  * A minted grant. `uploadUrl` is a CREDENTIAL: do not log it or store it.
277
428
  *
278
429
  * `requiredHeaders` is not advice. The provider rebuilds the signature from
279
- * what actually arrives, so a PUT that omits or alters either header is
430
+ * what actually arrives, so a PUT that omits or alters any header is
280
431
  * refused.
281
432
  */
282
433
  export interface UruUploadGrant {
@@ -301,20 +452,39 @@ export interface UruUploadResult {
301
452
  /** True only when a refused object could not be removed from storage. */
302
453
  readonly cleanupFailed: boolean;
303
454
  }
455
+ export interface UruUploadStatus {
456
+ readonly uploadId: string;
457
+ readonly state: UruUploadResult['state'];
458
+ readonly outcome: UruUploadOutcome | null;
459
+ readonly filename: string;
460
+ readonly contentType: string;
461
+ readonly sizeBytes: number | null;
462
+ readonly expiresAt: string;
463
+ /** True while the platform still needs to retry object cleanup. */
464
+ readonly cleanupFailed: boolean;
465
+ }
304
466
  /** The file-upload lane a Gem gets with the `storage` capability. */
305
467
  export interface UruUploadsContext {
306
468
  request(input: {
307
469
  filename: string;
308
470
  contentType: string;
309
471
  sizeBytes: number;
472
+ /** Reuse this key after an uncertain response. The SDK also retains an
473
+ * automatic key when its response is uncertain. */
474
+ idempotencyKey?: string;
310
475
  signal?: AbortSignal;
311
476
  }): Promise<UruUploadGrant>;
477
+ /** Read the saved result for a request key without starting another upload. */
478
+ status(idempotencyKey: string, options?: {
479
+ signal?: AbortSignal;
480
+ }): Promise<UruUploadStatus>;
312
481
  complete(uploadId: string, options?: {
313
482
  signal?: AbortSignal;
314
483
  }): Promise<UruUploadResult>;
315
484
  /** Request, PUT and complete in one call. What almost every caller wants. */
316
485
  upload(file: File, options?: {
317
486
  signal?: AbortSignal;
487
+ idempotencyKey?: string;
318
488
  }): Promise<UruUploadResult>;
319
489
  /**
320
490
  * Read one VERIFIED upload back, as a `Blob`.
@@ -337,6 +507,19 @@ export interface UruJobProgress {
337
507
  readonly message?: string;
338
508
  }
339
509
  export type UruJobCheckpoint = RuntimeJsonObject;
510
+ /** The step a job is running, as its work receives it. */
511
+ export interface UruJobStep {
512
+ /** The step's name. */
513
+ readonly name: string;
514
+ /**
515
+ * A key this job run owns for the step's own write. It is the same on
516
+ * every attempt of the run. Pass it as a file output's `idempotencyKey`, or
517
+ * to an external API that takes an idempotency key.
518
+ */
519
+ readonly idempotencyKey: string;
520
+ }
521
+ /** What a job step may return. It is saved as JSON in the job checkpoint. */
522
+ export type UruJobStepResult = RuntimeJsonValue | undefined | void;
340
523
  /** Everything a Uru server runtime hands an app. */
341
524
  export interface UruServerContext {
342
525
  files: UruFilesContext;
@@ -348,7 +531,23 @@ export interface UruServerContext {
348
531
  jobs: {
349
532
  start: UruCapabilityInvoker;
350
533
  progress: (progress: UruJobProgress) => Promise<void>;
534
+ /**
535
+ * Save the job's own resume data. It replaces the data saved before;
536
+ * saved step results stay, also when the value carries a copy of them
537
+ * under `$uruSteps`. It is refused while a job step runs.
538
+ */
351
539
  checkpoint: (value: UruJobCheckpoint) => Promise<void>;
540
+ /**
541
+ * Run one named step of a program job once per job run.
542
+ *
543
+ * The first time, `run` runs and its result is saved in the job
544
+ * checkpoint. When a lost attempt runs the job again, the step returns
545
+ * the saved result and `run` does not run. A step that was cut short runs
546
+ * again, and its calls send the same keys, so each call's first answer
547
+ * comes back instead of a second write. Steps run one at a time, each
548
+ * name runs once per job run, and results must be small JSON.
549
+ */
550
+ step: <T extends UruJobStepResult>(name: string, run: (step: UruJobStep) => Promise<T> | T) => Promise<T>;
352
551
  };
353
552
  secrets: {
354
553
  has: (name: string) => boolean;