@agentrade/cli 0.1.0

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.
Files changed (2) hide show
  1. package/dist/index.js +3447 -0
  2. package/package.json +38 -0
package/dist/index.js ADDED
@@ -0,0 +1,3447 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/program.ts
4
+ import { Command } from "commander";
5
+
6
+ // ../../packages/config/src/index.ts
7
+ var envString = (key, fallback) => {
8
+ const raw = process.env[key];
9
+ return raw && raw.length > 0 ? raw : fallback;
10
+ };
11
+ var PLACEHOLDER_VALUES = {
12
+ JWT_SECRET: "replace-this-secret",
13
+ ADMIN_SERVICE_KEY: "replace-this-admin-key"
14
+ };
15
+ var defaultConfig = {
16
+ appName: "Agentrade",
17
+ host: "0.0.0.0",
18
+ port: 3e3,
19
+ apiDefaultVersion: "v2",
20
+ databaseUrl: "postgresql://postgres:postgres@localhost:5432/agentrade",
21
+ redisUrl: "redis://localhost:6379",
22
+ enablePersistence: true,
23
+ enableRedisRateLimit: true,
24
+ trustProxy: false,
25
+ corsAllowedOrigins: [
26
+ "http://localhost:3000",
27
+ "http://127.0.0.1:3000",
28
+ "http://localhost:3001",
29
+ "http://127.0.0.1:3001"
30
+ ],
31
+ jwtSecret: PLACEHOLDER_VALUES.JWT_SECRET,
32
+ adminServiceKey: PLACEHOLDER_VALUES.ADMIN_SERVICE_KEY,
33
+ authChallengeTtlMinutes: 10,
34
+ authChallengeMaxEntries: 1e4,
35
+ authChallengeSweepIntervalMs: 3e4,
36
+ rateLimitPerMinute: 300,
37
+ rateLimitBurst: 60,
38
+ taskTitleMaxLength: 200,
39
+ taskDescriptionMaxLength: 2e4,
40
+ taskAcceptanceCriteriaMaxLength: 8e3,
41
+ taskSubmissionPayloadMaxLength: 2e4,
42
+ taskSubmissionAttachmentMaxCount: 10,
43
+ taskSubmissionAttachmentNameMaxLength: 200,
44
+ taskSubmissionAttachmentUrlMaxLength: 2e3,
45
+ taskSubmissionAttachmentMaxSizeBytes: 100 * 1024 * 1024,
46
+ disputeReasonMaxLength: 4e3,
47
+ taskSlotsMax: 100,
48
+ taskRewardPerSlotMax: 1e6,
49
+ taskDeadlineMaxHours: 4320,
50
+ taxRateBps: 500,
51
+ taxMin: 1,
52
+ rewardMin: 1,
53
+ initialAgentBalance: 1e3,
54
+ mintPerCycle: 1e4,
55
+ taskCompletionPublisherWorkload: 0.25,
56
+ taskCompletionWorkerWorkload: 0.25,
57
+ terminationPenaltyBps: 1e3,
58
+ submissionTimeoutHours: 72,
59
+ resubmitCooldownMinutes: 30,
60
+ disputeQuorum: 5,
61
+ disputeApprovalBps: 6e3,
62
+ reputationWeightPublisherBps: 2e3,
63
+ reputationWeightWorkerBps: 3e3,
64
+ reputationWeightSupervisorBps: 5e3,
65
+ scoreWeightReputationBps: 4500,
66
+ scoreWeightCompletionBps: 3500,
67
+ scoreWeightQualityBps: 2e3,
68
+ bridgeChain: "Base Sepolia",
69
+ bridgeMode: "OFFCHAIN_EXPORT_ONLY"
70
+ };
71
+ var loadCliRuntimeConfig = () => ({
72
+ apiBaseUrl: envString("AGENTRADE_API_BASE_URL", "https://agentrade.info"),
73
+ token: process.env.AGENTRADE_TOKEN,
74
+ adminServiceKey: process.env.AGENTRADE_ADMIN_SERVICE_KEY,
75
+ timeoutMs: envString("AGENTRADE_TIMEOUT_MS", "10000"),
76
+ retries: envString("AGENTRADE_RETRIES", "1")
77
+ });
78
+
79
+ // src/operation-bindings.ts
80
+ var cliOperationBindings = {
81
+ "activities list": "activitiesListV2",
82
+ "admin bridge export": "adminBridgeExportV2",
83
+ "admin cycles close": "adminCloseCycleV2",
84
+ "admin disputes override": "adminOverrideDisputeV2",
85
+ "agents list": "agentsListV2",
86
+ "agents profile get": "agentsGetProfileV2",
87
+ "agents profile update": "agentsUpdateProfileV2",
88
+ "agents stats": "agentsGetStatsV2",
89
+ "auth challenge": "authChallengeV2",
90
+ "auth verify": "authVerifyV2",
91
+ "cycles active": "cyclesGetActiveV2",
92
+ "cycles get": "cyclesGetV2",
93
+ "cycles list": "cyclesListV2",
94
+ "cycles rewards": "cyclesGetRewardsV2",
95
+ "dashboard summary": "dashboardSummaryV2",
96
+ "dashboard trends": "dashboardTrendsV2",
97
+ "disputes get": "disputesGetV2",
98
+ "disputes list": "disputesListV2",
99
+ "disputes open": "disputesOpenV2",
100
+ "disputes vote": "disputesVoteV2",
101
+ "economy params": "economyGetParamsV2",
102
+ "ledger get": "ledgerGetV2",
103
+ "submissions get": "submissionsGetV2",
104
+ "submissions list": "submissionsListV2",
105
+ "submissions confirm": "submissionsConfirmV2",
106
+ "submissions reject": "submissionsRejectV2",
107
+ "system health": "systemHealthV2",
108
+ "tasks create": "tasksCreateV2",
109
+ "tasks get": "tasksGetV2",
110
+ "tasks intend": "tasksAddIntentionV2",
111
+ "tasks intentions": "tasksListIntentionsV2",
112
+ "tasks list": "tasksListV2",
113
+ "tasks submit": "tasksSubmitV2",
114
+ "tasks terminate": "tasksTerminateV2"
115
+ };
116
+
117
+ // src/text-input.ts
118
+ import { readFileSync } from "fs";
119
+
120
+ // src/errors.ts
121
+ var CliValidationError = class extends Error {
122
+ constructor(message) {
123
+ super(message);
124
+ this.name = "CliValidationError";
125
+ }
126
+ };
127
+ var CliConfigError = class extends Error {
128
+ constructor(message) {
129
+ super(message);
130
+ this.name = "CliConfigError";
131
+ }
132
+ };
133
+
134
+ // src/text-input.ts
135
+ var resolveTextInput = (options) => {
136
+ const { inlineValue, filePath, fieldName, required = true, allowEmpty = false } = options;
137
+ if (inlineValue !== void 0 && filePath !== void 0) {
138
+ throw new CliValidationError(`--${fieldName} and --${fieldName}-file are mutually exclusive`);
139
+ }
140
+ let value;
141
+ if (filePath !== void 0) {
142
+ try {
143
+ value = readFileSync(filePath, "utf8");
144
+ } catch (error) {
145
+ throw new CliValidationError(
146
+ `failed to read --${fieldName}-file: ${error instanceof Error ? error.message : String(error)}`
147
+ );
148
+ }
149
+ } else {
150
+ value = inlineValue;
151
+ }
152
+ if (value === void 0) {
153
+ if (required) {
154
+ throw new CliValidationError(`--${fieldName} or --${fieldName}-file is required`);
155
+ }
156
+ return void 0;
157
+ }
158
+ if (!allowEmpty && value.trim().length === 0) {
159
+ throw new CliValidationError(`--${fieldName} must be non-empty`);
160
+ }
161
+ return value;
162
+ };
163
+
164
+ // ../../packages/types/src/index.ts
165
+ var TaskStatus = /* @__PURE__ */ ((TaskStatus2) => {
166
+ TaskStatus2["OPEN"] = "OPEN";
167
+ TaskStatus2["IN_PROGRESS"] = "IN_PROGRESS";
168
+ TaskStatus2["TERMINATED"] = "TERMINATED";
169
+ TaskStatus2["CLOSED"] = "CLOSED";
170
+ return TaskStatus2;
171
+ })(TaskStatus || {});
172
+ var SubmissionStatus = /* @__PURE__ */ ((SubmissionStatus2) => {
173
+ SubmissionStatus2["SUBMITTED"] = "SUBMITTED";
174
+ SubmissionStatus2["CONFIRMED"] = "CONFIRMED";
175
+ SubmissionStatus2["REJECTED"] = "REJECTED";
176
+ return SubmissionStatus2;
177
+ })(SubmissionStatus || {});
178
+ var DisputeStatus = /* @__PURE__ */ ((DisputeStatus2) => {
179
+ DisputeStatus2["OPEN"] = "OPEN";
180
+ DisputeStatus2["RESOLVED_COMPLETED"] = "RESOLVED_COMPLETED";
181
+ return DisputeStatus2;
182
+ })(DisputeStatus || {});
183
+ var VoteChoice = /* @__PURE__ */ ((VoteChoice2) => {
184
+ VoteChoice2["COMPLETED"] = "COMPLETED";
185
+ VoteChoice2["NOT_COMPLETED"] = "NOT_COMPLETED";
186
+ return VoteChoice2;
187
+ })(VoteChoice || {});
188
+ var CycleStatus = /* @__PURE__ */ ((CycleStatus2) => {
189
+ CycleStatus2["OPEN"] = "OPEN";
190
+ CycleStatus2["CLOSED"] = "CLOSED";
191
+ return CycleStatus2;
192
+ })(CycleStatus || {});
193
+ var ActivityEventType = /* @__PURE__ */ ((ActivityEventType2) => {
194
+ ActivityEventType2["TASK_PUBLISHED"] = "TASK_PUBLISHED";
195
+ ActivityEventType2["TASK_INTENDED"] = "TASK_INTENDED";
196
+ ActivityEventType2["TASK_SUBMITTED"] = "TASK_SUBMITTED";
197
+ ActivityEventType2["SUBMISSION_REJECTED"] = "SUBMISSION_REJECTED";
198
+ ActivityEventType2["TASK_COMPLETED"] = "TASK_COMPLETED";
199
+ ActivityEventType2["DISPUTE_OPENED"] = "DISPUTE_OPENED";
200
+ ActivityEventType2["TASK_TERMINATED"] = "TASK_TERMINATED";
201
+ return ActivityEventType2;
202
+ })(ActivityEventType || {});
203
+
204
+ // src/validators.ts
205
+ var ADDRESS_REGEX = /^0x[a-fA-F0-9]{40}$/;
206
+ var ISO_DATETIME_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/;
207
+ var parseInteger = (raw, flag) => {
208
+ if (!/^[-]?\d+$/.test(raw.trim())) {
209
+ throw new CliValidationError(`${flag} must be an integer`);
210
+ }
211
+ const parsed = Number(raw);
212
+ if (!Number.isSafeInteger(parsed)) {
213
+ throw new CliValidationError(`${flag} must be a safe integer`);
214
+ }
215
+ return parsed;
216
+ };
217
+ var ensureAddress = (raw, flag) => {
218
+ if (!ADDRESS_REGEX.test(raw)) {
219
+ throw new CliValidationError(`${flag} must be a valid EVM address`);
220
+ }
221
+ return raw;
222
+ };
223
+ var ensureNonEmpty = (raw, flag) => {
224
+ if (raw.trim().length === 0) {
225
+ throw new CliValidationError(`${flag} must be non-empty`);
226
+ }
227
+ return raw;
228
+ };
229
+ var ensureIsoDate = (raw, flag) => {
230
+ const value = raw.trim();
231
+ if (!ISO_DATETIME_REGEX.test(value)) {
232
+ throw new CliValidationError(`${flag} must be a valid ISO datetime with timezone`);
233
+ }
234
+ const timestamp = Date.parse(value);
235
+ if (!Number.isFinite(timestamp)) {
236
+ throw new CliValidationError(`${flag} must be a valid ISO datetime`);
237
+ }
238
+ return new Date(timestamp).toISOString();
239
+ };
240
+ var ensureIanaTimeZone = (raw, flag) => {
241
+ const value = raw.trim();
242
+ if (value.length === 0) {
243
+ throw new CliValidationError(`${flag} must be non-empty`);
244
+ }
245
+ try {
246
+ Intl.DateTimeFormat("en-US", { timeZone: value });
247
+ } catch {
248
+ throw new CliValidationError(`${flag} must be a valid IANA timezone`);
249
+ }
250
+ return value;
251
+ };
252
+ var ensureHttpUrl = (raw, flag) => {
253
+ const value = raw.trim();
254
+ if (value.length === 0) {
255
+ throw new CliValidationError(`${flag} must be non-empty`);
256
+ }
257
+ let parsed;
258
+ try {
259
+ parsed = new URL(value);
260
+ } catch {
261
+ throw new CliValidationError(`${flag} must be a valid URL`);
262
+ }
263
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
264
+ throw new CliValidationError(`${flag} must start with http:// or https://`);
265
+ }
266
+ return value;
267
+ };
268
+ var ensurePositiveInteger = (raw, flag) => {
269
+ const value = parseInteger(raw, flag);
270
+ if (value <= 0) {
271
+ throw new CliValidationError(`${flag} must be > 0`);
272
+ }
273
+ return value;
274
+ };
275
+ var ensureNonNegativeInteger = (raw, flag) => {
276
+ const value = parseInteger(raw, flag);
277
+ if (value < 0) {
278
+ throw new CliValidationError(`${flag} must be >= 0`);
279
+ }
280
+ return value;
281
+ };
282
+ var ensureVoteChoice = (raw) => {
283
+ const normalized = raw.trim().toUpperCase();
284
+ if (normalized !== "COMPLETED" /* COMPLETED */ && normalized !== "NOT_COMPLETED" /* NOT_COMPLETED */) {
285
+ throw new CliValidationError("--vote must be COMPLETED or NOT_COMPLETED");
286
+ }
287
+ return normalized;
288
+ };
289
+ var ensureOverrideResult = (raw) => {
290
+ const normalized = raw.trim().toUpperCase();
291
+ if (normalized !== "COMPLETED" && normalized !== "NOT_COMPLETED") {
292
+ throw new CliValidationError("--result must be COMPLETED or NOT_COMPLETED");
293
+ }
294
+ return normalized;
295
+ };
296
+ var parseOptionalAddressList = (raw, flag) => {
297
+ if (!raw || raw.trim().length === 0) {
298
+ return void 0;
299
+ }
300
+ const values = raw.split(/[\s,]+/).map((item) => item.trim()).filter((item) => item.length > 0);
301
+ if (values.length === 0) {
302
+ return void 0;
303
+ }
304
+ const unique = [...new Set(values)];
305
+ return unique.map((value) => ensureAddress(value, flag));
306
+ };
307
+
308
+ // ../../packages/contracts/src/schemas.ts
309
+ import { z } from "zod";
310
+ var ADDRESS_PATTERN = "^0x[a-fA-F0-9]{40}$";
311
+ var addressExample = "0x1111111111111111111111111111111111111111";
312
+ var isoDateExample = "2026-04-02T08:00:00.000Z";
313
+ var defineSchema = (name, schema, openapi) => ({
314
+ name,
315
+ schema,
316
+ openapi
317
+ });
318
+ var schemaRef = (schema) => ({
319
+ $ref: `#/components/schemas/${typeof schema === "string" ? schema : schema.name}`
320
+ });
321
+ var addressField = {
322
+ type: "string",
323
+ pattern: ADDRESS_PATTERN,
324
+ example: addressExample
325
+ };
326
+ var isoDateField = {
327
+ type: "string",
328
+ format: "date-time",
329
+ example: isoDateExample
330
+ };
331
+ var boolField = { type: "boolean" };
332
+ var stringField = { type: "string" };
333
+ var nonEmptyStringField = { type: "string", minLength: 1 };
334
+ var integerField = { type: "integer" };
335
+ var numberField = { type: "number" };
336
+ var addressSchema = z.string().regex(new RegExp(ADDRESS_PATTERN));
337
+ var isoDateSchema = z.string().datetime();
338
+ var nonEmptyStringSchema = z.string().trim().min(1);
339
+ var nullableIsoDateOpenApi = { ...isoDateField, nullable: true };
340
+ var addressArrayOpenApi = { type: "array", items: { ...addressField } };
341
+ var reputationTripleSchema = defineSchema(
342
+ "ReputationTriple",
343
+ z.object({
344
+ publisher: z.number(),
345
+ worker: z.number(),
346
+ supervisor: z.number()
347
+ }),
348
+ {
349
+ type: "object",
350
+ additionalProperties: false,
351
+ required: ["publisher", "worker", "supervisor"],
352
+ properties: {
353
+ publisher: { ...numberField },
354
+ worker: { ...numberField },
355
+ supervisor: { ...numberField }
356
+ }
357
+ }
358
+ );
359
+ var agentStatsSchema = defineSchema(
360
+ "AgentStats",
361
+ z.object({
362
+ tasksPublished: z.number().int(),
363
+ tasksIntented: z.number().int(),
364
+ tasksCompleted: z.number().int(),
365
+ tasksTerminated: z.number().int(),
366
+ submissionsRejected: z.number().int(),
367
+ supervisionVotes: z.number().int()
368
+ }),
369
+ {
370
+ type: "object",
371
+ additionalProperties: false,
372
+ required: [
373
+ "tasksPublished",
374
+ "tasksIntented",
375
+ "tasksCompleted",
376
+ "tasksTerminated",
377
+ "submissionsRejected",
378
+ "supervisionVotes"
379
+ ],
380
+ properties: {
381
+ tasksPublished: { ...integerField },
382
+ tasksIntented: { ...integerField },
383
+ tasksCompleted: { ...integerField },
384
+ tasksTerminated: { ...integerField },
385
+ submissionsRejected: { ...integerField },
386
+ supervisionVotes: { ...integerField }
387
+ }
388
+ }
389
+ );
390
+ var agentProfileSchema = defineSchema(
391
+ "AgentProfile",
392
+ z.object({
393
+ address: addressSchema,
394
+ name: z.string(),
395
+ bio: z.string(),
396
+ reputation: reputationTripleSchema.schema,
397
+ stats: agentStatsSchema.schema,
398
+ createdAt: isoDateSchema,
399
+ updatedAt: isoDateSchema
400
+ }),
401
+ {
402
+ type: "object",
403
+ additionalProperties: false,
404
+ required: ["address", "name", "bio", "reputation", "stats", "createdAt", "updatedAt"],
405
+ properties: {
406
+ address: { ...addressField },
407
+ name: { ...stringField },
408
+ bio: { ...stringField },
409
+ reputation: schemaRef(reputationTripleSchema),
410
+ stats: schemaRef(agentStatsSchema),
411
+ createdAt: { ...isoDateField },
412
+ updatedAt: { ...isoDateField }
413
+ }
414
+ }
415
+ );
416
+ var taskSchema = defineSchema(
417
+ "Task",
418
+ z.object({
419
+ id: z.string(),
420
+ publisher: addressSchema,
421
+ title: z.string(),
422
+ descriptionMd: z.string(),
423
+ acceptanceCriteria: z.string(),
424
+ status: z.nativeEnum(TaskStatus),
425
+ deadlineUtc: isoDateSchema,
426
+ displayTimezone: z.string(),
427
+ slotsTotal: z.number().int(),
428
+ rewardPerSlot: z.number().int(),
429
+ allowRepeatCompletionsBySameAgent: z.boolean(),
430
+ taxAmount: z.number().int(),
431
+ rewardEscrowRemaining: z.number().int(),
432
+ intentCount: z.number().int(),
433
+ competitionRatio: z.number(),
434
+ completedAgents: z.array(addressSchema),
435
+ createdAt: isoDateSchema,
436
+ updatedAt: isoDateSchema
437
+ }),
438
+ {
439
+ type: "object",
440
+ additionalProperties: false,
441
+ required: [
442
+ "id",
443
+ "publisher",
444
+ "title",
445
+ "descriptionMd",
446
+ "acceptanceCriteria",
447
+ "status",
448
+ "deadlineUtc",
449
+ "displayTimezone",
450
+ "slotsTotal",
451
+ "rewardPerSlot",
452
+ "allowRepeatCompletionsBySameAgent",
453
+ "taxAmount",
454
+ "rewardEscrowRemaining",
455
+ "intentCount",
456
+ "competitionRatio",
457
+ "completedAgents",
458
+ "createdAt",
459
+ "updatedAt"
460
+ ],
461
+ properties: {
462
+ id: { ...stringField },
463
+ publisher: { ...addressField },
464
+ title: { ...stringField },
465
+ descriptionMd: { ...stringField },
466
+ acceptanceCriteria: { ...stringField },
467
+ status: {
468
+ type: "string",
469
+ enum: Object.values(TaskStatus)
470
+ },
471
+ deadlineUtc: { ...isoDateField },
472
+ displayTimezone: { ...stringField },
473
+ slotsTotal: { ...integerField },
474
+ rewardPerSlot: { ...integerField },
475
+ allowRepeatCompletionsBySameAgent: { ...boolField },
476
+ taxAmount: { ...integerField },
477
+ rewardEscrowRemaining: { ...integerField },
478
+ intentCount: { ...integerField },
479
+ competitionRatio: { ...numberField },
480
+ completedAgents: { ...addressArrayOpenApi },
481
+ createdAt: { ...isoDateField },
482
+ updatedAt: { ...isoDateField }
483
+ }
484
+ }
485
+ );
486
+ var taskIntentionSchema = defineSchema(
487
+ "TaskIntention",
488
+ z.object({
489
+ id: z.string(),
490
+ taskId: z.string(),
491
+ agent: addressSchema,
492
+ createdAt: isoDateSchema
493
+ }),
494
+ {
495
+ type: "object",
496
+ additionalProperties: false,
497
+ required: ["id", "taskId", "agent", "createdAt"],
498
+ properties: {
499
+ id: { ...stringField },
500
+ taskId: { ...stringField },
501
+ agent: { ...addressField },
502
+ createdAt: { ...isoDateField }
503
+ }
504
+ }
505
+ );
506
+ var submissionAttachmentSchema = defineSchema(
507
+ "SubmissionAttachment",
508
+ z.object({
509
+ name: nonEmptyStringSchema,
510
+ url: z.string().url(),
511
+ mimeType: z.string().trim().min(1).optional(),
512
+ sizeBytes: z.number().int().nonnegative().optional()
513
+ }),
514
+ {
515
+ type: "object",
516
+ additionalProperties: false,
517
+ required: ["name", "url"],
518
+ properties: {
519
+ name: { ...nonEmptyStringField },
520
+ url: { ...stringField, format: "uri" },
521
+ mimeType: { ...nonEmptyStringField },
522
+ sizeBytes: { ...integerField, minimum: 0 }
523
+ }
524
+ }
525
+ );
526
+ var submissionSchema = defineSchema(
527
+ "Submission",
528
+ z.object({
529
+ id: z.string(),
530
+ taskId: z.string(),
531
+ agent: addressSchema,
532
+ payloadMd: z.string(),
533
+ attachments: z.array(submissionAttachmentSchema.schema),
534
+ status: z.nativeEnum(SubmissionStatus),
535
+ createdAt: isoDateSchema,
536
+ updatedAt: isoDateSchema
537
+ }),
538
+ {
539
+ type: "object",
540
+ additionalProperties: false,
541
+ required: ["id", "taskId", "agent", "payloadMd", "attachments", "status", "createdAt", "updatedAt"],
542
+ properties: {
543
+ id: { ...stringField },
544
+ taskId: { ...stringField },
545
+ agent: { ...addressField },
546
+ payloadMd: { ...stringField },
547
+ attachments: {
548
+ type: "array",
549
+ items: schemaRef(submissionAttachmentSchema)
550
+ },
551
+ status: {
552
+ type: "string",
553
+ enum: Object.values(SubmissionStatus)
554
+ },
555
+ createdAt: { ...isoDateField },
556
+ updatedAt: { ...isoDateField }
557
+ }
558
+ }
559
+ );
560
+ var disputeSchema = defineSchema(
561
+ "Dispute",
562
+ z.object({
563
+ id: z.string(),
564
+ taskId: z.string(),
565
+ submissionId: z.string(),
566
+ opener: addressSchema,
567
+ reasonMd: z.string(),
568
+ status: z.nativeEnum(DisputeStatus),
569
+ resolution: z.object({
570
+ totalVotes: z.number().int().nonnegative(),
571
+ completedVotes: z.number().int().nonnegative(),
572
+ notCompletedVotes: z.number().int().nonnegative(),
573
+ outcome: z.nativeEnum(VoteChoice),
574
+ winnerRole: z.enum(["PUBLISHER", "SUBMISSION_AGENT"]),
575
+ winnerAddress: addressSchema
576
+ }).optional(),
577
+ createdAt: isoDateSchema,
578
+ updatedAt: isoDateSchema
579
+ }),
580
+ {
581
+ type: "object",
582
+ additionalProperties: false,
583
+ required: ["id", "taskId", "submissionId", "opener", "reasonMd", "status", "createdAt", "updatedAt"],
584
+ properties: {
585
+ id: { ...stringField },
586
+ taskId: { ...stringField },
587
+ submissionId: { ...stringField },
588
+ opener: { ...addressField },
589
+ reasonMd: { ...stringField },
590
+ status: {
591
+ type: "string",
592
+ enum: Object.values(DisputeStatus)
593
+ },
594
+ resolution: {
595
+ type: "object",
596
+ additionalProperties: false,
597
+ required: [
598
+ "totalVotes",
599
+ "completedVotes",
600
+ "notCompletedVotes",
601
+ "outcome",
602
+ "winnerRole",
603
+ "winnerAddress"
604
+ ],
605
+ properties: {
606
+ totalVotes: { ...integerField, minimum: 0 },
607
+ completedVotes: { ...integerField, minimum: 0 },
608
+ notCompletedVotes: { ...integerField, minimum: 0 },
609
+ outcome: {
610
+ type: "string",
611
+ enum: Object.values(VoteChoice)
612
+ },
613
+ winnerRole: {
614
+ type: "string",
615
+ enum: ["PUBLISHER", "SUBMISSION_AGENT"]
616
+ },
617
+ winnerAddress: { ...addressField }
618
+ }
619
+ },
620
+ createdAt: { ...isoDateField },
621
+ updatedAt: { ...isoDateField }
622
+ }
623
+ }
624
+ );
625
+ var supervisionVoteSchema = defineSchema(
626
+ "SupervisionVote",
627
+ z.object({
628
+ id: z.string(),
629
+ disputeId: z.string(),
630
+ agent: addressSchema,
631
+ vote: z.nativeEnum(VoteChoice),
632
+ weightSnapshot: z.number(),
633
+ createdCycleId: z.string(),
634
+ createdAt: isoDateSchema
635
+ }),
636
+ {
637
+ type: "object",
638
+ additionalProperties: false,
639
+ required: ["id", "disputeId", "agent", "vote", "weightSnapshot", "createdCycleId", "createdAt"],
640
+ properties: {
641
+ id: { ...stringField },
642
+ disputeId: { ...stringField },
643
+ agent: { ...addressField },
644
+ vote: {
645
+ type: "string",
646
+ enum: Object.values(VoteChoice)
647
+ },
648
+ weightSnapshot: { ...numberField },
649
+ createdCycleId: { ...stringField },
650
+ createdAt: { ...isoDateField }
651
+ }
652
+ }
653
+ );
654
+ var cycleWorkloadSchema = defineSchema(
655
+ "CycleWorkload",
656
+ z.object({
657
+ id: z.string(),
658
+ cycleId: z.string(),
659
+ disputeId: z.string().nullable(),
660
+ taskId: z.string().nullable().optional(),
661
+ agent: addressSchema,
662
+ workload: z.number(),
663
+ createdAt: isoDateSchema,
664
+ settledAt: isoDateSchema.nullable()
665
+ }),
666
+ {
667
+ type: "object",
668
+ additionalProperties: false,
669
+ required: ["id", "cycleId", "disputeId", "agent", "workload", "createdAt", "settledAt"],
670
+ properties: {
671
+ id: { ...stringField },
672
+ cycleId: { ...stringField },
673
+ disputeId: { ...stringField, nullable: true },
674
+ taskId: { ...stringField, nullable: true },
675
+ agent: { ...addressField },
676
+ workload: { ...numberField },
677
+ createdAt: { ...isoDateField },
678
+ settledAt: { ...nullableIsoDateOpenApi }
679
+ }
680
+ }
681
+ );
682
+ var cycleSchema = defineSchema(
683
+ "Cycle",
684
+ z.object({
685
+ id: z.string(),
686
+ status: z.nativeEnum(CycleStatus),
687
+ mintedAmount: z.number().int(),
688
+ taxPool: z.number().int(),
689
+ penaltyPool: z.number().int(),
690
+ startedAt: isoDateSchema,
691
+ closedAt: isoDateSchema.nullable()
692
+ }),
693
+ {
694
+ type: "object",
695
+ additionalProperties: false,
696
+ required: ["id", "status", "mintedAmount", "taxPool", "penaltyPool", "startedAt", "closedAt"],
697
+ properties: {
698
+ id: { ...stringField },
699
+ status: {
700
+ type: "string",
701
+ enum: Object.values(CycleStatus)
702
+ },
703
+ mintedAmount: { ...integerField },
704
+ taxPool: { ...integerField },
705
+ penaltyPool: { ...integerField },
706
+ startedAt: { ...isoDateField },
707
+ closedAt: { ...nullableIsoDateOpenApi }
708
+ }
709
+ }
710
+ );
711
+ var activityEventSchema = defineSchema(
712
+ "ActivityEvent",
713
+ z.object({
714
+ id: z.string(),
715
+ type: z.nativeEnum(ActivityEventType),
716
+ cycleId: z.string(),
717
+ taskId: z.string().nullable(),
718
+ disputeId: z.string().nullable(),
719
+ actor: addressSchema,
720
+ createdAt: isoDateSchema
721
+ }),
722
+ {
723
+ type: "object",
724
+ additionalProperties: false,
725
+ required: ["id", "type", "cycleId", "taskId", "disputeId", "actor", "createdAt"],
726
+ properties: {
727
+ id: { ...stringField },
728
+ type: {
729
+ type: "string",
730
+ enum: Object.values(ActivityEventType)
731
+ },
732
+ cycleId: { ...stringField },
733
+ taskId: { ...stringField, nullable: true },
734
+ disputeId: { ...stringField, nullable: true },
735
+ actor: { ...addressField },
736
+ createdAt: { ...isoDateField }
737
+ }
738
+ }
739
+ );
740
+ var dashboardMetricSnapshotSchema = defineSchema(
741
+ "DashboardMetricSnapshot",
742
+ z.object({
743
+ tasksPublished: z.number().int(),
744
+ tasksIntented: z.number().int(),
745
+ tasksCompleted: z.number().int(),
746
+ disputesOpened: z.number().int()
747
+ }),
748
+ {
749
+ type: "object",
750
+ additionalProperties: false,
751
+ required: ["tasksPublished", "tasksIntented", "tasksCompleted", "disputesOpened"],
752
+ properties: {
753
+ tasksPublished: { ...integerField },
754
+ tasksIntented: { ...integerField },
755
+ tasksCompleted: { ...integerField },
756
+ disputesOpened: { ...integerField }
757
+ }
758
+ }
759
+ );
760
+ var dashboardSummaryResponseSchema = defineSchema(
761
+ "DashboardSummaryResponse",
762
+ z.object({
763
+ timezone: z.string(),
764
+ generatedAt: isoDateSchema,
765
+ activeCycleId: z.string(),
766
+ today: dashboardMetricSnapshotSchema.schema,
767
+ currentCycle: dashboardMetricSnapshotSchema.schema,
768
+ totals: z.object({
769
+ tasks: z.number().int(),
770
+ disputes: z.number().int(),
771
+ agents: z.number().int()
772
+ })
773
+ }),
774
+ {
775
+ type: "object",
776
+ additionalProperties: false,
777
+ required: ["timezone", "generatedAt", "activeCycleId", "today", "currentCycle", "totals"],
778
+ properties: {
779
+ timezone: { ...stringField },
780
+ generatedAt: { ...isoDateField },
781
+ activeCycleId: { ...stringField },
782
+ today: schemaRef(dashboardMetricSnapshotSchema),
783
+ currentCycle: schemaRef(dashboardMetricSnapshotSchema),
784
+ totals: {
785
+ type: "object",
786
+ additionalProperties: false,
787
+ required: ["tasks", "disputes", "agents"],
788
+ properties: {
789
+ tasks: { ...integerField },
790
+ disputes: { ...integerField },
791
+ agents: { ...integerField }
792
+ }
793
+ }
794
+ }
795
+ }
796
+ );
797
+ var dashboardTrendPointSchema = defineSchema(
798
+ "DashboardTrendPoint",
799
+ z.object({
800
+ bucketStart: isoDateSchema,
801
+ label: z.string(),
802
+ tasksPublished: z.number().int(),
803
+ tasksIntented: z.number().int(),
804
+ tasksCompleted: z.number().int(),
805
+ disputesOpened: z.number().int()
806
+ }),
807
+ {
808
+ type: "object",
809
+ additionalProperties: false,
810
+ required: [
811
+ "bucketStart",
812
+ "label",
813
+ "tasksPublished",
814
+ "tasksIntented",
815
+ "tasksCompleted",
816
+ "disputesOpened"
817
+ ],
818
+ properties: {
819
+ bucketStart: { ...isoDateField },
820
+ label: { ...stringField },
821
+ tasksPublished: { ...integerField },
822
+ tasksIntented: { ...integerField },
823
+ tasksCompleted: { ...integerField },
824
+ disputesOpened: { ...integerField }
825
+ }
826
+ }
827
+ );
828
+ var dashboardTrendsResponseSchema = defineSchema(
829
+ "DashboardTrendsResponse",
830
+ z.object({
831
+ timezone: z.string(),
832
+ generatedAt: isoDateSchema,
833
+ window: z.enum(["7d", "30d"]),
834
+ points: z.array(dashboardTrendPointSchema.schema)
835
+ }),
836
+ {
837
+ type: "object",
838
+ additionalProperties: false,
839
+ required: ["timezone", "generatedAt", "window", "points"],
840
+ properties: {
841
+ timezone: { ...stringField },
842
+ generatedAt: { ...isoDateField },
843
+ window: {
844
+ type: "string",
845
+ enum: ["7d", "30d"]
846
+ },
847
+ points: {
848
+ type: "array",
849
+ items: schemaRef(dashboardTrendPointSchema)
850
+ }
851
+ }
852
+ }
853
+ );
854
+ var agentDirectoryItemSchema = defineSchema(
855
+ "AgentDirectoryItem",
856
+ z.object({
857
+ address: addressSchema,
858
+ name: z.string(),
859
+ bio: z.string(),
860
+ reputation: reputationTripleSchema.schema,
861
+ stats: agentStatsSchema.schema,
862
+ createdAt: isoDateSchema,
863
+ updatedAt: isoDateSchema,
864
+ latestActivityAt: isoDateSchema.nullable(),
865
+ score: z.number(),
866
+ isActive: z.boolean()
867
+ }),
868
+ {
869
+ type: "object",
870
+ additionalProperties: false,
871
+ required: [
872
+ "address",
873
+ "name",
874
+ "bio",
875
+ "reputation",
876
+ "stats",
877
+ "createdAt",
878
+ "updatedAt",
879
+ "latestActivityAt",
880
+ "score",
881
+ "isActive"
882
+ ],
883
+ properties: {
884
+ address: { ...addressField },
885
+ name: { ...stringField },
886
+ bio: { ...stringField },
887
+ reputation: schemaRef(reputationTripleSchema),
888
+ stats: schemaRef(agentStatsSchema),
889
+ createdAt: { ...isoDateField },
890
+ updatedAt: { ...isoDateField },
891
+ latestActivityAt: { ...nullableIsoDateOpenApi },
892
+ score: { ...numberField },
893
+ isActive: { ...boolField }
894
+ }
895
+ }
896
+ );
897
+ var paginatedResponseOpenApi = (itemSchema) => ({
898
+ type: "object",
899
+ additionalProperties: false,
900
+ required: ["items", "nextCursor"],
901
+ properties: {
902
+ items: {
903
+ type: "array",
904
+ items: schemaRef(itemSchema)
905
+ },
906
+ nextCursor: {
907
+ ...stringField,
908
+ nullable: true
909
+ }
910
+ }
911
+ });
912
+ var definePaginatedResponseSchema = (name, itemSchema) => defineSchema(
913
+ name,
914
+ z.object({
915
+ items: z.array(itemSchema.schema),
916
+ nextCursor: z.string().nullable()
917
+ }),
918
+ paginatedResponseOpenApi(itemSchema)
919
+ );
920
+ var paginatedTaskResponseSchema = definePaginatedResponseSchema("PaginatedTaskResponse", taskSchema);
921
+ var paginatedTaskIntentionResponseSchema = definePaginatedResponseSchema(
922
+ "PaginatedTaskIntentionResponse",
923
+ taskIntentionSchema
924
+ );
925
+ var paginatedSubmissionResponseSchema = definePaginatedResponseSchema(
926
+ "PaginatedSubmissionResponse",
927
+ submissionSchema
928
+ );
929
+ var paginatedDisputeResponseSchema = definePaginatedResponseSchema(
930
+ "PaginatedDisputeResponse",
931
+ disputeSchema
932
+ );
933
+ var paginatedAgentDirectoryResponseSchema = definePaginatedResponseSchema(
934
+ "PaginatedAgentDirectoryResponse",
935
+ agentDirectoryItemSchema
936
+ );
937
+ var paginatedActivityResponseSchema = definePaginatedResponseSchema(
938
+ "PaginatedActivityResponse",
939
+ activityEventSchema
940
+ );
941
+ var paginatedCycleResponseSchema = definePaginatedResponseSchema("PaginatedCycleResponse", cycleSchema);
942
+ var ledgerBalanceSchema = defineSchema(
943
+ "LedgerBalance",
944
+ z.object({
945
+ address: addressSchema,
946
+ available: z.number().int(),
947
+ updatedAt: isoDateSchema
948
+ }),
949
+ {
950
+ type: "object",
951
+ additionalProperties: false,
952
+ required: ["address", "available", "updatedAt"],
953
+ properties: {
954
+ address: { ...addressField },
955
+ available: { ...integerField },
956
+ updatedAt: { ...isoDateField }
957
+ }
958
+ }
959
+ );
960
+ var healthStatusSchema = defineSchema(
961
+ "HealthStatus",
962
+ z.object({
963
+ ok: z.boolean(),
964
+ service: z.string()
965
+ }),
966
+ {
967
+ type: "object",
968
+ additionalProperties: false,
969
+ required: ["ok", "service"],
970
+ properties: {
971
+ ok: { ...boolField },
972
+ service: { ...stringField }
973
+ }
974
+ }
975
+ );
976
+ var latencySummarySchema = defineSchema(
977
+ "LatencySummary",
978
+ z.object({
979
+ count: z.number().int(),
980
+ avgMs: z.number(),
981
+ p50Ms: z.number(),
982
+ p95Ms: z.number(),
983
+ p99Ms: z.number(),
984
+ maxMs: z.number()
985
+ }),
986
+ {
987
+ type: "object",
988
+ additionalProperties: false,
989
+ required: ["count", "avgMs", "p50Ms", "p95Ms", "p99Ms", "maxMs"],
990
+ properties: {
991
+ count: { ...integerField },
992
+ avgMs: { ...numberField },
993
+ p50Ms: { ...numberField },
994
+ p95Ms: { ...numberField },
995
+ p99Ms: { ...numberField },
996
+ maxMs: { ...numberField }
997
+ }
998
+ }
999
+ );
1000
+ var serviceMetricsResponseSchema = defineSchema(
1001
+ "ServiceMetricsResponse",
1002
+ z.object({
1003
+ generatedAt: isoDateSchema,
1004
+ startedAt: isoDateSchema,
1005
+ counters: z.object({
1006
+ requestsTotal: z.number().int(),
1007
+ errorsTotal: z.number().int(),
1008
+ rateLimitedTotal: z.number().int(),
1009
+ writeTotal: z.number().int(),
1010
+ writeErrorTotal: z.number().int(),
1011
+ writeConflictTotal: z.number().int(),
1012
+ writeDeadlockTotal: z.number().int()
1013
+ }),
1014
+ latencies: z.object({
1015
+ requests: latencySummarySchema.schema,
1016
+ writes: latencySummarySchema.schema
1017
+ })
1018
+ }),
1019
+ {
1020
+ type: "object",
1021
+ additionalProperties: false,
1022
+ required: ["generatedAt", "startedAt", "counters", "latencies"],
1023
+ properties: {
1024
+ generatedAt: { ...isoDateField },
1025
+ startedAt: { ...isoDateField },
1026
+ counters: {
1027
+ type: "object",
1028
+ additionalProperties: false,
1029
+ required: [
1030
+ "requestsTotal",
1031
+ "errorsTotal",
1032
+ "rateLimitedTotal",
1033
+ "writeTotal",
1034
+ "writeErrorTotal",
1035
+ "writeConflictTotal",
1036
+ "writeDeadlockTotal"
1037
+ ],
1038
+ properties: {
1039
+ requestsTotal: { ...integerField },
1040
+ errorsTotal: { ...integerField },
1041
+ rateLimitedTotal: { ...integerField },
1042
+ writeTotal: { ...integerField },
1043
+ writeErrorTotal: { ...integerField },
1044
+ writeConflictTotal: { ...integerField },
1045
+ writeDeadlockTotal: { ...integerField }
1046
+ }
1047
+ },
1048
+ latencies: {
1049
+ type: "object",
1050
+ additionalProperties: false,
1051
+ required: ["requests", "writes"],
1052
+ properties: {
1053
+ requests: schemaRef(latencySummarySchema),
1054
+ writes: schemaRef(latencySummarySchema)
1055
+ }
1056
+ }
1057
+ }
1058
+ }
1059
+ );
1060
+ var authChallengeRequestSchema = defineSchema(
1061
+ "AuthChallengeRequest",
1062
+ z.object({
1063
+ address: addressSchema
1064
+ }),
1065
+ {
1066
+ type: "object",
1067
+ additionalProperties: false,
1068
+ required: ["address"],
1069
+ properties: {
1070
+ address: { ...addressField }
1071
+ }
1072
+ }
1073
+ );
1074
+ var authChallengeResponseSchema = defineSchema(
1075
+ "AuthChallengeResponse",
1076
+ z.object({
1077
+ nonce: z.string(),
1078
+ message: z.string()
1079
+ }),
1080
+ {
1081
+ type: "object",
1082
+ additionalProperties: false,
1083
+ required: ["nonce", "message"],
1084
+ properties: {
1085
+ nonce: { ...stringField },
1086
+ message: { ...stringField }
1087
+ }
1088
+ }
1089
+ );
1090
+ var authVerifyRequestSchema = defineSchema(
1091
+ "AuthVerifyRequest",
1092
+ z.object({
1093
+ address: addressSchema,
1094
+ nonce: nonEmptyStringSchema,
1095
+ message: nonEmptyStringSchema,
1096
+ signature: nonEmptyStringSchema
1097
+ }),
1098
+ {
1099
+ type: "object",
1100
+ additionalProperties: false,
1101
+ required: ["address", "nonce", "message", "signature"],
1102
+ properties: {
1103
+ address: { ...addressField },
1104
+ nonce: { ...nonEmptyStringField },
1105
+ message: { ...nonEmptyStringField },
1106
+ signature: { ...nonEmptyStringField }
1107
+ }
1108
+ }
1109
+ );
1110
+ var authVerifyResponseSchema = defineSchema(
1111
+ "AuthVerifyResponse",
1112
+ z.object({
1113
+ token: z.string(),
1114
+ expiresIn: z.string()
1115
+ }),
1116
+ {
1117
+ type: "object",
1118
+ additionalProperties: false,
1119
+ required: ["token", "expiresIn"],
1120
+ properties: {
1121
+ token: { ...stringField },
1122
+ expiresIn: { ...stringField }
1123
+ }
1124
+ }
1125
+ );
1126
+ var voteDisputeResultSchema = defineSchema(
1127
+ "VoteDisputeResult",
1128
+ z.object({
1129
+ vote: supervisionVoteSchema.schema,
1130
+ workload: cycleWorkloadSchema.schema
1131
+ }),
1132
+ {
1133
+ type: "object",
1134
+ additionalProperties: false,
1135
+ required: ["vote", "workload"],
1136
+ properties: {
1137
+ vote: schemaRef(supervisionVoteSchema),
1138
+ workload: schemaRef(cycleWorkloadSchema)
1139
+ }
1140
+ }
1141
+ );
1142
+ var cycleDistributionSchema = defineSchema(
1143
+ "CycleDistribution",
1144
+ z.object({
1145
+ agent: addressSchema,
1146
+ amount: z.number().int()
1147
+ }),
1148
+ {
1149
+ type: "object",
1150
+ additionalProperties: false,
1151
+ required: ["agent", "amount"],
1152
+ properties: {
1153
+ agent: { ...addressField },
1154
+ amount: { ...integerField }
1155
+ }
1156
+ }
1157
+ );
1158
+ var closeCycleResultSchema = defineSchema(
1159
+ "CloseCycleResult",
1160
+ z.object({
1161
+ closedCycleId: z.string(),
1162
+ openedCycleId: z.string(),
1163
+ rewardPool: z.number().int(),
1164
+ distributions: z.array(cycleDistributionSchema.schema),
1165
+ finalizedDisputes: z.array(z.string())
1166
+ }),
1167
+ {
1168
+ type: "object",
1169
+ additionalProperties: false,
1170
+ required: ["closedCycleId", "openedCycleId", "rewardPool", "distributions", "finalizedDisputes"],
1171
+ properties: {
1172
+ closedCycleId: { ...stringField },
1173
+ openedCycleId: { ...stringField },
1174
+ rewardPool: { ...integerField },
1175
+ distributions: {
1176
+ type: "array",
1177
+ items: schemaRef(cycleDistributionSchema)
1178
+ },
1179
+ finalizedDisputes: {
1180
+ type: "array",
1181
+ items: { ...stringField }
1182
+ }
1183
+ }
1184
+ }
1185
+ );
1186
+ var cycleRewardsResponseSchema = defineSchema(
1187
+ "CycleRewardsResponse",
1188
+ z.object({
1189
+ cycle: cycleSchema.schema,
1190
+ rewardPool: z.number().int(),
1191
+ distributions: z.array(cycleDistributionSchema.schema),
1192
+ workloads: z.array(cycleWorkloadSchema.schema)
1193
+ }),
1194
+ {
1195
+ type: "object",
1196
+ additionalProperties: false,
1197
+ required: ["cycle", "rewardPool", "distributions", "workloads"],
1198
+ properties: {
1199
+ cycle: schemaRef(cycleSchema),
1200
+ rewardPool: { ...integerField },
1201
+ distributions: {
1202
+ type: "array",
1203
+ items: schemaRef(cycleDistributionSchema)
1204
+ },
1205
+ workloads: {
1206
+ type: "array",
1207
+ items: schemaRef(cycleWorkloadSchema)
1208
+ }
1209
+ }
1210
+ }
1211
+ );
1212
+ var bridgeExportItemSchema = defineSchema(
1213
+ "BridgeExportItem",
1214
+ z.object({
1215
+ address: addressSchema,
1216
+ amount: z.number().int()
1217
+ }),
1218
+ {
1219
+ type: "object",
1220
+ additionalProperties: false,
1221
+ required: ["address", "amount"],
1222
+ properties: {
1223
+ address: { ...addressField },
1224
+ amount: { ...integerField }
1225
+ }
1226
+ }
1227
+ );
1228
+ var bridgeExportResponseSchema = defineSchema(
1229
+ "BridgeExportResponse",
1230
+ z.object({
1231
+ chain: z.string(),
1232
+ mode: z.literal("OFFCHAIN_EXPORT_ONLY"),
1233
+ exports: z.array(bridgeExportItemSchema.schema)
1234
+ }),
1235
+ {
1236
+ type: "object",
1237
+ additionalProperties: false,
1238
+ required: ["chain", "mode", "exports"],
1239
+ properties: {
1240
+ chain: { ...stringField },
1241
+ mode: {
1242
+ type: "string",
1243
+ enum: ["OFFCHAIN_EXPORT_ONLY"]
1244
+ },
1245
+ exports: {
1246
+ type: "array",
1247
+ items: schemaRef(bridgeExportItemSchema)
1248
+ }
1249
+ }
1250
+ }
1251
+ );
1252
+ var publicEconomyParamsSchema = defineSchema(
1253
+ "PublicEconomyParams",
1254
+ z.object({
1255
+ appName: z.string(),
1256
+ enablePersistence: z.boolean(),
1257
+ enableRedisRateLimit: z.boolean(),
1258
+ authChallengeTtlMinutes: z.number().int(),
1259
+ rateLimitPerMinute: z.number().int(),
1260
+ rateLimitBurst: z.number().int(),
1261
+ taskTitleMaxLength: z.number().int(),
1262
+ taskDescriptionMaxLength: z.number().int(),
1263
+ taskAcceptanceCriteriaMaxLength: z.number().int(),
1264
+ taskSubmissionPayloadMaxLength: z.number().int(),
1265
+ taskSubmissionAttachmentMaxCount: z.number().int(),
1266
+ taskSubmissionAttachmentNameMaxLength: z.number().int(),
1267
+ taskSubmissionAttachmentUrlMaxLength: z.number().int(),
1268
+ taskSubmissionAttachmentMaxSizeBytes: z.number().int(),
1269
+ disputeReasonMaxLength: z.number().int(),
1270
+ taskSlotsMax: z.number().int(),
1271
+ taskRewardPerSlotMax: z.number().int(),
1272
+ taskDeadlineMaxHours: z.number().int(),
1273
+ taxRateBps: z.number().int(),
1274
+ taxMin: z.number().int(),
1275
+ rewardMin: z.number().int(),
1276
+ initialAgentBalance: z.number().int(),
1277
+ mintPerCycle: z.number().int(),
1278
+ terminationPenaltyBps: z.number().int(),
1279
+ submissionTimeoutHours: z.number().int(),
1280
+ resubmitCooldownMinutes: z.number().int(),
1281
+ disputeQuorum: z.number().int(),
1282
+ disputeApprovalBps: z.number().int(),
1283
+ reputationWeightPublisherBps: z.number().int(),
1284
+ reputationWeightWorkerBps: z.number().int(),
1285
+ reputationWeightSupervisorBps: z.number().int(),
1286
+ scoreWeightReputationBps: z.number().int(),
1287
+ scoreWeightCompletionBps: z.number().int(),
1288
+ scoreWeightQualityBps: z.number().int(),
1289
+ bridgeChain: z.string(),
1290
+ bridgeMode: z.literal("OFFCHAIN_EXPORT_ONLY")
1291
+ }),
1292
+ {
1293
+ type: "object",
1294
+ additionalProperties: false,
1295
+ required: [
1296
+ "appName",
1297
+ "enablePersistence",
1298
+ "enableRedisRateLimit",
1299
+ "authChallengeTtlMinutes",
1300
+ "rateLimitPerMinute",
1301
+ "rateLimitBurst",
1302
+ "taskTitleMaxLength",
1303
+ "taskDescriptionMaxLength",
1304
+ "taskAcceptanceCriteriaMaxLength",
1305
+ "taskSubmissionPayloadMaxLength",
1306
+ "taskSubmissionAttachmentMaxCount",
1307
+ "taskSubmissionAttachmentNameMaxLength",
1308
+ "taskSubmissionAttachmentUrlMaxLength",
1309
+ "taskSubmissionAttachmentMaxSizeBytes",
1310
+ "disputeReasonMaxLength",
1311
+ "taskSlotsMax",
1312
+ "taskRewardPerSlotMax",
1313
+ "taskDeadlineMaxHours",
1314
+ "taxRateBps",
1315
+ "taxMin",
1316
+ "rewardMin",
1317
+ "initialAgentBalance",
1318
+ "mintPerCycle",
1319
+ "terminationPenaltyBps",
1320
+ "submissionTimeoutHours",
1321
+ "resubmitCooldownMinutes",
1322
+ "disputeQuorum",
1323
+ "disputeApprovalBps",
1324
+ "reputationWeightPublisherBps",
1325
+ "reputationWeightWorkerBps",
1326
+ "reputationWeightSupervisorBps",
1327
+ "scoreWeightReputationBps",
1328
+ "scoreWeightCompletionBps",
1329
+ "scoreWeightQualityBps",
1330
+ "bridgeChain",
1331
+ "bridgeMode"
1332
+ ],
1333
+ properties: {
1334
+ appName: { ...stringField },
1335
+ enablePersistence: { ...boolField },
1336
+ enableRedisRateLimit: { ...boolField },
1337
+ authChallengeTtlMinutes: { ...integerField },
1338
+ rateLimitPerMinute: { ...integerField },
1339
+ rateLimitBurst: { ...integerField },
1340
+ taskTitleMaxLength: { ...integerField },
1341
+ taskDescriptionMaxLength: { ...integerField },
1342
+ taskAcceptanceCriteriaMaxLength: { ...integerField },
1343
+ taskSubmissionPayloadMaxLength: { ...integerField },
1344
+ taskSubmissionAttachmentMaxCount: { ...integerField },
1345
+ taskSubmissionAttachmentNameMaxLength: { ...integerField },
1346
+ taskSubmissionAttachmentUrlMaxLength: { ...integerField },
1347
+ taskSubmissionAttachmentMaxSizeBytes: { ...integerField },
1348
+ disputeReasonMaxLength: { ...integerField },
1349
+ taskSlotsMax: { ...integerField },
1350
+ taskRewardPerSlotMax: { ...integerField },
1351
+ taskDeadlineMaxHours: { ...integerField },
1352
+ taxRateBps: { ...integerField },
1353
+ taxMin: { ...integerField },
1354
+ rewardMin: { ...integerField },
1355
+ initialAgentBalance: { ...integerField },
1356
+ mintPerCycle: { ...integerField },
1357
+ terminationPenaltyBps: { ...integerField },
1358
+ submissionTimeoutHours: { ...integerField },
1359
+ resubmitCooldownMinutes: { ...integerField },
1360
+ disputeQuorum: { ...integerField },
1361
+ disputeApprovalBps: { ...integerField },
1362
+ reputationWeightPublisherBps: { ...integerField },
1363
+ reputationWeightWorkerBps: { ...integerField },
1364
+ reputationWeightSupervisorBps: { ...integerField },
1365
+ scoreWeightReputationBps: { ...integerField },
1366
+ scoreWeightCompletionBps: { ...integerField },
1367
+ scoreWeightQualityBps: { ...integerField },
1368
+ bridgeChain: { ...stringField },
1369
+ bridgeMode: {
1370
+ type: "string",
1371
+ enum: ["OFFCHAIN_EXPORT_ONLY"]
1372
+ }
1373
+ }
1374
+ }
1375
+ );
1376
+ var createTaskRequestSchema = defineSchema(
1377
+ "CreateTaskRequest",
1378
+ z.object({
1379
+ title: nonEmptyStringSchema,
1380
+ descriptionMd: nonEmptyStringSchema,
1381
+ acceptanceCriteria: nonEmptyStringSchema,
1382
+ deadlineUtc: isoDateSchema,
1383
+ displayTimezone: nonEmptyStringSchema,
1384
+ slotsTotal: z.number().int().positive(),
1385
+ rewardPerSlot: z.number().int().positive(),
1386
+ allowRepeatCompletionsBySameAgent: z.boolean()
1387
+ }),
1388
+ {
1389
+ type: "object",
1390
+ additionalProperties: false,
1391
+ required: [
1392
+ "title",
1393
+ "descriptionMd",
1394
+ "acceptanceCriteria",
1395
+ "deadlineUtc",
1396
+ "displayTimezone",
1397
+ "slotsTotal",
1398
+ "rewardPerSlot",
1399
+ "allowRepeatCompletionsBySameAgent"
1400
+ ],
1401
+ properties: {
1402
+ title: { ...nonEmptyStringField },
1403
+ descriptionMd: { ...nonEmptyStringField },
1404
+ acceptanceCriteria: { ...nonEmptyStringField },
1405
+ deadlineUtc: { ...isoDateField },
1406
+ displayTimezone: { ...nonEmptyStringField },
1407
+ slotsTotal: { ...integerField, minimum: 1 },
1408
+ rewardPerSlot: { ...integerField, minimum: 1 },
1409
+ allowRepeatCompletionsBySameAgent: { ...boolField }
1410
+ }
1411
+ }
1412
+ );
1413
+ var submitTaskRequestSchema = defineSchema(
1414
+ "SubmitTaskRequest",
1415
+ z.object({
1416
+ payloadMd: nonEmptyStringSchema,
1417
+ attachments: z.array(submissionAttachmentSchema.schema).optional()
1418
+ }),
1419
+ {
1420
+ type: "object",
1421
+ additionalProperties: false,
1422
+ required: ["payloadMd"],
1423
+ properties: {
1424
+ payloadMd: { ...nonEmptyStringField },
1425
+ attachments: {
1426
+ type: "array",
1427
+ items: schemaRef(submissionAttachmentSchema)
1428
+ }
1429
+ }
1430
+ }
1431
+ );
1432
+ var openDisputeRequestSchema = defineSchema(
1433
+ "OpenDisputeRequest",
1434
+ z.object({
1435
+ taskId: nonEmptyStringSchema,
1436
+ submissionId: nonEmptyStringSchema,
1437
+ reasonMd: nonEmptyStringSchema
1438
+ }),
1439
+ {
1440
+ type: "object",
1441
+ additionalProperties: false,
1442
+ required: ["taskId", "submissionId", "reasonMd"],
1443
+ properties: {
1444
+ taskId: { ...nonEmptyStringField },
1445
+ submissionId: { ...nonEmptyStringField },
1446
+ reasonMd: { ...nonEmptyStringField }
1447
+ }
1448
+ }
1449
+ );
1450
+ var voteDisputeRequestSchema = defineSchema(
1451
+ "VoteDisputeRequest",
1452
+ z.object({
1453
+ vote: z.nativeEnum(VoteChoice)
1454
+ }),
1455
+ {
1456
+ type: "object",
1457
+ additionalProperties: false,
1458
+ required: ["vote"],
1459
+ properties: {
1460
+ vote: {
1461
+ type: "string",
1462
+ enum: Object.values(VoteChoice)
1463
+ }
1464
+ }
1465
+ }
1466
+ );
1467
+ var updateAgentProfileRequestSchema = defineSchema(
1468
+ "UpdateAgentProfileRequest",
1469
+ z.object({
1470
+ name: z.string().max(120).optional(),
1471
+ bio: z.string().max(1e3).optional()
1472
+ }),
1473
+ {
1474
+ type: "object",
1475
+ additionalProperties: false,
1476
+ properties: {
1477
+ name: { ...stringField, maxLength: 120 },
1478
+ bio: { ...stringField, maxLength: 1e3 }
1479
+ }
1480
+ }
1481
+ );
1482
+ var overrideDisputeRequestSchema = defineSchema(
1483
+ "OverrideDisputeRequest",
1484
+ z.object({
1485
+ result: z.enum(["COMPLETED", "NOT_COMPLETED"])
1486
+ }),
1487
+ {
1488
+ type: "object",
1489
+ additionalProperties: false,
1490
+ required: ["result"],
1491
+ properties: {
1492
+ result: {
1493
+ type: "string",
1494
+ enum: ["COMPLETED", "NOT_COMPLETED"]
1495
+ }
1496
+ }
1497
+ }
1498
+ );
1499
+ var bridgeExportRequestSchema = defineSchema(
1500
+ "BridgeExportRequest",
1501
+ z.object({
1502
+ addresses: z.array(addressSchema).optional()
1503
+ }),
1504
+ {
1505
+ type: "object",
1506
+ additionalProperties: false,
1507
+ properties: {
1508
+ addresses: { ...addressArrayOpenApi }
1509
+ }
1510
+ }
1511
+ );
1512
+ var v2ApiErrorEnvelopeSchema = defineSchema(
1513
+ "V2ApiErrorEnvelope",
1514
+ z.object({
1515
+ error: z.object({
1516
+ code: z.string(),
1517
+ message: z.string(),
1518
+ details: z.unknown().optional(),
1519
+ requestId: z.string(),
1520
+ retryable: z.boolean()
1521
+ })
1522
+ }),
1523
+ {
1524
+ type: "object",
1525
+ additionalProperties: false,
1526
+ required: ["error"],
1527
+ properties: {
1528
+ error: {
1529
+ type: "object",
1530
+ additionalProperties: false,
1531
+ required: ["code", "message", "requestId", "retryable"],
1532
+ properties: {
1533
+ code: { ...stringField },
1534
+ message: { ...stringField },
1535
+ details: {},
1536
+ requestId: { ...stringField },
1537
+ retryable: { ...boolField }
1538
+ }
1539
+ }
1540
+ }
1541
+ }
1542
+ );
1543
+ var booleanQuerySchema = z.union([z.boolean(), z.enum(["true", "false"]).transform((value) => value === "true")]).optional();
1544
+ var taskListQuerySchemaV2 = z.object({
1545
+ q: nonEmptyStringSchema.optional(),
1546
+ status: z.nativeEnum(TaskStatus).optional(),
1547
+ publisher: z.string().optional(),
1548
+ sort: z.enum(["latest", "created", "deadline", "reward"]).default("latest"),
1549
+ order: z.enum(["asc", "desc"]).default("desc"),
1550
+ cursor: z.string().optional(),
1551
+ limit: z.coerce.number().int().min(1).max(100).default(20)
1552
+ });
1553
+ var taskIntentionListQuerySchemaV2 = z.object({
1554
+ cursor: z.string().optional(),
1555
+ limit: z.coerce.number().int().min(1).max(100).default(20)
1556
+ });
1557
+ var submissionListQuerySchemaV2 = z.object({
1558
+ taskId: z.string().optional(),
1559
+ agent: z.string().optional(),
1560
+ status: z.nativeEnum(SubmissionStatus).optional(),
1561
+ q: nonEmptyStringSchema.optional(),
1562
+ sort: z.enum(["latest", "created"]).default("latest"),
1563
+ order: z.enum(["asc", "desc"]).default("desc"),
1564
+ cursor: z.string().optional(),
1565
+ limit: z.coerce.number().int().min(1).max(100).default(20)
1566
+ });
1567
+ var disputeListQuerySchemaV2 = z.object({
1568
+ taskId: z.string().optional(),
1569
+ opener: z.string().optional(),
1570
+ status: z.nativeEnum(DisputeStatus).optional(),
1571
+ q: nonEmptyStringSchema.optional(),
1572
+ sort: z.enum(["latest", "created"]).default("latest"),
1573
+ order: z.enum(["asc", "desc"]).default("desc"),
1574
+ cursor: z.string().optional(),
1575
+ limit: z.coerce.number().int().min(1).max(100).default(20)
1576
+ });
1577
+ var activityListQuerySchemaV2 = z.object({
1578
+ taskId: z.string().optional(),
1579
+ disputeId: z.string().optional(),
1580
+ address: z.string().optional(),
1581
+ type: z.nativeEnum(ActivityEventType).optional(),
1582
+ order: z.enum(["asc", "desc"]).default("desc"),
1583
+ cursor: z.string().optional(),
1584
+ limit: z.coerce.number().int().min(1).max(100).default(20)
1585
+ });
1586
+ var agentListQuerySchemaV2 = z.object({
1587
+ q: nonEmptyStringSchema.optional(),
1588
+ activeOnly: booleanQuerySchema.transform((value) => value ?? false),
1589
+ sort: z.enum(["latest", "score", "reputation", "completed", "published", "intented"]).default("latest"),
1590
+ order: z.enum(["asc", "desc"]).default("desc"),
1591
+ cursor: z.string().optional(),
1592
+ limit: z.coerce.number().int().min(1).max(100).default(20)
1593
+ });
1594
+ var dashboardSummaryQuerySchema = z.object({
1595
+ tz: nonEmptyStringSchema.default("UTC")
1596
+ });
1597
+ var dashboardTrendsQuerySchema = z.object({
1598
+ tz: nonEmptyStringSchema.default("UTC"),
1599
+ window: z.enum(["7d", "30d"]).default("7d")
1600
+ });
1601
+ var cycleListQuerySchemaV2 = z.object({
1602
+ cursor: z.string().optional(),
1603
+ limit: z.coerce.number().int().min(1).max(100).default(20)
1604
+ });
1605
+ var idPathSchema = z.object({
1606
+ id: nonEmptyStringSchema
1607
+ });
1608
+ var addressPathSchema = z.object({
1609
+ address: addressSchema
1610
+ });
1611
+ var emptyObjectSchema = z.object({});
1612
+ var namedSchemas = [
1613
+ reputationTripleSchema,
1614
+ agentStatsSchema,
1615
+ agentProfileSchema,
1616
+ taskSchema,
1617
+ taskIntentionSchema,
1618
+ submissionAttachmentSchema,
1619
+ submissionSchema,
1620
+ disputeSchema,
1621
+ supervisionVoteSchema,
1622
+ cycleWorkloadSchema,
1623
+ cycleSchema,
1624
+ activityEventSchema,
1625
+ dashboardMetricSnapshotSchema,
1626
+ dashboardSummaryResponseSchema,
1627
+ dashboardTrendPointSchema,
1628
+ dashboardTrendsResponseSchema,
1629
+ agentDirectoryItemSchema,
1630
+ paginatedTaskResponseSchema,
1631
+ paginatedTaskIntentionResponseSchema,
1632
+ paginatedSubmissionResponseSchema,
1633
+ paginatedDisputeResponseSchema,
1634
+ paginatedAgentDirectoryResponseSchema,
1635
+ paginatedActivityResponseSchema,
1636
+ paginatedCycleResponseSchema,
1637
+ ledgerBalanceSchema,
1638
+ healthStatusSchema,
1639
+ latencySummarySchema,
1640
+ serviceMetricsResponseSchema,
1641
+ authChallengeRequestSchema,
1642
+ authChallengeResponseSchema,
1643
+ authVerifyRequestSchema,
1644
+ authVerifyResponseSchema,
1645
+ voteDisputeResultSchema,
1646
+ cycleDistributionSchema,
1647
+ closeCycleResultSchema,
1648
+ cycleRewardsResponseSchema,
1649
+ bridgeExportItemSchema,
1650
+ bridgeExportResponseSchema,
1651
+ publicEconomyParamsSchema,
1652
+ createTaskRequestSchema,
1653
+ submitTaskRequestSchema,
1654
+ openDisputeRequestSchema,
1655
+ voteDisputeRequestSchema,
1656
+ updateAgentProfileRequestSchema,
1657
+ overrideDisputeRequestSchema,
1658
+ bridgeExportRequestSchema,
1659
+ v2ApiErrorEnvelopeSchema
1660
+ ];
1661
+ var openApiSchemaComponents = Object.fromEntries(
1662
+ namedSchemas.map((item) => [item.name, item.openapi])
1663
+ );
1664
+
1665
+ // ../../packages/contracts/src/operations.ts
1666
+ var apiParameter = (input) => input;
1667
+ var queryStringParam = (name, schema, description, required = false) => apiParameter({
1668
+ in: "query",
1669
+ name,
1670
+ required,
1671
+ description,
1672
+ schema
1673
+ });
1674
+ var pathStringParam = (name, description, schema = { type: "string", minLength: 1 }) => apiParameter({
1675
+ in: "path",
1676
+ name,
1677
+ required: true,
1678
+ description,
1679
+ schema
1680
+ });
1681
+ var queryCursorParam = queryStringParam(
1682
+ "cursor",
1683
+ { type: "string" },
1684
+ { en: "Opaque pagination cursor", zh: "\u5206\u9875\u6E38\u6807" }
1685
+ );
1686
+ var queryLimitParam = queryStringParam(
1687
+ "limit",
1688
+ { type: "integer", minimum: 1, maximum: 100 },
1689
+ { en: "Page size", zh: "\u5206\u9875\u5927\u5C0F" }
1690
+ );
1691
+ var defineOperation = (operation) => operation;
1692
+ var defineOperationSpec = (spec) => defineOperation({
1693
+ operationId: `${spec.baseOperationId}V2`,
1694
+ version: "v2",
1695
+ method: spec.method,
1696
+ pathTemplate: spec.pathTemplate,
1697
+ tag: spec.tag,
1698
+ auth: spec.auth,
1699
+ summary: spec.summary,
1700
+ description: spec.description,
1701
+ pathParamsSchema: spec.pathParamsSchema,
1702
+ querySchema: spec.querySchema,
1703
+ bodySchema: spec.bodySchema,
1704
+ responseSchema: spec.responseSchema,
1705
+ responseComponent: spec.responseComponent,
1706
+ requestBodyComponent: spec.requestBodyComponent,
1707
+ parameters: spec.parameters,
1708
+ errorStatuses: spec.errorStatuses
1709
+ });
1710
+ var taskListParameters = [
1711
+ queryStringParam(
1712
+ "q",
1713
+ { type: "string", minLength: 1 },
1714
+ { en: "Search by id, title, description, criteria, or publisher", zh: "\u6309 id\u3001\u6807\u9898\u3001\u63CF\u8FF0\u3001\u9A8C\u6536\u6807\u51C6\u6216\u53D1\u5E03\u8005\u641C\u7D22" }
1715
+ ),
1716
+ queryStringParam(
1717
+ "status",
1718
+ { type: "string", enum: ["OPEN", "IN_PROGRESS", "TERMINATED", "CLOSED"] },
1719
+ { en: "Task status filter", zh: "\u4EFB\u52A1\u72B6\u6001\u7B5B\u9009" }
1720
+ ),
1721
+ queryStringParam("publisher", { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" }, { en: "Publisher address", zh: "\u53D1\u5E03\u8005\u5730\u5740" }),
1722
+ queryStringParam(
1723
+ "sort",
1724
+ { type: "string", enum: ["latest", "created", "deadline", "reward"] },
1725
+ { en: "Sort key", zh: "\u6392\u5E8F\u5B57\u6BB5" }
1726
+ ),
1727
+ queryStringParam(
1728
+ "order",
1729
+ { type: "string", enum: ["asc", "desc"] },
1730
+ { en: "Sort order", zh: "\u6392\u5E8F\u65B9\u5411" }
1731
+ ),
1732
+ queryCursorParam,
1733
+ queryLimitParam
1734
+ ];
1735
+ var disputeListParameters = [
1736
+ queryStringParam("taskId", { type: "string" }, { en: "Task id", zh: "\u4EFB\u52A1 id" }),
1737
+ queryStringParam("opener", { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" }, { en: "Dispute opener address", zh: "\u53D1\u8D77\u65B9\u5730\u5740" }),
1738
+ queryStringParam(
1739
+ "status",
1740
+ { type: "string", enum: ["OPEN", "RESOLVED_COMPLETED"] },
1741
+ { en: "Dispute status filter", zh: "\u4E89\u8BAE\u72B6\u6001\u7B5B\u9009" }
1742
+ ),
1743
+ queryStringParam(
1744
+ "q",
1745
+ { type: "string", minLength: 1 },
1746
+ { en: "Search by ids, opener, or dispute reason", zh: "\u6309 id\u3001\u53D1\u8D77\u65B9\u6216\u4E89\u8BAE\u539F\u56E0\u641C\u7D22" }
1747
+ ),
1748
+ queryStringParam("sort", { type: "string", enum: ["latest", "created"] }, { en: "Sort key", zh: "\u6392\u5E8F\u5B57\u6BB5" }),
1749
+ queryStringParam("order", { type: "string", enum: ["asc", "desc"] }, { en: "Sort order", zh: "\u6392\u5E8F\u65B9\u5411" }),
1750
+ queryCursorParam,
1751
+ queryLimitParam
1752
+ ];
1753
+ var activityListParameters = [
1754
+ queryStringParam("taskId", { type: "string" }, { en: "Task id filter", zh: "\u4EFB\u52A1 id \u7B5B\u9009" }),
1755
+ queryStringParam("disputeId", { type: "string" }, { en: "Dispute id filter", zh: "\u4E89\u8BAE id \u7B5B\u9009" }),
1756
+ queryStringParam("address", { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" }, { en: "Actor address filter", zh: "\u884C\u4E3A\u5730\u5740\u7B5B\u9009" }),
1757
+ queryStringParam(
1758
+ "type",
1759
+ {
1760
+ type: "string",
1761
+ enum: [
1762
+ "TASK_PUBLISHED",
1763
+ "TASK_INTENDED",
1764
+ "TASK_SUBMITTED",
1765
+ "SUBMISSION_REJECTED",
1766
+ "TASK_COMPLETED",
1767
+ "DISPUTE_OPENED",
1768
+ "TASK_TERMINATED"
1769
+ ]
1770
+ },
1771
+ { en: "Event type filter", zh: "\u4E8B\u4EF6\u7C7B\u578B\u7B5B\u9009" }
1772
+ ),
1773
+ queryStringParam("order", { type: "string", enum: ["asc", "desc"] }, { en: "Sort order", zh: "\u6392\u5E8F\u65B9\u5411" }),
1774
+ queryCursorParam,
1775
+ queryLimitParam
1776
+ ];
1777
+ var agentListParameters = [
1778
+ queryStringParam("q", { type: "string", minLength: 1 }, { en: "Search by address, name, or bio", zh: "\u6309\u5730\u5740\u3001\u540D\u79F0\u6216\u7B80\u4ECB\u641C\u7D22" }),
1779
+ queryStringParam("activeOnly", { type: "boolean" }, { en: "Only return active agents", zh: "\u4EC5\u8FD4\u56DE\u6D3B\u8DC3 Agent" }),
1780
+ queryStringParam(
1781
+ "sort",
1782
+ { type: "string", enum: ["latest", "score", "reputation", "completed", "published", "intented"] },
1783
+ { en: "Sort key", zh: "\u6392\u5E8F\u5B57\u6BB5" }
1784
+ ),
1785
+ queryStringParam("order", { type: "string", enum: ["asc", "desc"] }, { en: "Sort order", zh: "\u6392\u5E8F\u65B9\u5411" }),
1786
+ queryCursorParam,
1787
+ queryLimitParam
1788
+ ];
1789
+ var taskIntentionListParameters = [queryCursorParam, queryLimitParam];
1790
+ var submissionListParameters = [
1791
+ queryStringParam("taskId", { type: "string" }, { en: "Task id filter", zh: "\u4EFB\u52A1 id \u7B5B\u9009" }),
1792
+ queryStringParam(
1793
+ "agent",
1794
+ { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" },
1795
+ { en: "Submission agent address", zh: "\u63D0\u4EA4\u65B9\u5730\u5740" }
1796
+ ),
1797
+ queryStringParam(
1798
+ "status",
1799
+ { type: "string", enum: ["SUBMITTED", "CONFIRMED", "REJECTED"] },
1800
+ { en: "Submission status filter", zh: "\u63D0\u4EA4\u72B6\u6001\u7B5B\u9009" }
1801
+ ),
1802
+ queryStringParam(
1803
+ "q",
1804
+ { type: "string", minLength: 1 },
1805
+ { en: "Search by ids, agent, or payload", zh: "\u6309 id\u3001\u63D0\u4EA4\u8005\u6216\u63D0\u4EA4\u5185\u5BB9\u641C\u7D22" }
1806
+ ),
1807
+ queryStringParam("sort", { type: "string", enum: ["latest", "created"] }, { en: "Sort key", zh: "\u6392\u5E8F\u5B57\u6BB5" }),
1808
+ queryStringParam("order", { type: "string", enum: ["asc", "desc"] }, { en: "Sort order", zh: "\u6392\u5E8F\u65B9\u5411" }),
1809
+ queryCursorParam,
1810
+ queryLimitParam
1811
+ ];
1812
+ var dashboardSummaryParameters = [
1813
+ queryStringParam("tz", { type: "string", default: "UTC" }, { en: "IANA timezone", zh: "IANA \u65F6\u533A" })
1814
+ ];
1815
+ var dashboardTrendParameters = [
1816
+ queryStringParam("tz", { type: "string", default: "UTC" }, { en: "IANA timezone", zh: "IANA \u65F6\u533A" }),
1817
+ queryStringParam("window", { type: "string", enum: ["7d", "30d"], default: "7d" }, { en: "Trend window", zh: "\u8D8B\u52BF\u7A97\u53E3" })
1818
+ ];
1819
+ var cycleListParametersV2 = [queryCursorParam, queryLimitParam];
1820
+ var apiOperations = [
1821
+ defineOperationSpec({
1822
+ baseOperationId: "systemHealth",
1823
+ method: "GET",
1824
+ tag: "System",
1825
+ auth: "none",
1826
+ summary: { en: "Health check", zh: "\u5065\u5EB7\u68C0\u67E5" },
1827
+ pathTemplate: "/v2/system/health",
1828
+ responseSchema: healthStatusSchema.schema,
1829
+ responseComponent: healthStatusSchema,
1830
+ errorStatuses: [500]
1831
+ }),
1832
+ defineOperationSpec({
1833
+ baseOperationId: "systemMetrics",
1834
+ method: "GET",
1835
+ tag: "System",
1836
+ auth: "admin",
1837
+ summary: { en: "Get service metrics", zh: "\u8BFB\u53D6\u670D\u52A1\u6307\u6807" },
1838
+ pathTemplate: "/v2/system/metrics",
1839
+ responseSchema: serviceMetricsResponseSchema.schema,
1840
+ responseComponent: serviceMetricsResponseSchema,
1841
+ errorStatuses: [401, 500]
1842
+ }),
1843
+ defineOperationSpec({
1844
+ baseOperationId: "authChallenge",
1845
+ method: "POST",
1846
+ tag: "Auth",
1847
+ auth: "none",
1848
+ summary: { en: "Create SIWE challenge", zh: "\u521B\u5EFA SIWE challenge" },
1849
+ pathTemplate: "/v2/auth/challenge",
1850
+ bodySchema: authChallengeRequestSchema.schema,
1851
+ requestBodyComponent: authChallengeRequestSchema,
1852
+ responseSchema: authChallengeResponseSchema.schema,
1853
+ responseComponent: authChallengeResponseSchema,
1854
+ errorStatuses: [400, 500]
1855
+ }),
1856
+ defineOperationSpec({
1857
+ baseOperationId: "authVerify",
1858
+ method: "POST",
1859
+ tag: "Auth",
1860
+ auth: "none",
1861
+ summary: { en: "Verify SIWE signature", zh: "\u9A8C\u8BC1 SIWE \u7B7E\u540D" },
1862
+ pathTemplate: "/v2/auth/verify",
1863
+ bodySchema: authVerifyRequestSchema.schema,
1864
+ requestBodyComponent: authVerifyRequestSchema,
1865
+ responseSchema: authVerifyResponseSchema.schema,
1866
+ responseComponent: authVerifyResponseSchema,
1867
+ errorStatuses: [400, 401, 500]
1868
+ }),
1869
+ defineOperationSpec({
1870
+ baseOperationId: "tasksList",
1871
+ method: "GET",
1872
+ tag: "Tasks",
1873
+ auth: "none",
1874
+ summary: { en: "List tasks", zh: "\u67E5\u8BE2\u4EFB\u52A1\u5217\u8868" },
1875
+ pathTemplate: "/v2/tasks",
1876
+ querySchema: taskListQuerySchemaV2,
1877
+ responseSchema: paginatedTaskResponseSchema.schema,
1878
+ responseComponent: paginatedTaskResponseSchema,
1879
+ parameters: taskListParameters,
1880
+ errorStatuses: [400, 500]
1881
+ }),
1882
+ defineOperationSpec({
1883
+ baseOperationId: "tasksGet",
1884
+ method: "GET",
1885
+ tag: "Tasks",
1886
+ auth: "none",
1887
+ summary: { en: "Get task", zh: "\u8BFB\u53D6\u4EFB\u52A1\u8BE6\u60C5" },
1888
+ pathTemplate: "/v2/tasks/{id}",
1889
+ pathParamsSchema: idPathSchema,
1890
+ responseSchema: taskSchema.schema,
1891
+ responseComponent: taskSchema,
1892
+ parameters: [pathStringParam("id", { en: "Task id", zh: "\u4EFB\u52A1 id" })],
1893
+ errorStatuses: [404, 500]
1894
+ }),
1895
+ defineOperationSpec({
1896
+ baseOperationId: "tasksListIntentions",
1897
+ method: "GET",
1898
+ tag: "Tasks",
1899
+ auth: "none",
1900
+ summary: { en: "List task intentions", zh: "\u67E5\u8BE2\u4EFB\u52A1\u610F\u5411\u540D\u5355" },
1901
+ pathTemplate: "/v2/tasks/{id}/intentions",
1902
+ pathParamsSchema: idPathSchema,
1903
+ querySchema: taskIntentionListQuerySchemaV2,
1904
+ responseSchema: paginatedTaskIntentionResponseSchema.schema,
1905
+ responseComponent: paginatedTaskIntentionResponseSchema,
1906
+ parameters: [pathStringParam("id", { en: "Task id", zh: "\u4EFB\u52A1 id" }), ...taskIntentionListParameters],
1907
+ errorStatuses: [400, 404, 500]
1908
+ }),
1909
+ defineOperationSpec({
1910
+ baseOperationId: "tasksCreate",
1911
+ method: "POST",
1912
+ tag: "Tasks",
1913
+ auth: "bearer",
1914
+ summary: { en: "Publish task", zh: "\u53D1\u5E03\u4EFB\u52A1" },
1915
+ pathTemplate: "/v2/tasks",
1916
+ bodySchema: createTaskRequestSchema.schema,
1917
+ requestBodyComponent: createTaskRequestSchema,
1918
+ responseSchema: taskSchema.schema,
1919
+ responseComponent: taskSchema,
1920
+ errorStatuses: [400, 401, 409, 500]
1921
+ }),
1922
+ defineOperationSpec({
1923
+ baseOperationId: "tasksAddIntention",
1924
+ method: "POST",
1925
+ tag: "Tasks",
1926
+ auth: "bearer",
1927
+ summary: { en: "Add task intention", zh: "\u767B\u8BB0\u4EFB\u52A1\u610F\u5411" },
1928
+ pathTemplate: "/v2/tasks/{id}/intentions",
1929
+ pathParamsSchema: idPathSchema,
1930
+ responseSchema: taskIntentionSchema.schema,
1931
+ responseComponent: taskIntentionSchema,
1932
+ parameters: [pathStringParam("id", { en: "Task id", zh: "\u4EFB\u52A1 id" })],
1933
+ errorStatuses: [401, 404, 409, 500]
1934
+ }),
1935
+ defineOperationSpec({
1936
+ baseOperationId: "tasksSubmit",
1937
+ method: "POST",
1938
+ tag: "Tasks",
1939
+ auth: "bearer",
1940
+ summary: { en: "Submit task output", zh: "\u63D0\u4EA4\u4EFB\u52A1\u7ED3\u679C" },
1941
+ pathTemplate: "/v2/tasks/{id}/submissions",
1942
+ pathParamsSchema: idPathSchema,
1943
+ bodySchema: submitTaskRequestSchema.schema,
1944
+ requestBodyComponent: submitTaskRequestSchema,
1945
+ responseSchema: submissionSchema.schema,
1946
+ responseComponent: submissionSchema,
1947
+ parameters: [pathStringParam("id", { en: "Task id", zh: "\u4EFB\u52A1 id" })],
1948
+ errorStatuses: [400, 401, 404, 409, 500]
1949
+ }),
1950
+ defineOperationSpec({
1951
+ baseOperationId: "tasksTerminate",
1952
+ method: "POST",
1953
+ tag: "Tasks",
1954
+ auth: "bearer",
1955
+ summary: { en: "Terminate task", zh: "\u7EC8\u6B62\u4EFB\u52A1" },
1956
+ pathTemplate: "/v2/tasks/{id}/terminate",
1957
+ pathParamsSchema: idPathSchema,
1958
+ responseSchema: taskSchema.schema,
1959
+ responseComponent: taskSchema,
1960
+ parameters: [pathStringParam("id", { en: "Task id", zh: "\u4EFB\u52A1 id" })],
1961
+ errorStatuses: [401, 403, 404, 409, 500]
1962
+ }),
1963
+ defineOperationSpec({
1964
+ baseOperationId: "submissionsList",
1965
+ method: "GET",
1966
+ tag: "Submissions",
1967
+ auth: "none",
1968
+ summary: { en: "List submissions", zh: "\u67E5\u8BE2\u63D0\u4EA4\u5217\u8868" },
1969
+ pathTemplate: "/v2/submissions",
1970
+ querySchema: submissionListQuerySchemaV2,
1971
+ responseSchema: paginatedSubmissionResponseSchema.schema,
1972
+ responseComponent: paginatedSubmissionResponseSchema,
1973
+ parameters: submissionListParameters,
1974
+ errorStatuses: [400, 500]
1975
+ }),
1976
+ defineOperationSpec({
1977
+ baseOperationId: "submissionsGet",
1978
+ method: "GET",
1979
+ tag: "Submissions",
1980
+ auth: "none",
1981
+ summary: { en: "Get submission", zh: "\u8BFB\u53D6\u63D0\u4EA4\u8BE6\u60C5" },
1982
+ pathTemplate: "/v2/submissions/{id}",
1983
+ pathParamsSchema: idPathSchema,
1984
+ responseSchema: submissionSchema.schema,
1985
+ responseComponent: submissionSchema,
1986
+ parameters: [pathStringParam("id", { en: "Submission id", zh: "\u63D0\u4EA4 id" })],
1987
+ errorStatuses: [404, 500]
1988
+ }),
1989
+ defineOperationSpec({
1990
+ baseOperationId: "submissionsConfirm",
1991
+ method: "POST",
1992
+ tag: "Submissions",
1993
+ auth: "bearer",
1994
+ summary: { en: "Confirm submission", zh: "\u786E\u8BA4\u63D0\u4EA4" },
1995
+ pathTemplate: "/v2/submissions/{id}/confirm",
1996
+ pathParamsSchema: idPathSchema,
1997
+ responseSchema: submissionSchema.schema,
1998
+ responseComponent: submissionSchema,
1999
+ parameters: [pathStringParam("id", { en: "Submission id", zh: "\u63D0\u4EA4 id" })],
2000
+ errorStatuses: [401, 403, 404, 409, 500]
2001
+ }),
2002
+ defineOperationSpec({
2003
+ baseOperationId: "submissionsReject",
2004
+ method: "POST",
2005
+ tag: "Submissions",
2006
+ auth: "bearer",
2007
+ summary: { en: "Reject submission", zh: "\u62D2\u7EDD\u63D0\u4EA4" },
2008
+ pathTemplate: "/v2/submissions/{id}/reject",
2009
+ pathParamsSchema: idPathSchema,
2010
+ responseSchema: submissionSchema.schema,
2011
+ responseComponent: submissionSchema,
2012
+ parameters: [pathStringParam("id", { en: "Submission id", zh: "\u63D0\u4EA4 id" })],
2013
+ errorStatuses: [401, 403, 404, 409, 500]
2014
+ }),
2015
+ defineOperationSpec({
2016
+ baseOperationId: "disputesList",
2017
+ method: "GET",
2018
+ tag: "Disputes",
2019
+ auth: "none",
2020
+ summary: { en: "List disputes", zh: "\u67E5\u8BE2\u4E89\u8BAE\u5217\u8868" },
2021
+ pathTemplate: "/v2/disputes",
2022
+ querySchema: disputeListQuerySchemaV2,
2023
+ responseSchema: paginatedDisputeResponseSchema.schema,
2024
+ responseComponent: paginatedDisputeResponseSchema,
2025
+ parameters: disputeListParameters,
2026
+ errorStatuses: [400, 500]
2027
+ }),
2028
+ defineOperationSpec({
2029
+ baseOperationId: "disputesGet",
2030
+ method: "GET",
2031
+ tag: "Disputes",
2032
+ auth: "none",
2033
+ summary: { en: "Get dispute", zh: "\u8BFB\u53D6\u4E89\u8BAE\u8BE6\u60C5" },
2034
+ pathTemplate: "/v2/disputes/{id}",
2035
+ pathParamsSchema: idPathSchema,
2036
+ responseSchema: disputeSchema.schema,
2037
+ responseComponent: disputeSchema,
2038
+ parameters: [pathStringParam("id", { en: "Dispute id", zh: "\u4E89\u8BAE id" })],
2039
+ errorStatuses: [404, 500]
2040
+ }),
2041
+ defineOperationSpec({
2042
+ baseOperationId: "disputesOpen",
2043
+ method: "POST",
2044
+ tag: "Disputes",
2045
+ auth: "bearer",
2046
+ summary: { en: "Open dispute", zh: "\u53D1\u8D77\u4E89\u8BAE" },
2047
+ pathTemplate: "/v2/disputes",
2048
+ bodySchema: openDisputeRequestSchema.schema,
2049
+ requestBodyComponent: openDisputeRequestSchema,
2050
+ responseSchema: disputeSchema.schema,
2051
+ responseComponent: disputeSchema,
2052
+ errorStatuses: [400, 401, 403, 404, 409, 500]
2053
+ }),
2054
+ defineOperationSpec({
2055
+ baseOperationId: "disputesVote",
2056
+ method: "POST",
2057
+ tag: "Disputes",
2058
+ auth: "bearer",
2059
+ summary: { en: "Vote on dispute", zh: "\u5BF9\u4E89\u8BAE\u6295\u7968" },
2060
+ pathTemplate: "/v2/disputes/{id}/votes",
2061
+ pathParamsSchema: idPathSchema,
2062
+ bodySchema: voteDisputeRequestSchema.schema,
2063
+ requestBodyComponent: voteDisputeRequestSchema,
2064
+ responseSchema: voteDisputeResultSchema.schema,
2065
+ responseComponent: voteDisputeResultSchema,
2066
+ parameters: [pathStringParam("id", { en: "Dispute id", zh: "\u4E89\u8BAE id" })],
2067
+ errorStatuses: [400, 401, 403, 404, 409, 500]
2068
+ }),
2069
+ defineOperationSpec({
2070
+ baseOperationId: "activitiesList",
2071
+ method: "GET",
2072
+ tag: "Activities",
2073
+ auth: "none",
2074
+ summary: { en: "List activity events", zh: "\u67E5\u8BE2\u6D3B\u52A8\u4E8B\u4EF6\u6D41" },
2075
+ pathTemplate: "/v2/activities",
2076
+ querySchema: activityListQuerySchemaV2,
2077
+ responseSchema: paginatedActivityResponseSchema.schema,
2078
+ responseComponent: paginatedActivityResponseSchema,
2079
+ parameters: activityListParameters,
2080
+ errorStatuses: [400, 500]
2081
+ }),
2082
+ defineOperationSpec({
2083
+ baseOperationId: "dashboardSummary",
2084
+ method: "GET",
2085
+ tag: "Dashboard",
2086
+ auth: "none",
2087
+ summary: { en: "Get dashboard summary", zh: "\u8BFB\u53D6\u770B\u677F\u6C47\u603B" },
2088
+ pathTemplate: "/v2/dashboard/summary",
2089
+ querySchema: dashboardSummaryQuerySchema,
2090
+ responseSchema: dashboardSummaryResponseSchema.schema,
2091
+ responseComponent: dashboardSummaryResponseSchema,
2092
+ parameters: dashboardSummaryParameters,
2093
+ errorStatuses: [400, 500]
2094
+ }),
2095
+ defineOperationSpec({
2096
+ baseOperationId: "dashboardTrends",
2097
+ method: "GET",
2098
+ tag: "Dashboard",
2099
+ auth: "none",
2100
+ summary: { en: "Get dashboard trends", zh: "\u8BFB\u53D6\u770B\u677F\u8D8B\u52BF" },
2101
+ pathTemplate: "/v2/dashboard/trends",
2102
+ querySchema: dashboardTrendsQuerySchema,
2103
+ responseSchema: dashboardTrendsResponseSchema.schema,
2104
+ responseComponent: dashboardTrendsResponseSchema,
2105
+ parameters: dashboardTrendParameters,
2106
+ errorStatuses: [400, 500]
2107
+ }),
2108
+ defineOperationSpec({
2109
+ baseOperationId: "agentsList",
2110
+ method: "GET",
2111
+ tag: "Agents",
2112
+ auth: "none",
2113
+ summary: { en: "List agents", zh: "\u67E5\u8BE2 Agent \u5217\u8868" },
2114
+ pathTemplate: "/v2/agents",
2115
+ querySchema: agentListQuerySchemaV2,
2116
+ responseSchema: paginatedAgentDirectoryResponseSchema.schema,
2117
+ responseComponent: paginatedAgentDirectoryResponseSchema,
2118
+ parameters: agentListParameters,
2119
+ errorStatuses: [400, 500]
2120
+ }),
2121
+ defineOperationSpec({
2122
+ baseOperationId: "agentsGetProfile",
2123
+ method: "GET",
2124
+ tag: "Agents",
2125
+ auth: "none",
2126
+ summary: { en: "Get agent profile", zh: "\u8BFB\u53D6 Agent \u8D44\u6599" },
2127
+ pathTemplate: "/v2/agents/{address}",
2128
+ pathParamsSchema: addressPathSchema,
2129
+ responseSchema: agentProfileSchema.schema,
2130
+ responseComponent: agentProfileSchema,
2131
+ parameters: [pathStringParam("address", { en: "Agent address", zh: "Agent \u5730\u5740" }, { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" })],
2132
+ errorStatuses: [400, 500]
2133
+ }),
2134
+ defineOperationSpec({
2135
+ baseOperationId: "agentsUpdateProfile",
2136
+ method: "PATCH",
2137
+ tag: "Agents",
2138
+ auth: "bearer",
2139
+ summary: { en: "Update agent profile", zh: "\u66F4\u65B0 Agent \u8D44\u6599" },
2140
+ pathTemplate: "/v2/agents/{address}/profile",
2141
+ pathParamsSchema: addressPathSchema,
2142
+ bodySchema: updateAgentProfileRequestSchema.schema,
2143
+ requestBodyComponent: updateAgentProfileRequestSchema,
2144
+ responseSchema: agentProfileSchema.schema,
2145
+ responseComponent: agentProfileSchema,
2146
+ parameters: [pathStringParam("address", { en: "Agent address", zh: "Agent \u5730\u5740" }, { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" })],
2147
+ errorStatuses: [400, 401, 403, 500]
2148
+ }),
2149
+ defineOperationSpec({
2150
+ baseOperationId: "agentsGetStats",
2151
+ method: "GET",
2152
+ tag: "Agents",
2153
+ auth: "none",
2154
+ summary: { en: "Get agent stats", zh: "\u8BFB\u53D6 Agent \u7EDF\u8BA1" },
2155
+ pathTemplate: "/v2/agents/{address}/stats",
2156
+ pathParamsSchema: addressPathSchema,
2157
+ responseSchema: agentStatsSchema.schema,
2158
+ responseComponent: agentStatsSchema,
2159
+ parameters: [pathStringParam("address", { en: "Agent address", zh: "Agent \u5730\u5740" }, { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" })],
2160
+ errorStatuses: [400, 500]
2161
+ }),
2162
+ defineOperationSpec({
2163
+ baseOperationId: "ledgerGet",
2164
+ method: "GET",
2165
+ tag: "Ledger",
2166
+ auth: "none",
2167
+ summary: { en: "Get ledger balance", zh: "\u8BFB\u53D6\u8D26\u672C\u4F59\u989D" },
2168
+ pathTemplate: "/v2/ledger/{address}",
2169
+ pathParamsSchema: addressPathSchema,
2170
+ responseSchema: ledgerBalanceSchema.schema,
2171
+ responseComponent: ledgerBalanceSchema,
2172
+ parameters: [pathStringParam("address", { en: "Agent address", zh: "Agent \u5730\u5740" }, { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" })],
2173
+ errorStatuses: [400, 500]
2174
+ }),
2175
+ defineOperationSpec({
2176
+ baseOperationId: "cyclesList",
2177
+ method: "GET",
2178
+ tag: "Cycles",
2179
+ auth: "none",
2180
+ summary: { en: "List cycles", zh: "\u67E5\u8BE2\u5468\u671F\u5217\u8868" },
2181
+ pathTemplate: "/v2/cycles",
2182
+ querySchema: cycleListQuerySchemaV2,
2183
+ responseSchema: paginatedCycleResponseSchema.schema,
2184
+ responseComponent: paginatedCycleResponseSchema,
2185
+ parameters: cycleListParametersV2,
2186
+ errorStatuses: [500]
2187
+ }),
2188
+ defineOperationSpec({
2189
+ baseOperationId: "cyclesGetActive",
2190
+ method: "GET",
2191
+ tag: "Cycles",
2192
+ auth: "none",
2193
+ summary: { en: "Get active cycle", zh: "\u8BFB\u53D6\u5F53\u524D\u5468\u671F" },
2194
+ pathTemplate: "/v2/cycles/active",
2195
+ responseSchema: cycleSchema.schema,
2196
+ responseComponent: cycleSchema,
2197
+ errorStatuses: [404, 500]
2198
+ }),
2199
+ defineOperationSpec({
2200
+ baseOperationId: "cyclesGet",
2201
+ method: "GET",
2202
+ tag: "Cycles",
2203
+ auth: "none",
2204
+ summary: { en: "Get cycle", zh: "\u8BFB\u53D6\u5468\u671F\u8BE6\u60C5" },
2205
+ pathTemplate: "/v2/cycles/{id}",
2206
+ pathParamsSchema: idPathSchema,
2207
+ responseSchema: cycleSchema.schema,
2208
+ responseComponent: cycleSchema,
2209
+ parameters: [pathStringParam("id", { en: "Cycle id", zh: "\u5468\u671F id" })],
2210
+ errorStatuses: [404, 500]
2211
+ }),
2212
+ defineOperationSpec({
2213
+ baseOperationId: "cyclesGetRewards",
2214
+ method: "GET",
2215
+ tag: "Cycles",
2216
+ auth: "none",
2217
+ summary: { en: "Get cycle rewards", zh: "\u8BFB\u53D6\u5468\u671F\u5956\u52B1\u89C6\u56FE" },
2218
+ pathTemplate: "/v2/cycles/{id}/rewards",
2219
+ pathParamsSchema: idPathSchema,
2220
+ responseSchema: cycleRewardsResponseSchema.schema,
2221
+ responseComponent: cycleRewardsResponseSchema,
2222
+ parameters: [pathStringParam("id", { en: "Cycle id", zh: "\u5468\u671F id" })],
2223
+ errorStatuses: [404, 500]
2224
+ }),
2225
+ defineOperationSpec({
2226
+ baseOperationId: "economyGetParams",
2227
+ method: "GET",
2228
+ tag: "Economy",
2229
+ auth: "none",
2230
+ summary: { en: "Get public economy params", zh: "\u8BFB\u53D6\u516C\u5F00\u7ECF\u6D4E\u53C2\u6570" },
2231
+ pathTemplate: "/v2/economy/params",
2232
+ responseSchema: publicEconomyParamsSchema.schema,
2233
+ responseComponent: publicEconomyParamsSchema,
2234
+ errorStatuses: [500]
2235
+ }),
2236
+ defineOperationSpec({
2237
+ baseOperationId: "adminCloseCycle",
2238
+ method: "POST",
2239
+ tag: "Admin",
2240
+ auth: "admin",
2241
+ summary: { en: "Close current cycle", zh: "\u5173\u95ED\u5F53\u524D\u5468\u671F" },
2242
+ pathTemplate: "/v2/admin/cycles/close",
2243
+ responseSchema: closeCycleResultSchema.schema,
2244
+ responseComponent: closeCycleResultSchema,
2245
+ errorStatuses: [401, 409, 500]
2246
+ }),
2247
+ defineOperationSpec({
2248
+ baseOperationId: "adminOverrideDispute",
2249
+ method: "POST",
2250
+ tag: "Admin",
2251
+ auth: "admin",
2252
+ summary: { en: "Override dispute", zh: "\u7BA1\u7406\u5458\u8986\u76D6\u4E89\u8BAE\u7ED3\u679C" },
2253
+ description: {
2254
+ en: "NOT_COMPLETED reopens dispute to OPEN. If another OPEN dispute already exists for the same submission, returns 409 OPEN_DISPUTE_ALREADY_EXISTS.",
2255
+ zh: "NOT_COMPLETED \u4F1A\u5C06\u4E89\u8BAE\u91CD\u5F00\u4E3A OPEN\u3002\u82E5\u540C\u4E00 submission \u5DF2\u5B58\u5728\u5176\u4ED6 OPEN \u4E89\u8BAE\uFF0C\u5219\u8FD4\u56DE 409 OPEN_DISPUTE_ALREADY_EXISTS\u3002"
2256
+ },
2257
+ pathTemplate: "/v2/admin/disputes/{id}/override",
2258
+ pathParamsSchema: idPathSchema,
2259
+ bodySchema: overrideDisputeRequestSchema.schema,
2260
+ requestBodyComponent: overrideDisputeRequestSchema,
2261
+ responseSchema: disputeSchema.schema,
2262
+ responseComponent: disputeSchema,
2263
+ parameters: [pathStringParam("id", { en: "Dispute id", zh: "\u4E89\u8BAE id" })],
2264
+ errorStatuses: [401, 404, 409, 500]
2265
+ }),
2266
+ defineOperationSpec({
2267
+ baseOperationId: "adminBridgeExport",
2268
+ method: "POST",
2269
+ tag: "Admin",
2270
+ auth: "admin",
2271
+ summary: { en: "Export bridge batch", zh: "\u5BFC\u51FA\u6865\u63A5\u6279\u6B21" },
2272
+ pathTemplate: "/v2/admin/bridge/export",
2273
+ bodySchema: bridgeExportRequestSchema.schema,
2274
+ requestBodyComponent: bridgeExportRequestSchema,
2275
+ responseSchema: bridgeExportResponseSchema.schema,
2276
+ responseComponent: bridgeExportResponseSchema,
2277
+ errorStatuses: [400, 401, 500]
2278
+ })
2279
+ ];
2280
+ var supportedApiVersions = [...new Set(apiOperations.map((operation) => operation.version))];
2281
+ var apiOperationsById = new Map(
2282
+ apiOperations.map((operation) => [operation.operationId, operation])
2283
+ );
2284
+ var getApiOperation = (operationId) => {
2285
+ const operation = apiOperationsById.get(operationId);
2286
+ if (!operation) {
2287
+ throw new Error(`unknown api operation: ${operationId}`);
2288
+ }
2289
+ return operation;
2290
+ };
2291
+ var buildOperationPath = (operation, input = {}) => {
2292
+ let path = operation.pathTemplate;
2293
+ if (input.pathParams) {
2294
+ for (const [key, value] of Object.entries(input.pathParams)) {
2295
+ path = path.replace(`{${key}}`, encodeURIComponent(String(value)));
2296
+ }
2297
+ }
2298
+ const query = new URLSearchParams();
2299
+ for (const [key, value] of Object.entries(input.query ?? {})) {
2300
+ if (value === void 0 || value === null) {
2301
+ continue;
2302
+ }
2303
+ query.set(key, String(value));
2304
+ }
2305
+ const suffix = query.toString();
2306
+ return suffix.length > 0 ? `${path}?${suffix}` : path;
2307
+ };
2308
+ var stripApiVersionPrefix = (path) => {
2309
+ const stripped = path.replace(/^\/v\d+(?=\/|$)/, "");
2310
+ return stripped.length > 0 ? stripped : "/";
2311
+ };
2312
+ var buildVersionlessOperationPath = (operation, input = {}) => stripApiVersionPrefix(buildOperationPath(operation, input));
2313
+
2314
+ // ../../packages/sdk/src/index.ts
2315
+ var ApiClientError = class extends Error {
2316
+ httpStatus;
2317
+ apiError;
2318
+ issues;
2319
+ retryable;
2320
+ responseBody;
2321
+ constructor(message, options = {}) {
2322
+ super(message);
2323
+ this.name = "ApiClientError";
2324
+ this.httpStatus = options.httpStatus ?? null;
2325
+ this.apiError = options.apiError ?? null;
2326
+ this.issues = options.issues ?? null;
2327
+ this.retryable = options.retryable ?? false;
2328
+ this.responseBody = options.responseBody ?? null;
2329
+ }
2330
+ };
2331
+ var DEFAULT_TIMEOUT_MS = 1e4;
2332
+ var DEFAULT_RETRIES = 1;
2333
+ var sleep = async (ms) => {
2334
+ await new Promise((resolve) => setTimeout(resolve, ms));
2335
+ };
2336
+ var shouldRetryStatus = (status) => status === 429 || status >= 500;
2337
+ var retryDelayMs = (attempt) => Math.min(1e3, 100 * 2 ** (attempt - 1));
2338
+ var isAbortError = (error) => error instanceof Error && error.name === "AbortError";
2339
+ var parseApiError = (body) => {
2340
+ if (!body || typeof body !== "object") {
2341
+ return null;
2342
+ }
2343
+ const envelope = body;
2344
+ if (typeof envelope.error === "string") {
2345
+ return {
2346
+ code: envelope.error,
2347
+ message: typeof envelope.message === "string" ? envelope.message : void 0,
2348
+ details: envelope.issues
2349
+ };
2350
+ }
2351
+ if (envelope.error && typeof envelope.error === "object") {
2352
+ const nested = envelope.error;
2353
+ if (typeof nested.code === "string") {
2354
+ return {
2355
+ code: nested.code,
2356
+ message: typeof nested.message === "string" ? nested.message : void 0,
2357
+ details: nested.details
2358
+ };
2359
+ }
2360
+ }
2361
+ return null;
2362
+ };
2363
+ var parseResponseBody = async (response) => {
2364
+ if (response.status === 204) {
2365
+ return null;
2366
+ }
2367
+ const text = await response.text();
2368
+ if (text.length === 0) {
2369
+ return null;
2370
+ }
2371
+ const contentType = response.headers.get("content-type") ?? "";
2372
+ if (contentType.includes("application/json")) {
2373
+ try {
2374
+ return JSON.parse(text);
2375
+ } catch {
2376
+ return text;
2377
+ }
2378
+ }
2379
+ return text;
2380
+ };
2381
+ var hasHeader = (headers, key) => {
2382
+ const lower = key.toLowerCase();
2383
+ return Object.keys(headers).some((header) => header.toLowerCase() === lower);
2384
+ };
2385
+ var AgentradeApiClient = class {
2386
+ baseUrl;
2387
+ token;
2388
+ adminKey;
2389
+ preferVersionlessPaths;
2390
+ timeoutMs;
2391
+ retries;
2392
+ fetchImpl;
2393
+ constructor(options) {
2394
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
2395
+ this.token = options.token;
2396
+ this.adminKey = options.adminKey;
2397
+ this.preferVersionlessPaths = options.preferVersionlessPaths ?? true;
2398
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2399
+ this.retries = options.retries ?? DEFAULT_RETRIES;
2400
+ this.fetchImpl = options.fetchImpl ?? fetch;
2401
+ }
2402
+ setToken(token) {
2403
+ this.token = token;
2404
+ }
2405
+ setAdminKey(adminKey) {
2406
+ this.adminKey = adminKey;
2407
+ }
2408
+ setTimeoutMs(timeoutMs) {
2409
+ this.timeoutMs = timeoutMs;
2410
+ }
2411
+ setRetries(retries) {
2412
+ this.retries = retries;
2413
+ }
2414
+ resolveAuthHeaders(auth) {
2415
+ if (auth === "bearer") {
2416
+ if (!this.token) {
2417
+ throw new ApiClientError("missing bearer token for authenticated request", {
2418
+ apiError: "MISSING_BEARER_TOKEN"
2419
+ });
2420
+ }
2421
+ return { authorization: `Bearer ${this.token}` };
2422
+ }
2423
+ if (auth === "admin") {
2424
+ if (!this.adminKey) {
2425
+ throw new ApiClientError("missing admin service key for admin request", {
2426
+ apiError: "MISSING_ADMIN_KEY"
2427
+ });
2428
+ }
2429
+ return { "x-admin-service-key": this.adminKey };
2430
+ }
2431
+ return {};
2432
+ }
2433
+ async requestRaw(options) {
2434
+ const retries = Math.max(0, options.retries ?? this.retries);
2435
+ const maxAttempts = retries + 1;
2436
+ const timeoutMs = Math.max(1, options.timeoutMs ?? this.timeoutMs);
2437
+ let lastError;
2438
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
2439
+ const controller = new AbortController();
2440
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
2441
+ try {
2442
+ const authHeaders = this.resolveAuthHeaders(options.auth);
2443
+ const headers = {
2444
+ ...authHeaders
2445
+ };
2446
+ let body;
2447
+ if (options.body !== void 0) {
2448
+ body = JSON.stringify(options.body);
2449
+ if (!hasHeader(headers, "content-type")) {
2450
+ headers["content-type"] = "application/json";
2451
+ }
2452
+ }
2453
+ const response = await this.fetchImpl(`${this.baseUrl}${options.path}`, {
2454
+ method: options.method,
2455
+ headers,
2456
+ body,
2457
+ signal: controller.signal
2458
+ });
2459
+ const payload = await parseResponseBody(response);
2460
+ if (!response.ok) {
2461
+ const envelope = parseApiError(payload);
2462
+ const retryable = shouldRetryStatus(response.status);
2463
+ if (retryable && attempt < maxAttempts) {
2464
+ await sleep(retryDelayMs(attempt));
2465
+ continue;
2466
+ }
2467
+ throw new ApiClientError(
2468
+ envelope?.message ?? `HTTP ${response.status} request failed`,
2469
+ {
2470
+ httpStatus: response.status,
2471
+ apiError: envelope?.code ?? null,
2472
+ issues: envelope?.details ?? null,
2473
+ retryable,
2474
+ responseBody: payload
2475
+ }
2476
+ );
2477
+ }
2478
+ return payload;
2479
+ } catch (error) {
2480
+ if (error instanceof ApiClientError) {
2481
+ throw error;
2482
+ }
2483
+ const retryable = isAbortError(error) || error instanceof TypeError;
2484
+ lastError = error;
2485
+ if (retryable && attempt < maxAttempts) {
2486
+ await sleep(retryDelayMs(attempt));
2487
+ continue;
2488
+ }
2489
+ throw new ApiClientError(
2490
+ error instanceof Error ? error.message : "network request failed",
2491
+ {
2492
+ retryable,
2493
+ responseBody: null
2494
+ }
2495
+ );
2496
+ } finally {
2497
+ clearTimeout(timer);
2498
+ }
2499
+ }
2500
+ throw new ApiClientError(lastError instanceof Error ? lastError.message : "request failed", {
2501
+ retryable: false
2502
+ });
2503
+ }
2504
+ async requestOperation(operationId, input = {}) {
2505
+ const operation = getApiOperation(operationId);
2506
+ const path = this.preferVersionlessPaths ? buildVersionlessOperationPath(operation, {
2507
+ pathParams: input.pathParams,
2508
+ query: input.query
2509
+ }) : buildOperationPath(operation, {
2510
+ pathParams: input.pathParams,
2511
+ query: input.query
2512
+ });
2513
+ const payload = await this.requestRaw({
2514
+ method: operation.method,
2515
+ path,
2516
+ auth: input.auth ?? operation.auth,
2517
+ body: input.body,
2518
+ timeoutMs: input.timeoutMs,
2519
+ retries: input.retries
2520
+ });
2521
+ return operation.responseSchema.parse(payload);
2522
+ }
2523
+ health() {
2524
+ return this.requestOperation("systemHealthV2");
2525
+ }
2526
+ metrics() {
2527
+ return this.requestOperation("systemMetricsV2");
2528
+ }
2529
+ authChallenge(payload) {
2530
+ return this.requestOperation("authChallengeV2", { body: payload });
2531
+ }
2532
+ authVerify(payload) {
2533
+ return this.requestOperation("authVerifyV2", { body: payload });
2534
+ }
2535
+ getTasks(params) {
2536
+ return this.requestOperation("tasksListV2", { query: params });
2537
+ }
2538
+ getTask(taskId) {
2539
+ return this.requestOperation("tasksGetV2", {
2540
+ pathParams: { id: taskId }
2541
+ });
2542
+ }
2543
+ createTask(payload) {
2544
+ return this.requestOperation("tasksCreateV2", {
2545
+ body: payload
2546
+ });
2547
+ }
2548
+ getTaskIntentions(taskId, params) {
2549
+ return this.requestOperation("tasksListIntentionsV2", {
2550
+ pathParams: { id: taskId },
2551
+ query: params
2552
+ });
2553
+ }
2554
+ addTaskIntention(taskId) {
2555
+ return this.requestOperation("tasksAddIntentionV2", {
2556
+ pathParams: { id: taskId }
2557
+ });
2558
+ }
2559
+ submitTask(taskId, payload) {
2560
+ return this.requestOperation("tasksSubmitV2", {
2561
+ pathParams: { id: taskId },
2562
+ body: payload
2563
+ });
2564
+ }
2565
+ terminateTask(taskId) {
2566
+ return this.requestOperation("tasksTerminateV2", {
2567
+ pathParams: { id: taskId }
2568
+ });
2569
+ }
2570
+ confirmSubmission(submissionId) {
2571
+ return this.requestOperation("submissionsConfirmV2", {
2572
+ pathParams: { id: submissionId }
2573
+ });
2574
+ }
2575
+ rejectSubmission(submissionId) {
2576
+ return this.requestOperation("submissionsRejectV2", {
2577
+ pathParams: { id: submissionId }
2578
+ });
2579
+ }
2580
+ getSubmissions(params) {
2581
+ return this.requestOperation("submissionsListV2", {
2582
+ query: params
2583
+ });
2584
+ }
2585
+ getSubmission(submissionId) {
2586
+ return this.requestOperation("submissionsGetV2", {
2587
+ pathParams: { id: submissionId }
2588
+ });
2589
+ }
2590
+ getDisputes(params) {
2591
+ return this.requestOperation("disputesListV2", {
2592
+ query: params
2593
+ });
2594
+ }
2595
+ getDispute(disputeId) {
2596
+ return this.requestOperation("disputesGetV2", {
2597
+ pathParams: { id: disputeId }
2598
+ });
2599
+ }
2600
+ openDispute(payload) {
2601
+ return this.requestOperation("disputesOpenV2", {
2602
+ body: payload
2603
+ });
2604
+ }
2605
+ voteDispute(disputeId, payload) {
2606
+ return this.requestOperation("disputesVoteV2", {
2607
+ pathParams: { id: disputeId },
2608
+ body: payload
2609
+ });
2610
+ }
2611
+ getAgentProfile(address) {
2612
+ return this.requestOperation("agentsGetProfileV2", {
2613
+ pathParams: { address }
2614
+ });
2615
+ }
2616
+ getAgents(params) {
2617
+ return this.requestOperation("agentsListV2", {
2618
+ query: params
2619
+ });
2620
+ }
2621
+ updateAgentProfile(address, payload) {
2622
+ return this.requestOperation("agentsUpdateProfileV2", {
2623
+ pathParams: { address },
2624
+ body: payload
2625
+ });
2626
+ }
2627
+ getAgentStats(address) {
2628
+ return this.requestOperation("agentsGetStatsV2", {
2629
+ pathParams: { address }
2630
+ });
2631
+ }
2632
+ getActivities(params) {
2633
+ return this.requestOperation("activitiesListV2", {
2634
+ query: params
2635
+ });
2636
+ }
2637
+ getDashboardSummary(params) {
2638
+ return this.requestOperation("dashboardSummaryV2", {
2639
+ query: params
2640
+ });
2641
+ }
2642
+ getDashboardTrends(params) {
2643
+ return this.requestOperation("dashboardTrendsV2", {
2644
+ query: params
2645
+ });
2646
+ }
2647
+ getLedger(address) {
2648
+ return this.requestOperation("ledgerGetV2", {
2649
+ pathParams: { address }
2650
+ });
2651
+ }
2652
+ getCycles(params) {
2653
+ return this.requestOperation("cyclesListV2", {
2654
+ query: params
2655
+ });
2656
+ }
2657
+ getActiveCycle() {
2658
+ return this.requestOperation("cyclesGetActiveV2");
2659
+ }
2660
+ getCycle(cycleId) {
2661
+ return this.requestOperation("cyclesGetV2", {
2662
+ pathParams: { id: cycleId }
2663
+ });
2664
+ }
2665
+ getCycleRewards(cycleId) {
2666
+ return this.requestOperation("cyclesGetRewardsV2", {
2667
+ pathParams: { id: cycleId }
2668
+ });
2669
+ }
2670
+ getEconomyParams() {
2671
+ return this.requestOperation("economyGetParamsV2");
2672
+ }
2673
+ closeCurrentCycleAdmin() {
2674
+ return this.requestOperation("adminCloseCycleV2");
2675
+ }
2676
+ overrideDisputeAdmin(disputeId, payload) {
2677
+ return this.requestOperation("adminOverrideDisputeV2", {
2678
+ pathParams: { id: disputeId },
2679
+ body: payload
2680
+ });
2681
+ }
2682
+ exportBridgeBatchAdmin(payload = {}) {
2683
+ return this.requestOperation("adminBridgeExportV2", {
2684
+ body: payload
2685
+ });
2686
+ }
2687
+ };
2688
+
2689
+ // src/context.ts
2690
+ var resolveCommandPath = (command) => {
2691
+ const segments = [];
2692
+ let cursor = command;
2693
+ while (cursor && cursor.name() !== "agentrade") {
2694
+ segments.push(cursor.name());
2695
+ cursor = cursor.parent ?? null;
2696
+ }
2697
+ return segments.reverse().join(" ");
2698
+ };
2699
+ var normalizeOptional = (value) => {
2700
+ if (!value) {
2701
+ return void 0;
2702
+ }
2703
+ return value.trim().length > 0 ? value : void 0;
2704
+ };
2705
+ var resolveGlobalOptions = (command) => {
2706
+ const raw = command.optsWithGlobals();
2707
+ const rawBaseUrl = normalizeOptional(raw.baseUrl);
2708
+ if (!rawBaseUrl) {
2709
+ throw new CliConfigError("--base-url is required");
2710
+ }
2711
+ const baseUrl = ensureHttpUrl(rawBaseUrl, "--base-url");
2712
+ const timeoutMs = typeof raw.timeoutMs === "number" ? raw.timeoutMs : ensurePositiveInteger(String(raw.timeoutMs ?? "10000"), "--timeout-ms");
2713
+ const retries = typeof raw.retries === "number" ? raw.retries : ensureNonNegativeInteger(String(raw.retries ?? "1"), "--retries");
2714
+ return {
2715
+ baseUrl,
2716
+ token: normalizeOptional(raw.token),
2717
+ adminKey: normalizeOptional(raw.adminKey),
2718
+ timeoutMs,
2719
+ retries,
2720
+ pretty: Boolean(raw.pretty)
2721
+ };
2722
+ };
2723
+ var createCommandContext = (command) => {
2724
+ const options = resolveGlobalOptions(command);
2725
+ const client = new AgentradeApiClient({
2726
+ baseUrl: options.baseUrl,
2727
+ token: options.token,
2728
+ adminKey: options.adminKey,
2729
+ timeoutMs: options.timeoutMs,
2730
+ retries: options.retries
2731
+ });
2732
+ return {
2733
+ commandPath: resolveCommandPath(command),
2734
+ options,
2735
+ client,
2736
+ requireToken: () => {
2737
+ if (!options.token) {
2738
+ throw new CliConfigError("missing token: use --token or AGENTRADE_TOKEN");
2739
+ }
2740
+ return options.token;
2741
+ },
2742
+ requireAdminKey: () => {
2743
+ if (!options.adminKey) {
2744
+ throw new CliConfigError("missing admin key: use --admin-key or AGENTRADE_ADMIN_SERVICE_KEY");
2745
+ }
2746
+ return options.adminKey;
2747
+ }
2748
+ };
2749
+ };
2750
+
2751
+ // src/output.ts
2752
+ var isCommanderError = (error) => {
2753
+ if (!error || typeof error !== "object") {
2754
+ return false;
2755
+ }
2756
+ const value = error;
2757
+ return typeof value.message === "string" && typeof value.code === "string" && value.code.startsWith("commander.");
2758
+ };
2759
+ var shouldSuppressCommanderError = (error) => {
2760
+ if (!isCommanderError(error)) {
2761
+ return false;
2762
+ }
2763
+ const exitCode = Number(error.exitCode ?? 1);
2764
+ return error.code === "commander.helpDisplayed" || exitCode === 0;
2765
+ };
2766
+ var messageOf = (error) => {
2767
+ if (error instanceof Error) {
2768
+ return error.message;
2769
+ }
2770
+ return String(error);
2771
+ };
2772
+ var commandFromError = (error) => {
2773
+ if (!error || typeof error !== "object") {
2774
+ return void 0;
2775
+ }
2776
+ const value = error;
2777
+ return typeof value.commandPath === "string" ? value.commandPath : void 0;
2778
+ };
2779
+ var printJson = (value, pretty) => {
2780
+ process.stdout.write(`${JSON.stringify(value, null, pretty ? 2 : 0)}
2781
+ `);
2782
+ };
2783
+ var printErrorJson = (value) => {
2784
+ process.stderr.write(`${JSON.stringify(value)}
2785
+ `);
2786
+ };
2787
+ var normalizeCliError = (error, fallbackCommand) => {
2788
+ const command = commandFromError(error) ?? fallbackCommand;
2789
+ if (error instanceof CliValidationError || isCommanderError(error)) {
2790
+ return {
2791
+ output: {
2792
+ type: "VALIDATION_ERROR",
2793
+ message: messageOf(error),
2794
+ httpStatus: null,
2795
+ apiError: null,
2796
+ issues: null,
2797
+ retryable: false,
2798
+ command
2799
+ },
2800
+ exitCode: 2 /* VALIDATION */
2801
+ };
2802
+ }
2803
+ if (error instanceof CliConfigError) {
2804
+ return {
2805
+ output: {
2806
+ type: "CONFIG_ERROR",
2807
+ message: error.message,
2808
+ httpStatus: null,
2809
+ apiError: null,
2810
+ issues: null,
2811
+ retryable: false,
2812
+ command
2813
+ },
2814
+ exitCode: 3 /* CONFIG */
2815
+ };
2816
+ }
2817
+ if (error instanceof ApiClientError) {
2818
+ if (error.apiError === "MISSING_BEARER_TOKEN" || error.apiError === "MISSING_ADMIN_KEY") {
2819
+ return {
2820
+ output: {
2821
+ type: "CONFIG_ERROR",
2822
+ message: error.message,
2823
+ httpStatus: null,
2824
+ apiError: error.apiError,
2825
+ issues: error.issues,
2826
+ retryable: false,
2827
+ command
2828
+ },
2829
+ exitCode: 3 /* CONFIG */
2830
+ };
2831
+ }
2832
+ if (error.httpStatus !== null) {
2833
+ return {
2834
+ output: {
2835
+ type: "API_ERROR",
2836
+ message: error.message,
2837
+ httpStatus: error.httpStatus,
2838
+ apiError: error.apiError,
2839
+ issues: error.issues,
2840
+ retryable: error.retryable,
2841
+ command
2842
+ },
2843
+ exitCode: 4 /* API */
2844
+ };
2845
+ }
2846
+ return {
2847
+ output: {
2848
+ type: "NETWORK_ERROR",
2849
+ message: error.message,
2850
+ httpStatus: null,
2851
+ apiError: error.apiError,
2852
+ issues: error.issues,
2853
+ retryable: error.retryable,
2854
+ command
2855
+ },
2856
+ exitCode: 5 /* NETWORK */
2857
+ };
2858
+ }
2859
+ return {
2860
+ output: {
2861
+ type: "UNKNOWN_ERROR",
2862
+ message: messageOf(error),
2863
+ httpStatus: null,
2864
+ apiError: null,
2865
+ issues: null,
2866
+ retryable: false,
2867
+ command
2868
+ },
2869
+ exitCode: 10 /* UNKNOWN */
2870
+ };
2871
+ };
2872
+
2873
+ // src/commands/shared.ts
2874
+ var enrichErrorWithCommandPath = (error, commandPath) => {
2875
+ if (!error || typeof error !== "object") {
2876
+ return;
2877
+ }
2878
+ const enriched = error;
2879
+ if (!enriched.commandPath) {
2880
+ enriched.commandPath = commandPath;
2881
+ }
2882
+ };
2883
+ var executeJsonCommand = async (command, handler) => {
2884
+ const ctx = createCommandContext(command);
2885
+ try {
2886
+ const result = await handler(ctx);
2887
+ printJson(result, ctx.options.pretty);
2888
+ } catch (error) {
2889
+ enrichErrorWithCommandPath(error, ctx.commandPath);
2890
+ throw error;
2891
+ }
2892
+ };
2893
+ var executeOperationCommand = async (command, operationId, buildInput) => {
2894
+ await executeJsonCommand(command, async (ctx) => {
2895
+ const input = buildInput ? await buildInput(ctx) : {};
2896
+ return ctx.client.requestOperation(operationId, input);
2897
+ });
2898
+ };
2899
+ var executeBearerOperationCommand = async (command, operationId, buildInput) => {
2900
+ await executeJsonCommand(command, async (ctx) => {
2901
+ ctx.requireToken();
2902
+ const input = buildInput ? await buildInput(ctx) : {};
2903
+ return ctx.client.requestOperation(operationId, input);
2904
+ });
2905
+ };
2906
+ var executeAdminOperationCommand = async (command, operationId, buildInput) => {
2907
+ await executeJsonCommand(command, async (ctx) => {
2908
+ ctx.requireAdminKey();
2909
+ const input = buildInput ? await buildInput(ctx) : {};
2910
+ return ctx.client.requestOperation(operationId, input);
2911
+ });
2912
+ };
2913
+
2914
+ // src/commands/admin.ts
2915
+ var registerAdminCommands = (program) => {
2916
+ const admin = program.command("admin").description("Admin-only commands");
2917
+ const adminCycles = admin.command("cycles").description("Cycle admin commands");
2918
+ adminCycles.command("close").description("Close current cycle").action(async (_options, command) => {
2919
+ await executeAdminOperationCommand(command, cliOperationBindings["admin cycles close"]);
2920
+ });
2921
+ const adminDisputes = admin.command("disputes").description("Dispute admin commands");
2922
+ adminDisputes.command("override").description("Override dispute result").requiredOption("--dispute <id>", "dispute id").requiredOption("--result <result>", "COMPLETED or NOT_COMPLETED").action(async (options, command) => {
2923
+ await executeAdminOperationCommand(command, cliOperationBindings["admin disputes override"], async () => ({
2924
+ pathParams: { id: ensureNonEmpty(String(options.dispute), "--dispute") },
2925
+ body: {
2926
+ result: ensureOverrideResult(String(options.result))
2927
+ }
2928
+ }));
2929
+ });
2930
+ const adminBridge = admin.command("bridge").description("Bridge export commands");
2931
+ adminBridge.command("export").description("Export bridge balances").option("--addresses <list>", "comma or whitespace separated addresses").option("--addresses-file <path>", "file containing comma or whitespace separated addresses").action(async (options, command) => {
2932
+ await executeAdminOperationCommand(command, cliOperationBindings["admin bridge export"], async () => {
2933
+ const rawAddresses = resolveTextInput({
2934
+ inlineValue: options.addresses,
2935
+ filePath: options.addressesFile,
2936
+ fieldName: "addresses",
2937
+ required: false,
2938
+ allowEmpty: true
2939
+ });
2940
+ const addresses = parseOptionalAddressList(rawAddresses, "--addresses");
2941
+ return {
2942
+ body: addresses ? { addresses } : {}
2943
+ };
2944
+ });
2945
+ });
2946
+ };
2947
+
2948
+ // src/commands/activities.ts
2949
+ var ensureActivityType = (raw) => {
2950
+ const normalized = raw.trim().toUpperCase();
2951
+ if (!Object.values(ActivityEventType).includes(normalized)) {
2952
+ throw new CliValidationError(
2953
+ "--type must be TASK_PUBLISHED|TASK_INTENDED|TASK_SUBMITTED|SUBMISSION_REJECTED|TASK_COMPLETED|DISPUTE_OPENED|TASK_TERMINATED"
2954
+ );
2955
+ }
2956
+ return normalized;
2957
+ };
2958
+ var registerActivityCommands = (program) => {
2959
+ const activities = program.command("activities").description("Activity timeline commands");
2960
+ activities.command("list").description("List activity events").option("--task <id>", "filter by task id").option("--dispute <id>", "filter by dispute id").option("--address <address>", "filter by actor address").option(
2961
+ "--type <type>",
2962
+ "TASK_PUBLISHED|TASK_INTENDED|TASK_SUBMITTED|SUBMISSION_REJECTED|TASK_COMPLETED|DISPUTE_OPENED|TASK_TERMINATED"
2963
+ ).option("--order <order>", "asc|desc").option("--cursor <offset>", "pagination cursor").option("--limit <number>", "page size").action(async (options, command) => {
2964
+ await executeOperationCommand(command, cliOperationBindings["activities list"], async () => {
2965
+ const type = typeof options.type === "string" ? ensureActivityType(options.type) : void 0;
2966
+ return {
2967
+ query: {
2968
+ taskId: typeof options.task === "string" ? ensureNonEmpty(options.task, "--task") : void 0,
2969
+ disputeId: typeof options.dispute === "string" ? ensureNonEmpty(options.dispute, "--dispute") : void 0,
2970
+ address: typeof options.address === "string" ? ensureAddress(options.address, "--address") : void 0,
2971
+ type,
2972
+ order: typeof options.order === "string" ? options.order.trim().toLowerCase() : void 0,
2973
+ cursor: typeof options.cursor === "string" ? ensureNonEmpty(options.cursor, "--cursor") : void 0,
2974
+ limit: typeof options.limit === "string" ? ensurePositiveInteger(options.limit, "--limit") : void 0
2975
+ }
2976
+ };
2977
+ });
2978
+ });
2979
+ };
2980
+
2981
+ // src/commands/agents.ts
2982
+ var registerAgentCommands = (program) => {
2983
+ const agents = program.command("agents").description("Agent profile and stats commands");
2984
+ agents.command("list").description("List agents").option("--q <text>", "search by address/name/bio").option("--active-only", "only include active agents").option("--sort <key>", "latest|score|reputation|completed|published|intented").option("--order <order>", "asc|desc").option("--cursor <offset>", "pagination cursor").option("--limit <number>", "page size").action(async (options, command) => {
2985
+ await executeOperationCommand(command, cliOperationBindings["agents list"], async () => ({
2986
+ query: {
2987
+ q: typeof options.q === "string" ? ensureNonEmpty(options.q, "--q") : void 0,
2988
+ activeOnly: options.activeOnly ? true : void 0,
2989
+ sort: typeof options.sort === "string" ? options.sort.trim().toLowerCase() : void 0,
2990
+ order: typeof options.order === "string" ? options.order.trim().toLowerCase() : void 0,
2991
+ cursor: typeof options.cursor === "string" ? ensureNonEmpty(options.cursor, "--cursor") : void 0,
2992
+ limit: typeof options.limit === "string" ? ensurePositiveInteger(options.limit, "--limit") : void 0
2993
+ }
2994
+ }));
2995
+ });
2996
+ const profile = agents.command("profile").description("Agent profile commands");
2997
+ profile.command("get").description("Get agent profile").requiredOption("--address <address>", "agent address").action(async (options, command) => {
2998
+ await executeOperationCommand(command, cliOperationBindings["agents profile get"], async () => ({
2999
+ pathParams: { address: ensureAddress(String(options.address), "--address") }
3000
+ }));
3001
+ });
3002
+ profile.command("update").description("Update own profile").requiredOption("--address <address>", "agent address").option("--name <text>", "profile display name").option("--name-file <path>", "file containing profile display name").option("--bio <text>", "profile bio").option("--bio-file <path>", "file containing profile bio").action(async (options, command) => {
3003
+ await executeBearerOperationCommand(command, cliOperationBindings["agents profile update"], async () => {
3004
+ const name = resolveTextInput({
3005
+ inlineValue: options.name,
3006
+ filePath: options.nameFile,
3007
+ fieldName: "name",
3008
+ required: false,
3009
+ allowEmpty: true
3010
+ });
3011
+ const bio = resolveTextInput({
3012
+ inlineValue: options.bio,
3013
+ filePath: options.bioFile,
3014
+ fieldName: "bio",
3015
+ required: false,
3016
+ allowEmpty: true
3017
+ });
3018
+ if (name === void 0 && bio === void 0) {
3019
+ throw new CliValidationError("at least one of --name/--name-file or --bio/--bio-file must be provided");
3020
+ }
3021
+ return {
3022
+ pathParams: { address: ensureAddress(String(options.address), "--address") },
3023
+ body: {
3024
+ ...name !== void 0 ? { name } : {},
3025
+ ...bio !== void 0 ? { bio } : {}
3026
+ }
3027
+ };
3028
+ });
3029
+ });
3030
+ agents.command("stats").description("Get agent stats").requiredOption("--address <address>", "agent address").action(async (options, command) => {
3031
+ await executeOperationCommand(command, cliOperationBindings["agents stats"], async () => ({
3032
+ pathParams: { address: ensureAddress(String(options.address), "--address") }
3033
+ }));
3034
+ });
3035
+ };
3036
+
3037
+ // src/commands/auth.ts
3038
+ import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
3039
+ var registerAuthCommands = (program) => {
3040
+ const auth = program.command("auth").description("Authentication commands");
3041
+ const privateKeySecurityNotice = "PRIVATE KEY IS DISPLAYED ONLY ONCE. SAVE IT SECURELY NOW. NEVER SHARE, LOG, COMMIT, OR SCREENSHOT THIS KEY.";
3042
+ auth.command("challenge").description("Request SIWE challenge message").requiredOption("--address <address>", "wallet address").action(async (options, command) => {
3043
+ await executeOperationCommand(command, cliOperationBindings["auth challenge"], async () => ({
3044
+ body: {
3045
+ address: ensureAddress(String(options.address), "--address")
3046
+ }
3047
+ }));
3048
+ });
3049
+ auth.command("register").description("Create wallet, run SIWE challenge+verify, and return JWT (private key shown once)").action(async (_, command) => {
3050
+ await executeJsonCommand(command, async (ctx) => {
3051
+ const privateKey = generatePrivateKey();
3052
+ const account = privateKeyToAccount(privateKey);
3053
+ const challenge = await ctx.client.authChallenge({
3054
+ address: account.address
3055
+ });
3056
+ const signature = await account.signMessage({
3057
+ message: challenge.message
3058
+ });
3059
+ const verified = await ctx.client.authVerify({
3060
+ address: account.address,
3061
+ nonce: challenge.nonce,
3062
+ signature,
3063
+ message: challenge.message
3064
+ });
3065
+ return {
3066
+ wallet: {
3067
+ address: account.address,
3068
+ privateKey
3069
+ },
3070
+ auth: {
3071
+ token: verified.token,
3072
+ expiresIn: verified.expiresIn
3073
+ },
3074
+ securityNotice: {
3075
+ level: "CRITICAL",
3076
+ message: privateKeySecurityNotice
3077
+ }
3078
+ };
3079
+ });
3080
+ });
3081
+ auth.command("verify").description("Verify SIWE signature and receive JWT").requiredOption("--address <address>", "wallet address").requiredOption("--nonce <nonce>", "challenge nonce").requiredOption("--signature <signature>", "wallet signature").option("--message <text>", "challenge message text").option("--message-file <path>", "file containing challenge message").action(async (options, command) => {
3082
+ await executeOperationCommand(command, cliOperationBindings["auth verify"], async () => {
3083
+ const address = ensureAddress(String(options.address), "--address");
3084
+ const nonce = ensureNonEmpty(String(options.nonce), "--nonce");
3085
+ const signature = ensureNonEmpty(String(options.signature), "--signature");
3086
+ const message = resolveTextInput({
3087
+ inlineValue: options.message,
3088
+ filePath: options.messageFile,
3089
+ fieldName: "message"
3090
+ });
3091
+ return {
3092
+ body: {
3093
+ address,
3094
+ nonce,
3095
+ signature,
3096
+ message: String(message)
3097
+ }
3098
+ };
3099
+ });
3100
+ });
3101
+ };
3102
+
3103
+ // src/commands/cycles.ts
3104
+ var registerCycleCommands = (program) => {
3105
+ const cycles = program.command("cycles").description("Cycle and settlement visibility commands");
3106
+ cycles.command("list").description("List cycles").option("--cursor <offset>", "pagination cursor").option("--limit <number>", "page size").action(async (options, command) => {
3107
+ await executeOperationCommand(command, cliOperationBindings["cycles list"], async () => ({
3108
+ query: {
3109
+ cursor: typeof options.cursor === "string" ? ensureNonEmpty(options.cursor, "--cursor") : void 0,
3110
+ limit: typeof options.limit === "string" ? ensurePositiveInteger(options.limit, "--limit") : void 0
3111
+ }
3112
+ }));
3113
+ });
3114
+ cycles.command("active").description("Get active cycle").action(async (_options, command) => {
3115
+ await executeOperationCommand(command, cliOperationBindings["cycles active"]);
3116
+ });
3117
+ cycles.command("get").description("Get cycle details").requiredOption("--cycle <id>", "cycle id").action(async (options, command) => {
3118
+ await executeOperationCommand(command, cliOperationBindings["cycles get"], async () => ({
3119
+ pathParams: { id: ensureNonEmpty(String(options.cycle), "--cycle") }
3120
+ }));
3121
+ });
3122
+ cycles.command("rewards").description("Get cycle workload and reward references").requiredOption("--cycle <id>", "cycle id").action(async (options, command) => {
3123
+ await executeOperationCommand(command, cliOperationBindings["cycles rewards"], async () => ({
3124
+ pathParams: { id: ensureNonEmpty(String(options.cycle), "--cycle") }
3125
+ }));
3126
+ });
3127
+ };
3128
+
3129
+ // src/commands/dashboard.ts
3130
+ var ensureTrendWindow = (raw) => {
3131
+ const normalized = raw.trim().toLowerCase();
3132
+ if (normalized !== "7d" && normalized !== "30d") {
3133
+ throw new CliValidationError("--window must be 7d or 30d");
3134
+ }
3135
+ return normalized;
3136
+ };
3137
+ var registerDashboardCommands = (program) => {
3138
+ const dashboard = program.command("dashboard").description("Dashboard read models");
3139
+ dashboard.command("summary").description("Get dashboard summary metrics").option("--tz <timezone>", "IANA timezone, e.g. Asia/Shanghai").action(async (options, command) => {
3140
+ await executeOperationCommand(command, cliOperationBindings["dashboard summary"], async () => ({
3141
+ query: {
3142
+ tz: typeof options.tz === "string" ? ensureIanaTimeZone(options.tz, "--tz") : void 0
3143
+ }
3144
+ }));
3145
+ });
3146
+ dashboard.command("trends").description("Get dashboard trend series").option("--tz <timezone>", "IANA timezone, e.g. Asia/Shanghai").option("--window <window>", "7d|30d").action(async (options, command) => {
3147
+ await executeOperationCommand(command, cliOperationBindings["dashboard trends"], async () => ({
3148
+ query: {
3149
+ tz: typeof options.tz === "string" ? ensureIanaTimeZone(options.tz, "--tz") : void 0,
3150
+ window: typeof options.window === "string" ? ensureTrendWindow(options.window) : void 0
3151
+ }
3152
+ }));
3153
+ });
3154
+ };
3155
+
3156
+ // src/commands/disputes.ts
3157
+ var ensureDisputeStatus = (raw) => {
3158
+ const normalized = raw.trim().toUpperCase();
3159
+ if (normalized !== "OPEN" && normalized !== "RESOLVED_COMPLETED") {
3160
+ throw new CliValidationError("--status must be OPEN|RESOLVED_COMPLETED");
3161
+ }
3162
+ return normalized;
3163
+ };
3164
+ var registerDisputeCommands = (program) => {
3165
+ const disputes = program.command("disputes").description("Dispute and supervision commands");
3166
+ disputes.command("list").description("List disputes").option("--task <id>", "task id").option("--opener <address>", "opener address").option("--status <status>", "OPEN|RESOLVED_COMPLETED").option("--q <text>", "search by ids/opener/reason").option("--sort <key>", "latest|created").option("--order <order>", "asc|desc").option("--cursor <offset>", "pagination cursor").option("--limit <number>", "page size").action(async (options, command) => {
3167
+ await executeOperationCommand(command, cliOperationBindings["disputes list"], async () => ({
3168
+ query: {
3169
+ taskId: typeof options.task === "string" ? ensureNonEmpty(options.task, "--task") : void 0,
3170
+ opener: typeof options.opener === "string" ? ensureAddress(options.opener, "--opener") : void 0,
3171
+ status: typeof options.status === "string" ? ensureDisputeStatus(options.status) : void 0,
3172
+ q: typeof options.q === "string" ? ensureNonEmpty(options.q, "--q") : void 0,
3173
+ sort: typeof options.sort === "string" ? options.sort.trim().toLowerCase() : void 0,
3174
+ order: typeof options.order === "string" ? options.order.trim().toLowerCase() : void 0,
3175
+ cursor: typeof options.cursor === "string" ? ensureNonEmpty(options.cursor, "--cursor") : void 0,
3176
+ limit: typeof options.limit === "string" ? ensurePositiveInteger(options.limit, "--limit") : void 0
3177
+ }
3178
+ }));
3179
+ });
3180
+ disputes.command("get").description("Get dispute details").requiredOption("--dispute <id>", "dispute id").action(async (options, command) => {
3181
+ await executeOperationCommand(command, cliOperationBindings["disputes get"], async () => ({
3182
+ pathParams: { id: ensureNonEmpty(String(options.dispute), "--dispute") }
3183
+ }));
3184
+ });
3185
+ disputes.command("open").description("Open a dispute").requiredOption("--task <id>", "task id").requiredOption("--submission <id>", "submission id").option("--reason <markdown>", "reason markdown").option("--reason-file <path>", "file containing dispute reason markdown").action(async (options, command) => {
3186
+ await executeBearerOperationCommand(command, cliOperationBindings["disputes open"], async () => {
3187
+ const reasonMd = resolveTextInput({
3188
+ inlineValue: options.reason,
3189
+ filePath: options.reasonFile,
3190
+ fieldName: "reason"
3191
+ });
3192
+ return {
3193
+ body: {
3194
+ taskId: ensureNonEmpty(String(options.task), "--task"),
3195
+ submissionId: ensureNonEmpty(String(options.submission), "--submission"),
3196
+ reasonMd: String(reasonMd)
3197
+ }
3198
+ };
3199
+ });
3200
+ });
3201
+ disputes.command("vote").description("Vote on a dispute").requiredOption("--dispute <id>", "dispute id").requiredOption("--vote <choice>", "COMPLETED or NOT_COMPLETED").action(async (options, command) => {
3202
+ await executeBearerOperationCommand(command, cliOperationBindings["disputes vote"], async () => ({
3203
+ pathParams: { id: ensureNonEmpty(String(options.dispute), "--dispute") },
3204
+ body: {
3205
+ vote: ensureVoteChoice(String(options.vote))
3206
+ }
3207
+ }));
3208
+ });
3209
+ };
3210
+
3211
+ // src/commands/economy.ts
3212
+ var registerEconomyCommands = (program) => {
3213
+ const economy = program.command("economy").description("Runtime economy parameters");
3214
+ economy.command("params").description("Get economy and guardrail parameters").action(async (_options, command) => {
3215
+ await executeOperationCommand(command, cliOperationBindings["economy params"]);
3216
+ });
3217
+ };
3218
+
3219
+ // src/commands/ledger.ts
3220
+ var registerLedgerCommands = (program) => {
3221
+ const ledger = program.command("ledger").description("Ledger commands");
3222
+ ledger.command("get").description("Get ledger balance for an address").requiredOption("--address <address>", "agent address").action(async (options, command) => {
3223
+ await executeOperationCommand(command, cliOperationBindings["ledger get"], async () => ({
3224
+ pathParams: { address: ensureAddress(String(options.address), "--address") }
3225
+ }));
3226
+ });
3227
+ };
3228
+
3229
+ // src/commands/submissions.ts
3230
+ var registerSubmissionCommands = (program) => {
3231
+ const submissions = program.command("submissions").description("Submission query and moderation commands");
3232
+ submissions.command("list").description("List submissions").option("--task <id>", "task id").option("--agent <address>", "submission agent address").option("--status <status>", "SUBMITTED|CONFIRMED|REJECTED").option("--q <text>", "search by id/agent/payload").option("--sort <key>", "latest|created").option("--order <order>", "asc|desc").option("--cursor <cursor>", "pagination cursor").option("--limit <number>", "page size").action(async (options, command) => {
3233
+ await executeOperationCommand(command, cliOperationBindings["submissions list"], async () => ({
3234
+ query: {
3235
+ taskId: typeof options.task === "string" ? ensureNonEmpty(options.task, "--task") : void 0,
3236
+ agent: typeof options.agent === "string" ? ensureAddress(options.agent, "--agent") : void 0,
3237
+ status: typeof options.status === "string" ? options.status.trim().toUpperCase() : void 0,
3238
+ q: typeof options.q === "string" ? ensureNonEmpty(options.q, "--q") : void 0,
3239
+ sort: typeof options.sort === "string" ? options.sort.trim().toLowerCase() : void 0,
3240
+ order: typeof options.order === "string" ? options.order.trim().toLowerCase() : void 0,
3241
+ cursor: typeof options.cursor === "string" ? ensureNonEmpty(options.cursor, "--cursor") : void 0,
3242
+ limit: typeof options.limit === "string" ? ensurePositiveInteger(options.limit, "--limit") : void 0
3243
+ }
3244
+ }));
3245
+ });
3246
+ submissions.command("get").description("Get submission details").requiredOption("--submission <id>", "submission id").action(async (options, command) => {
3247
+ await executeOperationCommand(command, cliOperationBindings["submissions get"], async () => ({
3248
+ pathParams: { id: ensureNonEmpty(String(options.submission), "--submission") }
3249
+ }));
3250
+ });
3251
+ submissions.command("confirm").description("Confirm a submission").requiredOption("--submission <id>", "submission id").action(async (options, command) => {
3252
+ await executeBearerOperationCommand(command, cliOperationBindings["submissions confirm"], async () => ({
3253
+ pathParams: { id: ensureNonEmpty(String(options.submission), "--submission") }
3254
+ }));
3255
+ });
3256
+ submissions.command("reject").description("Reject a submission").requiredOption("--submission <id>", "submission id").action(async (options, command) => {
3257
+ await executeBearerOperationCommand(command, cliOperationBindings["submissions reject"], async () => ({
3258
+ pathParams: { id: ensureNonEmpty(String(options.submission), "--submission") }
3259
+ }));
3260
+ });
3261
+ };
3262
+
3263
+ // src/commands/system.ts
3264
+ var registerSystemCommands = (program) => {
3265
+ const system = program.command("system").description("System and service commands");
3266
+ system.command("health").description("Get API health status").action(async (_options, command) => {
3267
+ await executeOperationCommand(command, cliOperationBindings["system health"]);
3268
+ });
3269
+ };
3270
+
3271
+ // src/commands/tasks.ts
3272
+ var registerTaskCommands = (program) => {
3273
+ const tasks = program.command("tasks").description("Task lifecycle commands");
3274
+ tasks.command("list").description("List tasks").option("--q <text>", "search by id/title/description/criteria/publisher").option("--status <status>", "OPEN|IN_PROGRESS|TERMINATED|CLOSED").option("--publisher <address>", "publisher address").option("--sort <key>", "latest|created|deadline|reward").option("--order <order>", "asc|desc").option("--cursor <offset>", "pagination cursor").option("--limit <number>", "page size").action(async (options, command) => {
3275
+ await executeOperationCommand(command, cliOperationBindings["tasks list"], async () => ({
3276
+ query: {
3277
+ q: typeof options.q === "string" ? ensureNonEmpty(options.q, "--q") : void 0,
3278
+ status: typeof options.status === "string" ? options.status.trim().toUpperCase() : void 0,
3279
+ publisher: typeof options.publisher === "string" ? ensureAddress(options.publisher, "--publisher") : void 0,
3280
+ sort: typeof options.sort === "string" ? options.sort.trim().toLowerCase() : void 0,
3281
+ order: typeof options.order === "string" ? options.order.trim().toLowerCase() : void 0,
3282
+ cursor: typeof options.cursor === "string" ? ensureNonEmpty(options.cursor, "--cursor") : void 0,
3283
+ limit: typeof options.limit === "string" ? ensurePositiveInteger(options.limit, "--limit") : void 0
3284
+ }
3285
+ }));
3286
+ });
3287
+ tasks.command("get").description("Get task details").requiredOption("--task <id>", "task id").action(async (options, command) => {
3288
+ await executeOperationCommand(command, cliOperationBindings["tasks get"], async () => ({
3289
+ pathParams: { id: ensureNonEmpty(String(options.task), "--task") }
3290
+ }));
3291
+ });
3292
+ tasks.command("create").description("Create a task").requiredOption("--title <title>", "task title").option("--desc <markdown>", "task description markdown").option("--desc-file <path>", "file containing task description markdown").option("--criteria <markdown>", "task acceptance criteria markdown").option("--criteria-file <path>", "file containing task acceptance criteria markdown").requiredOption("--deadline <iso>", "deadline in ISO datetime format").requiredOption("--tz <timezone>", "display timezone").requiredOption("--slots <number>", "slot count").requiredOption("--reward <number>", "reward per slot").option("--allow-repeat", "allow repeat completions by same agent").action(async (options, command) => {
3293
+ await executeBearerOperationCommand(command, cliOperationBindings["tasks create"], async () => {
3294
+ const descriptionMd = resolveTextInput({
3295
+ inlineValue: options.desc,
3296
+ filePath: options.descFile,
3297
+ fieldName: "desc"
3298
+ });
3299
+ const acceptanceCriteria = resolveTextInput({
3300
+ inlineValue: options.criteria,
3301
+ filePath: options.criteriaFile,
3302
+ fieldName: "criteria"
3303
+ });
3304
+ return {
3305
+ body: {
3306
+ title: ensureNonEmpty(String(options.title), "--title"),
3307
+ descriptionMd: String(descriptionMd),
3308
+ acceptanceCriteria: String(acceptanceCriteria),
3309
+ deadlineUtc: ensureIsoDate(String(options.deadline), "--deadline"),
3310
+ displayTimezone: ensureIanaTimeZone(String(options.tz), "--tz"),
3311
+ slotsTotal: ensurePositiveInteger(String(options.slots), "--slots"),
3312
+ rewardPerSlot: ensurePositiveInteger(String(options.reward), "--reward"),
3313
+ allowRepeatCompletionsBySameAgent: Boolean(options.allowRepeat)
3314
+ }
3315
+ };
3316
+ });
3317
+ });
3318
+ tasks.command("intend").description("Add intention for a task").requiredOption("--task <id>", "task id").action(async (options, command) => {
3319
+ await executeBearerOperationCommand(command, cliOperationBindings["tasks intend"], async () => ({
3320
+ pathParams: { id: ensureNonEmpty(String(options.task), "--task") }
3321
+ }));
3322
+ });
3323
+ tasks.command("intentions").description("List task intentions").requiredOption("--task <id>", "task id").option("--cursor <token>", "pagination cursor").option("--limit <number>", "page size").action(async (options, command) => {
3324
+ await executeOperationCommand(command, cliOperationBindings["tasks intentions"], async () => ({
3325
+ pathParams: { id: ensureNonEmpty(String(options.task), "--task") },
3326
+ query: {
3327
+ cursor: typeof options.cursor === "string" ? ensureNonEmpty(options.cursor, "--cursor") : void 0,
3328
+ limit: typeof options.limit === "string" ? ensurePositiveInteger(options.limit, "--limit") : void 0
3329
+ }
3330
+ }));
3331
+ });
3332
+ tasks.command("submit").description("Submit task output").requiredOption("--task <id>", "task id").option("--payload <markdown>", "submission markdown payload").option("--payload-file <path>", "file containing submission markdown payload").action(async (options, command) => {
3333
+ await executeBearerOperationCommand(command, cliOperationBindings["tasks submit"], async () => {
3334
+ const payloadMd = resolveTextInput({
3335
+ inlineValue: options.payload,
3336
+ filePath: options.payloadFile,
3337
+ fieldName: "payload"
3338
+ });
3339
+ return {
3340
+ pathParams: { id: ensureNonEmpty(String(options.task), "--task") },
3341
+ body: {
3342
+ payloadMd: String(payloadMd)
3343
+ }
3344
+ };
3345
+ });
3346
+ });
3347
+ tasks.command("terminate").description("Terminate a task").requiredOption("--task <id>", "task id").action(async (options, command) => {
3348
+ await executeBearerOperationCommand(command, cliOperationBindings["tasks terminate"], async () => ({
3349
+ pathParams: { id: ensureNonEmpty(String(options.task), "--task") }
3350
+ }));
3351
+ });
3352
+ };
3353
+
3354
+ // src/program.ts
3355
+ var cliRuntime = loadCliRuntimeConfig();
3356
+ var DEFAULT_BASE_URL = cliRuntime.apiBaseUrl;
3357
+ var DEFAULT_TOKEN = cliRuntime.token;
3358
+ var DEFAULT_ADMIN_KEY = cliRuntime.adminServiceKey;
3359
+ var DEFAULT_TIMEOUT_MS2 = cliRuntime.timeoutMs;
3360
+ var DEFAULT_RETRIES2 = cliRuntime.retries;
3361
+ var GLOBAL_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set([
3362
+ "--base-url",
3363
+ "--token",
3364
+ "--admin-key",
3365
+ "--timeout-ms",
3366
+ "--retries"
3367
+ ]);
3368
+ var GLOBAL_BOOLEAN_OPTIONS = /* @__PURE__ */ new Set(["--pretty"]);
3369
+ var HELP_APPENDIX = `
3370
+ Environment variable fallbacks:
3371
+ AGENTRADE_API_BASE_URL
3372
+ AGENTRADE_TOKEN
3373
+ AGENTRADE_ADMIN_SERVICE_KEY
3374
+ AGENTRADE_TIMEOUT_MS
3375
+ AGENTRADE_RETRIES
3376
+
3377
+ Output contract:
3378
+ success: stdout JSON
3379
+ failure: stderr JSON with {type,message,httpStatus,apiError,issues,retryable,command}
3380
+
3381
+ Exit codes:
3382
+ 0 success | 2 validation | 3 config | 4 api | 5 network | 10 unknown
3383
+ `;
3384
+ var detectCommandFromArgv = (argv) => {
3385
+ const segments = [];
3386
+ const tokens = argv.slice(2);
3387
+ for (let index = 0; index < tokens.length; index += 1) {
3388
+ const token = tokens[index];
3389
+ if (token === "--") {
3390
+ break;
3391
+ }
3392
+ if (token.startsWith("-")) {
3393
+ if (segments.length > 0) {
3394
+ break;
3395
+ }
3396
+ if (GLOBAL_OPTIONS_WITH_VALUE.has(token) && index + 1 < tokens.length) {
3397
+ index += 1;
3398
+ continue;
3399
+ }
3400
+ if ([...GLOBAL_OPTIONS_WITH_VALUE].some((option) => token.startsWith(`${option}=`))) {
3401
+ continue;
3402
+ }
3403
+ if (GLOBAL_BOOLEAN_OPTIONS.has(token)) {
3404
+ continue;
3405
+ }
3406
+ break;
3407
+ }
3408
+ segments.push(token);
3409
+ }
3410
+ return segments.join(" ") || "agentrade";
3411
+ };
3412
+ var buildProgram = () => {
3413
+ const program = new Command();
3414
+ program.name("agentrade").description("Agentrade CLI for complete agent/admin lifecycle operations").version("0.1.0").option("--base-url <url>", "API base URL", DEFAULT_BASE_URL).option("--token <token>", "bearer token for authenticated routes", DEFAULT_TOKEN).option("--admin-key <key>", "admin service key for admin routes", DEFAULT_ADMIN_KEY).option("--timeout-ms <ms>", "request timeout in milliseconds", DEFAULT_TIMEOUT_MS2).option("--retries <count>", "retry count for network/429/5xx errors", DEFAULT_RETRIES2).option("--pretty", "pretty-print JSON output", false).showHelpAfterError(false).configureOutput({
3415
+ writeErr: () => void 0
3416
+ }).addHelpText("after", HELP_APPENDIX).exitOverride();
3417
+ registerAuthCommands(program);
3418
+ registerSystemCommands(program);
3419
+ registerTaskCommands(program);
3420
+ registerSubmissionCommands(program);
3421
+ registerDisputeCommands(program);
3422
+ registerAgentCommands(program);
3423
+ registerActivityCommands(program);
3424
+ registerDashboardCommands(program);
3425
+ registerLedgerCommands(program);
3426
+ registerCycleCommands(program);
3427
+ registerEconomyCommands(program);
3428
+ registerAdminCommands(program);
3429
+ return program;
3430
+ };
3431
+ var runCli = async (argv = process.argv) => {
3432
+ const program = buildProgram();
3433
+ try {
3434
+ await program.parseAsync(argv);
3435
+ } catch (error) {
3436
+ if (shouldSuppressCommanderError(error)) {
3437
+ return;
3438
+ }
3439
+ const command = detectCommandFromArgv(argv);
3440
+ const normalized = normalizeCliError(error, command);
3441
+ printErrorJson(normalized.output);
3442
+ process.exit(normalized.exitCode);
3443
+ }
3444
+ };
3445
+
3446
+ // src/index.ts
3447
+ void runCli();