@uru-intelligence/app 1.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 +167 -13
- package/dist/dampers.d.ts +7 -74
- package/dist/dampers.js +36 -131
- package/dist/dataset-boundary.d.ts +31 -0
- package/dist/dataset-boundary.js +292 -0
- package/dist/datasets.d.ts +4 -4
- package/dist/datasets.js +111 -80
- package/dist/{errorResponse.d.ts → error-response.d.ts} +1 -1
- package/dist/error-response.js +11 -0
- package/dist/errors.js +1 -1
- package/dist/files.d.ts +2 -0
- package/dist/files.js +149 -0
- package/dist/index.d.ts +28 -12
- package/dist/index.js +96 -53
- package/dist/invocations.d.ts +7 -0
- package/dist/invocations.js +27 -0
- package/dist/jobs.d.ts +4 -0
- package/dist/jobs.js +35 -0
- package/dist/runtime.d.ts +5 -5
- package/dist/runtime.js +23 -23
- package/dist/transport-json.d.ts +9 -0
- package/dist/transport-json.js +101 -0
- package/dist/transport.d.ts +14 -13
- package/dist/transport.js +496 -443
- package/dist/types.d.ts +188 -42
- package/dist/types.js +2 -2
- package/dist/uploads.d.ts +32 -0
- package/dist/uploads.js +228 -0
- package/package.json +61 -59
- package/dist/errorResponse.js +0 -11
package/README.md
CHANGED
|
@@ -53,8 +53,15 @@ const page = await uru.datasets.queryRows('sales', {
|
|
|
53
53
|
sort: [{ field: 'closed_at', direction: 'desc' }],
|
|
54
54
|
});
|
|
55
55
|
|
|
56
|
-
// Actions: run a declared capability and
|
|
57
|
-
const summary = await uru.actions.run
|
|
56
|
+
// Actions: run a declared capability and decode its result, or throw.
|
|
57
|
+
const summary = await uru.actions.run('summarize', { region: 'emea' }, {
|
|
58
|
+
decodeResult: value => {
|
|
59
|
+
if (typeof value !== 'string') {
|
|
60
|
+
throw new Error('summary must be a string');
|
|
61
|
+
}
|
|
62
|
+
return value;
|
|
63
|
+
},
|
|
64
|
+
});
|
|
58
65
|
|
|
59
66
|
// Jobs: start long work and poll it, so the page can show real progress.
|
|
60
67
|
const job = await uru.jobs.start('rebuild-index');
|
|
@@ -69,6 +76,54 @@ and `URU_RUNTIME_TOKEN`. The Uru runtime injects all three. A missing binding
|
|
|
69
76
|
throws `UruAppRuntimeError` naming the binding, rather than failing later at a
|
|
70
77
|
request that could never have worked.
|
|
71
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
|
+
|
|
72
127
|
For a browser calling a public Gem page's runtime, build the client directly:
|
|
73
128
|
|
|
74
129
|
```ts
|
|
@@ -94,16 +149,115 @@ const response = await app.query('summary', {}, { onStatus: event => render(even
|
|
|
94
149
|
- **Server-side Datasets.** Read with `queryRows`; write with `insertRows`,
|
|
95
150
|
`upsertRows`, `deleteRows`, `restoreRows` and `sqlWrite`. Totals, counts and
|
|
96
151
|
top-N summaries must come from the server, never from one fetched page.
|
|
97
|
-
- **
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
`UruRunawayDamperOptions`.
|
|
152
|
+
- **Retry and refresh controls, on by default.** Each invocation gets a unique
|
|
153
|
+
idempotency key. Its HTTP retries keep that key. Equal calls from separate
|
|
154
|
+
clients or later calls remain separate operations. The client also backs off
|
|
155
|
+
on HTTP 429 and throttles `forceRefresh` per capability. Override these
|
|
156
|
+
controls through `dampers`; see `UruRunawayDamperOptions`. Supply an explicit
|
|
157
|
+
`idempotencyKey` when your application retries the same logical operation.
|
|
158
|
+
|
|
159
|
+
## Transport values
|
|
160
|
+
|
|
161
|
+
Capability input must be a plain JSON object. An omitted input becomes `{}`.
|
|
162
|
+
Nested values can contain objects, arrays, strings, finite numbers, booleans,
|
|
163
|
+
and `null`. Omit optional keys instead of setting them to `undefined`.
|
|
164
|
+
|
|
165
|
+
The client rejects values that JSON cannot preserve. These include cycles,
|
|
166
|
+
accessors, sparse arrays, symbols, `BigInt`, and class instances. The client
|
|
167
|
+
validates input before it sends a request or emits a runtime event.
|
|
168
|
+
Input that exceeds the JavaScript runtime's serialization limit also fails
|
|
169
|
+
before either action. `timeoutMs`, when set, must be an integer from 1,000 to
|
|
170
|
+
60,000, as required by the runtime HTTP contract.
|
|
171
|
+
|
|
172
|
+
Response diagnostics use the same JSON rules. Invalid diagnostics in a success
|
|
173
|
+
response cause `UruAppRuntimeError`. An HTTP error keeps its original status and
|
|
174
|
+
body. Diagnostic keys remain opaque; the client does not change their casing.
|
|
175
|
+
|
|
176
|
+
A custom `fetch` must implement the fetch call signature. It does not need
|
|
177
|
+
runtime-specific properties such as Bun's `preconnect` method.
|
|
178
|
+
|
|
179
|
+
## Result decoding
|
|
180
|
+
|
|
181
|
+
HTTP result values are untrusted. A capability call without `decodeResult`
|
|
182
|
+
returns `UruAppRuntimeInvocationResponse<unknown>`. `jobStatus` follows the
|
|
183
|
+
same rule. `actions.run` returns `unknown` without a decoder. Dataset mutation
|
|
184
|
+
methods return `UruDatasetMutationResult<unknown>` without one.
|
|
185
|
+
|
|
186
|
+
Pass a decoder when you need a domain type. The decoder receives `unknown` and
|
|
187
|
+
must validate it before returning the type. Its type is inferred from the
|
|
188
|
+
decoder, so a generic type argument is never an unchecked assertion:
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
type Summary = { total: number };
|
|
192
|
+
|
|
193
|
+
const decodeSummary = (value: unknown): Summary => {
|
|
194
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
195
|
+
throw new Error('summary must be an object');
|
|
196
|
+
}
|
|
197
|
+
if (!('total' in value) || typeof value.total !== 'number') {
|
|
198
|
+
throw new Error('summary.total must be a number');
|
|
199
|
+
}
|
|
200
|
+
return { total: value.total };
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const response = await uru.app.query('summary', { region: 'emea' }, {
|
|
204
|
+
decodeResult: decodeSummary,
|
|
205
|
+
});
|
|
206
|
+
const total = response.result?.total;
|
|
207
|
+
|
|
208
|
+
const summary = await uru.actions.run('summarize', { region: 'emea' }, {
|
|
209
|
+
decodeResult: decodeSummary,
|
|
210
|
+
});
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
`datasets.queryRows` accepts a row decoder as its third argument. A call without
|
|
214
|
+
one returns rows as `UruDatasetRow` (`RuntimeJsonObject`); a call with one returns
|
|
215
|
+
the decoder's row type. Dataset writes accept the result decoder as their third
|
|
216
|
+
argument. A decoder error is the caller's error and propagates unchanged. A
|
|
217
|
+
transport or platform failure remains `UruAppRuntimeError`.
|
|
218
|
+
|
|
219
|
+
Capability and job-status envelopes can omit `result` or return `null` while
|
|
220
|
+
work is pending. The client preserves both forms without calling the decoder.
|
|
221
|
+
Typed callers must still handle an absent or null result.
|
|
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.
|
|
102
254
|
|
|
103
255
|
## Errors
|
|
104
256
|
|
|
105
|
-
|
|
106
|
-
|
|
257
|
+
Transport and platform failures throw `UruAppRuntimeError`. Decoder failures
|
|
258
|
+
propagate unchanged from the caller's decoder. `UruAppRuntimeError` carries
|
|
259
|
+
`status` (the HTTP status, or `0` for a local failure) and `body` (the parsed
|
|
260
|
+
response, or `null`).
|
|
107
261
|
|
|
108
262
|
```ts
|
|
109
263
|
import { UruAppRuntimeError } from '@uru-intelligence/app';
|
|
@@ -120,10 +274,10 @@ try {
|
|
|
120
274
|
|
|
121
275
|
## Stability
|
|
122
276
|
|
|
123
|
-
Semantic versioning
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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.
|
|
127
281
|
|
|
128
282
|
The API still follows the Uru platform rather than the other way round. When the
|
|
129
283
|
platform's runtime contract moves, this package moves with it — additively where
|
package/dist/dampers.d.ts
CHANGED
|
@@ -1,72 +1,7 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Client-side runaway dampers for `@uru-intelligence/app` (P2 cost-safety guardrails).
|
|
3
|
-
*
|
|
4
|
-
* Motivation (2026-07-09 hosted-Gem runaway incident + cost-safety audit,
|
|
5
|
-
* `docs/plans/gem-runtime-cost-safety-audit.md`, recommendation "[P2] SDK-side
|
|
6
|
-
* runaway dampers"): the SDK gave a buggy render loop maximal ammunition —
|
|
7
|
-
*
|
|
8
|
-
* - it never defaulted an `idempotency_key`, so the backend minted a fresh
|
|
9
|
-
* random Temporal workflow id per call and `REJECT_DUPLICATE` dedup was dead:
|
|
10
|
-
* thousands of identical re-fires each spun a NEW workflow → external API call;
|
|
11
|
-
* - it applied no backoff on `rate_limited` / HTTP 429 responses, so a client
|
|
12
|
-
* that hit the limiter simply hammered it again on the next render;
|
|
13
|
-
* - `forceRefresh` bypassed the tool-call cache with no throttle, so a loop
|
|
14
|
-
* could pin the backend to cache-MISS work indefinitely.
|
|
15
|
-
*
|
|
16
|
-
* These helpers are the pure, dependency-free primitives the client
|
|
17
|
-
* (`index.ts`) composes to defuse the common accidental-loop case at the source.
|
|
18
|
-
* They do NOT stop a malicious client — the fail-closed server-side gates do
|
|
19
|
-
* that — they remove the buggy-loop foot-gun. Everything here is deterministic
|
|
20
|
-
* and clock-injectable so it is unit-testable offline.
|
|
21
|
-
*
|
|
22
|
-
* This module imports nothing at all — it takes primitives — so the
|
|
23
|
-
* `types → dampers` and `transport → dampers` edges are one-directional and
|
|
24
|
-
* this file can never be part of a cycle.
|
|
25
|
-
*/
|
|
26
|
-
/** A canonical-JSON stringify: object keys are emitted in sorted order at every
|
|
27
|
-
* depth so two structurally-equal inputs hash identically regardless of key
|
|
28
|
-
* insertion order. Arrays keep their order (order is semantic). Non-plain values
|
|
29
|
-
* fall through to `JSON.stringify`. Used only to derive an idempotency key, so a
|
|
30
|
-
* best-effort canonicalization is sufficient. */
|
|
31
|
-
export declare function stableStringify(value: unknown): string;
|
|
32
|
-
/** A stable FNV-1a 32-bit hash rendered as 8 hex chars. NOT cryptographic — an
|
|
33
|
-
* idempotency key only needs to be stable and well-distributed, and this avoids
|
|
34
|
-
* any dependency on `node:crypto` / Web Crypto so it runs identically in a
|
|
35
|
-
* browser, a Cloudflare Worker, and Node. */
|
|
36
|
-
export declare function fnv1aHex(input: string): string;
|
|
37
|
-
/** Inputs identifying one logical tool invocation for idempotency-key derivation. */
|
|
38
|
-
export interface IdempotencyKeyInput {
|
|
39
|
-
readonly deploymentId: string;
|
|
40
|
-
readonly capabilityType: string;
|
|
41
|
-
readonly capabilityName: string;
|
|
42
|
-
readonly input: unknown;
|
|
43
|
-
/** Current epoch ms, coarsened into a burst window (see {@link defaultIdempotencyKey}). */
|
|
44
|
-
readonly nowMs: number;
|
|
45
|
-
/** Burst window width in ms; identical calls inside one window collapse. */
|
|
46
|
-
readonly windowMs: number;
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* Derive a default `idempotency_key` for a logical tool invocation:
|
|
50
|
-
* `uru-app:<fnv(deployment | type | name | canonical(input) | window)>`.
|
|
51
|
-
*
|
|
52
|
-
* The window bucket (`floor(nowMs / windowMs)`) is the "action-instance id" the
|
|
53
|
-
* audit calls for: within one window, identical `(deployment, capability,
|
|
54
|
-
* params)` re-fires collapse to the SAME key → the backend derives the SAME
|
|
55
|
-
* deterministic workflow id → Temporal `REJECT_DUPLICATE` binds them to the one
|
|
56
|
-
* in-flight/just-completed workflow instead of spawning thousands. Across
|
|
57
|
-
* windows the key changes, so a legitimate repeat call in a later window is NOT
|
|
58
|
-
* permanently deduped against Temporal's retention (which a purely
|
|
59
|
-
* params-deterministic key would cause). A caller that needs exact-once or
|
|
60
|
-
* always-distinct semantics passes its own `idempotency_key` and this default
|
|
61
|
-
* never runs.
|
|
62
|
-
*
|
|
63
|
-
* The result is well under the backend's 128-char cap.
|
|
64
|
-
*/
|
|
65
|
-
export declare function defaultIdempotencyKey(input: IdempotencyKeyInput): string;
|
|
1
|
+
/** Client retry delays and force-refresh limits. */
|
|
66
2
|
/** Resolved, defaulted damper configuration (built once per client). */
|
|
67
3
|
export interface ResolvedDamperConfig {
|
|
68
4
|
readonly defaultIdempotencyKeys: boolean;
|
|
69
|
-
readonly idempotencyWindowMs: number;
|
|
70
5
|
readonly maxRateLimitRetries: number;
|
|
71
6
|
readonly rateLimitBaseDelayMs: number;
|
|
72
7
|
readonly rateLimitMaxDelayMs: number;
|
|
@@ -76,10 +11,8 @@ export interface ResolvedDamperConfig {
|
|
|
76
11
|
}
|
|
77
12
|
/** Caller-supplied damper overrides; every field defaults (see {@link resolveDamperConfig}). */
|
|
78
13
|
export interface UruRunawayDamperOptions {
|
|
79
|
-
/**
|
|
14
|
+
/** Give each invocation a unique key, reused by its retries (default `true`). */
|
|
80
15
|
defaultIdempotencyKeys?: boolean;
|
|
81
|
-
/** Burst window (ms) over which identical re-fires collapse to one key (default 15000). */
|
|
82
|
-
idempotencyWindowMs?: number;
|
|
83
16
|
/** Max automatic retries on a 429 / rate_limited response (default 3; `<= 0` disables backoff). */
|
|
84
17
|
maxRateLimitRetries?: number;
|
|
85
18
|
/** Base backoff delay (ms) for the first 429 retry (default 500). */
|
|
@@ -94,7 +27,7 @@ export interface UruRunawayDamperOptions {
|
|
|
94
27
|
sleep?: (ms: number) => Promise<void>;
|
|
95
28
|
}
|
|
96
29
|
/** Fold caller overrides into a fully-defaulted {@link ResolvedDamperConfig}. */
|
|
97
|
-
export declare
|
|
30
|
+
export declare const resolveDamperConfig: (options: UruRunawayDamperOptions | undefined) => ResolvedDamperConfig;
|
|
98
31
|
/**
|
|
99
32
|
* Compute the backoff delay (ms) before retrying a rate-limited response.
|
|
100
33
|
*
|
|
@@ -105,22 +38,22 @@ export declare function resolveDamperConfig(options: UruRunawayDamperOptions | u
|
|
|
105
38
|
*
|
|
106
39
|
* @param attempt zero-based retry index (0 = first retry).
|
|
107
40
|
*/
|
|
108
|
-
export declare
|
|
41
|
+
export declare const computeRateLimitBackoffMs: (args: {
|
|
109
42
|
attempt: number;
|
|
110
43
|
retryAfterSeconds: number | null | undefined;
|
|
111
44
|
baseDelayMs: number;
|
|
112
45
|
maxDelayMs: number;
|
|
113
|
-
})
|
|
46
|
+
}) => number;
|
|
114
47
|
/**
|
|
115
48
|
* Parse a retry-after hint (seconds) from a 429 response's `Retry-After` header
|
|
116
49
|
* and/or a `retryAfterSeconds` field in the parsed owned HTTP body. Prefers the header
|
|
117
50
|
* (HTTP-standard); a non-numeric header (an HTTP-date form) is ignored in favor
|
|
118
51
|
* of the body. Returns `null` when neither is a positive number.
|
|
119
52
|
*/
|
|
120
|
-
export declare
|
|
53
|
+
export declare const parseRetryAfterSeconds: (args: {
|
|
121
54
|
header: string | null | undefined;
|
|
122
55
|
body: unknown;
|
|
123
|
-
})
|
|
56
|
+
}) => number | null;
|
|
124
57
|
/**
|
|
125
58
|
* Per-client mutable state for the forceRefresh throttle: the last epoch-ms at
|
|
126
59
|
* which a forceRefresh was HONORED for each capability key. Created once per
|
package/dist/dampers.js
CHANGED
|
@@ -1,128 +1,34 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
3
|
-
*
|
|
4
|
-
* Motivation (2026-07-09 hosted-Gem runaway incident + cost-safety audit,
|
|
5
|
-
* `docs/plans/gem-runtime-cost-safety-audit.md`, recommendation "[P2] SDK-side
|
|
6
|
-
* runaway dampers"): the SDK gave a buggy render loop maximal ammunition —
|
|
7
|
-
*
|
|
8
|
-
* - it never defaulted an `idempotency_key`, so the backend minted a fresh
|
|
9
|
-
* random Temporal workflow id per call and `REJECT_DUPLICATE` dedup was dead:
|
|
10
|
-
* thousands of identical re-fires each spun a NEW workflow → external API call;
|
|
11
|
-
* - it applied no backoff on `rate_limited` / HTTP 429 responses, so a client
|
|
12
|
-
* that hit the limiter simply hammered it again on the next render;
|
|
13
|
-
* - `forceRefresh` bypassed the tool-call cache with no throttle, so a loop
|
|
14
|
-
* could pin the backend to cache-MISS work indefinitely.
|
|
15
|
-
*
|
|
16
|
-
* These helpers are the pure, dependency-free primitives the client
|
|
17
|
-
* (`index.ts`) composes to defuse the common accidental-loop case at the source.
|
|
18
|
-
* They do NOT stop a malicious client — the fail-closed server-side gates do
|
|
19
|
-
* that — they remove the buggy-loop foot-gun. Everything here is deterministic
|
|
20
|
-
* and clock-injectable so it is unit-testable offline.
|
|
21
|
-
*
|
|
22
|
-
* This module imports nothing at all — it takes primitives — so the
|
|
23
|
-
* `types → dampers` and `transport → dampers` edges are one-directional and
|
|
24
|
-
* this file can never be part of a cycle.
|
|
25
|
-
*/
|
|
26
|
-
/** A canonical-JSON stringify: object keys are emitted in sorted order at every
|
|
27
|
-
* depth so two structurally-equal inputs hash identically regardless of key
|
|
28
|
-
* insertion order. Arrays keep their order (order is semantic). Non-plain values
|
|
29
|
-
* fall through to `JSON.stringify`. Used only to derive an idempotency key, so a
|
|
30
|
-
* best-effort canonicalization is sufficient. */
|
|
31
|
-
export function stableStringify(value) {
|
|
32
|
-
return JSON.stringify(canonicalize(value));
|
|
33
|
-
}
|
|
34
|
-
function canonicalize(value) {
|
|
35
|
-
if (value === null || typeof value !== 'object') {
|
|
36
|
-
return value;
|
|
37
|
-
}
|
|
38
|
-
if (Array.isArray(value)) {
|
|
39
|
-
return value.map(canonicalize);
|
|
40
|
-
}
|
|
41
|
-
const record = value;
|
|
42
|
-
const sortedKeys = Object.keys(record).sort();
|
|
43
|
-
const out = {};
|
|
44
|
-
for (const key of sortedKeys) {
|
|
45
|
-
out[key] = canonicalize(record[key]);
|
|
46
|
-
}
|
|
47
|
-
return out;
|
|
48
|
-
}
|
|
49
|
-
/** A stable FNV-1a 32-bit hash rendered as 8 hex chars. NOT cryptographic — an
|
|
50
|
-
* idempotency key only needs to be stable and well-distributed, and this avoids
|
|
51
|
-
* any dependency on `node:crypto` / Web Crypto so it runs identically in a
|
|
52
|
-
* browser, a Cloudflare Worker, and Node. */
|
|
53
|
-
export function fnv1aHex(input) {
|
|
54
|
-
let hash = 0x811c9dc5;
|
|
55
|
-
for (let i = 0; i < input.length; i += 1) {
|
|
56
|
-
hash ^= input.charCodeAt(i);
|
|
57
|
-
// 32-bit FNV prime multiply via shifts (stays within safe-integer range,
|
|
58
|
-
// then masked back to 32 bits).
|
|
59
|
-
hash = Math.imul(hash, 0x01000193);
|
|
60
|
-
}
|
|
61
|
-
// `>>> 0` coerces to an unsigned 32-bit int before hex rendering.
|
|
62
|
-
return (hash >>> 0).toString(16).padStart(8, '0');
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* Derive a default `idempotency_key` for a logical tool invocation:
|
|
66
|
-
* `uru-app:<fnv(deployment | type | name | canonical(input) | window)>`.
|
|
67
|
-
*
|
|
68
|
-
* The window bucket (`floor(nowMs / windowMs)`) is the "action-instance id" the
|
|
69
|
-
* audit calls for: within one window, identical `(deployment, capability,
|
|
70
|
-
* params)` re-fires collapse to the SAME key → the backend derives the SAME
|
|
71
|
-
* deterministic workflow id → Temporal `REJECT_DUPLICATE` binds them to the one
|
|
72
|
-
* in-flight/just-completed workflow instead of spawning thousands. Across
|
|
73
|
-
* windows the key changes, so a legitimate repeat call in a later window is NOT
|
|
74
|
-
* permanently deduped against Temporal's retention (which a purely
|
|
75
|
-
* params-deterministic key would cause). A caller that needs exact-once or
|
|
76
|
-
* always-distinct semantics passes its own `idempotency_key` and this default
|
|
77
|
-
* never runs.
|
|
78
|
-
*
|
|
79
|
-
* The result is well under the backend's 128-char cap.
|
|
80
|
-
*/
|
|
81
|
-
export function defaultIdempotencyKey(input) {
|
|
82
|
-
const windowMs = input.windowMs > 0 ? input.windowMs : 1;
|
|
83
|
-
const bucket = Math.floor(input.nowMs / windowMs);
|
|
84
|
-
const material = [
|
|
85
|
-
input.deploymentId,
|
|
86
|
-
input.capabilityType,
|
|
87
|
-
input.capabilityName,
|
|
88
|
-
stableStringify(input.input ?? {}),
|
|
89
|
-
String(bucket),
|
|
90
|
-
].join('|');
|
|
91
|
-
return `uru-app:${fnv1aHex(material)}`;
|
|
92
|
-
}
|
|
93
|
-
const DEFAULT_IDEMPOTENCY_WINDOW_MS = 15_000;
|
|
1
|
+
/** Client retry delays and force-refresh limits. */
|
|
2
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
94
3
|
const DEFAULT_MAX_RATE_LIMIT_RETRIES = 3;
|
|
95
4
|
const DEFAULT_RATE_LIMIT_BASE_DELAY_MS = 500;
|
|
96
5
|
const DEFAULT_RATE_LIMIT_MAX_DELAY_MS = 10_000;
|
|
97
|
-
const DEFAULT_FORCE_REFRESH_MIN_INTERVAL_MS =
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
6
|
+
const DEFAULT_FORCE_REFRESH_MIN_INTERVAL_MS = 5000;
|
|
7
|
+
const positiveOr = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0
|
|
8
|
+
? value
|
|
9
|
+
: fallback;
|
|
10
|
+
const nonNegativeOr = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value >= 0
|
|
11
|
+
? value
|
|
12
|
+
: fallback;
|
|
13
|
+
const defaultSleep = async (ms) => {
|
|
14
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
15
|
+
setTimeout(() => {
|
|
16
|
+
resolve(true);
|
|
17
|
+
}, Math.max(0, ms));
|
|
18
|
+
await promise;
|
|
19
|
+
};
|
|
108
20
|
/** Fold caller overrides into a fully-defaulted {@link ResolvedDamperConfig}. */
|
|
109
|
-
export
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
// `<= 0` disables the throttle explicitly.
|
|
121
|
-
forceRefreshMinIntervalMs: nonNegativeOr(options?.forceRefreshMinIntervalMs, DEFAULT_FORCE_REFRESH_MIN_INTERVAL_MS),
|
|
122
|
-
now: options?.now ?? (() => Date.now()),
|
|
123
|
-
sleep: options?.sleep ?? defaultSleep,
|
|
124
|
-
};
|
|
125
|
-
}
|
|
21
|
+
export const resolveDamperConfig = (options) => ({
|
|
22
|
+
defaultIdempotencyKeys: options?.defaultIdempotencyKeys ?? true,
|
|
23
|
+
// `<= 0` disables the throttle explicitly.
|
|
24
|
+
forceRefreshMinIntervalMs: nonNegativeOr(options?.forceRefreshMinIntervalMs, DEFAULT_FORCE_REFRESH_MIN_INTERVAL_MS),
|
|
25
|
+
// `<= 0` disables backoff — clamped to 0 (no retries) rather than negative.
|
|
26
|
+
maxRateLimitRetries: nonNegativeOr(options?.maxRateLimitRetries, DEFAULT_MAX_RATE_LIMIT_RETRIES),
|
|
27
|
+
now: options?.now ?? (() => Date.now()),
|
|
28
|
+
rateLimitBaseDelayMs: positiveOr(options?.rateLimitBaseDelayMs, DEFAULT_RATE_LIMIT_BASE_DELAY_MS),
|
|
29
|
+
rateLimitMaxDelayMs: positiveOr(options?.rateLimitMaxDelayMs, DEFAULT_RATE_LIMIT_MAX_DELAY_MS),
|
|
30
|
+
sleep: options?.sleep ?? defaultSleep,
|
|
31
|
+
});
|
|
126
32
|
/**
|
|
127
33
|
* Compute the backoff delay (ms) before retrying a rate-limited response.
|
|
128
34
|
*
|
|
@@ -133,40 +39,39 @@ export function resolveDamperConfig(options) {
|
|
|
133
39
|
*
|
|
134
40
|
* @param attempt zero-based retry index (0 = first retry).
|
|
135
41
|
*/
|
|
136
|
-
export
|
|
42
|
+
export const computeRateLimitBackoffMs = (args) => {
|
|
137
43
|
const { attempt, retryAfterSeconds, baseDelayMs, maxDelayMs } = args;
|
|
138
|
-
if (typeof retryAfterSeconds ===
|
|
44
|
+
if (typeof retryAfterSeconds === "number" &&
|
|
139
45
|
Number.isFinite(retryAfterSeconds) &&
|
|
140
46
|
retryAfterSeconds > 0) {
|
|
141
47
|
return Math.min(maxDelayMs, Math.ceil(retryAfterSeconds * 1000));
|
|
142
48
|
}
|
|
143
49
|
const exponential = baseDelayMs * 2 ** Math.max(0, attempt);
|
|
144
50
|
return Math.min(maxDelayMs, exponential);
|
|
145
|
-
}
|
|
51
|
+
};
|
|
146
52
|
/**
|
|
147
53
|
* Parse a retry-after hint (seconds) from a 429 response's `Retry-After` header
|
|
148
54
|
* and/or a `retryAfterSeconds` field in the parsed owned HTTP body. Prefers the header
|
|
149
55
|
* (HTTP-standard); a non-numeric header (an HTTP-date form) is ignored in favor
|
|
150
56
|
* of the body. Returns `null` when neither is a positive number.
|
|
151
57
|
*/
|
|
152
|
-
export
|
|
153
|
-
const headerRaw =
|
|
154
|
-
if (headerRaw !==
|
|
58
|
+
export const parseRetryAfterSeconds = (args) => {
|
|
59
|
+
const headerRaw = (args.header ?? "").trim();
|
|
60
|
+
if (headerRaw !== "") {
|
|
155
61
|
const headerSeconds = Number(headerRaw);
|
|
156
62
|
if (Number.isFinite(headerSeconds) && headerSeconds > 0) {
|
|
157
63
|
return headerSeconds;
|
|
158
64
|
}
|
|
159
65
|
}
|
|
160
|
-
if (
|
|
161
|
-
const candidate = args.body
|
|
162
|
-
.retryAfterSeconds;
|
|
66
|
+
if (isRecord(args.body)) {
|
|
67
|
+
const candidate = args.body.retryAfterSeconds;
|
|
163
68
|
const seconds = Number(candidate);
|
|
164
69
|
if (Number.isFinite(seconds) && seconds > 0) {
|
|
165
70
|
return seconds;
|
|
166
71
|
}
|
|
167
72
|
}
|
|
168
73
|
return null;
|
|
169
|
-
}
|
|
74
|
+
};
|
|
170
75
|
/**
|
|
171
76
|
* Per-client mutable state for the forceRefresh throttle: the last epoch-ms at
|
|
172
77
|
* which a forceRefresh was HONORED for each capability key. Created once per
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime Dataset boundary helpers.
|
|
3
|
+
*
|
|
4
|
+
* Dataset requests and responses cross an untyped HTTP boundary. This module
|
|
5
|
+
* validates the owned fields at that boundary and leaves provider payloads
|
|
6
|
+
* opaque unless the caller supplies a decoder.
|
|
7
|
+
*/
|
|
8
|
+
import type { RuntimeJsonObject } from "./transport-json.js";
|
|
9
|
+
import type { UruDatasetMutationResult, UruDatasetRowsResult, UruResultDecoder } from "./types.js";
|
|
10
|
+
/** Decode a Dataset query page with a caller-owned row decoder. */
|
|
11
|
+
export declare const decodeDatasetRowsResult: <TRow>(value: unknown, decodeRow: UruResultDecoder<TRow>) => UruDatasetRowsResult<TRow>;
|
|
12
|
+
/** Decode a Dataset query page while retaining validated JSON row objects. */
|
|
13
|
+
export declare const decodeDefaultDatasetRowsResult: (value: unknown) => UruDatasetRowsResult;
|
|
14
|
+
/** Decode a Dataset mutation envelope with a caller-owned result decoder. */
|
|
15
|
+
export declare const decodeDatasetMutationResult: <TResult>(value: unknown, decodeResult: UruResultDecoder<TResult>) => UruDatasetMutationResult<TResult>;
|
|
16
|
+
/** Decode a Dataset mutation envelope without narrowing its provider result. */
|
|
17
|
+
export declare const decodeDefaultDatasetMutationResult: (value: unknown) => UruDatasetMutationResult;
|
|
18
|
+
/**
|
|
19
|
+
* Materialize a JSON request before any asynchronous header callback runs.
|
|
20
|
+
* This rejects cycles, accessors, non-JSON prototypes, sparse arrays, and
|
|
21
|
+
* non-finite numbers at the HTTP edge.
|
|
22
|
+
*/
|
|
23
|
+
export declare const serializeDatasetRequest: (value: unknown, label: string) => string;
|
|
24
|
+
/** Validate a row command's JSON-object rows before request serialization. */
|
|
25
|
+
export declare const datasetRowsForRequest: (rows: unknown, label?: string) => RuntimeJsonObject[];
|
|
26
|
+
/** Validate row IDs before request serialization. */
|
|
27
|
+
export declare const datasetRowIdsForRequest: (rowIds: unknown, label?: string) => string[];
|
|
28
|
+
/** Validate the target list used by a Dataset SQL write. */
|
|
29
|
+
export declare const datasetIdsForRequest: (datasetIds: unknown, label?: string) => string[];
|
|
30
|
+
/** Extract a useful message from a non-successful Dataset response. */
|
|
31
|
+
export declare const datasetWriteErrorMessage: (value: unknown, status: number) => string;
|