@uru-intelligence/app 1.0.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/LICENSE +58 -0
- package/README.md +146 -0
- package/dist/dampers.d.ts +145 -0
- package/dist/dampers.js +200 -0
- package/dist/datasets.d.ts +11 -0
- package/dist/datasets.js +119 -0
- package/dist/errorResponse.d.ts +2 -0
- package/dist/errorResponse.js +11 -0
- package/dist/errors.d.ts +18 -0
- package/dist/errors.js +20 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +118 -0
- package/dist/runtime.d.ts +32 -0
- package/dist/runtime.js +71 -0
- package/dist/transport.d.ts +58 -0
- package/dist/transport.js +625 -0
- package/dist/types.d.ts +211 -0
- package/dist/types.js +15 -0
- package/package.json +62 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
Uru App Runtime Client Licence
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Uru Intelligence Inc. All rights reserved.
|
|
4
|
+
|
|
5
|
+
This licence covers the `@uru-intelligence/app` software package ("the Software"). It does
|
|
6
|
+
not cover the Uru platform itself, which is governed separately by the Uru
|
|
7
|
+
Intelligence End User License Agreement.
|
|
8
|
+
|
|
9
|
+
1. GRANT
|
|
10
|
+
|
|
11
|
+
Uru Intelligence Inc. grants you a worldwide, royalty-free, non-exclusive
|
|
12
|
+
licence to:
|
|
13
|
+
|
|
14
|
+
a. download, install and copy the Software;
|
|
15
|
+
b. include the Software, in whole or in part, and in original, compiled,
|
|
16
|
+
bundled or minified form, in an application you build; and
|
|
17
|
+
c. distribute and publicly perform that application, including the portions
|
|
18
|
+
of the Software it contains.
|
|
19
|
+
|
|
20
|
+
This grant applies only where the Software is used to communicate with the Uru
|
|
21
|
+
platform, which is the only thing the Software does.
|
|
22
|
+
|
|
23
|
+
2. RESTRICTIONS
|
|
24
|
+
|
|
25
|
+
You may not:
|
|
26
|
+
|
|
27
|
+
a. distribute the Software on its own, or as part of a library or toolkit
|
|
28
|
+
whose purpose is to redistribute it;
|
|
29
|
+
b. remove or alter this licence, the copyright notice, or any attribution in
|
|
30
|
+
the Software; or
|
|
31
|
+
c. use the name "Uru", "Uru Intelligence", or any Uru mark to endorse or
|
|
32
|
+
promote your application without written permission.
|
|
33
|
+
|
|
34
|
+
3. RESERVATION
|
|
35
|
+
|
|
36
|
+
All rights not expressly granted above are reserved by Uru Intelligence Inc.
|
|
37
|
+
This licence grants no rights in any Uru patent, trademark, or service mark, and
|
|
38
|
+
no right to any Uru service. Access to the Uru platform requires a separate
|
|
39
|
+
agreement.
|
|
40
|
+
|
|
41
|
+
4. TERMINATION
|
|
42
|
+
|
|
43
|
+
This licence terminates automatically if you breach it. Applications you
|
|
44
|
+
distributed before termination, in compliance with this licence, remain
|
|
45
|
+
licensed.
|
|
46
|
+
|
|
47
|
+
5. NO WARRANTY
|
|
48
|
+
|
|
49
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
50
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
51
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
52
|
+
|
|
53
|
+
6. LIMITATION OF LIABILITY
|
|
54
|
+
|
|
55
|
+
IN NO EVENT SHALL URU INTELLIGENCE INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
|
56
|
+
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
57
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
58
|
+
THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# @uru-intelligence/app
|
|
2
|
+
|
|
3
|
+
**This package is the runtime client for [Uru](https://uruintelligence.com) Gems.
|
|
4
|
+
It is published so that Gem projects install and build outside the Uru hosted
|
|
5
|
+
builder. It talks only to an Uru workspace runtime and does nothing on its own.
|
|
6
|
+
The API tracks the Uru platform, and is versioned semantically against it. It is
|
|
7
|
+
not a general-purpose library.**
|
|
8
|
+
|
|
9
|
+
If you are not building a Uru Gem, this package will not do anything useful for
|
|
10
|
+
you.
|
|
11
|
+
|
|
12
|
+
## Why it exists
|
|
13
|
+
|
|
14
|
+
A Gem's generated project declares `@uru-intelligence/app` as a dependency. Before this
|
|
15
|
+
package was published, `npm install` on such a project failed with a 404, and
|
|
16
|
+
only Uru's own hosted builder could build a Gem — it vendored the package from
|
|
17
|
+
inside the platform image. Publishing removes that special case, so a Gem builds
|
|
18
|
+
the same way on a laptop, in an agent's sandbox, and in Uru's builder.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
npm install @uru-intelligence/app
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
- ESM only. There is no CommonJS build.
|
|
27
|
+
- Zero runtime dependencies.
|
|
28
|
+
- Node.js `>= 22.12.0`, and Cloudflare Workers. Both are measured against every
|
|
29
|
+
release before it publishes: the packed tarball is installed and exercised on
|
|
30
|
+
Node 22.12.0, 24 and 26 — 22.12.0 exactly, because that is the floor this
|
|
31
|
+
package promises — and it is bundled into a Workers build through Uru's own
|
|
32
|
+
Gem template. Anything else
|
|
33
|
+
with a global `fetch` will very likely work, but is not something this package
|
|
34
|
+
tests.
|
|
35
|
+
- TypeScript consumers need `fetch`, `Headers` and `Response` in their `lib` —
|
|
36
|
+
the `DOM` lib, `@types/node`, or `@cloudflare/workers-types`.
|
|
37
|
+
|
|
38
|
+
## Usage
|
|
39
|
+
|
|
40
|
+
Inside a Uru server runtime, build a context from the injected environment:
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { createUruServerContext } from '@uru-intelligence/app';
|
|
44
|
+
|
|
45
|
+
const uru = createUruServerContext(process.env);
|
|
46
|
+
|
|
47
|
+
// Datasets: filter, sort, paginate and aggregate on the SERVER.
|
|
48
|
+
const page = await uru.datasets.queryRows('sales', {
|
|
49
|
+
limit: 25,
|
|
50
|
+
offset: 0,
|
|
51
|
+
includeTotal: true,
|
|
52
|
+
where: [{ field: 'region', op: 'eq', value: 'emea' }],
|
|
53
|
+
sort: [{ field: 'closed_at', direction: 'desc' }],
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// Actions: run a declared capability and take its result, or throw.
|
|
57
|
+
const summary = await uru.actions.run<string>('summarize', { id: page.rows[0]?.id });
|
|
58
|
+
|
|
59
|
+
// Jobs: start long work and poll it, so the page can show real progress.
|
|
60
|
+
const job = await uru.jobs.start('rebuild-index');
|
|
61
|
+
const status = await uru.app.jobStatus(job.executionId ?? '');
|
|
62
|
+
|
|
63
|
+
// Secrets: the app's own declared bindings.
|
|
64
|
+
const key = uru.secrets.has('STRIPE_KEY') ? uru.secrets.get('STRIPE_KEY') : null;
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`createUruServerContext` requires `URU_DEPLOYMENT_ID`, `URU_RUNTIME_API_BASE`
|
|
68
|
+
and `URU_RUNTIME_TOKEN`. The Uru runtime injects all three. A missing binding
|
|
69
|
+
throws `UruAppRuntimeError` naming the binding, rather than failing later at a
|
|
70
|
+
request that could never have worked.
|
|
71
|
+
|
|
72
|
+
For a browser calling a public Gem page's runtime, build the client directly:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import { createUruAppRuntimeClient } from '@uru-intelligence/app';
|
|
76
|
+
|
|
77
|
+
const app = createUruAppRuntimeClient({
|
|
78
|
+
deploymentId,
|
|
79
|
+
publicPageSlug: 'quarterly-report',
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
const response = await app.query('summary', {}, { onStatus: event => render(event.state) });
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## What it gives you
|
|
86
|
+
|
|
87
|
+
- **Every capability kind** a Gem can declare: `query`, `action`, `job`,
|
|
88
|
+
`endpoint` and `serverFunction`, plus `jobStatus` and `cancelJob`.
|
|
89
|
+
- **Real states, not just success and failure.** Every response carries a
|
|
90
|
+
normalized `state` — `queued`, `running`, `cached`, `stale`, `refreshing`,
|
|
91
|
+
`rate_limited`, `budget_blocked`, `service_unavailable`, `canceled` and more.
|
|
92
|
+
Surface them. A Gem that hides expensive work behind a spinner is a Gem whose
|
|
93
|
+
users cannot tell a slow query from a blocked budget.
|
|
94
|
+
- **Server-side Datasets.** Read with `queryRows`; write with `insertRows`,
|
|
95
|
+
`upsertRows`, `deleteRows`, `restoreRows` and `sqlWrite`. Totals, counts and
|
|
96
|
+
top-N summaries must come from the server, never from one fetched page.
|
|
97
|
+
- **Runaway dampers, on by default.** An accidental render loop is the expensive
|
|
98
|
+
failure mode for a Gem, so the client defaults an idempotency key per
|
|
99
|
+
invocation, backs off on HTTP 429, and throttles `forceRefresh` per
|
|
100
|
+
capability. Override any of it through `dampers`; see
|
|
101
|
+
`UruRunawayDamperOptions`.
|
|
102
|
+
|
|
103
|
+
## Errors
|
|
104
|
+
|
|
105
|
+
Every failure throws `UruAppRuntimeError`, which carries `status` (the HTTP
|
|
106
|
+
status, or `0` for a local failure) and `body` (the parsed response, or `null`).
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
import { UruAppRuntimeError } from '@uru-intelligence/app';
|
|
110
|
+
|
|
111
|
+
try {
|
|
112
|
+
await uru.actions.run('summarize');
|
|
113
|
+
} catch (error) {
|
|
114
|
+
if (error instanceof UruAppRuntimeError && error.status === 429) {
|
|
115
|
+
// rate limited after the client's own retries were exhausted
|
|
116
|
+
}
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Stability
|
|
122
|
+
|
|
123
|
+
Semantic versioning, from `1.0.0` onward. A breaking change to the public
|
|
124
|
+
surface takes a major version. This package starts at `1.0.0` rather than `0.x`
|
|
125
|
+
because it is already load-bearing: every hosted Uru Gem runs against it, so
|
|
126
|
+
breaking it is expensive whatever the version number claims.
|
|
127
|
+
|
|
128
|
+
The API still follows the Uru platform rather than the other way round. When the
|
|
129
|
+
platform's runtime contract moves, this package moves with it — additively where
|
|
130
|
+
it can, and in a major version where it cannot. Pin an exact version if you need
|
|
131
|
+
a build to be reproducible; Uru's own Gem templates do.
|
|
132
|
+
|
|
133
|
+
The public surface is `createUruServerContext`, `createUruAppRuntimeClient`,
|
|
134
|
+
`UruAppRuntimeError`, and the exported types. Nothing else is API, even if you
|
|
135
|
+
can reach it.
|
|
136
|
+
|
|
137
|
+
## Documentation
|
|
138
|
+
|
|
139
|
+
Building Gems is documented at
|
|
140
|
+
[uruintelligence.com](https://uruintelligence.com). Bugs and questions go to the
|
|
141
|
+
[issue tracker](https://github.com/Ignition-Forward/uru-workspace-platform/issues).
|
|
142
|
+
|
|
143
|
+
## Licence
|
|
144
|
+
|
|
145
|
+
Proprietary. See [LICENSE](./LICENSE). You may use and redistribute this package
|
|
146
|
+
as part of an application that runs on the Uru platform.
|
|
@@ -0,0 +1,145 @@
|
|
|
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;
|
|
66
|
+
/** Resolved, defaulted damper configuration (built once per client). */
|
|
67
|
+
export interface ResolvedDamperConfig {
|
|
68
|
+
readonly defaultIdempotencyKeys: boolean;
|
|
69
|
+
readonly idempotencyWindowMs: number;
|
|
70
|
+
readonly maxRateLimitRetries: number;
|
|
71
|
+
readonly rateLimitBaseDelayMs: number;
|
|
72
|
+
readonly rateLimitMaxDelayMs: number;
|
|
73
|
+
readonly forceRefreshMinIntervalMs: number;
|
|
74
|
+
readonly now: () => number;
|
|
75
|
+
readonly sleep: (ms: number) => Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
/** Caller-supplied damper overrides; every field defaults (see {@link resolveDamperConfig}). */
|
|
78
|
+
export interface UruRunawayDamperOptions {
|
|
79
|
+
/** Default an idempotency_key per invocation when the caller supplies none (default `true`). */
|
|
80
|
+
defaultIdempotencyKeys?: boolean;
|
|
81
|
+
/** Burst window (ms) over which identical re-fires collapse to one key (default 15000). */
|
|
82
|
+
idempotencyWindowMs?: number;
|
|
83
|
+
/** Max automatic retries on a 429 / rate_limited response (default 3; `<= 0` disables backoff). */
|
|
84
|
+
maxRateLimitRetries?: number;
|
|
85
|
+
/** Base backoff delay (ms) for the first 429 retry (default 500). */
|
|
86
|
+
rateLimitBaseDelayMs?: number;
|
|
87
|
+
/** Ceiling on any single backoff wait (ms) (default 10000). */
|
|
88
|
+
rateLimitMaxDelayMs?: number;
|
|
89
|
+
/** Minimum spacing (ms) between honored forceRefresh calls per capability (default 5000; `<= 0` disables the throttle). */
|
|
90
|
+
forceRefreshMinIntervalMs?: number;
|
|
91
|
+
/** Clock (ms); injectable for tests. Defaults to `Date.now`. */
|
|
92
|
+
now?: () => number;
|
|
93
|
+
/** Async delay; injectable for tests. Defaults to `setTimeout`. */
|
|
94
|
+
sleep?: (ms: number) => Promise<void>;
|
|
95
|
+
}
|
|
96
|
+
/** Fold caller overrides into a fully-defaulted {@link ResolvedDamperConfig}. */
|
|
97
|
+
export declare function resolveDamperConfig(options: UruRunawayDamperOptions | undefined): ResolvedDamperConfig;
|
|
98
|
+
/**
|
|
99
|
+
* Compute the backoff delay (ms) before retrying a rate-limited response.
|
|
100
|
+
*
|
|
101
|
+
* Honors a server-advertised `Retry-After` / `retry_after_seconds` when present
|
|
102
|
+
* (the server knows its own window), otherwise a bounded exponential backoff
|
|
103
|
+
* `base * 2^attempt`. Either way the result is capped at `maxDelayMs` so a large
|
|
104
|
+
* or hostile `Retry-After` cannot park the client for minutes.
|
|
105
|
+
*
|
|
106
|
+
* @param attempt zero-based retry index (0 = first retry).
|
|
107
|
+
*/
|
|
108
|
+
export declare function computeRateLimitBackoffMs(args: {
|
|
109
|
+
attempt: number;
|
|
110
|
+
retryAfterSeconds: number | null | undefined;
|
|
111
|
+
baseDelayMs: number;
|
|
112
|
+
maxDelayMs: number;
|
|
113
|
+
}): number;
|
|
114
|
+
/**
|
|
115
|
+
* Parse a retry-after hint (seconds) from a 429 response's `Retry-After` header
|
|
116
|
+
* and/or a `retryAfterSeconds` field in the parsed owned HTTP body. Prefers the header
|
|
117
|
+
* (HTTP-standard); a non-numeric header (an HTTP-date form) is ignored in favor
|
|
118
|
+
* of the body. Returns `null` when neither is a positive number.
|
|
119
|
+
*/
|
|
120
|
+
export declare function parseRetryAfterSeconds(args: {
|
|
121
|
+
header: string | null | undefined;
|
|
122
|
+
body: unknown;
|
|
123
|
+
}): number | null;
|
|
124
|
+
/**
|
|
125
|
+
* Per-client mutable state for the forceRefresh throttle: the last epoch-ms at
|
|
126
|
+
* which a forceRefresh was HONORED for each capability key. Created once per
|
|
127
|
+
* client and closed over by the invocation path.
|
|
128
|
+
*/
|
|
129
|
+
export declare class ForceRefreshThrottle {
|
|
130
|
+
private readonly lastHonoredMs;
|
|
131
|
+
/**
|
|
132
|
+
* Decide whether a requested forceRefresh should be honored. Returns `true`
|
|
133
|
+
* (and records the timestamp) when the caller did not request a refresh, when
|
|
134
|
+
* the throttle is disabled (`minIntervalMs <= 0`), or when at least
|
|
135
|
+
* `minIntervalMs` has elapsed since the last honored refresh for `key`.
|
|
136
|
+
* Otherwise returns `false` — the caller then sends a normal cache-allowed
|
|
137
|
+
* request instead of hammering past the cache.
|
|
138
|
+
*/
|
|
139
|
+
shouldForceRefresh(args: {
|
|
140
|
+
key: string;
|
|
141
|
+
requested: boolean;
|
|
142
|
+
nowMs: number;
|
|
143
|
+
minIntervalMs: number;
|
|
144
|
+
}): boolean;
|
|
145
|
+
}
|
package/dist/dampers.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
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 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;
|
|
94
|
+
const DEFAULT_MAX_RATE_LIMIT_RETRIES = 3;
|
|
95
|
+
const DEFAULT_RATE_LIMIT_BASE_DELAY_MS = 500;
|
|
96
|
+
const DEFAULT_RATE_LIMIT_MAX_DELAY_MS = 10_000;
|
|
97
|
+
const DEFAULT_FORCE_REFRESH_MIN_INTERVAL_MS = 5_000;
|
|
98
|
+
function positiveOr(value, fallback) {
|
|
99
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0
|
|
100
|
+
? value
|
|
101
|
+
: fallback;
|
|
102
|
+
}
|
|
103
|
+
function nonNegativeOr(value, fallback) {
|
|
104
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0
|
|
105
|
+
? value
|
|
106
|
+
: fallback;
|
|
107
|
+
}
|
|
108
|
+
/** Fold caller overrides into a fully-defaulted {@link ResolvedDamperConfig}. */
|
|
109
|
+
export function resolveDamperConfig(options) {
|
|
110
|
+
const defaultSleep = (ms) => new Promise(resolve => {
|
|
111
|
+
setTimeout(resolve, Math.max(0, ms));
|
|
112
|
+
});
|
|
113
|
+
return {
|
|
114
|
+
defaultIdempotencyKeys: options?.defaultIdempotencyKeys ?? true,
|
|
115
|
+
idempotencyWindowMs: positiveOr(options?.idempotencyWindowMs, DEFAULT_IDEMPOTENCY_WINDOW_MS),
|
|
116
|
+
// `<= 0` disables backoff — clamped to 0 (no retries) rather than negative.
|
|
117
|
+
maxRateLimitRetries: nonNegativeOr(options?.maxRateLimitRetries, DEFAULT_MAX_RATE_LIMIT_RETRIES),
|
|
118
|
+
rateLimitBaseDelayMs: positiveOr(options?.rateLimitBaseDelayMs, DEFAULT_RATE_LIMIT_BASE_DELAY_MS),
|
|
119
|
+
rateLimitMaxDelayMs: positiveOr(options?.rateLimitMaxDelayMs, DEFAULT_RATE_LIMIT_MAX_DELAY_MS),
|
|
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
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Compute the backoff delay (ms) before retrying a rate-limited response.
|
|
128
|
+
*
|
|
129
|
+
* Honors a server-advertised `Retry-After` / `retry_after_seconds` when present
|
|
130
|
+
* (the server knows its own window), otherwise a bounded exponential backoff
|
|
131
|
+
* `base * 2^attempt`. Either way the result is capped at `maxDelayMs` so a large
|
|
132
|
+
* or hostile `Retry-After` cannot park the client for minutes.
|
|
133
|
+
*
|
|
134
|
+
* @param attempt zero-based retry index (0 = first retry).
|
|
135
|
+
*/
|
|
136
|
+
export function computeRateLimitBackoffMs(args) {
|
|
137
|
+
const { attempt, retryAfterSeconds, baseDelayMs, maxDelayMs } = args;
|
|
138
|
+
if (typeof retryAfterSeconds === 'number' &&
|
|
139
|
+
Number.isFinite(retryAfterSeconds) &&
|
|
140
|
+
retryAfterSeconds > 0) {
|
|
141
|
+
return Math.min(maxDelayMs, Math.ceil(retryAfterSeconds * 1000));
|
|
142
|
+
}
|
|
143
|
+
const exponential = baseDelayMs * 2 ** Math.max(0, attempt);
|
|
144
|
+
return Math.min(maxDelayMs, exponential);
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Parse a retry-after hint (seconds) from a 429 response's `Retry-After` header
|
|
148
|
+
* and/or a `retryAfterSeconds` field in the parsed owned HTTP body. Prefers the header
|
|
149
|
+
* (HTTP-standard); a non-numeric header (an HTTP-date form) is ignored in favor
|
|
150
|
+
* of the body. Returns `null` when neither is a positive number.
|
|
151
|
+
*/
|
|
152
|
+
export function parseRetryAfterSeconds(args) {
|
|
153
|
+
const headerRaw = String(args.header ?? '').trim();
|
|
154
|
+
if (headerRaw !== '') {
|
|
155
|
+
const headerSeconds = Number(headerRaw);
|
|
156
|
+
if (Number.isFinite(headerSeconds) && headerSeconds > 0) {
|
|
157
|
+
return headerSeconds;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (typeof args.body === 'object' && args.body !== null) {
|
|
161
|
+
const candidate = args.body
|
|
162
|
+
.retryAfterSeconds;
|
|
163
|
+
const seconds = Number(candidate);
|
|
164
|
+
if (Number.isFinite(seconds) && seconds > 0) {
|
|
165
|
+
return seconds;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Per-client mutable state for the forceRefresh throttle: the last epoch-ms at
|
|
172
|
+
* which a forceRefresh was HONORED for each capability key. Created once per
|
|
173
|
+
* client and closed over by the invocation path.
|
|
174
|
+
*/
|
|
175
|
+
export class ForceRefreshThrottle {
|
|
176
|
+
lastHonoredMs = new Map();
|
|
177
|
+
/**
|
|
178
|
+
* Decide whether a requested forceRefresh should be honored. Returns `true`
|
|
179
|
+
* (and records the timestamp) when the caller did not request a refresh, when
|
|
180
|
+
* the throttle is disabled (`minIntervalMs <= 0`), or when at least
|
|
181
|
+
* `minIntervalMs` has elapsed since the last honored refresh for `key`.
|
|
182
|
+
* Otherwise returns `false` — the caller then sends a normal cache-allowed
|
|
183
|
+
* request instead of hammering past the cache.
|
|
184
|
+
*/
|
|
185
|
+
shouldForceRefresh(args) {
|
|
186
|
+
if (!args.requested) {
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
if (args.minIntervalMs <= 0) {
|
|
190
|
+
this.lastHonoredMs.set(args.key, args.nowMs);
|
|
191
|
+
return true;
|
|
192
|
+
}
|
|
193
|
+
const last = this.lastHonoredMs.get(args.key);
|
|
194
|
+
if (last !== undefined && args.nowMs - last < args.minIntervalMs) {
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
this.lastHonoredMs.set(args.key, args.nowMs);
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dataset read and write surface for hosted Uru Gems.
|
|
3
|
+
*
|
|
4
|
+
* Reads go through the capability client (a declared `query`); writes are
|
|
5
|
+
* direct provider-runtime calls, because a write is not a cached capability.
|
|
6
|
+
* The shapes this file produces are declared in `./types.js` — see the note
|
|
7
|
+
* there on why no module in this package imports the public barrel.
|
|
8
|
+
*/
|
|
9
|
+
import type { CreateUruAppRuntimeClientOptions, UruAppRuntimeClient, UruDatasetsContext } from './types.js';
|
|
10
|
+
/** Build the Dataset surface hung off a server context. */
|
|
11
|
+
export declare function createDatasetsContext(app: UruAppRuntimeClient, clientOptions: CreateUruAppRuntimeClientOptions): UruDatasetsContext;
|
package/dist/datasets.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dataset read and write surface for hosted Uru Gems.
|
|
3
|
+
*
|
|
4
|
+
* Reads go through the capability client (a declared `query`); writes are
|
|
5
|
+
* direct provider-runtime calls, because a write is not a cached capability.
|
|
6
|
+
* The shapes this file produces are declared in `./types.js` — see the note
|
|
7
|
+
* there on why no module in this package imports the public barrel.
|
|
8
|
+
*/
|
|
9
|
+
import { UruAppRuntimeError } from './errors.js';
|
|
10
|
+
import { requireCompletedRuntimeResponse, resolveHeaders, runtimeBasePath, trimTrailingSlash, } from './runtime.js';
|
|
11
|
+
async function postProviderDatasetWrite(options, subpath, body) {
|
|
12
|
+
const runtimeFetch = options.fetch ?? globalThis.fetch;
|
|
13
|
+
if (!runtimeFetch) {
|
|
14
|
+
throw new UruAppRuntimeError('Uru app runtime fetch is not available.', {
|
|
15
|
+
status: 0,
|
|
16
|
+
body: null,
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
const deploymentId = options.deploymentId.trim();
|
|
20
|
+
if (!deploymentId) {
|
|
21
|
+
throw new UruAppRuntimeError('Uru app runtime deployment id is required.', {
|
|
22
|
+
status: 0,
|
|
23
|
+
body: null,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
const baseUrl = options.baseUrl ? trimTrailingSlash(options.baseUrl) : '';
|
|
27
|
+
const basePath = runtimeBasePath(options);
|
|
28
|
+
const url = `${baseUrl}${basePath}/apps/${encodeURIComponent(deploymentId)}/${subpath}`;
|
|
29
|
+
const headers = new Headers(await resolveHeaders(options.headers));
|
|
30
|
+
headers.set('content-type', 'application/json');
|
|
31
|
+
const response = await runtimeFetch(url, {
|
|
32
|
+
method: 'POST',
|
|
33
|
+
headers,
|
|
34
|
+
body: JSON.stringify(body),
|
|
35
|
+
});
|
|
36
|
+
const parsed = (await response.json().catch(() => null));
|
|
37
|
+
if (!response.ok) {
|
|
38
|
+
const message = datasetWriteErrorMessage(parsed, response.status);
|
|
39
|
+
throw new UruAppRuntimeError(message, {
|
|
40
|
+
status: response.status,
|
|
41
|
+
body: parsed,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return (parsed ?? {
|
|
45
|
+
ok: false,
|
|
46
|
+
operation: 'unknown',
|
|
47
|
+
result: null,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function datasetWriteErrorMessage(parsed, status) {
|
|
51
|
+
if (typeof parsed !== 'object' || parsed === null) {
|
|
52
|
+
return `Uru Dataset write failed with HTTP ${status}`;
|
|
53
|
+
}
|
|
54
|
+
const record = parsed;
|
|
55
|
+
if (typeof record['detail'] === 'string')
|
|
56
|
+
return record['detail'];
|
|
57
|
+
const error = record['error'];
|
|
58
|
+
if (typeof error === 'object' && error !== null) {
|
|
59
|
+
const message = error['message'];
|
|
60
|
+
if (typeof message === 'string' && message.trim() !== '')
|
|
61
|
+
return message;
|
|
62
|
+
}
|
|
63
|
+
return `Uru Dataset write failed with HTTP ${status}`;
|
|
64
|
+
}
|
|
65
|
+
function invokeDatasetRowMutation(options, datasetRef, body) {
|
|
66
|
+
const slug = datasetRef.trim();
|
|
67
|
+
if (!slug) {
|
|
68
|
+
throw new UruAppRuntimeError('Uru Dataset reference is required.', {
|
|
69
|
+
status: 0,
|
|
70
|
+
body: null,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
return postProviderDatasetWrite(options, `mutate/${encodeURIComponent(slug)}`, body);
|
|
74
|
+
}
|
|
75
|
+
function invokeDatasetSqlWrite(options, sql, writeOptions) {
|
|
76
|
+
const statement = sql.trim();
|
|
77
|
+
if (!statement) {
|
|
78
|
+
throw new UruAppRuntimeError('SQL statement is required.', {
|
|
79
|
+
status: 0,
|
|
80
|
+
body: null,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
const body = {
|
|
84
|
+
sql: statement,
|
|
85
|
+
dataset_ids: [...writeOptions.datasetIds],
|
|
86
|
+
};
|
|
87
|
+
if (writeOptions.maxRows !== undefined)
|
|
88
|
+
body['max_rows'] = writeOptions.maxRows;
|
|
89
|
+
if (writeOptions.maxAffected !== undefined) {
|
|
90
|
+
body['max_affected'] = writeOptions.maxAffected;
|
|
91
|
+
}
|
|
92
|
+
if (writeOptions.timeoutMs !== undefined) {
|
|
93
|
+
body['timeout_ms'] = writeOptions.timeoutMs;
|
|
94
|
+
}
|
|
95
|
+
return postProviderDatasetWrite(options, 'dataset-sql', body);
|
|
96
|
+
}
|
|
97
|
+
/** Build the Dataset surface hung off a server context. */
|
|
98
|
+
export function createDatasetsContext(app, clientOptions) {
|
|
99
|
+
return {
|
|
100
|
+
queryRows: (datasetRef, query = {}) => requireCompletedRuntimeResponse(app.query(datasetRef, { query })),
|
|
101
|
+
insertRows: (datasetRef, rows) => invokeDatasetRowMutation(clientOptions, datasetRef, {
|
|
102
|
+
operation: 'upsert',
|
|
103
|
+
rows,
|
|
104
|
+
}),
|
|
105
|
+
upsertRows: (datasetRef, rows) => invokeDatasetRowMutation(clientOptions, datasetRef, {
|
|
106
|
+
operation: 'upsert',
|
|
107
|
+
rows,
|
|
108
|
+
}),
|
|
109
|
+
deleteRows: (datasetRef, rowIds) => invokeDatasetRowMutation(clientOptions, datasetRef, {
|
|
110
|
+
operation: 'delete',
|
|
111
|
+
row_ids: rowIds,
|
|
112
|
+
}),
|
|
113
|
+
restoreRows: (datasetRef, rowIds) => invokeDatasetRowMutation(clientOptions, datasetRef, {
|
|
114
|
+
operation: 'restore',
|
|
115
|
+
row_ids: rowIds,
|
|
116
|
+
}),
|
|
117
|
+
sqlWrite: (sql, options) => invokeDatasetSqlWrite(clientOptions, sql, options),
|
|
118
|
+
};
|
|
119
|
+
}
|