@auctra/sdk 0.6.0 → 0.6.2

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/src/client.ts ADDED
@@ -0,0 +1,555 @@
1
+ /** @auctra/sdk — Authority Protocol client (Stage 1.0 modular layout). */
2
+ import { AuctraApiError, retryDelay, wait } from "./artifacts.js";
3
+ import type {
4
+ ActionEvaluation,
5
+ ActionRequest,
6
+ ActorType,
7
+ Agent,
8
+ ApiKeySummary,
9
+ ArtifactVerification,
10
+ AuditChainVerification,
11
+ AuditEvent,
12
+ AuthorityGraph,
13
+ AuthoritySummary,
14
+ AuctraClientOptions,
15
+ CreateAgentInput,
16
+ CreateAuthorityEdgeInput,
17
+ CreateCustomActionTypeInput,
18
+ CreateIntentInput,
19
+ CreatePolicyInput,
20
+ CustomActionType,
21
+ DecisionEvidence,
22
+ DecisionEvidencePayload,
23
+ DelegateAuthorityInput,
24
+ Delegation,
25
+ EvaluateActionInput,
26
+ EvaluateActionResponse,
27
+ Intent,
28
+ IntentDetail,
29
+ IntentStatus,
30
+ IssueAuthorityInput,
31
+ MandateEvidence,
32
+ MandatePayload,
33
+ Policy,
34
+ PolicySimulation,
35
+ RequestOptions,
36
+ RiskLevel,
37
+ RootIntentChain,
38
+ UpdateAgentStatusInput,
39
+ UpdateIntentInput,
40
+ } from "./types.js";
41
+ import { AUCTRA_SDK_VERSION, DEFAULT_BASE_URL } from "./types.js";
42
+
43
+ export class Auctra {
44
+ private readonly apiKey: string;
45
+ private readonly baseUrl: string;
46
+ private readonly timeoutMs: number;
47
+ private readonly maxRetries: number;
48
+ private readonly fetchImpl: typeof fetch;
49
+
50
+ constructor(options: AuctraClientOptions) {
51
+ if (!options.apiKey.trim()) throw new Error("apiKey is required");
52
+ if (options.timeoutMs !== undefined && options.timeoutMs <= 0) {
53
+ throw new Error("timeoutMs must be greater than zero");
54
+ }
55
+ if (
56
+ options.maxRetries !== undefined &&
57
+ (!Number.isInteger(options.maxRetries) || options.maxRetries < 0)
58
+ ) {
59
+ throw new Error("maxRetries must be a non-negative integer");
60
+ }
61
+ this.apiKey = options.apiKey;
62
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
63
+ this.timeoutMs = options.timeoutMs ?? 10_000;
64
+ this.maxRetries = options.maxRetries ?? 2;
65
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
66
+ if (!this.fetchImpl) throw new Error("A fetch implementation is required");
67
+ }
68
+
69
+ private async request<T>(
70
+ method: string,
71
+ path: string,
72
+ body?: unknown,
73
+ options: RequestOptions = {},
74
+ ): Promise<T> {
75
+ const retryableRequest = method === "GET" || Boolean(options.idempotencyKey);
76
+ let lastError: unknown;
77
+
78
+ for (let attempt = 0; attempt <= this.maxRetries; attempt += 1) {
79
+ if (options.signal?.aborted) throw options.signal.reason;
80
+ const timeoutSignal = AbortSignal.timeout(this.timeoutMs);
81
+ const signal = options.signal
82
+ ? AbortSignal.any([options.signal, timeoutSignal])
83
+ : timeoutSignal;
84
+ let response: Response | undefined;
85
+
86
+ try {
87
+ response = await this.fetchImpl(`${this.baseUrl}${path}`, {
88
+ method,
89
+ signal,
90
+ headers: {
91
+ ...(body !== undefined ? { "content-type": "application/json" } : {}),
92
+ ...(options.idempotencyKey ? { "idempotency-key": options.idempotencyKey } : {}),
93
+ authorization: `Bearer ${this.apiKey}`,
94
+ "x-auctra-sdk-version": AUCTRA_SDK_VERSION,
95
+ },
96
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
97
+ });
98
+
99
+ const data = (await response.json().catch(() => ({}))) as Record<string, unknown>;
100
+ if (response.ok) return data as T;
101
+
102
+ if (
103
+ retryableRequest &&
104
+ (response.status === 429 || response.status >= 500) &&
105
+ attempt < this.maxRetries
106
+ ) {
107
+ await wait(retryDelay(response, attempt), options.signal);
108
+ continue;
109
+ }
110
+
111
+ throw new AuctraApiError(
112
+ typeof data.error === "string" ? data.error : `Auctra API error (${response.status})`,
113
+ {
114
+ status: response.status,
115
+ code: typeof data.code === "string" ? data.code : undefined,
116
+ details: data.details,
117
+ requestId: response.headers.get("x-request-id") ?? undefined,
118
+ },
119
+ );
120
+ } catch (error) {
121
+ lastError = error;
122
+ if (options.signal?.aborted) throw options.signal.reason;
123
+ if (error instanceof AuctraApiError || !retryableRequest || attempt >= this.maxRetries) {
124
+ throw error;
125
+ }
126
+ await wait(retryDelay(response, attempt), options.signal);
127
+ }
128
+ }
129
+
130
+ throw lastError;
131
+ }
132
+
133
+ private async executeOrEvaluateAction(
134
+ input: EvaluateActionInput,
135
+ options: RequestOptions,
136
+ mode: "execute" | "evaluate",
137
+ ): Promise<EvaluateActionResponse> {
138
+ const idempotencyKey =
139
+ mode === "execute" ? (options.idempotencyKey ?? crypto.randomUUID()) : options.idempotencyKey;
140
+ const path = mode === "execute" ? "/v1/actions/execute" : "/v1/actions/evaluate";
141
+ return this.request(
142
+ "POST",
143
+ path,
144
+ {
145
+ agent_id: input.agentId,
146
+ action_type: input.actionType,
147
+ payload: input.payload ?? {},
148
+ claimed_intent_id: input.claimedIntentId,
149
+ intent_anchor_token: input.intentAnchorToken,
150
+ parent_action_id: input.parentActionId,
151
+ dry_run: mode === "evaluate",
152
+ actor: input.actor
153
+ ? {
154
+ id: input.actor.id,
155
+ type: input.actor.type,
156
+ name: input.actor.name,
157
+ }
158
+ : undefined,
159
+ action: input.action
160
+ ? {
161
+ target: input.action.target,
162
+ description: input.action.description,
163
+ risk_level: input.action.riskLevel,
164
+ metadata: input.action.metadata,
165
+ }
166
+ : undefined,
167
+ },
168
+ mode === "execute" ? { ...options, idempotencyKey } : options,
169
+ );
170
+ }
171
+
172
+ private async issueAuthorityRequest(
173
+ input: IssueAuthorityInput & { parentAuthorityId?: string },
174
+ ): Promise<{
175
+ authority: AuthoritySummary;
176
+ authority_id: string;
177
+ delegation: Delegation;
178
+ }> {
179
+ const response = await this.request<{
180
+ delegation: Delegation;
181
+ authority_id?: string;
182
+ authority?: AuthoritySummary;
183
+ }>("POST", "/v1/authorities", {
184
+ agent_id: input.subject,
185
+ action_types: input.capabilities,
186
+ valid_until: input.expiresAt,
187
+ max_amount: input.constraints?.maxAmount,
188
+ max_count: input.constraints?.maxCount,
189
+ environment: input.constraints?.environment,
190
+ currency: input.constraints?.currency,
191
+ delegator_user_id: input.delegatorUserId ?? input.issuer,
192
+ parent_authority_id: input.parentAuthorityId,
193
+ max_delegation_depth: input.delegation?.maxDepth,
194
+ max_actions_per_window: input.maxActionsPerWindow
195
+ ? {
196
+ count: input.maxActionsPerWindow.count,
197
+ window_seconds: input.maxActionsPerWindow.windowSeconds,
198
+ action_type: input.maxActionsPerWindow.actionType,
199
+ }
200
+ : undefined,
201
+ max_amount_per_window: input.maxAmountPerWindow
202
+ ? {
203
+ amount: input.maxAmountPerWindow.amount,
204
+ window_seconds: input.maxAmountPerWindow.windowSeconds,
205
+ }
206
+ : undefined,
207
+ });
208
+
209
+ const authorityId = response.authority_id ?? response.delegation.id;
210
+ const authority: AuthoritySummary = response.authority ?? {
211
+ id: authorityId,
212
+ protocol_version: "0.1",
213
+ status: response.delegation.status,
214
+ payload_hash: "",
215
+ signed: false,
216
+ parent_authority_id: input.parentAuthorityId ?? null,
217
+ capabilities: input.capabilities,
218
+ };
219
+
220
+ return {
221
+ authority,
222
+ authority_id: authorityId,
223
+ delegation: response.delegation,
224
+ };
225
+ }
226
+
227
+ /**
228
+ * Authority Protocol — issue, verify, delegate (subset), revoke.
229
+ * There is no legacy createDelegation() surface.
230
+ */
231
+ get authority() {
232
+ return {
233
+ issue: (input: IssueAuthorityInput) => this.issueAuthorityRequest(input),
234
+ verify: (
235
+ payload: Record<string, unknown>,
236
+ artifact: Record<string, unknown>,
237
+ ): Promise<{
238
+ valid: boolean;
239
+ hashValid: boolean;
240
+ signatureValid: boolean;
241
+ expired: boolean;
242
+ status: string;
243
+ issuer: string;
244
+ subject: string;
245
+ capabilities: string[];
246
+ constraints: Record<string, unknown>;
247
+ expiresAt: string;
248
+ protocolVersion: string;
249
+ }> => this.request("POST", "/v1/authorities/verify", { payload, artifact }),
250
+ delegate: (input: DelegateAuthorityInput) =>
251
+ this.issueAuthorityRequest({
252
+ ...input,
253
+ parentAuthorityId: input.parent,
254
+ }),
255
+ revoke: (authorityId: string): Promise<{ ok: true }> =>
256
+ this.request("POST", `/v1/authorities/${encodeURIComponent(authorityId)}/revoke`, {}),
257
+ };
258
+ }
259
+
260
+ /**
261
+ * Action Protocol — evaluate (dry-run) vs execute (enforce + evidence).
262
+ * There is no legacy evaluateAction() surface.
263
+ */
264
+ get action() {
265
+ return {
266
+ evaluate: (input: EvaluateActionInput, options: RequestOptions = {}) =>
267
+ this.executeOrEvaluateAction(input, options, "evaluate"),
268
+ execute: (input: EvaluateActionInput, options: RequestOptions = {}) =>
269
+ this.executeOrEvaluateAction(input, options, "execute"),
270
+ };
271
+ }
272
+
273
+ get evidence() {
274
+ return {
275
+ verify: (
276
+ payload: DecisionEvidencePayload,
277
+ evidence: DecisionEvidence,
278
+ ): Promise<ArtifactVerification> =>
279
+ this.request("POST", "/v1/evidence/verify", { payload, evidence }),
280
+ };
281
+ }
282
+
283
+ async verifyMandate(
284
+ payload: MandatePayload,
285
+ evidence: MandateEvidence,
286
+ ): Promise<ArtifactVerification> {
287
+ return this.request("POST", "/v1/mandates/verify", { payload, evidence });
288
+ }
289
+
290
+ async listIntents(): Promise<{ intents: Intent[] }> {
291
+ return this.request("GET", "/v1/intents");
292
+ }
293
+
294
+ async createIntent(
295
+ input: CreateIntentInput,
296
+ ): Promise<{ intent: { id: string; title: string; status: string } }> {
297
+ return this.request("POST", "/v1/intents", {
298
+ title: input.title,
299
+ description: input.description,
300
+ intent_type: input.intentType,
301
+ risk_level: input.riskLevel,
302
+ max_risk_level: input.maxRiskLevel,
303
+ expires_at: input.expiresAt,
304
+ allowed_action_types: input.allowedActionTypes,
305
+ target_pattern: input.targetPattern,
306
+ resource_allowlist: input.resourceAllowlist,
307
+ });
308
+ }
309
+
310
+ async getIntent(intentId: string): Promise<{ intent: IntentDetail }> {
311
+ return this.request("GET", `/v1/intents/${encodeURIComponent(intentId)}`);
312
+ }
313
+
314
+ async updateIntentStatus(
315
+ intentId: string,
316
+ status: Exclude<IntentStatus, "expired">,
317
+ ): Promise<{ intent: { id: string; title: string; status: IntentStatus } }> {
318
+ return this.updateIntent(intentId, { status });
319
+ }
320
+
321
+ async updateIntent(
322
+ intentId: string,
323
+ input: UpdateIntentInput,
324
+ ): Promise<{
325
+ intent: {
326
+ id: string;
327
+ title: string;
328
+ status: IntentStatus;
329
+ description?: string | null;
330
+ intent_type?: string | null;
331
+ risk_level?: RiskLevel;
332
+ max_risk_level?: RiskLevel;
333
+ expires_at?: string | null;
334
+ };
335
+ }> {
336
+ return this.request("PATCH", `/v1/intents/${encodeURIComponent(intentId)}`, {
337
+ status: input.status,
338
+ title: input.title,
339
+ description: input.description,
340
+ intent_type: input.intentType,
341
+ risk_level: input.riskLevel,
342
+ max_risk_level: input.maxRiskLevel,
343
+ expires_at: input.expiresAt,
344
+ });
345
+ }
346
+
347
+ async getAuthorityGraph(): Promise<{ authority_graph: AuthorityGraph }> {
348
+ return this.request("GET", "/v1/authority/graph");
349
+ }
350
+
351
+ async createAuthorityEdge(input: CreateAuthorityEdgeInput): Promise<{ edge: { id: string } }> {
352
+ return this.request("POST", "/v1/authority/edges", {
353
+ from_actor_id: input.fromActorId,
354
+ from_actor_type: input.fromActorType,
355
+ to_actor_id: input.toActorId,
356
+ to_actor_type: input.toActorType,
357
+ authority_scope: input.authorityScope,
358
+ conditions: input.conditions,
359
+ max_risk_level: input.maxRiskLevel,
360
+ expires_at: input.expiresAt,
361
+ });
362
+ }
363
+
364
+ async getActionEvaluation(actionRequestId: string): Promise<{ evaluation: ActionEvaluation }> {
365
+ return this.request(
366
+ "GET",
367
+ `/v1/action-requests/${encodeURIComponent(actionRequestId)}/evaluation`,
368
+ );
369
+ }
370
+
371
+ async getRootIntentChain(
372
+ actionRequestId: string,
373
+ ): Promise<{ root_intent_chain: RootIntentChain }> {
374
+ return this.request(
375
+ "GET",
376
+ `/v1/action-requests/${encodeURIComponent(actionRequestId)}/root-intent`,
377
+ );
378
+ }
379
+
380
+ async listAgents(): Promise<{ agents: Agent[] }> {
381
+ return this.request("GET", "/v1/agents");
382
+ }
383
+
384
+ async getAgent(agentId: string): Promise<{ agent: Agent }> {
385
+ return this.request("GET", `/v1/agents/${encodeURIComponent(agentId)}`);
386
+ }
387
+
388
+ async createAgent(input: CreateAgentInput): Promise<{ agent: Agent }> {
389
+ return this.request("POST", "/v1/agents", {
390
+ name: input.name,
391
+ model_provider: input.modelProvider,
392
+ model_name: input.modelName,
393
+ description: input.description,
394
+ environment: input.environment,
395
+ authority_level: input.authorityLevel,
396
+ sponsor_user_id: input.sponsorUserId,
397
+ });
398
+ }
399
+
400
+ async updateAgentStatus(
401
+ agentId: string,
402
+ input: UpdateAgentStatusInput,
403
+ ): Promise<{ agent: { id: string; name: string; status: Agent["status"] } }> {
404
+ return this.request("PATCH", `/v1/agents/${encodeURIComponent(agentId)}`, {
405
+ status: input.status,
406
+ reason: input.reason,
407
+ revoke_delegations: input.revokeDelegations,
408
+ restore_delegations: input.restoreDelegations,
409
+ });
410
+ }
411
+
412
+ async deleteAgent(agentId: string): Promise<{ ok: true }> {
413
+ return this.request("DELETE", `/v1/agents/${encodeURIComponent(agentId)}`);
414
+ }
415
+
416
+ async listAuthorities(): Promise<{
417
+ delegations: Delegation[];
418
+ authorities?: AuthoritySummary[];
419
+ }> {
420
+ return this.request("GET", "/v1/authorities");
421
+ }
422
+
423
+ async getAuthority(authorityId: string): Promise<{ delegation: Delegation }> {
424
+ return this.request("GET", `/v1/authorities/${encodeURIComponent(authorityId)}`);
425
+ }
426
+
427
+ async listActionRequests(): Promise<{ action_requests: ActionRequest[] }> {
428
+ return this.request("GET", "/v1/action-requests");
429
+ }
430
+
431
+ async approveActionRequest(actionRequestId: string, approverUserId: string, reason?: string) {
432
+ return this.resolveActionRequest(actionRequestId, "approve", approverUserId, reason);
433
+ }
434
+
435
+ async rejectActionRequest(actionRequestId: string, approverUserId: string, reason?: string) {
436
+ return this.resolveActionRequest(actionRequestId, "reject", approverUserId, reason);
437
+ }
438
+
439
+ async escalateActionRequest(actionRequestId: string, approverUserId: string, reason?: string) {
440
+ return this.resolveActionRequest(actionRequestId, "escalate", approverUserId, reason);
441
+ }
442
+
443
+ private async resolveActionRequest(
444
+ actionRequestId: string,
445
+ action: "approve" | "reject" | "escalate",
446
+ approverUserId: string,
447
+ reason?: string,
448
+ ): Promise<{
449
+ ok: true;
450
+ decision: "approved" | "rejected" | "escalated";
451
+ action_decision: "allowed" | "blocked" | "require_approval";
452
+ reason: string;
453
+ }> {
454
+ return this.request(
455
+ "POST",
456
+ `/v1/action-requests/${encodeURIComponent(actionRequestId)}/${action}`,
457
+ { reason, approver_user_id: approverUserId },
458
+ );
459
+ }
460
+
461
+ async listPolicies(): Promise<{ policies: Policy[] }> {
462
+ return this.request("GET", "/v1/policies");
463
+ }
464
+
465
+ async createPolicy(
466
+ input: CreatePolicyInput,
467
+ ): Promise<{ policy: Pick<Policy, "id" | "name" | "status" | "created_at"> }> {
468
+ return this.request("POST", "/v1/policies", {
469
+ name: input.name,
470
+ description: input.description,
471
+ policy_type: input.policyType,
472
+ status: input.status,
473
+ priority: input.priority,
474
+ action_type: input.actionType,
475
+ amount_greater_than: input.amountGreaterThan,
476
+ resource_sensitivity: input.resourceSensitivity,
477
+ external_recipient: input.externalRecipient,
478
+ environment: input.environment,
479
+ decision: input.decision,
480
+ approver_role: input.approverRole,
481
+ max_actions_per_window: input.maxActionsPerWindow
482
+ ? {
483
+ count: input.maxActionsPerWindow.count,
484
+ window_seconds: input.maxActionsPerWindow.windowSeconds,
485
+ action_type: input.maxActionsPerWindow.actionType,
486
+ }
487
+ : undefined,
488
+ max_amount_per_window: input.maxAmountPerWindow
489
+ ? {
490
+ amount: input.maxAmountPerWindow.amount,
491
+ window_seconds: input.maxAmountPerWindow.windowSeconds,
492
+ }
493
+ : undefined,
494
+ });
495
+ }
496
+
497
+ async simulatePolicy(
498
+ policyId: string,
499
+ input: { limit?: number; since?: string } = {},
500
+ ): Promise<{
501
+ simulation: PolicySimulation;
502
+ meta: {
503
+ simulated_at: string;
504
+ sample_size: number;
505
+ changed_count: number;
506
+ unchanged_count: number;
507
+ };
508
+ }> {
509
+ return this.request("POST", `/v1/policies/${encodeURIComponent(policyId)}/simulate`, input);
510
+ }
511
+
512
+ async publishPolicy(
513
+ policyId: string,
514
+ input: { force?: boolean } = {},
515
+ ): Promise<{ ok: true; policyId: string; simulation: Record<string, unknown> }> {
516
+ return this.request("POST", `/v1/policies/${encodeURIComponent(policyId)}/publish`, input);
517
+ }
518
+
519
+ async listActionTypes(): Promise<{ action_types: CustomActionType[] }> {
520
+ return this.listCustomActionTypes();
521
+ }
522
+
523
+ async listCustomActionTypes(): Promise<{ action_types: CustomActionType[] }> {
524
+ return this.request("GET", "/v1/action-types");
525
+ }
526
+
527
+ async createCustomActionType(input: CreateCustomActionTypeInput): Promise<{
528
+ action_type: Pick<CustomActionType, "id" | "label" | "policy_type" | "source" | "created_at">;
529
+ }> {
530
+ return this.request("POST", "/v1/action-types", {
531
+ id: input.id,
532
+ label: input.label,
533
+ description: input.description,
534
+ category: input.category,
535
+ policy_type: input.policyType,
536
+ payload_schema: input.payloadSchema ?? {},
537
+ });
538
+ }
539
+
540
+ async listAuditEvents(): Promise<{ audit_events: AuditEvent[] }> {
541
+ return this.request("GET", "/v1/audit-events");
542
+ }
543
+
544
+ async getAuditEvent(auditEventId: string): Promise<{ audit_event: AuditEvent }> {
545
+ return this.request("GET", `/v1/audit-events/${encodeURIComponent(auditEventId)}`);
546
+ }
547
+
548
+ async verifyAuditChain(): Promise<AuditChainVerification> {
549
+ return this.request("GET", "/v1/audit-events/verify");
550
+ }
551
+
552
+ async listApiKeys(): Promise<{ api_keys: ApiKeySummary[] }> {
553
+ return this.request("GET", "/v1/api-keys");
554
+ }
555
+ }
@@ -0,0 +1,9 @@
1
+ /** Evidence verification surface. */
2
+ export type {
3
+ ArtifactVerification,
4
+ DecisionEvidence,
5
+ DecisionEvidencePayload,
6
+ MandateEvidence,
7
+ MandatePayload,
8
+ } from "./types.js";
9
+ export { verifyDecisionArtifact, verifyMandateArtifact } from "./artifacts.js";