@tangle-network/agent-app 0.57.13 → 0.57.14
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.
|
@@ -67,10 +67,10 @@ function createRouterProtectedModelPort(options) {
|
|
|
67
67
|
return activation;
|
|
68
68
|
},
|
|
69
69
|
settle: async (value) => {
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
receipts.set(value.preparationId,
|
|
73
|
-
return
|
|
70
|
+
const settlement = await request("settle", value, true);
|
|
71
|
+
assertWithinCap(settlement, options.maxCostUsd);
|
|
72
|
+
receipts.set(value.preparationId, settlement);
|
|
73
|
+
return settlement;
|
|
74
74
|
}
|
|
75
75
|
};
|
|
76
76
|
const port = createProtectedAgentCandidateModelPort({
|
|
@@ -97,40 +97,23 @@ function createRouterProtectedModelPort(options) {
|
|
|
97
97
|
}
|
|
98
98
|
};
|
|
99
99
|
}
|
|
100
|
-
function
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
throw new Error("Protected model billing receipt is incomplete or exceeds its reservation");
|
|
104
|
-
}
|
|
105
|
-
const billingFields = /* @__PURE__ */ new Set(["status", "authorizationId", "transactionId", "reservedCostUsdNanos", "settledCostUsdNanos"]);
|
|
106
|
-
if (Object.keys(billing).some((key) => !billingFields.has(key))) {
|
|
107
|
-
throw new Error("Protected model billing receipt contains an unknown field");
|
|
108
|
-
}
|
|
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);
|
|
109
103
|
let cost = 0;
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
if (!Number.isSafeInteger(count) || count < 0 || count > call.accountedInputTokens) {
|
|
113
|
-
throw new Error("Protected model cache-write receipt is invalid");
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
if (cacheWrite5mTokens + cacheWrite1hTokens > cacheWriteTokens) {
|
|
117
|
-
throw new Error("Protected model cache-write receipt does not reconcile");
|
|
118
|
-
}
|
|
119
|
-
if (!Number.isSafeInteger(call.costUsdNanos) || call.costUsdNanos < 0) {
|
|
104
|
+
for (const call of settlement.calls) {
|
|
105
|
+
if (!Number.isSafeInteger(call?.costUsdNanos) || call.costUsdNanos < 0) {
|
|
120
106
|
throw new Error("Protected model call cost is invalid");
|
|
121
107
|
}
|
|
122
108
|
cost += call.costUsdNanos;
|
|
123
|
-
if (!Number.isSafeInteger(cost)
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
}
|
|
127
|
-
if (cost !== billing.settledCostUsdNanos) throw new Error("Protected model billing does not match its call ledger");
|
|
128
|
-
const { billing: _billing, ...settlement } = wire;
|
|
129
|
-
return { ...settlement, calls };
|
|
109
|
+
if (!Number.isSafeInteger(cost) || cost > capNanos) {
|
|
110
|
+
throw new Error("Protected model settlement exceeds its cost cap");
|
|
111
|
+
}
|
|
112
|
+
}
|
|
130
113
|
}
|
|
131
114
|
|
|
132
115
|
export {
|
|
133
116
|
ProtectedModelSettlementError,
|
|
134
117
|
createRouterProtectedModelPort
|
|
135
118
|
};
|
|
136
|
-
//# sourceMappingURL=chunk-
|
|
119
|
+
//# sourceMappingURL=chunk-RN2N75EI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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,EACvB;AAAA,EAAuB;AAAA,EAA0B;AAAA,EAAkB;AAAA,EACnE;AAAA,EAAqB;AAAA,EAAwB;AAC/C;AAWO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EACvD,YAAqB,YAAyE,OAAgB;AAC5G,UAAM,oEAAoE,EAAE,MAAM,CAAC;AADhE;AAEnB,SAAK,OAAO;AAAA,EACd;AAAA,EAHqB;AAIvB;AAGO,SAAS,+BAA+B,SAAmE;AAChH,MAAI,CAAC,QAAQ,UAAU,CAAC,OAAO,SAAS,QAAQ,UAAU,KAAK,QAAQ,cAAc,KAChF,CAAC,OAAO,cAAc,KAAK,MAAM,QAAQ,aAAa,GAAa,CAAC,GAAG;AAC1E,UAAM,IAAI,MAAM,0EAA0E;AAAA,EAC5F;AACA,QAAM,WAAW,oBAAI,IAA4C;AACjE,iBAAe,QAAW,WAAmB,MAAe,WAAW,OAAmB;AACxF,UAAM,UAAU,YAAY,QAAQ,WAAW,MAAS,IAAM;AAC9D,UAAM,SAAS,CAAC,YAAY,QAAQ,SAAS,YAAY,IAAI,CAAC,SAAS,QAAQ,MAAM,CAAC,IAAI;AAC1F,QAAI;AACJ,QAAI;AACF,iBAAW,MAAM,MAAM,GAAG,cAAc,IAAI,SAAS,IAAI;AAAA;AAAA,QAEvD,QAAQ;AAAA,QAAQ,UAAU;AAAA,QAAU;AAAA,QACpC,SAAS;AAAA,UACP,eAAe,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AS,IAAI,MAAM,eAAe,UAAU;AAC5C,aAAO;AAAA,IACT;AAAA,EACF;AACA,QAAM,OAAO,uCAAuC;AAAA,IAClD;AAAA,IAAQ,cAAc,CAAC,UAAU,QAAQ,WAAW,KAAK;AAAA,IACzD,eAAe;AAAA,IAAiC,oBAAoB;AAAA,EACtE,CAAC;AACD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,aAAa,OAAO,UAAU;AAC5B,YAAM,aAAa,MAAM,KAAK,YAAY,KAAK;AAC/C,YAAM,UAAU,SAAS,IAAI,MAAM,aAAa;AAChD,UAAI,SAAS;AACX,YAAI;AACF,gBAAM,QAAQ,eAAe,gBAAgB,OAAO,CAAC;AAAA,QACvD,SAAS,OAAO;AACd,gBAAM,IAAI,8BAA8B,YAAY,KAAK;AAAA,QAC3D,UAAE;AACA,mBAAS,OAAO,MAAM,aAAa;AAAA,QACrC;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAUA,SAAS,gBAAgB,YAA4C,QAAsB;AACzF,MAAI,CAAC,MAAM,QAAQ,YAAY,KAAK,EAAG,OAAM,IAAI,MAAM,+CAA+C;AACtG,QAAM,WAAW,KAAK,MAAM,SAAS,GAAa;AAClD,MAAI,OAAO;AACX,aAAW,QAAQ,WAAW,OAAO;AACnC,QAAI,CAAC,OAAO,cAAc,MAAM,YAAY,KAAK,KAAK,eAAe,GAAG;AACtE,YAAM,IAAI,MAAM,sCAAsC;AAAA,IACxD;AACA,YAAQ,KAAK;AACb,QAAI,CAAC,OAAO,cAAc,IAAI,KAAK,OAAO,UAAU;AAClD,YAAM,IAAI,MAAM,iDAAiD;AAAA,IACnE;AAAA,EACF;AACF;","names":["body","value"]}
|
package/dist/runtime/index.js
CHANGED
|
@@ -13,17 +13,9 @@ export declare class ProtectedModelSettlementError extends Error {
|
|
|
13
13
|
}
|
|
14
14
|
/** Bind one turn to Router's atomic grant ledger without exposing its parent key. */
|
|
15
15
|
export declare function createRouterProtectedModelPort(options: RouterProtectedModelPortOptions): AgentCandidateModelPort;
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
settledCostUsdNanos: number;
|
|
23
|
-
};
|
|
24
|
-
calls: Array<Omit<Awaited<ReturnType<AgentCandidateModelGrantClient['settle']>>['calls'][number], 'costProvenance'> & {
|
|
25
|
-
cacheWriteTokens: number;
|
|
26
|
-
cacheWrite5mTokens: number;
|
|
27
|
-
cacheWrite1hTokens: number;
|
|
28
|
-
}>;
|
|
29
|
-
}
|
|
16
|
+
/**
|
|
17
|
+
* Router's settle response is Runtime's exact settlement ledger. Router keeps
|
|
18
|
+
* the billing hold and charge behind it and refuses a settlement outside the
|
|
19
|
+
* grant's frozen limits; Runtime rejects unknown or missing ledger fields.
|
|
20
|
+
*/
|
|
21
|
+
export type RouterProtectedModelSettlement = Awaited<ReturnType<AgentCandidateModelGrantClient['settle']>>;
|
package/package.json
CHANGED
|
@@ -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 wire = await request<RouterProtectedModelSettlement>('settle', value, true)\n const projected = runtimeSettlement(wire, options.maxCostUsd)\n receipts.set(value.preparationId, wire)\n return projected\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\nexport interface RouterProtectedModelSettlement extends Omit<Awaited<ReturnType<AgentCandidateModelGrantClient['settle']>>, 'calls'> {\n billing: {\n status: string\n authorizationId?: string\n transactionId?: string\n reservedCostUsdNanos: number\n settledCostUsdNanos: number\n }\n calls: Array<Omit<Awaited<ReturnType<AgentCandidateModelGrantClient['settle']>>['calls'][number], 'costProvenance'> & {\n cacheWriteTokens: number\n cacheWrite5mTokens: number\n cacheWrite1hTokens: number\n }>\n}\n\n/** Check Router's billing extension before projecting its portable Runtime ledger. */\nfunction runtimeSettlement(wire: RouterProtectedModelSettlement, capUsd: number): Awaited<ReturnType<AgentCandidateModelGrantClient['settle']>> {\n const billing = wire?.billing\n if (!Array.isArray(wire?.calls) || !billing || billing.status !== 'settled'\n || typeof billing.authorizationId !== 'string' || billing.authorizationId.length === 0\n || billing.reservedCostUsdNanos !== Math.round(capUsd * 1_000_000_000)\n || !Number.isSafeInteger(billing.settledCostUsdNanos) || billing.settledCostUsdNanos < 0\n || billing.settledCostUsdNanos > billing.reservedCostUsdNanos\n || (billing.settledCostUsdNanos > 0 && (typeof billing.transactionId !== 'string' || billing.transactionId.length === 0))) {\n throw new Error('Protected model billing receipt is incomplete or exceeds its reservation')\n }\n const billingFields = new Set(['status', 'authorizationId', 'transactionId', 'reservedCostUsdNanos', 'settledCostUsdNanos'])\n if (Object.keys(billing).some((key) => !billingFields.has(key))) {\n throw new Error('Protected model billing receipt contains an unknown field')\n }\n let cost = 0\n const calls = wire.calls.map(({ cacheWriteTokens, cacheWrite5mTokens, cacheWrite1hTokens, ...call }) => {\n for (const count of [cacheWriteTokens, cacheWrite5mTokens, cacheWrite1hTokens]) {\n if (!Number.isSafeInteger(count) || count < 0 || count > call.accountedInputTokens) {\n throw new Error('Protected model cache-write receipt is invalid')\n }\n }\n if (cacheWrite5mTokens + cacheWrite1hTokens > cacheWriteTokens) {\n throw new Error('Protected model cache-write receipt does not reconcile')\n }\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)) throw new Error('Protected model cumulative cost is invalid')\n if ('costProvenance' in call) throw new Error('Router call receipt contains an unknown field')\n return { ...call, costProvenance: 'observed' as const }\n })\n if (cost !== billing.settledCostUsdNanos) throw new Error('Protected model billing does not match its call ledger')\n const { billing: _billing, ...settlement } = wire\n return { ...settlement, calls }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAGK;AAEP,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AAAA,EACvB;AAAA,EAAuB;AAAA,EAA0B;AAAA,EAAkB;AAAA,EACnE;AAAA,EAAqB;AAAA,EAAwB;AAC/C;AAWO,I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