@uru-intelligence/app 2.0.0 → 2.1.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
@@ -76,6 +76,54 @@ and `URU_RUNTIME_TOKEN`. The Uru runtime injects all three. A missing binding
76
76
  throws `UruAppRuntimeError` naming the binding, rather than failing later at a
77
77
  request that could never have worked.
78
78
 
79
+ ## Program job handlers
80
+
81
+ A Gem can declare a job that runs code from its published source:
82
+
83
+ ```json
84
+ {
85
+ "capabilities": {
86
+ "jobs": {
87
+ "sync_orders": {
88
+ "handler": { "module": "src/jobs.ts", "export": "syncOrders" }
89
+ }
90
+ }
91
+ }
92
+ }
93
+ ```
94
+
95
+ The handler receives the injected environment, saved input, the last
96
+ checkpoint, and an abort signal. Use the server context to report progress and
97
+ save small resume data after each completed write:
98
+
99
+ ```ts
100
+ import {
101
+ createUruServerContext,
102
+ type UruJobCheckpoint,
103
+ type UruProviderRuntimeEnvironment,
104
+ } from '@uru-intelligence/app';
105
+
106
+ export async function syncOrders(
107
+ env: UruProviderRuntimeEnvironment,
108
+ input: { source: string },
109
+ checkpoint: UruJobCheckpoint | null,
110
+ signal: AbortSignal,
111
+ ) {
112
+ const uru = createUruServerContext(env);
113
+ if (signal.aborted) return { processed: 0 };
114
+
115
+ await saveNextBatch(uru, input.source, checkpoint, signal);
116
+ await uru.jobs.progress({ completed: 1, message: 'Batch saved' });
117
+ await uru.jobs.checkpoint({ source: input.source, processed: 1 });
118
+ return { processed: 1 };
119
+ }
120
+ ```
121
+
122
+ `saveNextBatch` is Gem code. Check `signal.aborted` before each external write.
123
+ Make writes safe to repeat. Keep progress messages and checkpoints small. Do
124
+ not put secrets or source rows in them. A progress update does not complete a
125
+ job. The handler completes the job when it returns.
126
+
79
127
  For a browser calling a public Gem page's runtime, build the client directly:
80
128
 
