@uru-intelligence/app 2.2.5 → 2.3.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,91 @@
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
+
17
+ On the server, use `createUruServerContext(env).storage`. The server verifies
18
+ the runtime token and chooses the Gem, workspace, environment, and viewer
19
+ partition. Do not send those identities in stored values to choose a partition.
20
+ Browser and server calls share data only when their verified partition matches.
21
+ Published visitors keep their own partition. A server token uses the Gem owner's
22
+ partition. Preview data and released data remain separate.
23
+
24
+ Values must be JSON. Each value can use at most 256 KiB. The existing storage
25
+ quota, request size limits, and permission checks apply. Public requests have
26
+ a 100 KB body limit. `list` returns keys and `nextCursor`; pass
27
+ that cursor to read the next page. A missing key returns `{ found: false }`.
28
+ `null` is a stored value and returns `{ found: true, value: null }`.
29
+
30
+ Each call has a request identity. You can set `requestId` in its options.
31
+ Storage does not replay a completed write. A repeated completed identity returns
32
+ an error; read the value to resolve an uncertain write. The client does not retry
33
+ writes automatically. A program job that writes storage loses automatic attempt
34
+ retry because the storage service cannot replay its first result.
35
+
36
+ Use the Dataset API for rows and queries. Use the file and upload APIs for bytes.
37
+ Gem storage does not provide a private SQL database.
38
+
39
+ ## Declare operation inputs and outputs
40
+
41
+ The root `uru.json` remains the only authored declaration. Add `description`,
42
+ `inputSchema`, and `outputSchema` to a named action or job. For an existing query,
43
+ put these fields in `capabilities.queryContracts` under its declared name:
44
+
45
+ ```json
46
+ {
47
+ "capabilities": {
48
+ "queries": ["summary"],
49
+ "queryContracts": {
50
+ "summary": {
51
+ "description": "Read the summary for one year.",
52
+ "inputSchema": {
53
+ "type": "object",
54
+ "properties": { "year": { "type": "integer" } },
55
+ "required": ["year"],
56
+ "additionalProperties": false
57
+ },
58
+ "outputSchema": { "type": "object" }
59
+ }
60
+ }
61
+ }
62
+ }
63
+ ```
64
+
65
+ This fragment belongs inside a complete `uru.gem.v2` root. A query contract must
66
+ name a query in `capabilities.queries`. Schemas can use boolean schemas and local
67
+ references such as `#/$defs/Year`. Unsupported references or formats fail source
68
+ validation. A saved job input must match its input schema.
69
+
70
+ The build copies these declarations into its immutable runtime contract. Runtime
71
+ calls check the declared input before execution and the completed output before
72
+ returning it. Program jobs check their final `outputSummary`. Tool providers keep
73
+ their own validation; an authored schema adds constraints and cannot remove them.
74
+ Tool descriptions use the same saved declarations.
75
+
76
+ The build also creates `uru.generated.d.ts` beside the root declaration. It is
77
+ build input, not a saved source edit. Import `GemInput` and `GemOutput` from it
78
+ to type browser code, for example `GemInput<'query:summary'>`. Complex schemas
79
+ that TypeScript cannot express remain `unknown`; runtime checks still apply.
80
+ Do not create your own `uru.generated.d.ts` file.
81
+
82
+ ```ts
83
+ import type { GemInput } from './uru.generated';
84
+
85
+ const input: GemInput<'query:summary'> = { year: 2026 };
86
+ await app.query('summary', input);
87
+ ```
88
+
3
89
  **This package is the runtime client for [Uru](https://uruintelligence.com) Gems.
4
90
  It is published so that Gem projects install and build outside the Uru hosted
5
91
  builder. It talks only to an Uru workspace runtime and does nothing on its own.
@@ -748,7 +834,8 @@ a build to be reproducible; Uru's own Gem templates do.
748
834
 
749
835
  The public surface includes `createUruServerContext`,
750
836
  `createUruAppRuntimeClient`, `createUruBackgroundJobCoordinator`,
751
- `createUruUploadsContext`, `UruAppRuntimeError`, and the exported types.
837
+ `createUruUploadsContext`, `createUruStorageContext`, `UruAppRuntimeError`, and
838
+ the exported types.
752
839
  Nothing else is API, even if you can reach it.
753
840
 
754
841
  ## Documentation
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 } 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, 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 } 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,3 @@
1
+ import type { CreateUruAppRuntimeClientOptions, UruStorageContext } from "./types.js";
2
+ /** Named JSON values in the existing Gem storage partition. */
3
+ export declare function createStorageContext(options: CreateUruAppRuntimeClientOptions): UruStorageContext;
@@ -0,0 +1,149 @@
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
+ const KEY_LENGTH = 512;
7
+ function invalid() {
8
+ throw new UruAppRuntimeError("Invalid storage request or response.", {
9
+ status: 0,
10
+ body: null,
11
+ });
12
+ }
13
+ function key(value, allowEmpty = false) {
14
+ if (typeof value !== "string" ||
15
+ value.trim().length > KEY_LENGTH ||
16
+ value.includes("\0") ||
17
+ (!allowEmpty && value.trim() === ""))
18
+ invalid();
19
+ return value.trim();
20
+ }
21
+ async function readJson(response) {
22
+ const reader = response.body?.getReader();
23
+ if (reader === undefined)
24
+ invalid();
25
+ let size = 0;
26
+ let text = "";
27
+ const decoder = new TextDecoder();
28
+ try {
29
+ for (;;) {
30
+ const chunk = await reader.read();
31
+ if (chunk.done)
32
+ break;
33
+ size += chunk.value.byteLength;
34
+ if (size > RESPONSE_BYTES) {
35
+ await reader.cancel();
36
+ invalid();
37
+ }
38
+ text += decoder.decode(chunk.value, { stream: true });
39
+ }
40
+ return JSON.parse(text + decoder.decode());
41
+ }
42
+ catch (error) {
43
+ if (error instanceof UruAppRuntimeError)
44
+ throw error;
45
+ return invalid();
46
+ }
47
+ finally {
48
+ reader.releaseLock();
49
+ }
50
+ }
51
+ /** Named JSON values in the existing Gem storage partition. */
52
+ export function createStorageContext(options) {
53
+ const deploymentId = options.deploymentId.trim();
54
+ if (deploymentId === "")
55
+ invalid();
56
+ const url = `${trimTrailingSlash(options.baseUrl ?? "")}${runtimeBasePath(options)}/apps/${encodeURIComponent(deploymentId)}/storage`;
57
+ const request = async (payload, settings) => {
58
+ const serialized = JSON.stringify(payload);
59
+ const headers = new Headers(await resolveHeaders(options.headers));
60
+ headers.set("content-type", "application/json");
61
+ const requestId = settings?.requestId ?? `uru-storage:${crypto.randomUUID()}`;
62
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(requestId))
63
+ invalid();
64
+ headers.set("x-uru-storage-request-id", requestId);
65
+ const response = await resolveRuntimeFetch(options)(url, {
66
+ method: "POST",
67
+ headers,
68
+ body: serialized,
69
+ signal: settings?.signal === undefined
70
+ ? AbortSignal.timeout(30_000)
71
+ : AbortSignal.any([settings.signal, AbortSignal.timeout(30_000)]),
72
+ });
73
+ const body = response.ok
74
+ ? await readJson(response)
75
+ : await readJson(response).catch(() => null);
76
+ if (!response.ok) {
77
+ throw new UruAppRuntimeError(runtimeErrorMessage(body, "Storage request was not accepted."), { status: response.status, body });
78
+ }
79
+ if (!isRuntimeJsonObject(body) ||
80
+ body["operation"] !== payload["operation"])
81
+ invalid();
82
+ return body;
83
+ };
84
+ return {
85
+ get: async (name, settings) => {
86
+ const normalized = key(name);
87
+ const result = await request({ operation: "get", key: normalized }, settings);
88
+ if (result["key"] !== normalized || typeof result["found"] !== "boolean")
89
+ invalid();
90
+ if (!result["found"])
91
+ return { found: false };
92
+ const value = result["value"];
93
+ if (value === undefined)
94
+ invalid();
95
+ return { found: true, value };
96
+ },
97
+ put: async (name, value, settings) => {
98
+ if (!isRuntimeJsonObject({ value }))
99
+ invalid();
100
+ const normalized = key(name);
101
+ const payload = { operation: "put", key: normalized, value };
102
+ // Reject before sending a value that the private route cannot accept.
103
+ if (new TextEncoder().encode(JSON.stringify(payload)).byteLength >
104
+ RESPONSE_BYTES)
105
+ invalid();
106
+ const result = await request(payload, settings);
107
+ const storedValue = result["value"];
108
+ if (result["key"] !== normalized || storedValue === undefined)
109
+ invalid();
110
+ return { value: storedValue };
111
+ },
112
+ delete: async (name, settings) => {
113
+ const normalized = key(name);
114
+ const result = await request({ operation: "delete", key: normalized }, settings);
115
+ if (result["key"] !== normalized ||
116
+ typeof result["deleted"] !== "boolean")
117
+ invalid();
118
+ return { deleted: result["deleted"] };
119
+ },
120
+ list: async (settings = {}) => {
121
+ if (settings.limit !== undefined &&
122
+ (!Number.isInteger(settings.limit) ||
123
+ settings.limit < 1 ||
124
+ settings.limit > 100))
125
+ invalid();
126
+ const result = await request({
127
+ operation: "list",
128
+ ...(settings.prefix === undefined
129
+ ? {}
130
+ : { prefix: key(settings.prefix, true) }),
131
+ ...(settings.cursor === undefined
132
+ ? {}
133
+ : { cursor: key(settings.cursor) }),
134
+ ...(settings.limit === undefined ? {} : { limit: settings.limit }),
135
+ }, settings);
136
+ const keys = result["keys"];
137
+ const nextCursor = result["nextCursor"];
138
+ if (!Array.isArray(keys) ||
139
+ keys.length > (settings.limit ?? 50) ||
140
+ keys.some((value) => typeof value !== "string") ||
141
+ (nextCursor !== null && typeof nextCursor !== "string"))
142
+ invalid();
143
+ return {
144
+ keys: keys.map((value) => key(String(value))),
145
+ nextCursor: nextCursor === null ? null : key(nextCursor),
146
+ };
147
+ },
148
+ };
149
+ }
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,35 @@ 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
+ /** Small named JSON values. Scope and quotas are enforced by the server. */
567
+ export interface UruStorageContext {
568
+ get(name: string, options?: UruStorageRequestOptions): Promise<{
569
+ found: false;
570
+ } | {
571
+ found: true;
572
+ value: UruStorageValue;
573
+ }>;
574
+ put(name: string, value: UruStorageValue, options?: UruStorageRequestOptions): Promise<{
575
+ value: UruStorageValue;
576
+ }>;
577
+ delete(name: string, options?: UruStorageRequestOptions): Promise<{
578
+ deleted: boolean;
579
+ }>;
580
+ list(options?: UruStorageRequestOptions & {
581
+ prefix?: string;
582
+ cursor?: string;
583
+ limit?: number;
584
+ }): Promise<{
585
+ keys: string[];
586
+ nextCursor: string | null;
587
+ }>;
588
+ }
557
589
  /**
558
590
  * The environment a Uru provider runtime injects.
559
591
  *
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@uru-intelligence/app",
3
- "version": "2.2.5",
3
+ "version": "2.3.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",
@@ -85,5 +85,5 @@
85
85
  "engines": {
86
86
  "node": ">=22.12.0"
87
87
  },
88
- "packageManager": "bun@1.3.14"
88
+ "packageManager": "bun@1.4.2"
89
89
  }