@tangle-network/agent-app 0.60.119 → 0.60.120

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.
@@ -1,119 +0,0 @@
1
- // src/runtime/protected-model.ts
2
- import {
3
- createProtectedAgentCandidateModelPort
4
- } from "@tangle-network/agent-runtime/candidate-execution";
5
- var GATEWAY_ORIGIN = "https://candidate-router.tangle.tools";
6
- var CONTROL_ORIGIN = "https://router.tangle.tools/v1/candidate-model-grants";
7
- var ACTIVATION_NAMES = [
8
- "MODEL_GATEWAY_TOKEN",
9
- "MODEL_GATEWAY_BASE_URL",
10
- "OPENAI_API_KEY",
11
- "OPENAI_BASE_URL",
12
- "ANTHROPIC_API_KEY",
13
- "ANTHROPIC_AUTH_TOKEN",
14
- "ANTHROPIC_BASE_URL"
15
- ];
16
- var ProtectedModelSettlementError = class extends Error {
17
- constructor(settlement, cause) {
18
- super("Protected model settled, but its audit record could not be saved", { cause });
19
- this.settlement = settlement;
20
- this.name = "ProtectedModelSettlementError";
21
- }
22
- settlement;
23
- };
24
- function createRouterProtectedModelPort(options) {
25
- if (!options.apiKey || !Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0 || !Number.isSafeInteger(Math.round(options.maxCostUsd * 1e9))) {
26
- throw new Error("Protected Router transport requires a parent key and finite positive cap");
27
- }
28
- const receipts = /* @__PURE__ */ new Map();
29
- async function request(operation, body, settling = false) {
30
- const timeout = AbortSignal.timeout(settling ? 3e4 : 15e3);
31
- const signal = !settling && options.signal ? AbortSignal.any([timeout, options.signal]) : timeout;
32
- let response;
33
- try {
34
- response = await fetch(`${CONTROL_ORIGIN}/${operation}`, {
35
- // Workerd supports manual redirects; non-2xx responses below still fail closed.
36
- method: "POST",
37
- redirect: "manual",
38
- signal,
39
- headers: {
40
- Authorization: `Bearer ${options.apiKey}`,
41
- "Content-Type": "application/json",
42
- "X-Tangle-Client": options.clientName ?? "agent-app"
43
- },
44
- body: JSON.stringify(body)
45
- });
46
- } catch {
47
- if (!settling && options.signal?.aborted) throw options.signal.reason;
48
- throw new Error(`Protected model ${operation} transport failed`);
49
- }
50
- if (!response.ok) {
51
- const body2 = await response.json().catch(() => null);
52
- const code = body2?.error?.code;
53
- const safeCode = typeof code === "string" && /^candidate_[a-z_]{1,80}$/.test(code) ? code : "request_failed";
54
- throw new Error(`Protected model ${operation}: ${safeCode} (HTTP ${response.status})`);
55
- }
56
- return await response.json();
57
- }
58
- const client = {
59
- reserve: (value) => request("reserve", value),
60
- activate: async (value) => {
61
- const activation = await request("activate", value);
62
- const env = activation?.env;
63
- const token = env?.MODEL_GATEWAY_TOKEN;
64
- if (typeof token !== "string" || !/^sk-tgr-[A-Za-z0-9_-]{32,}$/.test(token) || env.MODEL_GATEWAY_BASE_URL !== `${GATEWAY_ORIGIN}/v1` || env.OPENAI_BASE_URL !== `${GATEWAY_ORIGIN}/v1` || env.ANTHROPIC_BASE_URL !== GATEWAY_ORIGIN || [env.OPENAI_API_KEY, env.ANTHROPIC_API_KEY, env.ANTHROPIC_AUTH_TOKEN].some((value2) => value2 !== token)) {
65
- throw new Error("Protected model activation changed the gateway or credential binding");
66
- }
67
- return activation;
68
- },
69
- settle: async (value) => {
70
- const settlement = await request("settle", value, true);
71
- assertWithinCap(settlement, options.maxCostUsd);
72
- receipts.set(value.preparationId, settlement);
73
- return settlement;
74
- }
75
- };
76
- const port = createProtectedAgentCandidateModelPort({
77
- client,
78
- resolveModel: (value) => request("resolve", value),
79
- gatewayDomain: "candidate-router.tangle.tools",
80
- activationEnvNames: ACTIVATION_NAMES
81
- });
82
- return {
83
- ...port,
84
- settleGrant: async (value) => {
85
- const settlement = await port.settleGrant(value);
86
- const receipt = receipts.get(value.preparationId);
87
- if (receipt) {
88
- try {
89
- await options.onSettlement?.(structuredClone(receipt));
90
- } catch (error) {
91
- throw new ProtectedModelSettlementError(settlement, error);
92
- } finally {
93
- receipts.delete(value.preparationId);
94
- }
95
- }
96
- return settlement;
97
- }
98
- };
99
- }
100
- function assertWithinCap(settlement, capUsd) {
101
- if (!Array.isArray(settlement?.calls)) throw new Error("Protected model settlement has no call ledger");
102
- const capNanos = Math.round(capUsd * 1e9);
103
- let cost = 0;
104
- for (const call of settlement.calls) {
105
- if (!Number.isSafeInteger(call?.costUsdNanos) || call.costUsdNanos < 0) {
106
- throw new Error("Protected model call cost is invalid");
107
- }
108
- cost += call.costUsdNanos;
109
- if (!Number.isSafeInteger(cost) || cost > capNanos) {
110
- throw new Error("Protected model settlement exceeds its cost cap");
111
- }
112
- }
113
- }
114
-
115
- export {
116
- ProtectedModelSettlementError,
117
- createRouterProtectedModelPort
118
- };
119
- //# sourceMappingURL=chunk-RN2N75EI.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/runtime/protected-model.ts"],"sourcesContent":["import {\n createProtectedAgentCandidateModelPort,\n type AgentCandidateModelGrantClient,\n type AgentCandidateModelPort,\n} from '@tangle-network/agent-runtime/candidate-execution'\n\nconst GATEWAY_ORIGIN = 'https://candidate-router.tangle.tools'\nconst CONTROL_ORIGIN = 'https://router.tangle.tools/v1/candidate-model-grants'\nconst ACTIVATION_NAMES = [\n 'MODEL_GATEWAY_TOKEN', 'MODEL_GATEWAY_BASE_URL', 'OPENAI_API_KEY', 'OPENAI_BASE_URL',\n 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL',\n] as const\n\nexport interface RouterProtectedModelPortOptions {\n apiKey: string\n maxCostUsd: number\n clientName?: string\n signal?: AbortSignal\n onSettlement?(receipt: RouterProtectedModelSettlement): Promise<void> | void\n}\n\n/** A validated charge remains authoritative when the product cannot save its audit record. */\nexport class ProtectedModelSettlementError extends Error {\n constructor(readonly settlement: Awaited<ReturnType<AgentCandidateModelPort['settleGrant']>>, cause: unknown) {\n super('Protected model settled, but its audit record could not be saved', { cause })\n this.name = 'ProtectedModelSettlementError'\n }\n}\n\n/** Bind one turn to Router's atomic grant ledger without exposing its parent key. */\nexport function createRouterProtectedModelPort(options: RouterProtectedModelPortOptions): AgentCandidateModelPort {\n if (!options.apiKey || !Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0\n || !Number.isSafeInteger(Math.round(options.maxCostUsd * 1_000_000_000))) {\n throw new Error('Protected Router transport requires a parent key and finite positive cap')\n }\n const receipts = new Map<string, RouterProtectedModelSettlement>()\n async function request<T>(operation: string, body: unknown, settling = false): Promise<T> {\n const timeout = AbortSignal.timeout(settling ? 30_000 : 15_000)\n const signal = !settling && options.signal ? AbortSignal.any([timeout, options.signal]) : timeout\n let response: Response\n try {\n response = await fetch(`${CONTROL_ORIGIN}/${operation}`, {\n // Workerd supports manual redirects; non-2xx responses below still fail closed.\n method: 'POST', redirect: 'manual', signal,\n headers: {\n Authorization: `Bearer ${options.apiKey}`,\n 'Content-Type': 'application/json', 'X-Tangle-Client': options.clientName ?? 'agent-app',\n },\n body: JSON.stringify(body),\n })\n } catch {\n if (!settling && options.signal?.aborted) throw options.signal.reason\n throw new Error(`Protected model ${operation} transport failed`)\n }\n if (!response.ok) {\n const body = await response.json().catch(() => null) as { error?: { code?: unknown } } | null\n const code = body?.error?.code\n // Preserve Runtime's draining retry contract without echoing server text or credentials.\n const safeCode = typeof code === 'string' && /^candidate_[a-z_]{1,80}$/.test(code) ? code : 'request_failed'\n throw new Error(`Protected model ${operation}: ${safeCode} (HTTP ${response.status})`)\n }\n return await response.json() as T\n }\n\n const client: AgentCandidateModelGrantClient = {\n reserve: (value) => request('reserve', value),\n activate: async (value) => {\n const activation = await request<Awaited<ReturnType<AgentCandidateModelGrantClient['activate']>>>('activate', value)\n const env = activation?.env\n const token = env?.MODEL_GATEWAY_TOKEN\n if (typeof token !== 'string' || !/^sk-tgr-[A-Za-z0-9_-]{32,}$/.test(token)\n || env.MODEL_GATEWAY_BASE_URL !== `${GATEWAY_ORIGIN}/v1`\n || env.OPENAI_BASE_URL !== `${GATEWAY_ORIGIN}/v1`\n || env.ANTHROPIC_BASE_URL !== GATEWAY_ORIGIN\n || [env.OPENAI_API_KEY, env.ANTHROPIC_API_KEY, env.ANTHROPIC_AUTH_TOKEN].some((value) => value !== token)) {\n throw new Error('Protected model activation changed the gateway or credential binding')\n }\n return activation\n },\n settle: async (value) => {\n const settlement = await request<RouterProtectedModelSettlement>('settle', value, true)\n assertWithinCap(settlement, options.maxCostUsd)\n receipts.set(value.preparationId, settlement)\n return settlement\n },\n }\n const port = createProtectedAgentCandidateModelPort({\n client, resolveModel: (value) => request('resolve', value),\n gatewayDomain: 'candidate-router.tangle.tools', activationEnvNames: ACTIVATION_NAMES,\n })\n return {\n ...port,\n settleGrant: async (value) => {\n const settlement = await port.settleGrant(value)\n const receipt = receipts.get(value.preparationId)\n if (receipt) {\n try {\n await options.onSettlement?.(structuredClone(receipt))\n } catch (error) {\n throw new ProtectedModelSettlementError(settlement, error)\n } finally {\n receipts.delete(value.preparationId)\n }\n }\n return settlement\n },\n }\n}\n\n/**\n * Router's settle response is Runtime's exact settlement ledger. Router keeps\n * the billing hold and charge behind it and refuses a settlement outside the\n * grant's frozen limits; Runtime rejects unknown or missing ledger fields.\n */\nexport type RouterProtectedModelSettlement = Awaited<ReturnType<AgentCandidateModelGrantClient['settle']>>\n\n/** Bound the ledger's cumulative cost by this turn's cap before anything retains it. */\nfunction assertWithinCap(settlement: RouterProtectedModelSettlement, capUsd: number): void {\n if (!Array.isArray(settlement?.calls)) throw new Error('Protected model settlement has no call ledger')\n const capNanos = Math.round(capUsd * 1_000_000_000)\n let cost = 0\n for (const call of settlement.calls) {\n if (!Number.isSafeInteger(call?.costUsdNanos) || call.costUsdNanos < 0) {\n throw new Error('Protected model call cost is invalid')\n }\n cost += call.costUsdNanos\n if (!Number.isSafeInteger(cost) || cost > capNanos) {\n throw new Error('Protected model settlement exceeds its cost cap')\n }\n }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAGK;AAEP,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AAAA,EAC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