export type Money = { amount: string; currency: string }; export class AgentXError extends Error { constructor( public status: number, public problem: Record, public idempotencyKey?: string, ) { super(String(problem.detail ?? problem.code ?? "AgentX request failed")); } } export class AgentXClient { private token?: string; private expires = 0; constructor( private options: { origin: string; clientId: string; clientSecret?: string; assertion?: () => Promise; audience: "trade" | "finance-export" | "operations"; }, ) { const origin = new URL(options.origin); if ( origin.protocol !== "https:" && !( ["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname) && origin.protocol === "http:" ) ) throw new Error("Use HTTPS outside local development."); } private async authenticate() { if (this.token && Date.now() < this.expires) return; const proof = this.options.assertion ? { client_assertion: await this.options.assertion(), client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", } : { client_secret: this.options.clientSecret }; const response = await fetch(this.options.origin + "/auth/token", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ grant_type: "client_credentials", client_id: this.options.clientId, audience: this.options.audience, ...proof, }), signal: AbortSignal.timeout(15000), redirect: "error", }); const data = await response.json(); if (!response.ok) throw new AgentXError(response.status, data); this.token = data.access_token; this.expires = Date.now() + (data.expires_in - 30) * 1000; } async request( method: string, path: string, body?: unknown, idempotencyKey?: string, ): Promise { if (!path.startsWith("/v1/") || path.startsWith("//")) throw new Error("Use a relative versioned AgentX API path."); await this.authenticate(); const mutation = !["GET", "HEAD", "OPTIONS"].includes(method.toUpperCase()); if (mutation && !idempotencyKey) throw new Error( "Choose and persist an idempotency key before sending a command. Reuse it for retries.", ); const response = await fetch(new URL(path, this.options.origin), { method, headers: { authorization: "Bearer " + this.token, ...(body ? { "content-type": "application/json" } : {}), ...(idempotencyKey ? { "idempotency-key": idempotencyKey } : {}), }, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(15000), redirect: "error", }); const result = await response.json(); if (!response.ok) throw new AgentXError(response.status, result, idempotencyKey); return result as T; } me() { return this.request("GET", "/v1/agent/me"); } demandSources() { return this.request("GET", "/v1/demand-sources"); } createDemandSource(body: unknown, key: string) { return this.request("POST", "/v1/demand-sources", body, key); } importDemand(body: unknown, key: string) { return this.request("POST", "/v1/demand-requests", body, key); } demandStatus(id: string) { return this.request("GET", "/v1/demand-requests/" + encodeURIComponent(id)); } createCreativeDependency(rfqId: string, body: unknown, key: string) { return this.request( "POST", "/v1/rfqs/" + encodeURIComponent(rfqId) + "/creative-dependency", body, key, ); } creativeStatus(id: string) { return this.request( "GET", "/v1/creative-dependencies/" + encodeURIComponent(id), ); } acceptCreative(id: string, body: unknown, key: string) { return this.request( "POST", "/v1/creative-dependencies/" + encodeURIComponent(id) + "/acceptances", body, key, ); } offerAssessments(id: string) { return this.request( "GET", "/v1/offers/" + encodeURIComponent(id) + "/assessments", ); } moderationCases(after = "") { return this.request( "GET", "/v1/moderation/cases?after=" + encodeURIComponent(after), ); } moderationCase(caseId: string) { return this.request( "GET", "/v1/moderation/cases/" + encodeURIComponent(caseId), ); } appealModeration( caseId: string, body: { body: string; evidence_refs: string[] }, idempotencyKey: string, ) { return this.request( "POST", "/v1/moderation/cases/" + encodeURIComponent(caseId) + "/appeals", body, idempotencyKey, ); } /** Uses principal-authority proof instead of the revoked client credential. */ async recoverOwner(body: { case_id: string; action_id: string; replacement_client_id: string; reason: string; evidence_refs: string[]; ownership_proof: string; }) { const response = await fetch( this.options.origin + "/v1/security/recovery", { method: "POST", redirect: "error", signal: AbortSignal.timeout(15000), headers: { "content-type": "application/json" }, body: JSON.stringify(body), }, ); const result = await response.json(); if (!response.ok) throw new AgentXError(response.status, result); return result; } events(after = "0") { return this.request("GET", "/v1/events?after=" + encodeURIComponent(after)); } paymentProfile(profileId: string) { return this.request( "GET", "/v1/payment-profiles/" + encodeURIComponent(profileId), ); } payments(after = "") { return this.request( "GET", "/v1/payments?after=" + encodeURIComponent(after), ); } paymentSchedule(orderId: string) { return this.request( "GET", "/v1/orders/" + encodeURIComponent(orderId) + "/payments", ); } paymentCases(after = "") { return this.request( "GET", "/v1/payment-cases?after=" + encodeURIComponent(after), ); } openPaymentCase(body: unknown, idempotencyKey: string) { return this.request("POST", "/v1/payment-cases", body, idempotencyKey); } paymentCaseAction(caseId: string, body: unknown, idempotencyKey: string) { return this.request( "POST", "/v1/payment-cases/" + encodeURIComponent(caseId) + "/actions", body, idempotencyKey, ); } reviewInvoice(orderId: string, body: unknown, idempotencyKey: string) { return this.request( "POST", "/v1/orders/" + encodeURIComponent(orderId) + "/invoice-review", body, idempotencyKey, ); } }