@tangle-network/agent-app 0.60.270 → 0.60.271
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/dist/chat-routes/index.js +2 -1
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/{chunk-UJKWM4UY.js → chunk-DJIN3YUJ.js} +1 -59
- package/dist/chunk-DJIN3YUJ.js.map +1 -0
- package/dist/chunk-F4TUZYMX.js +63 -0
- package/dist/chunk-F4TUZYMX.js.map +1 -0
- package/dist/platform/billable-turn-admission.d.ts +83 -0
- package/dist/platform/index.d.ts +1 -0
- package/dist/platform/index.js +49 -0
- package/dist/platform/index.js.map +1 -1
- package/dist/public-consultation/index.d.ts +2 -2
- package/dist/sandbox/index.js +4 -2
- package/package.json +1 -1
- package/dist/chunk-UJKWM4UY.js.map +0 -1
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// src/sandbox/warm-cache.ts
|
|
2
|
+
var MAX_ENTRIES = 500;
|
|
3
|
+
function coloCache() {
|
|
4
|
+
return typeof caches === "undefined" ? void 0 : caches.default;
|
|
5
|
+
}
|
|
6
|
+
function createWarmCache(namespace, options = {}) {
|
|
7
|
+
const useIsolate = options.isolate ?? true;
|
|
8
|
+
const env = options.env;
|
|
9
|
+
const entries = /* @__PURE__ */ new Map();
|
|
10
|
+
const coloKey = (key) => {
|
|
11
|
+
const scope = (typeof env === "function" ? env() : env) ?? "production";
|
|
12
|
+
return new Request(`https://${namespace}/${encodeURIComponent(scope)}/${encodeURIComponent(key)}`);
|
|
13
|
+
};
|
|
14
|
+
const remember = (key, value, expiresAt) => {
|
|
15
|
+
entries.delete(key);
|
|
16
|
+
if (!useIsolate) return;
|
|
17
|
+
const now = Date.now();
|
|
18
|
+
for (const [k, entry] of entries) if (entry.expiresAt <= now) entries.delete(k);
|
|
19
|
+
if (entries.size >= MAX_ENTRIES) {
|
|
20
|
+
const oldest = entries.keys().next().value;
|
|
21
|
+
if (oldest !== void 0) entries.delete(oldest);
|
|
22
|
+
}
|
|
23
|
+
entries.set(key, { value, expiresAt });
|
|
24
|
+
};
|
|
25
|
+
return {
|
|
26
|
+
async read(key) {
|
|
27
|
+
const local = entries.get(key);
|
|
28
|
+
if (local && local.expiresAt > Date.now()) return { value: local.value, source: "isolate" };
|
|
29
|
+
const hit = await coloCache()?.match(coloKey(key)).catch(() => void 0);
|
|
30
|
+
if (!hit) return null;
|
|
31
|
+
const expiresAt = Number(hit.headers.get("x-expires-at"));
|
|
32
|
+
if (!(expiresAt > Date.now())) return null;
|
|
33
|
+
const value = await hit.json().catch(() => void 0);
|
|
34
|
+
if (typeof value !== "object" || value === null || !("v" in value)) return null;
|
|
35
|
+
const stored = value.v;
|
|
36
|
+
remember(key, stored, expiresAt);
|
|
37
|
+
return { value: stored, source: "colo" };
|
|
38
|
+
},
|
|
39
|
+
async write(key, value, ttlMs) {
|
|
40
|
+
const expiresAt = Date.now() + ttlMs;
|
|
41
|
+
remember(key, value, expiresAt);
|
|
42
|
+
await coloCache()?.put(coloKey(key), new Response(JSON.stringify({ v: value }), { headers: {
|
|
43
|
+
"cache-control": `max-age=${Math.max(1, Math.ceil(ttlMs / 1e3))}`,
|
|
44
|
+
"x-expires-at": String(expiresAt)
|
|
45
|
+
} })).catch(() => {
|
|
46
|
+
});
|
|
47
|
+
},
|
|
48
|
+
async forget(key) {
|
|
49
|
+
entries.delete(key);
|
|
50
|
+
await coloCache()?.delete(coloKey(key)).catch((error) => {
|
|
51
|
+
console.warn("[warm-cache] forget failed", { namespace, key, error: error instanceof Error ? error.message : String(error) });
|
|
52
|
+
});
|
|
53
|
+
},
|
|
54
|
+
clearIsolate() {
|
|
55
|
+
entries.clear();
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export {
|
|
61
|
+
createWarmCache
|
|
62
|
+
};
|
|
63
|
+
//# sourceMappingURL=chunk-F4TUZYMX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sandbox/warm-cache.ts"],"sourcesContent":["/**\n * A value computed once and read by every later request of the same key until\n * it expires: this isolate's Map first, then the data center's Workers cache, so\n * a request served by another isolate (or warmed by a workspace prewarm on page\n * open or composer focus) reads the value instead of computing it again.\n *\n * Mechanism only: the product decides what is cached, for how long, and when a\n * refusal must `forget` it. Lifted from Creative (creative-agent#691), which\n * caches its connected-tool catalog and its billing verdicts with it.\n *\n * Keys name a subject (a user), never a credential: a key in a cache URL is\n * stored in the clear.\n */\n\nconst MAX_ENTRIES = 500\n\n/** Which layer answered a read: this isolate's memory or the data center's Workers cache. */\nexport type WarmCacheSource = 'isolate' | 'colo'\n\nexport interface WarmCache<T> {\n read(key: string): Promise<{ value: T; source: WarmCacheSource } | null>\n /** Awaited: a prewarm's response ends right after it, which could cancel the write. */\n write(key: string, value: T, ttlMs: number): Promise<void>\n forget(key: string): Promise<void>\n /** Test seam: clears this isolate's layer only. */\n clearIsolate(): void\n}\n\nexport interface WarmCacheOptions {\n /**\n * `false` keeps only the data center's layer, so `forget` reaches every\n * isolate there: use it for a value a refusal must end everywhere at once.\n * Default `true`.\n */\n isolate?: boolean\n /**\n * The deployment environment, part of every cache key because staging and\n * production share a zone's cache. A function is read on each call, so a\n * module-level cache can follow an environment bound after import.\n * Default `'production'`.\n */\n env?: string | (() => string | undefined)\n}\n\nfunction coloCache(): Cache | undefined {\n return typeof caches === 'undefined' ? undefined : (caches as unknown as { default: Cache }).default\n}\n\n/**\n * `namespace` is the cache URL's host; it names no origin and is never routed.\n * Use one namespace per product and value kind, such as\n * `connected-tools.creative.internal`.\n */\nexport function createWarmCache<T>(namespace: string, options: WarmCacheOptions = {}): WarmCache<T> {\n const useIsolate = options.isolate ?? true\n const env = options.env\n const entries = new Map<string, { value: T; expiresAt: number }>()\n const coloKey = (key: string) => {\n const scope = (typeof env === 'function' ? env() : env) ?? 'production'\n return new Request(`https://${namespace}/${encodeURIComponent(scope)}/${encodeURIComponent(key)}`)\n }\n\n // Delete-before-set keeps Map order close to recency, so evicting the first\n // entry drops the least recently refreshed one: a soft memory bound.\n const remember = (key: string, value: T, expiresAt: number) => {\n entries.delete(key)\n if (!useIsolate) return\n const now = Date.now()\n for (const [k, entry] of entries) if (entry.expiresAt <= now) entries.delete(k)\n if (entries.size >= MAX_ENTRIES) {\n const oldest = entries.keys().next().value\n if (oldest !== undefined) entries.delete(oldest)\n }\n entries.set(key, { value, expiresAt })\n }\n\n return {\n async read(key) {\n const local = entries.get(key)\n if (local && local.expiresAt > Date.now()) return { value: local.value, source: 'isolate' }\n const hit = await coloCache()?.match(coloKey(key)).catch(() => undefined)\n if (!hit) return null\n const expiresAt = Number(hit.headers.get('x-expires-at'))\n if (!(expiresAt > Date.now())) return null\n const value: unknown = await hit.json().catch(() => undefined)\n if (typeof value !== 'object' || value === null || !('v' in value)) return null\n const stored = (value as { v: T }).v\n remember(key, stored, expiresAt)\n return { value: stored, source: 'colo' }\n },\n async write(key, value, ttlMs) {\n const expiresAt = Date.now() + ttlMs\n remember(key, value, expiresAt)\n await coloCache()?.put(coloKey(key), new Response(JSON.stringify({ v: value }), { headers: {\n 'cache-control': `max-age=${Math.max(1, Math.ceil(ttlMs / 1000))}`, 'x-expires-at': String(expiresAt),\n } })).catch(() => {})\n },\n async forget(key) {\n entries.delete(key)\n // A failed delete leaves the value served until it expires: say so (namespace and key only, never a value).\n await coloCache()?.delete(coloKey(key)).catch((error: unknown) => {\n console.warn('[warm-cache] forget failed', { namespace, key, error: error instanceof Error ? error.message : String(error) })\n })\n },\n clearIsolate() {\n entries.clear()\n },\n }\n}\n"],"mappings":";AAcA,IAAM,cAAc;AA8BpB,SAAS,YAA+B;AACtC,SAAO,OAAO,WAAW,cAAc,SAAa,OAAyC;AAC/F;AAOO,SAAS,gBAAmB,WAAmB,UAA4B,CAAC,GAAiB;AAClG,QAAM,aAAa,QAAQ,WAAW;AACtC,QAAM,MAAM,QAAQ;AACpB,QAAM,UAAU,oBAAI,IAA6C;AACjE,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,IACzC;AAAA,IACA,MAAM,MAAM,KAAK,OAAO,OAAO;AAC7B,YAAM,YAAY,KAAK,IAAI,IAAI;AAC/B,eAAS,KAAK,OAAO,SAAS;AAC9B,YAAM,UAAU,GAAG,IAAI,QAAQ,GAAG,GAAG,IAAI,SAAS,KAAK,UAAU,EAAE,GAAG,MAAM,CAAC,GAAG,EAAE,SAAS;AAAA,QACzF,iBAAiB,WAAW,KAAK,IAAI,GAAG,KAAK,KAAK,QAAQ,GAAI,CAAC,CAAC;AAAA,QAAI,gBAAgB,OAAO,SAAS;AAAA,MACtG,EAAE,CAAC,CAAC,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IACtB;AAAA,IACA,MAAM,OAAO,KAAK;AAChB,cAAQ,OAAO,GAAG;AAElB,YAAM,UAAU,GAAG,OAAO,QAAQ,GAAG,CAAC,EAAE,MAAM,CAAC,UAAmB;AAChE,gBAAQ,KAAK,8BAA8B,EAAE,WAAW,KAAK,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC;AAAA,MAC9H,CAAC;AAAA,IACH;AAAA,IACA,eAAe;AACb,cAAQ,MAAM;AAAA,IAChB;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { type WarmCacheOptions, type WarmCacheSource } from '../sandbox/warm-cache';
|
|
2
|
+
/**
|
|
3
|
+
* A billable turn's seat and balance verdict, read from Platform once per user
|
|
4
|
+
* per window instead of on every turn. Lifted from Creative
|
|
5
|
+
* (creative-agent#692): in production on 2026-10-21 its seat and balance reads
|
|
6
|
+
* took 723 ms each, most of the 949 ms of its turn gates.
|
|
7
|
+
*
|
|
8
|
+
* Only a passing verdict is kept. A refusal is never cached, so a seatless or
|
|
9
|
+
* unfunded user always gets the live read and its 402. Within the window the
|
|
10
|
+
* balance stays enforced where money moves: the Tangle Router holds spend
|
|
11
|
+
* before it calls a provider and refuses a balance at or below zero. The entry
|
|
12
|
+
* ends at `windowMs` or at the seat's `paidThrough`, whichever is first, and is
|
|
13
|
+
* dropped on any refusal: a seat or balance refusal read here, or one the
|
|
14
|
+
* product sees elsewhere and reports with `forget` (Creative calls it when
|
|
15
|
+
* Platform refuses to fund a turn's Router key). Only the data center's cache
|
|
16
|
+
* holds it (no isolate copy), so that drop reaches every isolate in the data
|
|
17
|
+
* center where it runs. The Workers cache is per data center: a verdict kept
|
|
18
|
+
* in another data center lives on until its own window ends, and the Tangle
|
|
19
|
+
* Router still refuses an unfunded key there.
|
|
20
|
+
*
|
|
21
|
+
* The verdict is keyed by `userId` unless `key` says otherwise: an app whose
|
|
22
|
+
* seat or balance read depends on more than the user (a workspace, an
|
|
23
|
+
* organization) must pass `key`, or one scope's verdict admits another.
|
|
24
|
+
*
|
|
25
|
+
* `windowMs` has no default. Platform sends apps no billing webhook, so the
|
|
26
|
+
* window is how long a seat or balance change made on Platform can go unseen
|
|
27
|
+
* by admission. Creative ships 5 minutes (`5 * 60_000`); the window for other
|
|
28
|
+
* apps is Drew's call.
|
|
29
|
+
*/
|
|
30
|
+
/** A Platform read's verdict: only `allowed` decides admission. */
|
|
31
|
+
export interface BillableTurnVerdict {
|
|
32
|
+
allowed: boolean;
|
|
33
|
+
}
|
|
34
|
+
/** A seat verdict; `paidThrough` (ISO) ends a kept verdict early, `null` when access is not a dated seat. */
|
|
35
|
+
export interface BillableTurnSeatVerdict extends BillableTurnVerdict {
|
|
36
|
+
paidThrough?: string | null;
|
|
37
|
+
}
|
|
38
|
+
export interface BillableTurnAdmissionOptions<Input extends {
|
|
39
|
+
userId: string;
|
|
40
|
+
}, Seat extends BillableTurnSeatVerdict, Balance extends BillableTurnVerdict> {
|
|
41
|
+
/** The cache URL's host, one per product, such as `billing-admission.creative.internal`. */
|
|
42
|
+
namespace: string;
|
|
43
|
+
/** How long a passing verdict is kept. Required: see the module note. */
|
|
44
|
+
windowMs: number;
|
|
45
|
+
readSeat(input: Input): Promise<Seat>;
|
|
46
|
+
readBalance(input: Input): Promise<Balance>;
|
|
47
|
+
/** The deployment environment in the cache key (see {@link WarmCacheOptions.env}). */
|
|
48
|
+
env?: WarmCacheOptions['env'];
|
|
49
|
+
/** What a verdict is kept under: everything `readSeat` and `readBalance` depend on. Default `input.userId`. */
|
|
50
|
+
key?(input: Input): string;
|
|
51
|
+
}
|
|
52
|
+
export interface AdmitBillableTurnOptions {
|
|
53
|
+
/** Turns a Platform read failure into the caller's error. */
|
|
54
|
+
mapError?: (error: unknown) => never;
|
|
55
|
+
/** Names each Platform read (`gate_seat`, `gate_balance`) for the turn's timing. */
|
|
56
|
+
track?: <T>(name: string, work: Promise<T>) => Promise<T>;
|
|
57
|
+
/** Read Platform even over a kept verdict, so the window starts now (a prewarm step). */
|
|
58
|
+
refresh?: boolean;
|
|
59
|
+
}
|
|
60
|
+
export type BillableTurnAdmissionResult<Seat, Balance> = {
|
|
61
|
+
source: WarmCacheSource;
|
|
62
|
+
} | {
|
|
63
|
+
source: 'platform';
|
|
64
|
+
seat: Seat;
|
|
65
|
+
balance?: Balance;
|
|
66
|
+
};
|
|
67
|
+
export interface BillableTurnAdmission<Input extends {
|
|
68
|
+
userId: string;
|
|
69
|
+
}, Seat, Balance> {
|
|
70
|
+
/**
|
|
71
|
+
* Seat, then balance, read concurrently: a seat refusal or seat read failure
|
|
72
|
+
* wins over anything the balance read returned. A kept verdict returns
|
|
73
|
+
* without calling Platform. `balance` is absent only when the seat refused.
|
|
74
|
+
*/
|
|
75
|
+
admit(input: Input & AdmitBillableTurnOptions): Promise<BillableTurnAdmissionResult<Seat, Balance>>;
|
|
76
|
+
/** A refusal seen elsewhere: the next turn under this key (the user id unless `key` is set) reads Platform again. */
|
|
77
|
+
forget(key: string): Promise<void>;
|
|
78
|
+
/** How long a verdict read now is kept: the window, or less when `paidThrough` comes first. */
|
|
79
|
+
heldMs(paidThrough: string | null | undefined): number;
|
|
80
|
+
}
|
|
81
|
+
export declare function createBillableTurnAdmission<Input extends {
|
|
82
|
+
userId: string;
|
|
83
|
+
}, Seat extends BillableTurnSeatVerdict, Balance extends BillableTurnVerdict>(options: BillableTurnAdmissionOptions<Input, Seat, Balance>): BillableTurnAdmission<Input, Seat, Balance>;
|
package/dist/platform/index.d.ts
CHANGED
package/dist/platform/index.js
CHANGED
|
@@ -25,6 +25,9 @@ import {
|
|
|
25
25
|
import {
|
|
26
26
|
assertWorkspaceKeyCryptoUsable
|
|
27
27
|
} from "../chunk-VGS2NXLB.js";
|
|
28
|
+
import {
|
|
29
|
+
createWarmCache
|
|
30
|
+
} from "../chunk-F4TUZYMX.js";
|
|
28
31
|
import {
|
|
29
32
|
resolveTangleExecutionEnvironment
|
|
30
33
|
} from "../chunk-D6UJEOZQ.js";
|
|
@@ -1320,6 +1323,51 @@ function delegatedKeyFallbackFetch(input) {
|
|
|
1320
1323
|
return send();
|
|
1321
1324
|
};
|
|
1322
1325
|
}
|
|
1326
|
+
|
|
1327
|
+
// src/platform/billable-turn-admission.ts
|
|
1328
|
+
function createBillableTurnAdmission(options) {
|
|
1329
|
+
if (!(Number.isFinite(options.windowMs) && options.windowMs > 0)) {
|
|
1330
|
+
throw new Error("createBillableTurnAdmission: windowMs must be a positive number of milliseconds");
|
|
1331
|
+
}
|
|
1332
|
+
const verdicts = createWarmCache(options.namespace, { isolate: false, env: options.env });
|
|
1333
|
+
const keyOf = options.key ?? ((input) => input.userId);
|
|
1334
|
+
const heldMs = (paidThrough) => Math.min(options.windowMs, paidThrough ? Date.parse(paidThrough) - Date.now() : Infinity);
|
|
1335
|
+
return {
|
|
1336
|
+
heldMs,
|
|
1337
|
+
forget: (key) => verdicts.forget(key),
|
|
1338
|
+
async admit(input) {
|
|
1339
|
+
const key = keyOf(input);
|
|
1340
|
+
const warm = input.refresh ? null : await verdicts.read(key);
|
|
1341
|
+
if (warm && (warm.value.paidThrough === null || Date.parse(warm.value.paidThrough) > Date.now())) {
|
|
1342
|
+
return { source: warm.source };
|
|
1343
|
+
}
|
|
1344
|
+
const track = input.track ?? ((_name, work) => work);
|
|
1345
|
+
const mapError = input.mapError ?? ((error) => {
|
|
1346
|
+
throw error;
|
|
1347
|
+
});
|
|
1348
|
+
const [seatSettled, balanceSettled] = await Promise.allSettled([
|
|
1349
|
+
track("gate_seat", options.readSeat(input).catch(mapError)),
|
|
1350
|
+
track("gate_balance", options.readBalance(input).catch(mapError))
|
|
1351
|
+
]);
|
|
1352
|
+
if (seatSettled.status === "rejected") throw seatSettled.reason;
|
|
1353
|
+
const seat = seatSettled.value;
|
|
1354
|
+
if (!seat.allowed) {
|
|
1355
|
+
await verdicts.forget(key);
|
|
1356
|
+
return { source: "platform", seat };
|
|
1357
|
+
}
|
|
1358
|
+
if (balanceSettled.status === "rejected") throw balanceSettled.reason;
|
|
1359
|
+
const balance = balanceSettled.value;
|
|
1360
|
+
if (!balance.allowed) {
|
|
1361
|
+
await verdicts.forget(key);
|
|
1362
|
+
return { source: "platform", seat, balance };
|
|
1363
|
+
}
|
|
1364
|
+
const paidThrough = seat.paidThrough ?? null;
|
|
1365
|
+
const ttlMs = heldMs(paidThrough);
|
|
1366
|
+
if (ttlMs > 0) await verdicts.write(key, { paidThrough }, ttlMs);
|
|
1367
|
+
return { source: "platform", seat, balance };
|
|
1368
|
+
}
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1323
1371
|
export {
|
|
1324
1372
|
DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR,
|
|
1325
1373
|
DEFAULT_TANGLE_TIER_POLICY,
|
|
@@ -1341,6 +1389,7 @@ export {
|
|
|
1341
1389
|
createApiKeyRequestAuth,
|
|
1342
1390
|
createAuthGuard,
|
|
1343
1391
|
createBetterAuthSessionCookieMinter,
|
|
1392
|
+
createBillableTurnAdmission,
|
|
1344
1393
|
createD1TangleIdentityStore,
|
|
1345
1394
|
createDelegatedKeyProvisioner,
|
|
1346
1395
|
createDelegatedTurnKeys,
|