81
129
  ```ts
@@ -172,6 +220,38 @@ Capability and job-status envelopes can omit `result` or return `null` while
172
220
  work is pending. The client preserves both forms without calling the decoder.
173
221
  Typed callers must still handle an absent or null result.
174
222
 
223
+ ## Files
224
+
225
+ Declare Library file IDs in `uru.json` under `bindings.files`. Each file needs
226
+ its own approved grant. Read access does not permit changes to the file.
227
+
228
+ ```ts
229
+ const source = await uru.files.read(fileId, { signal });
230
+ // source.content is a Uint8Array. Library reads are limited to 5 MiB.
231
+ ```
232
+
233
+ Set `fileOutputs: true` in `uru.json` to request permission to create output
234
+ files. Output permission is separate from Library read permission and app
235
+ storage. Reuse the same key when you repeat a write after an uncertain result.
236
+
237
+ ```ts
238
+ const created = await uru.files.createOutput({
239
+ name: 'summary.txt',
240
+ contentType: 'text/plain',
241
+ content: new TextEncoder().encode('Completed work'),
242
+ idempotencyKey: `summary:${batchId}`,
243
+ signal,
244
+ });
245
+ const saved = await uru.files.readOutput(created.outputId, { signal });
246
+ const page = await uru.files.listOutputs({ limit: 25, signal });
247
+ const nextPage = page.nextCursor === null ? null
248
+ : await uru.files.listOutputs({ cursor: page.nextCursor, limit: 25, signal });
249
+ ```
250
+
251
+ Output reads and writes are limited to 10 MiB. Later approved releases of the
252
+ same Gem can read its outputs in the same environment. Preview builds cannot
253
+ create unattended outputs. Every request checks current access.
254
+
175
255
  ## Errors
176
256
 
177
257
  Transport and platform failures throw `UruAppRuntimeError`. Decoder failures
@@ -194,10 +274,10 @@ try {
194
274
 
195
275
  ## Stability
196
276
 
197
- Semantic versioning, from `1.0.0` onward. A breaking change to the public
198
- surface takes a major version. This package starts at `1.0.0` rather than `0.x`
199
- because it is already load-bearing: every hosted Uru Gem runs against it, so
200
- breaking it is expensive whatever the version number claims.
277
+ Semantic versioning applies. A breaking change to the public surface takes a
278
+ major version. The package is already load-bearing:
279
+ every hosted Uru Gem runs against it, so breaking it is expensive whatever the
280
+ version number claims.
201
281
 
202
282
  The API still follows the Uru platform rather than the other way round. When the
203
283
  platform's runtime contract moves, this package moves with it — additively where
package/dist/datasets.js CHANGED
@@ -35,6 +35,7 @@ const fetchDatasetWrite = async (options, subpath, body) => {
35
35
  body: serializedBody,
36
36
  headers,
37
37
  method: "POST",
38
+ signal: AbortSignal.timeout(30_000),
38
39
  });
39
40
  const parsed = await response.json().catch(() => null);
40
41
  if (!response.ok) {
@@ -0,0 +1,2 @@
1
+ import type { CreateUruAppRuntimeClientOptions, UruFilesContext } from './types.js';
2
+ export declare function createFilesContext(options: CreateUruAppRuntimeClientOptions): UruFilesContext;
package/dist/files.js ADDED
@@ -0,0 +1,149 @@
1
+ import { UruAppRuntimeError } from './errors.js';
2
+ import { resolveHeaders, runtimeBasePath, trimTrailingSlash } from './runtime.js';
3
+ import { isRuntimeJsonObject } from './transport-json.js';
4
+ const LIBRARY_READ_BYTES = 5 * 1024 * 1024;
5
+ const OUTPUT_BYTES = 10 * 1024 * 1024;
6
+ const RESPONSE_BYTES = Math.ceil(OUTPUT_BYTES / 3) * 4 + 8192;
7
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
+ const HASH = /^[0-9a-f]{64}$/;
9
+ function invalid() {
10
+ throw new UruAppRuntimeError('Invalid file request or response.', { status: 0, body: null });
11
+ }
12
+ const identifier = (value) => typeof value === 'string' && UUID.test(value) ? value : invalid();
13
+ const object = (value) => isRuntimeJsonObject(value) ? value : invalid();
14
+ const string = (value) => typeof value === 'string' ? value : invalid();
15
+ function metadata(value, maxBytes) {
16
+ const sizeBytes = value['sizeBytes'];
17
+ const filename = string(value['filename']);
18
+ const contentType = string(value['contentType']);
19
+ const sha256 = string(value['sha256']);
20
+ if (typeof sizeBytes !== 'number' || !Number.isSafeInteger(sizeBytes) || sizeBytes < 0 || sizeBytes > maxBytes ||
21
+ filename.length < 1 || filename.length > 255 || contentType.length < 1 || contentType.length > 255 || !HASH.test(sha256))
22
+ invalid();
23
+ return { fileId: identifier(string(value['fileId'])), filename, contentType, sizeBytes, sha256 };
24
+ }
25
+ function output(value) {
26
+ const row = object(value);
27
+ const createdAt = string(row['createdAt']);
28
+ if (!Number.isFinite(Date.parse(createdAt)))
29
+ invalid();
30
+ return { ...metadata(row, OUTPUT_BYTES), outputId: identifier(string(row['outputId'])), createdAt };
31
+ }
32
+ function content(value, maxBytes) {
33
+ const row = object(value);
34
+ const meta = metadata(row, maxBytes);
35
+ const encoded = string(row['contentBase64']);
36
+ if (encoded.length > Math.ceil(maxBytes / 3) * 4 ||
37
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded))
38
+ invalid();
39
+ let decoded;
40
+ try {
41
+ decoded = atob(encoded);
42
+ }
43
+ catch {
44
+ return invalid();
45
+ }
46
+ if (decoded.length !== meta.sizeBytes)
47
+ invalid();
48
+ return { ...meta, content: Uint8Array.from(decoded, character => character.charCodeAt(0)) };
49
+ }
50
+ function base64(bytes) {
51
+ let binary = '';
52
+ for (let offset = 0; offset < bytes.length; offset += 8192) {
53
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
54
+ }
55
+ return btoa(binary);
56
+ }
57
+ async function readJson(response) {
58
+ const reader = response.body?.getReader();
59
+ if (reader === undefined)
60
+ invalid();
61
+ const decoder = new TextDecoder();
62
+ let size = 0;
63
+ let text = '';
64
+ try {
65
+ for (;;) {
66
+ const chunk = await reader.read();
67
+ if (chunk.done)
68
+ break;
69
+ size += chunk.value.byteLength;
70
+ if (size > RESPONSE_BYTES) {
71
+ await reader.cancel();
72
+ invalid();
73
+ }
74
+ text += decoder.decode(chunk.value, { stream: true });
75
+ }
76
+ text += decoder.decode();
77
+ return JSON.parse(text);
78
+ }
79
+ catch (error) {
80
+ if (error instanceof UruAppRuntimeError)
81
+ throw error;
82
+ return invalid();
83
+ }
84
+ finally {
85
+ reader.releaseLock();
86
+ }
87
+ }
88
+ export function createFilesContext(options) {
89
+ const base = `${trimTrailingSlash(options.baseUrl ?? '')}${runtimeBasePath(options)}/apps/${encodeURIComponent(options.deploymentId)}/files`;
90
+ const request = async (path, payload, signal) => {
91
+ const headers = new Headers(await resolveHeaders(options.headers));
92
+ if (payload !== undefined)
93
+ headers.set('content-type', 'application/json');
94
+ const response = await (options.fetch ?? globalThis.fetch)(`${base}${path}`, {
95
+ method: payload === undefined ? 'GET' : 'POST', headers,
96
+ ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
97
+ signal: signal === undefined ? AbortSignal.timeout(30_000) : AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
98
+ });
99
+ if (!response.ok) {
100
+ await response.body?.cancel();
101
+ throw new UruAppRuntimeError('File access was not accepted.', { status: response.status, body: null });
102
+ }
103
+ return readJson(response);
104
+ };
105
+ return {
106
+ read: async (fileId, settings) => content(await request(`/${identifier(fileId)}`, undefined, settings?.signal), LIBRARY_READ_BYTES),
107
+ readOutput: async (outputId, settings) => content(await request(`/outputs/${identifier(outputId)}`, undefined, settings?.signal), OUTPUT_BYTES),
108
+ createOutput: async (input) => {
109
+ if (!(input.content instanceof Uint8Array) || input.content.byteLength > OUTPUT_BYTES ||
110
+ typeof input.name !== 'string' || typeof input.contentType !== 'string' || typeof input.idempotencyKey !== 'string' ||
111
+ input.name.trim().length < 1 || input.name.length > 255 ||
112
+ input.contentType.trim().length < 1 || input.contentType.length > 255 ||
113
+ input.idempotencyKey.trim().length < 1 || input.idempotencyKey.length > 128 ||
114
+ (input.sha256 !== undefined && !HASH.test(input.sha256)))
115
+ invalid();
116
+ return output(await request('/outputs', {
117
+ name: input.name, contentType: input.contentType, contentBase64: base64(input.content),
118
+ idempotencyKey: input.idempotencyKey,
119
+ ...(input.sha256 === undefined ? {} : { sha256: input.sha256 }),
120
+ }, input.signal));
121
+ },
122
+ listOutputs: async (settings = {}) => {
123
+ if (settings.limit !== undefined && (!Number.isInteger(settings.limit) || settings.limit < 1 || settings.limit > 100))
124
+ invalid();
125
+ if (settings.cursor !== undefined && (typeof settings.cursor !== 'string' || settings.cursor.length === 0 || settings.cursor.length > 4096))
126
+ invalid();
127
+ const params = new URLSearchParams();
128
+ if (settings.cursor !== undefined)
129
+ params.set('cursor', settings.cursor);
130
+ if (settings.limit !== undefined)
131
+ params.set('limit', String(settings.limit));
132
+ const result = object(await request(`/outputs${params.size === 0 ? '' : `?${params}`}`, undefined, settings.signal));
133
+ const values = result['items'];
134
+ if (!Array.isArray(values) || values.length > (settings.limit ?? 100))
135
+ invalid();
136
+ const items = values.map(value => {
137
+ const row = object(value);
138
+ return { ...output(row),
139
+ releaseId: row['releaseId'] === null ? null : identifier(string(row['releaseId'])),
140
+ buildId: row['buildId'] === null ? null : identifier(string(row['buildId'])),
141
+ };
142
+ });
143
+ const nextCursor = result['nextCursor'] === null ? null : string(result['nextCursor']);
144
+ if (nextCursor !== null && (nextCursor.length === 0 || nextCursor.length > 4096))
145
+ invalid();
146
+ return { items, nextCursor };
147
+ },
148
+ };
149
+ }
package/dist/index.d.ts CHANGED
@@ -11,16 +11,19 @@
11
11
  */
12
12
  import type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, UruAppRuntimeClient, UruProviderRuntimeEnvironment, UruServerContext } from "./types.js";
13
13
  export { UruAppRuntimeError } from "./errors.js";
14
+ export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext } from "./uploads.js";
14
15
  export type { UruRunawayDamperOptions } from "./dampers.js";
15
- export type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruAppRuntimeEvent, UruAppRuntimeEventType, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruAppRuntimeState, UruDecodedInvocationOptions, UruResultDecoder, UruDatasetMutationResult, UruDatasetQuery, UruDatasetRow, UruDatasetRowsResult, UruDatasetSortClause, UruDatasetSqlWriteOptions, UruDatasetWhereClause, UruDatasetWhereOperator, UruDatasetsContext, UruProviderRuntimeEnvironment, UruServerContext, } from "./types.js";
16
+ export type { CreateUruAppRuntimeClientOptions, CreateUruServerContextOptions, UruAppRuntimeCapabilityType, UruAppRuntimeClient, UruAppRuntimeEvent, UruAppRuntimeEventType, UruAppRuntimeExecutionStatus, UruAppRuntimeInvocationOptions, UruAppRuntimeInvocationResponse, UruAppRuntimeState, UruDecodedInvocationOptions, UruResultDecoder, UruDatasetMutationResult, UruDatasetQuery, UruDatasetRow, UruDatasetRowsResult, UruDatasetSortClause, UruDatasetSqlWriteOptions, UruDatasetWhereClause, UruDatasetWhereOperator, UruDatasetsContext, UruFilesContext, UruFileMetadata, UruFileContent, UruFileOutput, UruFileOutputSummary, UruJobProgress, UruJobCheckpoint, UruProviderRuntimeEnvironment, UruServerContext, UruUploadGrant, UruUploadOutcome, UruUploadResult, UruUploadsContext, } from "./types.js";
16
17
  /**
17
18
  * Build a capability-invocation client against a Uru app runtime.
18
19
  *
19
- * Most apps want {@link createUruServerContext} instead, which reads the
20
- * provider bindings out of the environment and adds Datasets, actions, jobs and
21
- * secrets on top. Use this directly when the caller already knows its
22
- * deployment id and how to authenticate — a browser calling a public page's
23
- * runtime, for example.
20
+ * {@link createUruServerContext} is the easier way to get one from a request
21
+ * handler's own environment bindings, and it also adds Datasets, actions,
22
+ * jobs and secrets on top — but only where a runtime token actually reaches
23
+ * that handler (see its own doc comment; a serverful Gem's request handler is
24
+ * the one place it never does). Use this directly when the caller already
25
+ * knows its deployment id and how to authenticate — a browser calling a
26
+ * public page's runtime, for example.
24
27
  */
25
28
  export declare const createUruAppRuntimeClient: (options: CreateUruAppRuntimeClientOptions) => UruAppRuntimeClient;
26
29
  /**
@@ -31,5 +34,18 @@ export declare const createUruAppRuntimeClient: (options: CreateUruAppRuntimeCli
31
34
  * required and are injected by the Uru runtime. A missing one throws
32
35
  * {@link UruAppRuntimeError} naming the binding, rather than failing later at a
33
36
  * request that could not have worked.
37
+ *
38
+ * **Not every hosting class carries `URU_RUNTIME_TOKEN` at request time, so
39
+ * this does not run everywhere a Gem's own code runs:**
40
+ *
41
+ * - A Cloudflare Worker Gem always has it, at every request.
42
+ * - A serverful (Fly) Gem's REQUEST HANDLER never does. The token is
43
+ * deliberately left out of that deployment's environment, and the guest
44
+ * refuses to even boot if one is somehow present — so calling this from a
45
+ * Fly `server_web_app` request handler throws every time, not just
46
+ * sometimes. Do the work in a program job instead.
47
+ * - A program job is unaffected either way: it runs on its own dedicated
48
+ * Machine, which is provisioned with its own token regardless of the app's
49
+ * hosting class.
34
50
  */
35
51
  export declare const createUruServerContext: (env: UruProviderRuntimeEnvironment, options?: CreateUruServerContextOptions) => UruServerContext;
package/dist/index.js CHANGED
@@ -11,9 +11,12 @@
11
11
  */
12
12
  import { ForceRefreshThrottle, resolveDamperConfig } from "./dampers.js";
13
13
  import { createDatasetsContext } from "./datasets.js";
14
+ import { createFilesContext } from './files.js';
15
+ import { createJobProgress, createJobCheckpoint } from './jobs.js';
14
16
  import { UruAppRuntimeError } from "./errors.js";
15
17
  import { createActionInvoker, createCancelJobInvoker, createCapabilityInvoker, createJobStatusInvoker, } from "./invocations.js";
16
18
  export { UruAppRuntimeError } from "./errors.js";
19
+ export { URU_UPLOAD_MAX_BYTES, createUploadsContext as createUruUploadsContext } from "./uploads.js";
17
20
  const ownEnvironmentValue = (env, key) => {
18
21
  if (!Object.hasOwn(env, key)) {
19
22
  return undefined;
@@ -21,10 +24,27 @@ const ownEnvironmentValue = (env, key) => {
21
24
  const value = env[key];
22
25
  return typeof value === "string" ? value : undefined;
23
26
  };
24
- /** Read a required runtime binding, or throw naming the one that is missing. */
27
+ /**
28
+ * Read a required runtime binding, or throw naming the one that is missing.
29
+ *
30
+ * `URU_RUNTIME_TOKEN` gets its own message: on a serverful (Fly) Gem's
31
+ * request handler, this binding is not merely unset by accident — that
32
+ * hosting class never carries it at request time (see
33
+ * {@link createUruServerContext}'s own doc comment for exactly which classes
34
+ * do), so "missing" would read as a fixable configuration bug when it is
35
+ * actually the platform's own design.
36
+ */
25
37
  const requiredRuntimeEnv = (env, key) => {
26
38
  const value = (ownEnvironmentValue(env, key) ?? "").trim();
27
39
  if (value === "") {
40
+ if (key === "URU_RUNTIME_TOKEN") {
41
+ throw new UruAppRuntimeError("This hosting class does not carry a runtime token at request time, " +
42
+ "so createUruServerContext cannot run here. A serverful (Fly) Gem's " +
43
+ "request handler never receives one, by design; a Cloudflare Worker " +
44
+ "Gem always does. If this code needs platform capabilities, run it " +
45
+ "from a program job instead — a program job runs on its own " +
46
+ "dedicated Machine with its own token, regardless of hosting class.", { body: null, status: 0 });
47
+ }
28
48
  throw new UruAppRuntimeError(`Missing Uru runtime binding: ${key}`, {
29
49
  body: null,
30
50
  status: 0,
@@ -46,11 +66,13 @@ const normalizedSecretName = (name) => {
46
66
  /**
47
67
  * Build a capability-invocation client against a Uru app runtime.
48
68
  *
49
- * Most apps want {@link createUruServerContext} instead, which reads the
50
- * provider bindings out of the environment and adds Datasets, actions, jobs and
51
- * secrets on top. Use this directly when the caller already knows its
52
- * deployment id and how to authenticate — a browser calling a public page's
53
- * runtime, for example.
69
+ * {@link createUruServerContext} is the easier way to get one from a request
70
+ * handler's own environment bindings, and it also adds Datasets, actions,
71
+ * jobs and secrets on top — but only where a runtime token actually reaches
72
+ * that handler (see its own doc comment; a serverful Gem's request handler is
73
+ * the one place it never does). Use this directly when the caller already
74
+ * knows its deployment id and how to authenticate — a browser calling a
75
+ * public page's runtime, for example.
54
76
  */
55
77
  export const createUruAppRuntimeClient = (options) => {
56
78
  // One damper runtime per client: the resolved config plus the forceRefresh
@@ -77,6 +99,19 @@ export const createUruAppRuntimeClient = (options) => {
77
99
  * required and are injected by the Uru runtime. A missing one throws
78
100
  * {@link UruAppRuntimeError} naming the binding, rather than failing later at a
79
101
  * request that could not have worked.
102
+ *
103
+ * **Not every hosting class carries `URU_RUNTIME_TOKEN` at request time, so
104
+ * this does not run everywhere a Gem's own code runs:**
105
+ *
106
+ * - A Cloudflare Worker Gem always has it, at every request.
107
+ * - A serverful (Fly) Gem's REQUEST HANDLER never does. The token is
108
+ * deliberately left out of that deployment's environment, and the guest
109
+ * refuses to even boot if one is somehow present — so calling this from a
110
+ * Fly `server_web_app` request handler throws every time, not just
111
+ * sometimes. Do the work in a program job instead.
112
+ * - A program job is unaffected either way: it runs on its own dedicated
113
+ * Machine, which is provisioned with its own token regardless of the app's
114
+ * hosting class.
80
115
  */
81
116
  export const createUruServerContext = (env, options = {}) => {
82
117
  const deploymentId = requiredRuntimeEnv(env, "URU_DEPLOYMENT_ID");
@@ -98,7 +133,12 @@ export const createUruServerContext = (env, options = {}) => {
98
133
  actions: { run: createActionInvoker(app) },
99
134
  app,
100
135
  datasets: createDatasetsContext(app, clientOptions),
101
- jobs: { start: app.job },
136
+ files: createFilesContext(clientOptions),
137
+ jobs: {
138
+ start: app.job,
139
+ progress: createJobProgress(clientOptions, env),
140
+ checkpoint: createJobCheckpoint(clientOptions, env),
141
+ },
102
142
  secrets: {
103
143
  get: (name) => {
104
144
  const key = normalizedSecretName(name);
package/dist/jobs.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { RuntimeJsonObject } from './transport-json.js';
2
+ import type { CreateUruAppRuntimeClientOptions, UruJobProgress, UruProviderRuntimeEnvironment } from './types.js';
3
+ export declare const createJobProgress: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) => (progress: UruJobProgress) => Promise<void>;
4
+ export declare const createJobCheckpoint: (options: CreateUruAppRuntimeClientOptions, env: UruProviderRuntimeEnvironment) => (value: RuntimeJsonObject) => Promise<void>;
package/dist/jobs.js ADDED
@@ -0,0 +1,35 @@
1
+ import { UruAppRuntimeError } from './errors.js';
2
+ import { resolveHeaders, runtimeBasePath, trimTrailingSlash } from './runtime.js';
3
+ import { isRuntimeJsonObject } from './transport-json.js';
4
+ const postJobUpdate = async (options, env, operation, payload) => {
5
+ const runId = Object.hasOwn(env, 'URU_JOB_RUN_ID') ? env['URU_JOB_RUN_ID']?.trim() : undefined;
6
+ const attemptId = Object.hasOwn(env, 'URU_JOB_ATTEMPT_ID') ? env['URU_JOB_ATTEMPT_ID']?.trim() : undefined;
7
+ if (!runId || !attemptId) {
8
+ throw new UruAppRuntimeError('Job updates require an active job attempt.', { status: 0, body: null });
9
+ }
10
+ const headers = new Headers(await resolveHeaders(options.headers));
11
+ headers.set('content-type', 'application/json');
12
+ const url = `${trimTrailingSlash(options.baseUrl ?? '')}${runtimeBasePath(options)}/apps/${encodeURIComponent(options.deploymentId)}/jobs/executions/${encodeURIComponent(runId)}/attempts/${encodeURIComponent(attemptId)}/${operation}`;
13
+ const response = await (options.fetch ?? globalThis.fetch)(url, {
14
+ method: 'POST', headers, body: JSON.stringify(payload), signal: AbortSignal.timeout(30_000),
15
+ });
16
+ if (!response.ok) {
17
+ await response.body?.cancel();
18
+ throw new UruAppRuntimeError('Job update was not accepted.', { status: response.status, body: null });
19
+ }
20
+ await response.body?.cancel();
21
+ };
22
+ export const createJobProgress = (options, env) => async (progress) => {
23
+ if (!Number.isSafeInteger(progress.completed) || progress.completed < 0 ||
24
+ (progress.total !== undefined && (!Number.isSafeInteger(progress.total) || progress.total < progress.completed)) ||
25
+ (progress.message !== undefined && typeof progress.message !== 'string')) {
26
+ throw new UruAppRuntimeError('Invalid job progress.', { status: 0, body: null });
27
+ }
28
+ await postJobUpdate(options, env, 'progress', progress);
29
+ };
30
+ export const createJobCheckpoint = (options, env) => async (value) => {
31
+ if (!isRuntimeJsonObject(value)) {
32
+ throw new UruAppRuntimeError('A job checkpoint must contain JSON data.', { status: 0, body: null });
33
+ }
34
+ await postJobUpdate(options, env, 'checkpoint', { value });
35
+ };
@@ -3,5 +3,7 @@ export type RuntimeJsonValue = boolean | null | number | string | RuntimeJsonVal
3
3
  [key: string]: RuntimeJsonValue;
4
4
  };
5
5
  export type RuntimeJsonObject = Record<string, RuntimeJsonValue>;
6
+ /** Keep later JSON.stringify calls below the JavaScript stack limit. */
7
+ export declare const RUNTIME_JSON_NESTING_DEPTH_MAX = 64;
6
8
  /** Validate without invoking getters or recursing on the JavaScript call stack. */
7
9
  export declare const isRuntimeJsonObject: (value: unknown) => value is RuntimeJsonObject;
@@ -1,3 +1,5 @@
1
+ /** Keep later JSON.stringify calls below the JavaScript stack limit. */
2
+ export const RUNTIME_JSON_NESTING_DEPTH_MAX = 64;
1
3
  const isJsonPrimitive = (value) => value === null ||
2
4
  typeof value === "string" ||
3
5
  typeof value === "boolean" ||
@@ -49,7 +51,7 @@ const inspectRuntimeJsonObject = (value) => {
49
51
  return false;
50
52
  }
51
53
  const ancestors = new WeakSet();
52
- const frames = [{ phase: "enter", value }];
54
+ const frames = [{ phase: "enter", value, depth: 0 }];
53
55
  while (frames.length > 0) {
54
56
  const frame = frames.pop();
55
57
  if (frame === undefined) {
@@ -60,6 +62,9 @@ const inspectRuntimeJsonObject = (value) => {
60
62
  continue;
61
63
  }
62
64
  const candidate = frame.value;
65
+ if (frame.depth > RUNTIME_JSON_NESTING_DEPTH_MAX) {
66
+ return false;
67
+ }
63
68
  if (isJsonPrimitive(candidate)) {
64
69
  continue;
65
70
  }
@@ -75,7 +80,11 @@ const inspectRuntimeJsonObject = (value) => {
75
80
  ancestors.add(candidate);
76
81
  frames.push({ phase: "leave", value: candidate });
77
82
  for (const property of properties) {
78
- frames.push({ phase: "enter", value: property.value });
83
+ frames.push({
84
+ phase: "enter",
85
+ value: property.value,
86
+ depth: frame.depth + 1,
87
+ });
79
88
  }
80
89
  }
81
90
  return true;
package/dist/types.d.ts CHANGED
@@ -207,8 +207,104 @@ export interface UruDatasetsContext {
207
207
  restoreRows: UruDatasetIdMutation;
208
208
  sqlWrite: UruDatasetSqlWrite;
209
209
  }
210
+ export interface UruFileMetadata {
211
+ readonly fileId: string;
212
+ readonly filename: string;
213
+ readonly contentType: string;
214
+ readonly sizeBytes: number;
215
+ readonly sha256: string;
216
+ }
217
+ export interface UruFileContent extends UruFileMetadata {
218
+ readonly content: Uint8Array;
219
+ }
220
+ export interface UruFileOutput extends UruFileMetadata {
221
+ readonly outputId: string;
222
+ readonly createdAt: string;
223
+ }
224
+ export interface UruFileOutputSummary extends UruFileOutput {
225
+ readonly releaseId: string | null;
226
+ readonly buildId: string | null;
227
+ }
228
+ export interface UruFilesContext {
229
+ read(fileId: string, options?: {
230
+ signal?: AbortSignal;
231
+ }): Promise<UruFileContent>;
232
+ readOutput(outputId: string, options?: {
233
+ signal?: AbortSignal;
234
+ }): Promise<UruFileContent>;
235
+ createOutput(input: {
236
+ name: string;
237
+ contentType: string;
238
+ content: Uint8Array;
239
+ idempotencyKey: string;
240
+ sha256?: string;
241
+ signal?: AbortSignal;
242
+ }): Promise<UruFileOutput>;
243
+ listOutputs(options?: {
244
+ cursor?: string;
245
+ limit?: number;
246
+ signal?: AbortSignal;
247
+ }): Promise<{
248
+ items: readonly UruFileOutputSummary[];
249
+ nextCursor: string | null;
250
+ }>;
251
+ }
252
+ /** Every conclusion the platform can reach about one upload. */
253
+ export type UruUploadOutcome = "verified" | "pending" | "absent" | "expired" | "unverifiable" | "size_mismatch" | "type_mismatch";
254
+ /**
255
+ * A minted grant. `uploadUrl` is a CREDENTIAL: do not log it or store it.
256
+ *
257
+ * `requiredHeaders` is not advice. The provider rebuilds the signature from
258
+ * what actually arrives, so a PUT that omits or alters either header is
259
+ * refused.
260
+ */
261
+ export interface UruUploadGrant {
262
+ readonly uploadId: string;
263
+ readonly uploadUrl: string;
264
+ readonly method: "PUT";
265
+ readonly requiredHeaders: Readonly<Record<string, string>>;
266
+ readonly filename: string;
267
+ readonly contentType: string;
268
+ readonly sizeBytes: number;
269
+ readonly expiresAt: string;
270
+ }
271
+ /** The verdict a completion reached. */
272
+ export interface UruUploadResult {
273
+ readonly uploadId: string;
274
+ readonly state: "granted" | "verified" | "rejected" | "expired";
275
+ readonly outcome: UruUploadOutcome;
276
+ readonly filename: string;
277
+ readonly contentType: string;
278
+ /** The VERIFIED byte count, or `null` when the object was not admitted. */
279
+ readonly sizeBytes: number | null;
280
+ /** True only when a refused object could not be removed from storage. */
281
+ readonly cleanupFailed: boolean;
282
+ }
283
+ /** The file-upload lane a Gem gets with the `storage` capability. */
284
+ export interface UruUploadsContext {
285
+ request(input: {
286
+ filename: string;
287
+ contentType: string;
288
+ sizeBytes: number;
289
+ signal?: AbortSignal;
290
+ }): Promise<UruUploadGrant>;
291
+ complete(uploadId: string, options?: {
292
+ signal?: AbortSignal;
293
+ }): Promise<UruUploadResult>;
294
+ /** Request, PUT and complete in one call. What almost every caller wants. */
295
+ upload(file: File, options?: {
296
+ signal?: AbortSignal;
297
+ }): Promise<UruUploadResult>;
298
+ }
299
+ export interface UruJobProgress {
300
+ readonly completed: number;
301
+ readonly total?: number;
302
+ readonly message?: string;
303
+ }
304
+ export type UruJobCheckpoint = RuntimeJsonObject;
210
305
  /** Everything a Uru server runtime hands an app. */
211
306
  export interface UruServerContext {
307
+ files: UruFilesContext;
212
308
  datasets: UruDatasetsContext;
213
309
  app: UruAppRuntimeClient;
214
310
  actions: {
@@ -216,6 +312,8 @@ export interface UruServerContext {
216
312
  };
217
313
  jobs: {
218
314
  start: UruCapabilityInvoker;
315
+ progress: (progress: UruJobProgress) => Promise<void>;
316
+ checkpoint: (value: UruJobCheckpoint) => Promise<void>;
219
317
  };
220
318
  secrets: {
221
319
  has: (name: string) => boolean;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * `uru.uploads` — how a Gem accepts a file from the person using it.
3
+ *
4
+ * ## Three hops, and the middle one does not touch Uru
5
+ *
6
+ * 1. `request(...)` asks the platform for a grant. The answer carries a
7
+ * credential that authorizes ONE PUT: exactly one object key, exactly the
8
+ * declared byte count, exactly the declared media type, for a short window
9
+ * the server derived from the size.
10
+ * 2. The browser PUTs the bytes STRAIGHT to object storage with that
11
+ * credential. They never pass through Uru: every runtime invocation body is
12
+ * capped at 100 KB and hashed in worker memory before it is forwarded, so a
13
+ * file could not travel that way at any size worth calling a file.
14
+ * 3. `complete(...)` consumes the grant. The platform then READS the stored
15
+ * object and decides for itself whether it is what was authorized. A
16
+ * "done!" from this SDK is a trigger for that read, never evidence.
17
+ *
18
+ * `upload(file)` performs all three, which is what almost every caller wants.
19
+ *
20
+ * ## The refusals are values, not exceptions
21
+ *
22
+ * A grant that is refused (`size_mismatch`, `type_mismatch`, `unverifiable`) or
23
+ * that nobody redeemed (`expired`) is a normal outcome of an upload a user
24
+ * started, and a Gem has to render it. So `complete` RESOLVES with the verdict
25
+ * and throws only when the platform could not be asked at all. `pending` is the
26
+ * one non-terminal outcome: the window is still open and nothing has landed, so
27
+ * the grant is untouched and may be completed again.
28
+ */
29
+ import type { CreateUruAppRuntimeClientOptions, UruUploadsContext } from './types.js';
30
+ /** The platform's per-file ceiling. Restated so a caller is refused locally. */
31
+ export declare const URU_UPLOAD_MAX_BYTES: number;
32
+ export declare function createUploadsContext(options: CreateUruAppRuntimeClientOptions): UruUploadsContext;
@@ -0,0 +1,228 @@
1
+ /**
2
+ * `uru.uploads` — how a Gem accepts a file from the person using it.
3
+ *
4
+ * ## Three hops, and the middle one does not touch Uru
5
+ *
6
+ * 1. `request(...)` asks the platform for a grant. The answer carries a
7
+ * credential that authorizes ONE PUT: exactly one object key, exactly the
8
+ * declared byte count, exactly the declared media type, for a short window
9
+ * the server derived from the size.
10
+ * 2. The browser PUTs the bytes STRAIGHT to object storage with that
11
+ * credential. They never pass through Uru: every runtime invocation body is
12
+ * capped at 100 KB and hashed in worker memory before it is forwarded, so a
13
+ * file could not travel that way at any size worth calling a file.
14
+ * 3. `complete(...)` consumes the grant. The platform then READS the stored
15
+ * object and decides for itself whether it is what was authorized. A
16
+ * "done!" from this SDK is a trigger for that read, never evidence.
17
+ *
18
+ * `upload(file)` performs all three, which is what almost every caller wants.
19
+ *
20
+ * ## The refusals are values, not exceptions
21
+ *
22
+ * A grant that is refused (`size_mismatch`, `type_mismatch`, `unverifiable`) or
23
+ * that nobody redeemed (`expired`) is a normal outcome of an upload a user
24
+ * started, and a Gem has to render it. So `complete` RESOLVES with the verdict
25
+ * and throws only when the platform could not be asked at all. `pending` is the
26
+ * one non-terminal outcome: the window is still open and nothing has landed, so
27
+ * the grant is untouched and may be completed again.
28
+ */
29
+ import { UruAppRuntimeError } from './errors.js';
30
+ import { resolveHeaders, runtimeBasePath, trimTrailingSlash } from './runtime.js';
31
+ import { isRuntimeJsonObject } from './transport-json.js';
32
+ /** The platform's per-file ceiling. Restated so a caller is refused locally. */
33
+ export const URU_UPLOAD_MAX_BYTES = 100 * 1024 * 1024;
34
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
35
+ const RESPONSE_BYTES = 64 * 1024;
36
+ const OUTCOMES = [
37
+ 'verified',
38
+ 'pending',
39
+ 'absent',
40
+ 'expired',
41
+ 'unverifiable',
42
+ 'size_mismatch',
43
+ 'type_mismatch',
44
+ ];
45
+ function invalid() {
46
+ throw new UruAppRuntimeError('Invalid upload request or response.', {
47
+ status: 0,
48
+ body: null,
49
+ });
50
+ }
51
+ const object = (value) => isRuntimeJsonObject(value) ? value : invalid();
52
+ const string = (value) => typeof value === 'string' ? value : invalid();
53
+ /**
54
+ * Read a bounded JSON body.
55
+ *
56
+ * Bounded rather than trusted for the same reason the files context bounds its
57
+ * own: a runtime that answered with an unbounded body would otherwise be able
58
+ * to exhaust the Gem's memory through a call the Gem made on purpose.
59
+ */
60
+ async function readJson(response) {
61
+ const reader = response.body?.getReader();
62
+ if (reader === undefined)
63
+ invalid();
64
+ const decoder = new TextDecoder();
65
+ let size = 0;
66
+ let text = '';
67
+ try {
68
+ for (;;) {
69
+ const chunk = await reader.read();
70
+ if (chunk.done)
71
+ break;
72
+ size += chunk.value.byteLength;
73
+ if (size > RESPONSE_BYTES) {
74
+ await reader.cancel();
75
+ invalid();
76
+ }
77
+ text += decoder.decode(chunk.value, { stream: true });
78
+ }
79
+ text += decoder.decode();
80
+ return JSON.parse(text);
81
+ }
82
+ catch (error) {
83
+ if (error instanceof UruAppRuntimeError)
84
+ throw error;
85
+ return invalid();
86
+ }
87
+ finally {
88
+ reader.releaseLock();
89
+ }
90
+ }
91
+ function grantFrom(value) {
92
+ const row = object(value);
93
+ const uploadId = string(row['uploadId']);
94
+ const uploadUrl = string(row['uploadUrl']);
95
+ const sizeBytes = row['sizeBytes'];
96
+ const headers = row['requiredHeaders'];
97
+ if (!UUID.test(uploadId) ||
98
+ uploadUrl === '' ||
99
+ typeof sizeBytes !== 'number' ||
100
+ !Number.isSafeInteger(sizeBytes) ||
101
+ sizeBytes < 1 ||
102
+ !isRuntimeJsonObject(headers)) {
103
+ invalid();
104
+ }
105
+ const requiredHeaders = {};
106
+ for (const [name, headerValue] of Object.entries(headers)) {
107
+ requiredHeaders[name] = string(headerValue);
108
+ }
109
+ return {
110
+ uploadId,
111
+ uploadUrl,
112
+ method: 'PUT',
113
+ requiredHeaders,
114
+ filename: string(row['filename']),
115
+ contentType: string(row['contentType']),
116
+ sizeBytes,
117
+ expiresAt: string(row['expiresAt']),
118
+ };
119
+ }
120
+ function resultFrom(value) {
121
+ const row = object(value);
122
+ const outcome = string(row['outcome']);
123
+ const state = string(row['state']);
124
+ const sizeBytes = row['sizeBytes'];
125
+ if (!OUTCOMES.includes(outcome) ||
126
+ (state !== 'granted' &&
127
+ state !== 'verified' &&
128
+ state !== 'rejected' &&
129
+ state !== 'expired') ||
130
+ (sizeBytes !== null && typeof sizeBytes !== 'number')) {
131
+ invalid();
132
+ }
133
+ return {
134
+ uploadId: string(row['uploadId']),
135
+ state,
136
+ outcome: outcome,
137
+ filename: string(row['filename']),
138
+ contentType: string(row['contentType']),
139
+ sizeBytes: sizeBytes === null ? null : sizeBytes,
140
+ cleanupFailed: row['cleanupFailed'] === true,
141
+ };
142
+ }
143
+ export function createUploadsContext(options) {
144
+ const base = `${trimTrailingSlash(options.baseUrl ?? '')}${runtimeBasePath(options)}/apps/${encodeURIComponent(options.deploymentId)}/uploads`;
145
+ const doFetch = options.fetch ?? globalThis.fetch;
146
+ const post = async (path, payload, signal) => {
147
+ const headers = new Headers(await resolveHeaders(options.headers));
148
+ if (payload !== undefined)
149
+ headers.set('content-type', 'application/json');
150
+ const response = await doFetch(`${base}${path}`, {
151
+ method: 'POST',
152
+ headers,
153
+ ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
154
+ signal: signal === undefined
155
+ ? AbortSignal.timeout(30_000)
156
+ : AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
157
+ });
158
+ if (!response.ok) {
159
+ await response.body?.cancel();
160
+ throw new UruAppRuntimeError('Upload request was not accepted.', {
161
+ status: response.status,
162
+ body: null,
163
+ });
164
+ }
165
+ return readJson(response);
166
+ };
167
+ const request = async (input) => {
168
+ if (typeof input.filename !== 'string' ||
169
+ input.filename.trim().length < 1 ||
170
+ input.filename.length > 255 ||
171
+ typeof input.contentType !== 'string' ||
172
+ input.contentType.trim().length < 3 ||
173
+ input.contentType.length > 255 ||
174
+ !Number.isSafeInteger(input.sizeBytes) ||
175
+ input.sizeBytes < 1 ||
176
+ input.sizeBytes > URU_UPLOAD_MAX_BYTES) {
177
+ invalid();
178
+ }
179
+ return grantFrom(await post('', {
180
+ filename: input.filename,
181
+ contentType: input.contentType,
182
+ sizeBytes: input.sizeBytes,
183
+ }, input.signal));
184
+ };
185
+ const complete = async (uploadId, settings) => {
186
+ if (typeof uploadId !== 'string' || !UUID.test(uploadId))
187
+ invalid();
188
+ return resultFrom(await post(`/${uploadId}/complete`, undefined, settings?.signal));
189
+ };
190
+ return {
191
+ request,
192
+ complete,
193
+ upload: async (file, settings) => {
194
+ // The media type is the browser's, lower-cased by it already. A file the
195
+ // OS could not type at all gets the generic one rather than an empty
196
+ // header, because a grant must name ONE concrete media type and an empty
197
+ // one would be refused at the mint with a message about a header the
198
+ // caller never wrote.
199
+ const contentType = typeof file.type === 'string' && file.type.trim() !== ''
200
+ ? file.type
201
+ : 'application/octet-stream';
202
+ const grant = await request({
203
+ filename: file.name,
204
+ contentType,
205
+ sizeBytes: file.size,
206
+ ...(settings?.signal === undefined ? {} : { signal: settings.signal }),
207
+ });
208
+ const put = await doFetch(grant.uploadUrl, {
209
+ method: 'PUT',
210
+ // Exactly the headers the grant was SIGNED with. Adding or altering one
211
+ // changes the canonical request the provider rebuilds, and the PUT is
212
+ // refused with a signature error that names nothing.
213
+ headers: new Headers(grant.requiredHeaders),
214
+ body: file,
215
+ ...(settings?.signal === undefined ? {} : { signal: settings.signal }),
216
+ });
217
+ if (!put.ok) {
218
+ await put.body?.cancel();
219
+ throw new UruAppRuntimeError('Upload was refused by object storage.', {
220
+ status: put.status,
221
+ body: null,
222
+ });
223
+ }
224
+ await put.body?.cancel();
225
+ return complete(grant.uploadId, settings?.signal === undefined ? undefined : { signal: settings.signal });
226
+ },
227
+ };
228
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uru-intelligence/app",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "private": false,
5
5
  "description": "Runtime client for Uru Gems: capability calls, Datasets, jobs and secrets",
6
6
  "keywords": [