@uru-intelligence/app 2.2.5 → 2.4.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/README.md CHANGED
@@ -1,5 +1,118 @@
1
1
  # @uru-intelligence/app
2
2
 
3
+ ## Named values in Gem storage
4
+
5
+ Declare `"storage": true` in the root `uru.json`. The browser client and the
6
+ server context expose the same four operations:
7
+
8
+ ```ts
9
+ const app = createUruAppRuntimeClient({ deploymentId });
10
+ await app.storage.put('settings', { theme: 'dark' });
11
+ const settings = await app.storage.get('settings');
12
+ if (settings.found) console.log(settings.value);
13
+ const page = await app.storage.list({ prefix: 'settings', limit: 50 });
14
+ await app.storage.delete('settings');
15
+
16
+ // The Gem's one shared scope: every viewer reads and writes it.
17
+ await app.storage.put('scores', { top: 42 }, { shared: true });
18
+ const scores = await app.storage.get('scores', { shared: true });
19
+ ```
20
+
21
+ A Gem has one store for every version, preview and release. It has two
22
+ scopes:
23
+
24
+ - Personal (the default): one scope for each viewer, the owner included.
25
+ Nobody else reads it, the owner neither.
26
+ - Shared (`{ shared: true }`): one scope for the Gem. Every viewer reads and
27
+ writes it, and the owner can see, delete, and clear its keys.
28
+
29
+ The server verifies the caller and chooses the Gem, the workspace, and the
30
+ viewer. Do not send those identities in stored values to choose a scope. A
31
+ signed-in person keeps one personal scope for the Gem. A public visitor who is
32
+ not signed in keeps a personal scope tied to a browser cookie. On the server,
33
+ use `createUruServerContext(env).storage`: a server token uses the Gem owner's
34
+ personal scope, and it can read and write the shared scope with
35
+ `{ shared: true }` without a question.
36
+
37
+ The first shared put of a person to a Gem waits for that person's answer to
38
+ `URU_STORAGE_SHARED_WRITE_NOTICE` ("Your data will be visible to others using
39
+ this Gem."). Inside Uru, the Uru shell asks and sends the put again on a Yes.
40
+ A Gem on its own web address has no shell: the put fails with an
41
+ `UruAppRuntimeError` whose `code` is `storage_shared_consent_required`. Show
42
+ the same words to the person, and on a Yes send the put again with
43
+ `{ shared: true, sharedWriteConfirmed: true }`. On a No, do not send it. Uru
44
+ keeps a Yes for that person and that Gem. The flag is a notice, not an access
45
+ control: it gives no access that the viewer does not already have.
46
+
47
+ A key has 1 to 1000 UTF-8 bytes. Values must be JSON, and each value can use
48
+ at most 256 KiB. All personal and shared values of one Gem, for every viewer
49
+ together, can use at most 20 MB; a write past that fails with the code
50
+ `storage_gem_full`. Public requests have a 100 KB body limit. `list` returns
51
+ keys and `nextCursor`; pass that cursor to read the next page. A missing key
52
+ returns `{ found: false }`. `null` is a stored value and returns
53
+ `{ found: true, value: null }`. Stored values do not expire. When the last
54
+ link or person that can open the Gem goes, Uru deletes all of the Gem's
55
+ stored data.
56
+
57
+ Each call has a request identity. You can set `requestId` in its options.
58
+ Storage does not replay a completed write. A repeated completed identity returns
59
+ an error; read the value to resolve an uncertain write. The client does not retry
60
+ writes automatically. A program job that writes storage loses automatic attempt
61
+ retry because the storage service cannot replay its first result.
62
+
63
+ Use the Dataset API for rows and queries. Use the file and upload APIs for bytes.
64
+ Gem storage does not provide a private SQL database.
65
+
66
+ ## Declare operation inputs and outputs
67
+
68
+ The root `uru.json` remains the only authored declaration. Add `description`,
69
+ `inputSchema`, and `outputSchema` to a named action or job. For an existing query,
70
+ put these fields in `capabilities.queryContracts` under its declared name:
71
+
72
+ ```json
73
+ {
74
+ "capabilities": {
75
+ "queries": ["summary"],
76
+ "queryContracts": {
77
+ "summary": {
78
+ "description": "Read the summary for one year.",
79
+ "inputSchema": {
80
+ "type": "object",
81
+ "properties": { "year": { "type": "integer" } },
82
+ "required": ["year"],
83
+ "additionalProperties": false
84
+ },
85
+ "outputSchema": { "type": "object" }
86
+ }
87
+ }
88
+ }
89
+ }
90
+ ```
91
+
92
+ This fragment belongs inside a complete `uru.gem.v2` root. A query contract must
93
+ name a query in `capabilities.queries`. Schemas can use boolean schemas and local
94
+ references such as `#/$defs/Year`. Unsupported references or formats fail source
95
+ validation. A saved job input must match its input schema.
96
+
97
+ The build copies these declarations into its immutable runtime contract. Runtime
98
+ calls check the declared input before execution and the completed output before
99
+ returning it. Program jobs check their final `outputSummary`. Tool providers keep
100
+ their own validation; an authored schema adds constraints and cannot remove them.
101
+ Tool descriptions use the same saved declarations.
102
+
103
+ The build also creates `uru.generated.d.ts` beside the root declaration. It is
104
+ build input, not a saved source edit. Import `GemInput` and `GemOutput` from it
105
+ to type browser code, for example `GemInput<'query:summary'>`. Complex schemas
106
+ that TypeScript cannot express remain `unknown`; runtime checks still apply.
107
+ Do not create your own `uru.generated.d.ts` file.
108
+
109
+ ```ts
110
+ import type { GemInput } from './uru.generated';
111
+
112
+ const input: GemInput<'query:summary'> = { year: 2026 };
113
+ await app.query('summary', input);
114
+ ```
115
+
3
116
  **This package is the runtime client for [Uru](https://uruintelligence.com) Gems.
4
117
  It is published so that Gem projects install and build outside the Uru hosted
5
118
  builder. It talks only to an Uru workspace runtime and does nothing on its own.
@@ -748,7 +861,8 @@ a build to be reproducible; Uru's own Gem templates do.
748
861
 
749
862
  The public surface includes `createUruServerContext`,
750
863
  `createUruAppRuntimeClient`, `createUruBackgroundJobCoordinator`,
751
- `createUruUploadsContext`, `UruAppRuntimeError`, and the exported types.
864
+ `createUruUploadsContext`, `createUruStorageContext`, `UruAppRuntimeError`, and
865
+ the exported types.
752
866
  Nothing else is API, even if you can reach it.
753
867
 
754
868
  ## Documentation
@@ -791,5 +905,26 @@ not supply a native revision and remain read-only.
791
905
 
792
906
  The fourth argument is the mutation options object. The optional third argument
793
907
  remains the result decoder. Native query responses also include `runtimeContext`
794
- with the server-verified `artifactId` and `viewerUserId` for local recovery state.
795
- These returned identifiers do not grant access to other resources.
908
+ with the server-set `artifactId` and `viewerUserId`. Use them only to key local
909
+ recovery state. These returned identifiers do not grant access to other resources.
910
+
911
+ `viewerUserId` is the Uru user id of the person who opened the Gem only in two
912
+ cases: a signed-in user who opens the Gem inside Uru, and a signed-in person
913
+ whom a Share's workspace or Organization access admitted. In every other case it
914
+ is `null`: a visitor on an anyone link, a passcode link, or an email-code link
915
+ (Uru verifies that email but does not give it to Gem code), and a call that Gem
916
+ server code makes with its runtime token. Gem code cannot learn who a link visitor is.
917
+
918
+ Never use `viewerUserId` to give roles, an admin view, or access to data. Code
919
+ in the browser can be changed by the visitor, so a check there only hides
920
+ screens. Control who may open the Gem with the Share instead: name the people,
921
+ or set the `email_otp` gate with an `email_allowlist`. Every person who can open
922
+ the Share can read the Gem's bound Datasets. When two groups must see different
923
+ data, give each group its own Gem or its own Share and Datasets.
924
+
925
+ The Share is the Gem's one sign-in. Do not build a second one in the Gem: no
926
+ login page, password, user table, session cookie, or sign-in library. Keep an
927
+ app key in the Gem's secrets, never in source or a Dataset, and read it only in
928
+ server code (`uru.secrets.get` in a program job, or `process.env` in the
929
+ request handler of a serverful Gem). A viewer identity on every link, and roles
930
+ that Gem code can check, are not in Uru yet.
package/dist/errors.js CHANGED
@@ -43,6 +43,11 @@ const SAFE_RUNTIME_FAILURE_CODES = new Set([
43
43
  "artifact_tool_pre_dispatch_failed",
44
44
  "artifact_tool_provider_outcome_unknown",
45
45
  "artifact_tool_terminalization_unavailable",
46
+ "artifact_policy_receipt_invalid",
47
+ "artifact_policy_receipt_unavailable",
48
+ "receipt_identity_mismatch",
49
+ "artifact_tool_proxy_refused",
50
+ "artifact_tool_policy_receipt_too_large",
46
51
  "job_provider_gateway_unavailable",
47
52
  "job_machine_admission_invalid",
48
53
  "job_runtime_image_base_unavailable",
@@ -106,6 +111,9 @@ const SAFE_RUNTIME_FAILURE_CODES = new Set([
106
111
  "tool_transport_failed",
107
112
  "usage_limit_reached",
108
113
  "usage_limit_unavailable",
114
+ "storage_shared_consent_required",
115
+ "storage_write_already_completed",
116
+ "storage_gem_full",
109
117
  ]);
110
118
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
111
119
  const safeRecordValue = (record, field) => {
package/dist/index.d.ts CHANGED
@@ -14,9 +14,10 @@ import type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, U
14
14
  export { datasetRowForMutation } from "./dataset-row.js";
15
15
  export { UruAppRuntimeError } from "./errors.js";
16
16
  export { createUruBackgroundJobCoordinator } from "./background-jobs.js";
17
- export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext } from "./uploads.js";
17
+ export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext, } from "./uploads.js";
18
+ export { createStorageContext as createUruStorageContext, URU_STORAGE_SHARED_CONSENT_REQUIRED_CODE, URU_STORAGE_SHARED_WRITE_NOTICE, } from "./storage.js";
18
19
  export type { UruRunawayDamperOptions } from "./dampers.js";
19
- export type { CreateUruAppRuntimeClientOptions, CreateUruBackgroundJobCoordinatorOptions, CreateUruServerContextOptions, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruAppRuntimeEvent, UruAppRuntimeEventType, UruAppRuntimeExecutionDiagnostics, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruAppRuntimeState, UruBackgroundJobCallOptions, UruBackgroundJobCoordinator, UruBackgroundJobObservation, UruBackgroundJobRecord, UruBackgroundJobRequest, UruBackgroundJobResumeResult, UruBackgroundJobStore, UruBackgroundJobWaitResult, UruDecodedInvocationOptions, UruResultDecoder, UruDatasetMutationResult, UruDatasetQuery, UruDatasetRow, UruDatasetRowInput, UruDatasetRowMetadata, UruDatasetRowMutationInput, UruDatasetRowsResult, UruDatasetRowView, UruDatasetRowViewMutation, UruDatasetSortClause, UruDatasetSqlWriteOptions, UruDatasetWhereClause, UruDatasetWhereOperator, UruDatasetsContext, UruFilesContext, UruFileMetadata, UruFileContent, UruFileOutput, UruFileOutputSummary, UruJobProgress, UruJobCheckpoint, UruJobStep, UruJobStepResult, UruProviderRuntimeEnvironment, UruServerContext, UruUploadGrant, UruUploadOutcome, UruUploadResult, UruUploadStatus, UruUploadsContext, } from "./types.js";
20
+ export type { CreateUruAppRuntimeClientOptions, CreateUruBackgroundJobCoordinatorOptions, CreateUruServerContextOptions, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruAppRuntimeEvent, UruAppRuntimeEventType, UruAppRuntimeExecutionDiagnostics, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruAppRuntimeState, UruBackgroundJobCallOptions, UruBackgroundJobCoordinator, UruBackgroundJobObservation, UruBackgroundJobRecord, UruBackgroundJobRequest, UruBackgroundJobResumeResult, UruBackgroundJobStore, UruBackgroundJobWaitResult, UruDecodedInvocationOptions, UruResultDecoder, UruDatasetMutationResult, UruDatasetQuery, UruDatasetRow, UruDatasetRowInput, UruDatasetRowMetadata, UruDatasetRowMutationInput, UruDatasetRowsResult, UruDatasetRowView, UruDatasetRowViewMutation, UruDatasetSortClause, UruDatasetSqlWriteOptions, UruDatasetWhereClause, UruDatasetWhereOperator, UruDatasetsContext, UruFilesContext, UruFileMetadata, UruFileContent, UruFileOutput, UruFileOutputSummary, UruJobProgress, UruJobCheckpoint, UruJobStep, UruJobStepResult, UruProviderRuntimeEnvironment, UruServerContext, UruStorageContext, UruStoragePutOptions, UruStorageRequestOptions, UruStorageValue, UruUploadGrant, UruUploadOutcome, UruUploadResult, UruUploadStatus, UruUploadsContext, } from "./types.js";
20
21
  /**
21
22
  * Build a capability-invocation client against a Uru app runtime.
22
23
  *
package/dist/index.js CHANGED
@@ -12,15 +12,17 @@
12
12
  */
13
13
  import { ForceRefreshThrottle, resolveDamperConfig } from "./dampers.js";
14
14
  import { createDatasetsContext } from "./datasets.js";
15
- import { createFilesContext } from './files.js';
16
- import { createJobProgress, createJobCheckpoint, createJobStep } from './jobs.js';
17
- import { RANDOM_CALL_KEYS, jobAttemptFor, jobCallKeys } from './job-run.js';
18
15
  import { UruAppRuntimeError } from "./errors.js";
16
+ import { createFilesContext } from "./files.js";
19
17
  import { createActionInvoker, createCancelJobInvoker, createCapabilityInvoker, createJobStatusInvoker, } from "./invocations.js";
18
+ import { RANDOM_CALL_KEYS, jobAttemptFor, jobCallKeys } from "./job-run.js";
19
+ import { createJobProgress, createJobCheckpoint, createJobStep, } from "./jobs.js";
20
+ import { createStorageContext } from "./storage.js";
20
21
  export { datasetRowForMutation } from "./dataset-row.js";
21
22
  export { UruAppRuntimeError } from "./errors.js";
22
23
  export { createUruBackgroundJobCoordinator } from "./background-jobs.js";
23
- export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext } from "./uploads.js";
24
+ export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext, } from "./uploads.js";
25
+ export { createStorageContext as createUruStorageContext, URU_STORAGE_SHARED_CONSENT_REQUIRED_CODE, URU_STORAGE_SHARED_WRITE_NOTICE, } from "./storage.js";
24
26
  const ownEnvironmentValue = (env, key) => {
25
27
  if (!Object.hasOwn(env, key)) {
26
28
  return undefined;
@@ -88,6 +90,7 @@ const appRuntimeClient = (options, keys) => {
88
90
  throttle: new ForceRefreshThrottle(),
89
91
  };
90
92
  return {
93
+ storage: createStorageContext(options),
91
94
  action: createCapabilityInvoker(options, damper, "action"),
92
95
  cancelJob: createCancelJobInvoker(options, damper),
93
96
  deploymentId: options.deploymentId.trim(),
@@ -144,6 +147,7 @@ export const createUruServerContext = (env, options = {}) => {
144
147
  return {
145
148
  actions: { run: createActionInvoker(app) },
146
149
  app,
150
+ storage: app.storage,
147
151
  datasets: createDatasetsContext(app, clientOptions, keys),
148
152
  files: createFilesContext(clientOptions),
149
153
  jobs: {
@@ -0,0 +1,15 @@
1
+ import type { CreateUruAppRuntimeClientOptions, UruStorageContext } from "./types.js";
2
+ /**
3
+ * The words a person confirms before a Gem first writes their data to the
4
+ * Gem's shared storage. A shared put without that answer fails with the code
5
+ * `storage_shared_consent_required`.
6
+ */
7
+ export declare const URU_STORAGE_SHARED_WRITE_NOTICE = "Your data will be visible to others using this Gem.";
8
+ /** The error code of a shared put that waits for the person's answer. */
9
+ export declare const URU_STORAGE_SHARED_CONSENT_REQUIRED_CODE = "storage_shared_consent_required";
10
+ /**
11
+ * Named JSON values in Gem storage: the caller's personal scope, or with
12
+ * `shared: true` the Gem's one shared scope that every viewer reads and
13
+ * writes.
14
+ */
15
+ export declare function createStorageContext(options: CreateUruAppRuntimeClientOptions): UruStorageContext;
@@ -0,0 +1,175 @@
1
+ import { runtimeErrorMessage } from "./error-response.js";
2
+ import { UruAppRuntimeError } from "./errors.js";
3
+ import { resolveHeaders, resolveRuntimeFetch, runtimeBasePath, trimTrailingSlash, } from "./runtime.js";
4
+ import { isRuntimeJsonObject } from "./transport-json.js";
5
+ const RESPONSE_BYTES = 540_672;
6
+ /** A key has 1 to 1000 UTF-8 bytes after trimming. */
7
+ const KEY_BYTES = 1000;
8
+ /**
9
+ * The words a person confirms before a Gem first writes their data to the
10
+ * Gem's shared storage. A shared put without that answer fails with the code
11
+ * `storage_shared_consent_required`.
12
+ */
13
+ export const URU_STORAGE_SHARED_WRITE_NOTICE = "Your data will be visible to others using this Gem.";
14
+ /** The error code of a shared put that waits for the person's answer. */
15
+ export const URU_STORAGE_SHARED_CONSENT_REQUIRED_CODE = "storage_shared_consent_required";
16
+ function invalid() {
17
+ throw new UruAppRuntimeError("Invalid storage request or response.", {
18
+ status: 0,
19
+ body: null,
20
+ });
21
+ }
22
+ function key(value, allowEmpty = false) {
23
+ if (typeof value !== "string" ||
24
+ new TextEncoder().encode(value.trim()).byteLength > KEY_BYTES ||
25
+ value.includes("\0") ||
26
+ (!allowEmpty && value.trim() === ""))
27
+ invalid();
28
+ return value.trim();
29
+ }
30
+ /** `shared: true` addresses the Gem's one shared scope; otherwise the caller's personal scope. */
31
+ function scopeOf(settings) {
32
+ return settings?.shared === true ? { shared: true } : {};
33
+ }
34
+ async function readJson(response) {
35
+ const reader = response.body?.getReader();
36
+ if (reader === undefined)
37
+ invalid();
38
+ let size = 0;
39
+ let text = "";
40
+ const decoder = new TextDecoder();
41
+ try {
42
+ for (;;) {
43
+ const chunk = await reader.read();
44
+ if (chunk.done)
45
+ break;
46
+ size += chunk.value.byteLength;
47
+ if (size > RESPONSE_BYTES) {
48
+ await reader.cancel();
49
+ invalid();
50
+ }
51
+ text += decoder.decode(chunk.value, { stream: true });
52
+ }
53
+ return JSON.parse(text + decoder.decode());
54
+ }
55
+ catch (error) {
56
+ if (error instanceof UruAppRuntimeError)
57
+ throw error;
58
+ return invalid();
59
+ }
60
+ finally {
61
+ reader.releaseLock();
62
+ }
63
+ }
64
+ /**
65
+ * Named JSON values in Gem storage: the caller's personal scope, or with
66
+ * `shared: true` the Gem's one shared scope that every viewer reads and
67
+ * writes.
68
+ */
69
+ export function createStorageContext(options) {
70
+ const deploymentId = options.deploymentId.trim();
71
+ if (deploymentId === "")
72
+ invalid();
73
+ const url = `${trimTrailingSlash(options.baseUrl ?? "")}${runtimeBasePath(options)}/apps/${encodeURIComponent(deploymentId)}/storage`;
74
+ const request = async (payload, settings) => {
75
+ const serialized = JSON.stringify(payload);
76
+ const headers = new Headers(await resolveHeaders(options.headers));
77
+ headers.set("content-type", "application/json");
78
+ const requestId = settings?.requestId ?? `uru-storage:${crypto.randomUUID()}`;
79
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(requestId))
80
+ invalid();
81
+ headers.set("x-uru-storage-request-id", requestId);
82
+ const response = await resolveRuntimeFetch(options)(url, {
83
+ method: "POST",
84
+ headers,
85
+ body: serialized,
86
+ signal: settings?.signal === undefined
87
+ ? AbortSignal.timeout(30_000)
88
+ : AbortSignal.any([settings.signal, AbortSignal.timeout(30_000)]),
89
+ });
90
+ const body = response.ok
91
+ ? await readJson(response)
92
+ : await readJson(response).catch(() => null);
93
+ if (!response.ok) {
94
+ throw new UruAppRuntimeError(runtimeErrorMessage(body, "Storage request was not accepted."), { status: response.status, body });
95
+ }
96
+ if (!isRuntimeJsonObject(body) ||
97
+ body["operation"] !== payload["operation"])
98
+ invalid();
99
+ return body;
100
+ };
101
+ return {
102
+ get: async (name, settings) => {
103
+ const normalized = key(name);
104
+ const result = await request({ operation: "get", key: normalized, ...scopeOf(settings) }, settings);
105
+ if (result["key"] !== normalized || typeof result["found"] !== "boolean")
106
+ invalid();
107
+ if (!result["found"])
108
+ return { found: false };
109
+ const value = result["value"];
110
+ if (value === undefined)
111
+ invalid();
112
+ return { found: true, value };
113
+ },
114
+ put: async (name, value, settings) => {
115
+ if (!isRuntimeJsonObject({ value }))
116
+ invalid();
117
+ const normalized = key(name);
118
+ const payload = {
119
+ operation: "put",
120
+ key: normalized,
121
+ value,
122
+ ...scopeOf(settings),
123
+ ...(settings?.shared === true && settings.sharedWriteConfirmed === true
124
+ ? { sharedWriteConfirmed: true }
125
+ : {}),
126
+ };
127
+ // Reject before sending a value that the private route cannot accept.
128
+ if (new TextEncoder().encode(JSON.stringify(payload)).byteLength >
129
+ RESPONSE_BYTES)
130
+ invalid();
131
+ const result = await request(payload, settings);
132
+ const storedValue = result["value"];
133
+ if (result["key"] !== normalized || storedValue === undefined)
134
+ invalid();
135
+ return { value: storedValue };
136
+ },
137
+ delete: async (name, settings) => {
138
+ const normalized = key(name);
139
+ const result = await request({ operation: "delete", key: normalized, ...scopeOf(settings) }, settings);
140
+ if (result["key"] !== normalized ||
141
+ typeof result["deleted"] !== "boolean")
142
+ invalid();
143
+ return { deleted: result["deleted"] };
144
+ },
145
+ list: async (settings = {}) => {
146
+ if (settings.limit !== undefined &&
147
+ (!Number.isInteger(settings.limit) ||
148
+ settings.limit < 1 ||
149
+ settings.limit > 100))
150
+ invalid();
151
+ const result = await request({
152
+ operation: "list",
153
+ ...scopeOf(settings),
154
+ ...(settings.prefix === undefined
155
+ ? {}
156
+ : { prefix: key(settings.prefix, true) }),
157
+ ...(settings.cursor === undefined
158
+ ? {}
159
+ : { cursor: key(settings.cursor) }),
160
+ ...(settings.limit === undefined ? {} : { limit: settings.limit }),
161
+ }, settings);
162
+ const keys = result["keys"];
163
+ const nextCursor = result["nextCursor"];
164
+ if (!Array.isArray(keys) ||
165
+ keys.length > (settings.limit ?? 50) ||
166
+ keys.some((value) => typeof value !== "string") ||
167
+ (nextCursor !== null && typeof nextCursor !== "string"))
168
+ invalid();
169
+ return {
170
+ keys: keys.map((value) => key(String(value))),
171
+ nextCursor: nextCursor === null ? null : key(nextCursor),
172
+ };
173
+ },
174
+ };
175
+ }
@@ -2,6 +2,12 @@ import type { DamperRuntime } from "./transport.js";
2
2
  import type { UruAppRuntimeCapabilityType, UruAppRuntimeEvent } from "./types.js";
3
3
  import type { RuntimeFetch } from "./runtime.js";
4
4
  export interface InvocationFetchArguments {
5
+ /**
6
+ * The longest one send waits for its answer's headers, or null for no
7
+ * limit of its own ({@link queryAnswerLimitMs}). A send that reaches it
8
+ * counts as lost.
9
+ */
10
+ answerLimitMs: number | null;
5
11
  capabilityName: string;
6
12
  capabilityType: UruAppRuntimeCapabilityType;
7
13
  damper: DamperRuntime;
@@ -25,6 +31,15 @@ interface SendCounts {
25
31
  readonly rateLimited: number;
26
32
  readonly resent: number;
27
33
  }
34
+ /**
35
+ * The longest one query send waits for its answer's headers. A live API
36
+ * replica answers a query by its server deadline, a temporary 503 at worst.
37
+ * A send with no answer later than that went to a replica that stopped, or
38
+ * stalled before the query reached its deadline, so it is lost, and a query
39
+ * is sent again. Kill Proof 40082762738 (Development, 2026-10-24): four
40
+ * queries each waited 30 s on one send that never got an answer.
41
+ */
42
+ export declare const queryAnswerLimitMs: (timeoutMs: number | undefined) => number;
28
43
  export declare const fetchInvocation: (args: InvocationFetchArguments, counts?: SendCounts) => Promise<RuntimeFetchResult>;
29
44
  /** One job execution call: a status read or a cancel. */
30
45
  export interface JobStatusFetchArguments {
@@ -2,24 +2,71 @@ import { computeRateLimitRetryDelayMs, parseRetryable, parseRetryAfterSeconds, }
2
2
  import { awaitWithAbort } from "./transport-deadline.js";
3
3
  import { canResend, isLostRequest, isLostResponse, isTemporaryAnswer, readRuntimeResponseBody, resendDelayMs, waitBeforeResend, } from "./transport-retry.js";
4
4
  const FIRST_SEND = { rateLimited: 0, resent: 0 };
5
- /** One send. A lost request comes back as an outcome so the caller can decide. */
6
- const sendOnce = async (runtimeFetch, url, init, signal) => {
5
+ /**
6
+ * The API answers a query by its server deadline: the caller's `timeoutMs`
7
+ * less 1 s, at most 20 s, at least 0.5 s
8
+ * (`apps/backend-ts/src/modules/app_runtime/query-deadline.ts`). The server
9
+ * reads 25 s when the caller names no `timeoutMs`.
10
+ */
11
+ const QUERY_SERVER_TIMEOUT_DEFAULT_MS = 25_000;
12
+ const QUERY_SERVER_DEADLINE_MAX_MS = 20_000;
13
+ const QUERY_SERVER_DEADLINE_MARGIN_MS = 1_000;
14
+ const QUERY_SERVER_DEADLINE_MIN_MS = 500;
15
+ /** The time a deadline answer has to reach the SDK after the server sends it. */
16
+ const QUERY_ANSWER_TRAVEL_MS = 1_000;
17
+ /**
18
+ * The longest one query send waits for its answer's headers. A live API
19
+ * replica answers a query by its server deadline, a temporary 503 at worst.
20
+ * A send with no answer later than that went to a replica that stopped, or
21
+ * stalled before the query reached its deadline, so it is lost, and a query
22
+ * is sent again. Kill Proof 40082762738 (Development, 2026-10-24): four
23
+ * queries each waited 30 s on one send that never got an answer.
24
+ */
25
+ export const queryAnswerLimitMs = (timeoutMs) => {
26
+ const callerLimit = timeoutMs ?? QUERY_SERVER_TIMEOUT_DEFAULT_MS;
27
+ const serverDeadline = Math.max(QUERY_SERVER_DEADLINE_MIN_MS, Math.min(callerLimit - QUERY_SERVER_DEADLINE_MARGIN_MS, QUERY_SERVER_DEADLINE_MAX_MS));
28
+ return serverDeadline + QUERY_ANSWER_TRAVEL_MS;
29
+ };
30
+ /** The reason a send stops at its answer limit. */
31
+ const answerLimitReached = () => new DOMException("The send got no answer in time.", "TimeoutError");
32
+ /**
33
+ * One send. A lost request comes back as an outcome so the caller can decide.
34
+ * With `answerLimitMs`, a send whose answer's headers have not arrived by
35
+ * then is stopped and comes back lost. The limit ends once the headers
36
+ * arrive: a replica that sent them is answering.
37
+ */
38
+ const sendOnce = async (runtimeFetch, url, init, signal, answerLimitMs = null) => {
7
39
  signal?.throwIfAborted();
40
+ const send = answerLimitMs === null ? null : new AbortController();
41
+ const sendSignal = send === null
42
+ ? signal
43
+ : signal === undefined
44
+ ? send.signal
45
+ : AbortSignal.any([signal, send.signal]);
46
+ const limit = send === null
47
+ ? undefined
48
+ : setTimeout(() => send.abort(answerLimitReached()), answerLimitMs ?? 0);
8
49
  let response;
9
50
  try {
10
51
  response = await awaitWithAbort(Promise.resolve().then(() => {
11
- signal?.throwIfAborted();
52
+ sendSignal?.throwIfAborted();
12
53
  return runtimeFetch(url, {
13
54
  ...init,
14
- ...(signal === undefined ? {} : { signal }),
55
+ ...(sendSignal === undefined ? {} : { signal: sendSignal }),
15
56
  });
16
- }), signal);
57
+ }), sendSignal);
17
58
  }
18
59
  catch (error) {
60
+ if (send?.signal.aborted === true && signal?.aborted !== true) {
61
+ return { error: send.signal.reason, kind: "lost" };
62
+ }
19
63
  if (isLostRequest(error, signal))
20
64
  return { error, kind: "lost" };
21
65
  throw error;
22
66
  }
67
+ finally {
68
+ clearTimeout(limit);
69
+ }
23
70
  const { body, cut } = await readRuntimeResponseBody(response, signal);
24
71
  return { kind: cut ? "cut" : "response", result: { body, response } };
25
72
  };
@@ -52,7 +99,7 @@ export const fetchInvocation = async (args, counts = FIRST_SEND) => {
52
99
  body: args.requestBody(counts.resent),
53
100
  headers: args.headers,
54
101
  method: "POST",
55
- }, args.signal);
102
+ }, args.signal, args.resendLost ? args.answerLimitMs : null);
56
103
  if ((isLost(outcome) || isTemporaryQueryAnswer(args.capabilityType, outcome)) &&
57
104
  args.resendLost &&
58
105
  canResend(args.damper.config, counts.resent)) {
package/dist/transport.js CHANGED
@@ -20,7 +20,7 @@ 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
22
  import { abortReason, validateRuntimeInvocationOptions, withRuntimeRequestSignal, } from "./transport-deadline.js";
23
- import { fetchInvocation, fetchJobCancel, fetchJobStatus, } from "./transport-invocation.js";
23
+ import { fetchInvocation, fetchJobCancel, fetchJobStatus, queryAnswerLimitMs, } 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);
@@ -497,6 +497,11 @@ export const invokeAppRuntime = async (options, damper, capabilityType, name, in
497
497
  // most `maxTransportRetries` times, when the call is safe to send again. So
498
498
  // is a query's temporary answer: a query only reads.
499
499
  const { body, response } = await withRuntimeRequestSignal(invocationOptions, async (requestSignal) => await fetchInvocation({
500
+ // A query's send that outlives the API's own query deadline is
501
+ // lost, and the query is sent again (`queryAnswerLimitMs`).
502
+ answerLimitMs: capabilityType === "query"
503
+ ? queryAnswerLimitMs(transport.timeoutMs)
504
+ : null,
500
505
  capabilityName,
501
506
  capabilityType,
502
507
  damper,
package/dist/types.d.ts CHANGED
@@ -117,6 +117,8 @@ export interface UruActionInvoker {
117
117
  }
118
118
  /** The capability-invocation client returned by `createUruAppRuntimeClient`. */
119
119
  export interface UruAppRuntimeClient {
120
+ /** Named JSON values in this Gem's authorized storage partition. */
121
+ storage: UruStorageContext;
120
122
  /** Deployment identity used by every operation on this client. */
121
123
  readonly deploymentId: string;
122
124
  query: UruCapabilityInvoker;
@@ -454,7 +456,7 @@ export interface UruUploadResult {
454
456
  }
455
457
  export interface UruUploadStatus {
456
458
  readonly uploadId: string;
457
- readonly state: UruUploadResult['state'];
459
+ readonly state: UruUploadResult["state"];
458
460
  readonly outcome: UruUploadOutcome | null;
459
461
  readonly filename: string;
460
462
  readonly contentType: string;
@@ -522,6 +524,7 @@ export interface UruJobStep {
522
524
  export type UruJobStepResult = RuntimeJsonValue | undefined | void;
523
525
  /** Everything a Uru server runtime hands an app. */
524
526
  export interface UruServerContext {
527
+ storage: UruStorageContext;
525
528
  files: UruFilesContext;
526
529
  datasets: UruDatasetsContext;
527
530
  app: UruAppRuntimeClient;
@@ -554,6 +557,52 @@ export interface UruServerContext {
554
557
  get: (name: string) => string;
555
558
  };
556
559
  }
560
+ export type UruStorageValue = RuntimeJsonValue;
561
+ export interface UruStorageRequestOptions {
562
+ signal?: AbortSignal;
563
+ /** Stable retry identity. Completed writes are reported as completed, not replayed. */
564
+ requestId?: string;
565
+ /**
566
+ * `true` addresses the Gem's one shared scope, which every viewer reads and
567
+ * writes. Absent or `false` addresses the caller's personal scope.
568
+ */
569
+ shared?: boolean;
570
+ }
571
+ export interface UruStoragePutOptions extends UruStorageRequestOptions {
572
+ /**
573
+ * Send `true` only on a shared put that follows the person's Yes to
574
+ * `URU_STORAGE_SHARED_WRITE_NOTICE`, after a put failed with the code
575
+ * `storage_shared_consent_required`. Uru keeps the answer for this person
576
+ * and this Gem. Inside Uru the shell asks the question itself.
577
+ */
578
+ sharedWriteConfirmed?: boolean;
579
+ }
580
+ /**
581
+ * Small named JSON values. The server chooses the Gem and the viewer from
582
+ * verified identity and enforces the Gem's one 20 MB cap.
583
+ */
584
+ export interface UruStorageContext {
585
+ get(name: string, options?: UruStorageRequestOptions): Promise<{
586
+ found: false;
587
+ } | {
588
+ found: true;
589
+ value: UruStorageValue;
590
+ }>;
591
+ put(name: string, value: UruStorageValue, options?: UruStoragePutOptions): Promise<{
592
+ value: UruStorageValue;
593
+ }>;
594
+ delete(name: string, options?: UruStorageRequestOptions): Promise<{
595
+ deleted: boolean;
596
+ }>;
597
+ list(options?: UruStorageRequestOptions & {
598
+ prefix?: string;
599
+ cursor?: string;
600
+ limit?: number;
601
+ }): Promise<{
602
+ keys: string[];
603
+ nextCursor: string | null;
604
+ }>;
605
+ }
557
606
  /**
558
607
  * The environment a Uru provider runtime injects.
559
608
  *
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@uru-intelligence/app",
3
- "version": "2.2.5",
3
+ "version": "2.4.0",
4
4
  "private": false,
5
- "description": "Runtime client for Uru Gems: capability calls, Datasets, jobs and secrets",
5
+ "description": "Runtime client for Uru Gems: capability calls, Datasets, storage, jobs and secrets",
6
6
  "keywords": [
7
7
  "gem",
8
8
  "runtime",
@@ -67,8 +67,9 @@
67
67
  "clean": "rm -rf dist",
68
68
  "prepack": "bun run clean && bun run build",
69
69
  "type-check": "tsc --noEmit && tsc -p tsconfig.examples.json --noEmit",
70
- "lint": "node ../../scripts/run-with-repo-node.mjs oxlint --type-aware --deny-warnings -c ../../oxlint.config.mts . && node ../../scripts/checks/check-bun-test-integrity.mjs",
71
- "lint:fix": "node ../../scripts/run-with-repo-node.mjs oxlint --type-aware --deny-warnings -c ../../oxlint.config.mts --fix .",
70
+ "type-check:bun": "node ../../scripts/ci/bun-check-workspaces.mjs --workspace",
71
+ "lint": "node ../../scripts/run-with-repo-node.mjs oxlint --type-aware --deny-warnings -c ../../.oxlintrc.json . && node ../../scripts/checks/check-bun-test-integrity.mjs",
72
+ "lint:fix": "node ../../scripts/run-with-repo-node.mjs oxlint --type-aware --deny-warnings -c ../../.oxlintrc.json --fix .",
72
73
  "test": "bun run test:safety",
73
74
  "test:unit": "bun run test:safety",
74
75
  "test:safety": "node ../../scripts/ci/run-named-test-files.mjs bun test --files-from test-lists/test-safety.txt",
@@ -80,10 +81,10 @@
80
81
  "@types/node": "24.13.3",
81
82
  "bun-types": "1.3.14",
82
83
  "publint": "0.3.24",
83
- "typescript": "7.0.2"
84
+ "typescript": "7.1.0-beta"
84
85
  },
85
86
  "engines": {
86
87
  "node": ">=22.12.0"
87
88
  },
88
- "packageManager": "bun@1.3.14"
89
+ "packageManager": "bun@1.4.4"
89
90
  }