@lucid-agents/taskmarket 1.3.0 → 1.4.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 +2374 -1536
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -6,1449 +6,996 @@ var __export = (target, all) => {
6
6
  };
7
7
 
8
8
  // src/index.ts
9
- import { Command as Command61 } from "commander";
9
+ import { Command as Command62 } from "commander";
10
10
  import { createRequire } from "module";
11
11
 
12
12
  // src/commands/init.ts
13
- import { Command } from "commander";
13
+ import { Command as Command2 } from "commander";
14
14
 
15
- // src/lib/keystore.ts
16
- import { createCipheriv, createDecipheriv, randomBytes } from "crypto";
17
- import { promises as fs } from "fs";
18
- import os from "os";
19
- import path from "path";
20
- import { privateKeyToAccount } from "viem/accounts";
21
- function getKeystorePath() {
22
- return path.join(os.homedir(), ".taskmarket", "keystore.json");
23
- }
24
- function generateKeypair() {
25
- const keyBytes = randomBytes(32);
26
- const privateKey = "0x" + keyBytes.toString("hex");
27
- const account = privateKeyToAccount(privateKey);
28
- return { privateKey, address: account.address };
29
- }
30
- function encryptPrivateKey(deviceEncryptionKeyHex, privateKey) {
31
- const key = Buffer.from(deviceEncryptionKeyHex, "hex");
32
- const iv = randomBytes(12);
33
- const cipher = createCipheriv("aes-256-gcm", key, iv);
34
- const plaintext = Buffer.from(privateKey, "utf8");
35
- const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
36
- const tag = cipher.getAuthTag();
37
- return Buffer.concat([iv, tag, encrypted]).toString("hex");
38
- }
39
- function decryptPrivateKey(deviceEncryptionKeyHex, encryptedHex) {
40
- const key = Buffer.from(deviceEncryptionKeyHex, "hex");
41
- const data = Buffer.from(encryptedHex, "hex");
42
- const iv = data.subarray(0, 12);
43
- const tag = data.subarray(12, 28);
44
- const ciphertext = data.subarray(28);
45
- const decipher = createDecipheriv("aes-256-gcm", key, iv);
46
- decipher.setAuthTag(tag);
47
- const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
48
- return decrypted.toString("utf8");
49
- }
50
- async function saveKeystore(keystore, keystorePath) {
51
- const p = keystorePath ?? getKeystorePath();
52
- await fs.mkdir(path.dirname(p), { recursive: true });
53
- await fs.writeFile(p, JSON.stringify(keystore, null, 2), "utf8");
54
- }
55
- async function loadKeystore(keystorePath) {
56
- const p = keystorePath ?? getKeystorePath();
57
- let data;
58
- try {
59
- data = await fs.readFile(p, "utf8");
60
- } catch {
61
- throw new Error(`Keystore not found at ${p}. Run 'taskmarket init' first.`);
62
- }
63
- return JSON.parse(data);
64
- }
65
- async function keystoreExists(keystorePath) {
66
- const p = keystorePath ?? getKeystorePath();
67
- try {
68
- await fs.access(p);
69
- return true;
70
- } catch {
71
- return false;
72
- }
73
- }
15
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
16
+ var external_exports = {};
17
+ __export(external_exports, {
18
+ BRAND: () => BRAND,
19
+ DIRTY: () => DIRTY,
20
+ EMPTY_PATH: () => EMPTY_PATH,
21
+ INVALID: () => INVALID,
22
+ NEVER: () => NEVER,
23
+ OK: () => OK,
24
+ ParseStatus: () => ParseStatus,
25
+ Schema: () => ZodType,
26
+ ZodAny: () => ZodAny,
27
+ ZodArray: () => ZodArray,
28
+ ZodBigInt: () => ZodBigInt,
29
+ ZodBoolean: () => ZodBoolean,
30
+ ZodBranded: () => ZodBranded,
31
+ ZodCatch: () => ZodCatch,
32
+ ZodDate: () => ZodDate,
33
+ ZodDefault: () => ZodDefault,
34
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
35
+ ZodEffects: () => ZodEffects,
36
+ ZodEnum: () => ZodEnum,
37
+ ZodError: () => ZodError,
38
+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
39
+ ZodFunction: () => ZodFunction,
40
+ ZodIntersection: () => ZodIntersection,
41
+ ZodIssueCode: () => ZodIssueCode,
42
+ ZodLazy: () => ZodLazy,
43
+ ZodLiteral: () => ZodLiteral,
44
+ ZodMap: () => ZodMap,
45
+ ZodNaN: () => ZodNaN,
46
+ ZodNativeEnum: () => ZodNativeEnum,
47
+ ZodNever: () => ZodNever,
48
+ ZodNull: () => ZodNull,
49
+ ZodNullable: () => ZodNullable,
50
+ ZodNumber: () => ZodNumber,
51
+ ZodObject: () => ZodObject,
52
+ ZodOptional: () => ZodOptional,
53
+ ZodParsedType: () => ZodParsedType,
54
+ ZodPipeline: () => ZodPipeline,
55
+ ZodPromise: () => ZodPromise,
56
+ ZodReadonly: () => ZodReadonly,
57
+ ZodRecord: () => ZodRecord,
58
+ ZodSchema: () => ZodType,
59
+ ZodSet: () => ZodSet,
60
+ ZodString: () => ZodString,
61
+ ZodSymbol: () => ZodSymbol,
62
+ ZodTransformer: () => ZodEffects,
63
+ ZodTuple: () => ZodTuple,
64
+ ZodType: () => ZodType,
65
+ ZodUndefined: () => ZodUndefined,
66
+ ZodUnion: () => ZodUnion,
67
+ ZodUnknown: () => ZodUnknown,
68
+ ZodVoid: () => ZodVoid,
69
+ addIssueToContext: () => addIssueToContext,
70
+ any: () => anyType,
71
+ array: () => arrayType,
72
+ bigint: () => bigIntType,
73
+ boolean: () => booleanType,
74
+ coerce: () => coerce,
75
+ custom: () => custom,
76
+ date: () => dateType,
77
+ datetimeRegex: () => datetimeRegex,
78
+ defaultErrorMap: () => en_default,
79
+ discriminatedUnion: () => discriminatedUnionType,
80
+ effect: () => effectsType,
81
+ enum: () => enumType,
82
+ function: () => functionType,
83
+ getErrorMap: () => getErrorMap,
84
+ getParsedType: () => getParsedType,
85
+ instanceof: () => instanceOfType,
86
+ intersection: () => intersectionType,
87
+ isAborted: () => isAborted,
88
+ isAsync: () => isAsync,
89
+ isDirty: () => isDirty,
90
+ isValid: () => isValid,
91
+ late: () => late,
92
+ lazy: () => lazyType,
93
+ literal: () => literalType,
94
+ makeIssue: () => makeIssue,
95
+ map: () => mapType,
96
+ nan: () => nanType,
97
+ nativeEnum: () => nativeEnumType,
98
+ never: () => neverType,
99
+ null: () => nullType,
100
+ nullable: () => nullableType,
101
+ number: () => numberType,
102
+ object: () => objectType,
103
+ objectUtil: () => objectUtil,
104
+ oboolean: () => oboolean,
105
+ onumber: () => onumber,
106
+ optional: () => optionalType,
107
+ ostring: () => ostring,
108
+ pipeline: () => pipelineType,
109
+ preprocess: () => preprocessType,
110
+ promise: () => promiseType,
111
+ quotelessJson: () => quotelessJson,
112
+ record: () => recordType,
113
+ set: () => setType,
114
+ setErrorMap: () => setErrorMap,
115
+ strictObject: () => strictObjectType,
116
+ string: () => stringType,
117
+ symbol: () => symbolType,
118
+ transformer: () => effectsType,
119
+ tuple: () => tupleType,
120
+ undefined: () => undefinedType,
121
+ union: () => unionType,
122
+ unknown: () => unknownType,
123
+ util: () => util,
124
+ void: () => voidType
125
+ });
74
126
 
75
- // src/lib/api.ts
76
- var API_URL = process.env.TASKMARKET_API_URL ?? "https://api.taskmarket.dev";
77
- async function apiGet(path3, options) {
78
- const res = await fetch(`${API_URL}${path3}`, {
79
- method: "GET",
80
- headers: {
81
- "Content-Type": "application/json",
82
- ...options?.headers ?? {}
83
- }
84
- });
85
- const body = await res.json();
86
- if (!res.ok) {
87
- throw new Error(`GET ${path3} failed (${res.status}): ${JSON.stringify(body)}`);
127
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
128
+ var util;
129
+ (function(util2) {
130
+ util2.assertEqual = (_) => {
131
+ };
132
+ function assertIs(_arg) {
88
133
  }
89
- return body;
90
- }
91
- async function apiPost(path3, body) {
92
- const res = await fetch(`${API_URL}${path3}`, {
93
- method: "POST",
94
- headers: { "Content-Type": "application/json" },
95
- body: JSON.stringify(body)
96
- });
97
- const result = await res.json();
98
- if (!res.ok) {
99
- throw new Error(`POST ${path3} failed (${res.status}): ${JSON.stringify(result)}`);
134
+ util2.assertIs = assertIs;
135
+ function assertNever(_x) {
136
+ throw new Error();
100
137
  }
101
- return result;
102
- }
103
-
104
- // src/lib/output.ts
105
- function printResult(data) {
106
- console.log(JSON.stringify({ ok: true, data }));
107
- }
108
- function printError(message) {
109
- process.stderr.write(JSON.stringify({ ok: false, error: message }) + "\n");
110
- process.exit(1);
111
- }
112
-
113
- // src/lib/agent.ts
114
- async function pollAgentId(address, maxWaitMs = 6e4) {
115
- const interval = 3e3;
116
- const deadline = Date.now() + maxWaitMs;
117
- while (Date.now() < deadline) {
118
- await new Promise((r) => setTimeout(r, interval));
119
- try {
120
- const res = await fetch(`${API_URL}/api/identity/status?address=${address}`);
121
- if (res.ok) {
122
- const data = await res.json();
123
- if (data.agentId) return data.agentId;
138
+ util2.assertNever = assertNever;
139
+ util2.arrayToEnum = (items) => {
140
+ const obj = {};
141
+ for (const item of items) {
142
+ obj[item] = item;
143
+ }
144
+ return obj;
145
+ };
146
+ util2.getValidEnumValues = (obj) => {
147
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
148
+ const filtered = {};
149
+ for (const k of validKeys) {
150
+ filtered[k] = obj[k];
151
+ }
152
+ return util2.objectValues(filtered);
153
+ };
154
+ util2.objectValues = (obj) => {
155
+ return util2.objectKeys(obj).map(function(e) {
156
+ return obj[e];
157
+ });
158
+ };
159
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
160
+ const keys = [];
161
+ for (const key in object) {
162
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
163
+ keys.push(key);
124
164
  }
125
- } catch {
126
165
  }
127
- }
128
- return null;
129
- }
130
-
131
- // src/lib/encryption.ts
132
- import { createECDH, hkdfSync, createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes2 } from "crypto";
133
- var VERSION = 1;
134
- var EPH_PUB_LEN = 65;
135
- var IV_LEN = 12;
136
- var TAG_LEN = 16;
137
- var HEADER_LEN = 1 + EPH_PUB_LEN + IV_LEN + TAG_LEN;
138
- function ecdhSharedSecret(privateKeyHex, otherPubKeyHex) {
139
- const ecdh = createECDH("secp256k1");
140
- ecdh.setPrivateKey(Buffer.from(privateKeyHex.replace(/^0x/, ""), "hex"));
141
- const shared = ecdh.computeSecret(Buffer.from(otherPubKeyHex, "hex"));
142
- return shared;
143
- }
144
- function hkdfKey(sharedSecret) {
145
- return Buffer.from(hkdfSync("sha256", sharedSecret, Buffer.alloc(0), "taskmarket-ecies-v1", 32));
146
- }
147
- function aesGcmEncrypt(key, iv, plaintext) {
148
- const cipher = createCipheriv2("aes-256-gcm", key, iv);
149
- const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
150
- const tag = cipher.getAuthTag();
151
- return { ciphertext, tag };
152
- }
153
- function aesGcmDecrypt(key, iv, tag, ciphertext) {
154
- const decipher = createDecipheriv2("aes-256-gcm", key, iv);
155
- decipher.setAuthTag(tag);
156
- return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
157
- }
158
- function derivePublicKey(privateKeyHex) {
159
- const ecdh = createECDH("secp256k1");
160
- ecdh.setPrivateKey(Buffer.from(privateKeyHex.replace(/^0x/, ""), "hex"));
161
- return ecdh.getPublicKey(void 0, "uncompressed").toString("hex");
162
- }
163
- function deriveCompressedPublicKey(privateKeyHex) {
164
- const ecdh = createECDH("secp256k1");
165
- ecdh.setPrivateKey(Buffer.from(privateKeyHex.replace(/^0x/, ""), "hex"));
166
- return ecdh.getPublicKey(void 0, "compressed").toString("hex");
167
- }
168
- function encryptForRecipient(fileBuffer, recipientPubKeyHex) {
169
- const ephEcdh = createECDH("secp256k1");
170
- ephEcdh.generateKeys();
171
- const ephPubKey = ephEcdh.getPublicKey(void 0, "uncompressed");
172
- const ephPrivKeyHex = ephEcdh.getPrivateKey("hex");
173
- const shared = ecdhSharedSecret(ephPrivKeyHex, recipientPubKeyHex);
174
- const aesKey = hkdfKey(shared);
175
- const iv = randomBytes2(IV_LEN);
176
- const { ciphertext, tag } = aesGcmEncrypt(aesKey, iv, fileBuffer);
177
- return Buffer.concat([Buffer.from([VERSION]), ephPubKey, iv, tag, ciphertext]);
178
- }
179
- function decryptWithPrivateKey(fileBuffer, privateKeyHex) {
180
- if (fileBuffer.length < HEADER_LEN + 1) {
181
- throw new Error("Decryption failed: invalid key or corrupted file");
182
- }
183
- const version2 = fileBuffer[0];
184
- if (version2 !== VERSION) {
185
- throw new Error(`Decryption failed: unsupported file version 0x${version2.toString(16)}`);
186
- }
187
- const ephPubKeyHex = fileBuffer.subarray(1, 1 + EPH_PUB_LEN).toString("hex");
188
- const iv = fileBuffer.subarray(1 + EPH_PUB_LEN, 1 + EPH_PUB_LEN + IV_LEN);
189
- const tag = fileBuffer.subarray(1 + EPH_PUB_LEN + IV_LEN, 1 + EPH_PUB_LEN + IV_LEN + TAG_LEN);
190
- const ciphertext = fileBuffer.subarray(1 + EPH_PUB_LEN + IV_LEN + TAG_LEN);
191
- const shared = ecdhSharedSecret(privateKeyHex, ephPubKeyHex);
192
- const aesKey = hkdfKey(shared);
193
- try {
194
- return aesGcmDecrypt(aesKey, iv, tag, ciphertext);
195
- } catch {
196
- throw new Error("Decryption failed: invalid key or corrupted file");
197
- }
198
- }
199
-
200
- // src/commands/init.ts
201
- function sanitizeEmailUsername(agentId, suffix) {
202
- const maxBase = 30 - 1 - suffix.length;
203
- if (maxBase < 2) return null;
204
- const base = agentId.toLowerCase().replace(/[^a-z0-9]/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "").slice(0, maxBase).replace(/-+$/, "");
205
- if (base.length < 2) return null;
206
- const candidate = `${base}-${suffix}`;
207
- return /^[a-z0-9][a-z0-9-]{1,28}[a-z0-9]$/.test(candidate) ? candidate : null;
208
- }
209
- async function tryRegisterEmail(deviceId, apiToken, username, explicit) {
210
- try {
211
- const reg = await apiPost("/api/emails/register", {
212
- deviceId,
213
- apiToken,
214
- username
215
- });
216
- return reg.emailAddress;
217
- } catch (err) {
218
- if (explicit) {
219
- const msg = err instanceof Error ? err.message : String(err);
220
- process.stderr.write(
221
- JSON.stringify({
222
- ok: false,
223
- error: `Email registration failed: ${msg}. Run: taskmarket email register --username ${username}`
224
- }) + "\n"
225
- );
166
+ return keys;
167
+ };
168
+ util2.find = (arr, checker) => {
169
+ for (const item of arr) {
170
+ if (checker(item))
171
+ return item;
226
172
  }
227
- return null;
173
+ return void 0;
174
+ };
175
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
176
+ function joinValues(array, separator = " | ") {
177
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
228
178
  }
229
- }
230
- var initCommand = new Command("init").description("Create and register a new agent wallet (safe to re-run)").option(
231
- "--email <username>",
232
- "Claim a custom email username (default: auto-generated from agent ID)"
233
- ).action(async (opts) => {
234
- if (opts.email) {
235
- const check = await apiGet(
236
- `/api/emails/check-username?username=${encodeURIComponent(opts.email)}`
237
- );
238
- if (!check.available) {
239
- printError(`Email username "${opts.email}" is not available.`);
179
+ util2.joinValues = joinValues;
180
+ util2.jsonStringifyReplacer = (_, value) => {
181
+ if (typeof value === "bigint") {
182
+ return value.toString();
240
183
  }
241
- }
242
- if (await keystoreExists()) {
243
- const keystore = await loadKeystore();
244
- let agentId2 = keystore.agentId;
245
- if (!agentId2) {
246
- agentId2 = await pollAgentId(keystore.walletAddress);
247
- if (agentId2) {
248
- await saveKeystore({ ...keystore, agentId: agentId2 });
184
+ return value;
185
+ };
186
+ })(util || (util = {}));
187
+ var objectUtil;
188
+ (function(objectUtil2) {
189
+ objectUtil2.mergeShapes = (first, second) => {
190
+ return {
191
+ ...first,
192
+ ...second
193
+ // second overwrites first
194
+ };
195
+ };
196
+ })(objectUtil || (objectUtil = {}));
197
+ var ZodParsedType = util.arrayToEnum([
198
+ "string",
199
+ "nan",
200
+ "number",
201
+ "integer",
202
+ "float",
203
+ "boolean",
204
+ "date",
205
+ "bigint",
206
+ "symbol",
207
+ "function",
208
+ "undefined",
209
+ "null",
210
+ "array",
211
+ "object",
212
+ "unknown",
213
+ "promise",
214
+ "void",
215
+ "never",
216
+ "map",
217
+ "set"
218
+ ]);
219
+ var getParsedType = (data) => {
220
+ const t = typeof data;
221
+ switch (t) {
222
+ case "undefined":
223
+ return ZodParsedType.undefined;
224
+ case "string":
225
+ return ZodParsedType.string;
226
+ case "number":
227
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
228
+ case "boolean":
229
+ return ZodParsedType.boolean;
230
+ case "function":
231
+ return ZodParsedType.function;
232
+ case "bigint":
233
+ return ZodParsedType.bigint;
234
+ case "symbol":
235
+ return ZodParsedType.symbol;
236
+ case "object":
237
+ if (Array.isArray(data)) {
238
+ return ZodParsedType.array;
249
239
  }
250
- }
251
- let networkInfo2;
252
- try {
253
- const response = await apiGet("/trpc/network.info");
254
- networkInfo2 = response.result.data;
255
- } catch {
256
- }
257
- let emailAddress2 = null;
258
- try {
259
- const existing = await apiGet(`/api/agents/stats?address=${keystore.walletAddress}`);
260
- emailAddress2 = existing.emailAddress ?? null;
261
- } catch {
262
- }
263
- if (!emailAddress2) {
264
- const username2 = opts.email ?? (agentId2 && networkInfo2 ? sanitizeEmailUsername(agentId2, String(networkInfo2.chainId)) : null);
265
- if (username2) {
266
- emailAddress2 = await tryRegisterEmail(
267
- keystore.deviceId,
268
- keystore.apiToken,
269
- username2,
270
- !!opts.email
271
- );
240
+ if (data === null) {
241
+ return ZodParsedType.null;
272
242
  }
273
- }
274
- printResult({
275
- address: keystore.walletAddress,
276
- agentId: agentId2,
277
- network: networkInfo2?.networkName,
278
- chainId: networkInfo2?.chainId,
279
- emailAddress: emailAddress2
280
- });
281
- return;
282
- }
283
- const { privateKey, address } = generateKeypair();
284
- const publicKey = deriveCompressedPublicKey(privateKey);
285
- const res = await fetch(`${API_URL}/api/devices`, {
286
- method: "POST",
287
- headers: { "Content-Type": "application/json" },
288
- body: JSON.stringify({ walletAddress: address, publicKey })
289
- });
290
- if (!res.ok) {
291
- const text = await res.text().catch(() => "");
292
- throw new Error(`Device registration failed (${res.status}): ${text}`);
243
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
244
+ return ZodParsedType.promise;
245
+ }
246
+ if (typeof Map !== "undefined" && data instanceof Map) {
247
+ return ZodParsedType.map;
248
+ }
249
+ if (typeof Set !== "undefined" && data instanceof Set) {
250
+ return ZodParsedType.set;
251
+ }
252
+ if (typeof Date !== "undefined" && data instanceof Date) {
253
+ return ZodParsedType.date;
254
+ }
255
+ return ZodParsedType.object;
256
+ default:
257
+ return ZodParsedType.unknown;
293
258
  }
294
- const {
295
- deviceId,
296
- apiToken,
297
- deviceEncryptionKey,
298
- agentId: initialAgentId
299
- } = await res.json();
300
- const encryptedKey = encryptPrivateKey(deviceEncryptionKey, privateKey);
301
- let agentId = initialAgentId;
302
- await saveKeystore({
303
- encryptedKey,
304
- walletAddress: address,
305
- deviceId,
306
- apiToken,
307
- agentId,
308
- keyServerUrl: API_URL
309
- });
310
- if (!agentId) {
311
- agentId = await pollAgentId(address);
312
- if (agentId) {
313
- const keystore = await loadKeystore();
314
- await saveKeystore({ ...keystore, agentId });
315
- }
259
+ };
260
+
261
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
262
+ var ZodIssueCode = util.arrayToEnum([
263
+ "invalid_type",
264
+ "invalid_literal",
265
+ "custom",
266
+ "invalid_union",
267
+ "invalid_union_discriminator",
268
+ "invalid_enum_value",
269
+ "unrecognized_keys",
270
+ "invalid_arguments",
271
+ "invalid_return_type",
272
+ "invalid_date",
273
+ "invalid_string",
274
+ "too_small",
275
+ "too_big",
276
+ "invalid_intersection_types",
277
+ "not_multiple_of",
278
+ "not_finite"
279
+ ]);
280
+ var quotelessJson = (obj) => {
281
+ const json = JSON.stringify(obj, null, 2);
282
+ return json.replace(/"([^"]+)":/g, "$1:");
283
+ };
284
+ var ZodError = class _ZodError extends Error {
285
+ get errors() {
286
+ return this.issues;
316
287
  }
317
- let networkInfo;
318
- try {
319
- const response = await apiGet("/trpc/network.info");
320
- networkInfo = response.result.data;
321
- } catch {
288
+ constructor(issues) {
289
+ super();
290
+ this.issues = [];
291
+ this.addIssue = (sub) => {
292
+ this.issues = [...this.issues, sub];
293
+ };
294
+ this.addIssues = (subs = []) => {
295
+ this.issues = [...this.issues, ...subs];
296
+ };
297
+ const actualProto = new.target.prototype;
298
+ if (Object.setPrototypeOf) {
299
+ Object.setPrototypeOf(this, actualProto);
300
+ } else {
301
+ this.__proto__ = actualProto;
302
+ }
303
+ this.name = "ZodError";
304
+ this.issues = issues;
322
305
  }
323
- const username = opts.email ?? (agentId && networkInfo ? sanitizeEmailUsername(agentId, String(networkInfo.chainId)) : null);
324
- const emailAddress = username ? await tryRegisterEmail(deviceId, apiToken, username, !!opts.email) : null;
325
- printResult({
326
- address,
327
- agentId,
328
- network: networkInfo?.networkName,
329
- chainId: networkInfo?.chainId,
330
- emailAddress
331
- });
332
- });
333
-
334
- // src/commands/address.ts
335
- import { Command as Command2 } from "commander";
336
- var addressCommand = new Command2("address").description("Print the wallet address").action(async () => {
337
- const keystore = await loadKeystore();
338
- printResult({ address: keystore.walletAddress });
339
- });
340
-
341
- // src/commands/identity.ts
342
- import { Command as Command3 } from "commander";
343
-
344
- // src/lib/signer.ts
345
- import { privateKeyToAccount as privateKeyToAccount2 } from "viem/accounts";
346
- import { toHex } from "viem";
347
- async function fetchDeviceKey(deviceId, apiToken, keyServerUrl) {
348
- const base = keyServerUrl ?? API_URL;
349
- const res = await fetch(`${base}/api/devices/${deviceId}/key`, {
350
- method: "POST",
351
- headers: { "Content-Type": "application/json" },
352
- body: JSON.stringify({ deviceId, apiToken })
353
- });
354
- if (!res.ok) {
355
- const text = await res.text().catch(() => "");
356
- throw new Error(`Failed to fetch device key (${res.status}): ${text}`);
306
+ format(_mapper) {
307
+ const mapper = _mapper || function(issue) {
308
+ return issue.message;
309
+ };
310
+ const fieldErrors = { _errors: [] };
311
+ const processError = (error) => {
312
+ for (const issue of error.issues) {
313
+ if (issue.code === "invalid_union") {
314
+ issue.unionErrors.map(processError);
315
+ } else if (issue.code === "invalid_return_type") {
316
+ processError(issue.returnTypeError);
317
+ } else if (issue.code === "invalid_arguments") {
318
+ processError(issue.argumentsError);
319
+ } else if (issue.path.length === 0) {
320
+ fieldErrors._errors.push(mapper(issue));
321
+ } else {
322
+ let curr = fieldErrors;
323
+ let i = 0;
324
+ while (i < issue.path.length) {
325
+ const el = issue.path[i];
326
+ const terminal = i === issue.path.length - 1;
327
+ if (!terminal) {
328
+ curr[el] = curr[el] || { _errors: [] };
329
+ } else {
330
+ curr[el] = curr[el] || { _errors: [] };
331
+ curr[el]._errors.push(mapper(issue));
332
+ }
333
+ curr = curr[el];
334
+ i++;
335
+ }
336
+ }
337
+ }
338
+ };
339
+ processError(this);
340
+ return fieldErrors;
357
341
  }
358
- const data = await res.json();
359
- return data.deviceEncryptionKey;
360
- }
361
- async function signTypedData(typedData, keystore) {
362
- const account = await createWalletAccountFromKeystore(keystore);
363
- const sig = await account.signTypedData(typedData);
364
- return sig;
365
- }
366
- async function signMessage(message, keystore) {
367
- const account = await createWalletAccountFromKeystore(keystore);
368
- const sig = await account.signMessage({ message });
369
- return sig;
370
- }
371
- async function createWalletAccountFromKeystore(keystore) {
372
- const dek = await fetchDeviceKey(keystore.deviceId, keystore.apiToken, keystore.keyServerUrl);
373
- const privateKey = decryptPrivateKey(dek, keystore.encryptedKey);
374
- return privateKeyToAccount2(privateKey);
375
- }
376
- async function getWalletAddress() {
377
- const keystore = await loadKeystore();
378
- return keystore.walletAddress;
379
- }
380
- async function createTransferAuthorization(accept, keystore) {
381
- const now = Math.floor(Date.now() / 1e3);
382
- const authorization = {
383
- from: keystore.walletAddress,
384
- to: accept.payTo,
385
- value: accept.amount,
386
- validAfter: String(now - 60),
387
- validBefore: String(now + accept.maxTimeoutSeconds),
388
- nonce: toHex(crypto.getRandomValues(new Uint8Array(32)))
389
- };
390
- const signature = await signTypedData(
391
- {
392
- domain: accept.extra.eip712.domain,
393
- types: accept.extra.eip712.types,
394
- primaryType: accept.extra.eip712.primaryType,
395
- message: authorization
396
- },
397
- keystore
398
- );
399
- return { authorization, signature };
400
- }
401
-
402
- // src/lib/x402.ts
403
- async function x402Post(path3, body) {
404
- const url = `${API_URL}${path3}`;
405
- const keystore = await loadKeystore();
406
- const r1 = await fetch(url, {
407
- method: "POST",
408
- headers: { "Content-Type": "application/json" },
409
- body: JSON.stringify(body)
410
- });
411
- if (r1.status !== 402) {
412
- if (r1.ok) {
413
- return r1.json();
342
+ static assert(value) {
343
+ if (!(value instanceof _ZodError)) {
344
+ throw new Error(`Not a ZodError: ${value}`);
414
345
  }
415
- const text = await r1.text().catch(() => "");
416
- throw new Error(`POST ${path3} failed (${r1.status}): ${text}`);
417
346
  }
418
- const requirements = await r1.json();
419
- if (!requirements.accepts || requirements.accepts.length === 0) {
420
- throw new Error("No payment methods accepted by server");
347
+ toString() {
348
+ return this.message;
421
349
  }
422
- const accept = requirements.accepts[0];
423
- const { authorization, signature } = await createTransferAuthorization(accept, keystore);
424
- const paymentPayload = {
425
- x402Version: 2,
426
- resource: requirements.resource,
427
- accepted: {
428
- scheme: accept.scheme,
429
- network: accept.network,
430
- amount: accept.amount,
431
- asset: accept.asset,
432
- payTo: accept.payTo,
433
- maxTimeoutSeconds: accept.maxTimeoutSeconds,
434
- extra: accept.extra
435
- },
436
- payload: { authorization, signature }
437
- };
438
- const r2 = await fetch(url, {
439
- method: "POST",
440
- headers: {
441
- "Content-Type": "application/json",
442
- "PAYMENT-SIGNATURE": Buffer.from(JSON.stringify(paymentPayload)).toString("base64")
443
- },
444
- body: JSON.stringify(body)
445
- });
446
- const result = await r2.json();
447
- if (!r2.ok) {
448
- throw new Error(`POST ${path3} failed after payment (${r2.status}): ${JSON.stringify(result)}`);
350
+ get message() {
351
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
449
352
  }
450
- return result;
451
- }
452
-
453
- // src/commands/identity.ts
454
- var identityCommand = new Command3("identity").description("Manage agent identity");
455
- identityCommand.command("register").description("Register ERC-8004 agent identity (costs 0.001 USDC)").action(async () => {
456
- const result = await x402Post("/api/identity/register", {});
457
- printResult({ agentId: result.agentId });
458
- });
459
- identityCommand.command("status").description("Check identity registration status").action(async () => {
460
- const keystore = await loadKeystore();
461
- const result = await apiGet(`/api/identity/status?address=${keystore.walletAddress}`);
462
- printResult({ registered: result.registered, agentId: result.agentId });
463
- });
353
+ get isEmpty() {
354
+ return this.issues.length === 0;
355
+ }
356
+ flatten(mapper = (issue) => issue.message) {
357
+ const fieldErrors = {};
358
+ const formErrors = [];
359
+ for (const sub of this.issues) {
360
+ if (sub.path.length > 0) {
361
+ const firstEl = sub.path[0];
362
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
363
+ fieldErrors[firstEl].push(mapper(sub));
364
+ } else {
365
+ formErrors.push(mapper(sub));
366
+ }
367
+ }
368
+ return { formErrors, fieldErrors };
369
+ }
370
+ get formErrors() {
371
+ return this.flatten();
372
+ }
373
+ };
374
+ ZodError.create = (issues) => {
375
+ const error = new ZodError(issues);
376
+ return error;
377
+ };
464
378
 
465
- // src/commands/stats.ts
466
- import { Command as Command4 } from "commander";
379
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
380
+ var errorMap = (issue, _ctx) => {
381
+ let message;
382
+ switch (issue.code) {
383
+ case ZodIssueCode.invalid_type:
384
+ if (issue.received === ZodParsedType.undefined) {
385
+ message = "Required";
386
+ } else {
387
+ message = `Expected ${issue.expected}, received ${issue.received}`;
388
+ }
389
+ break;
390
+ case ZodIssueCode.invalid_literal:
391
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
392
+ break;
393
+ case ZodIssueCode.unrecognized_keys:
394
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
395
+ break;
396
+ case ZodIssueCode.invalid_union:
397
+ message = `Invalid input`;
398
+ break;
399
+ case ZodIssueCode.invalid_union_discriminator:
400
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
401
+ break;
402
+ case ZodIssueCode.invalid_enum_value:
403
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
404
+ break;
405
+ case ZodIssueCode.invalid_arguments:
406
+ message = `Invalid function arguments`;
407
+ break;
408
+ case ZodIssueCode.invalid_return_type:
409
+ message = `Invalid function return type`;
410
+ break;
411
+ case ZodIssueCode.invalid_date:
412
+ message = `Invalid date`;
413
+ break;
414
+ case ZodIssueCode.invalid_string:
415
+ if (typeof issue.validation === "object") {
416
+ if ("includes" in issue.validation) {
417
+ message = `Invalid input: must include "${issue.validation.includes}"`;
418
+ if (typeof issue.validation.position === "number") {
419
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
420
+ }
421
+ } else if ("startsWith" in issue.validation) {
422
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
423
+ } else if ("endsWith" in issue.validation) {
424
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
425
+ } else {
426
+ util.assertNever(issue.validation);
427
+ }
428
+ } else if (issue.validation !== "regex") {
429
+ message = `Invalid ${issue.validation}`;
430
+ } else {
431
+ message = "Invalid";
432
+ }
433
+ break;
434
+ case ZodIssueCode.too_small:
435
+ if (issue.type === "array")
436
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
437
+ else if (issue.type === "string")
438
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
439
+ else if (issue.type === "number")
440
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
441
+ else if (issue.type === "bigint")
442
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
443
+ else if (issue.type === "date")
444
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
445
+ else
446
+ message = "Invalid input";
447
+ break;
448
+ case ZodIssueCode.too_big:
449
+ if (issue.type === "array")
450
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
451
+ else if (issue.type === "string")
452
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
453
+ else if (issue.type === "number")
454
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
455
+ else if (issue.type === "bigint")
456
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
457
+ else if (issue.type === "date")
458
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
459
+ else
460
+ message = "Invalid input";
461
+ break;
462
+ case ZodIssueCode.custom:
463
+ message = `Invalid input`;
464
+ break;
465
+ case ZodIssueCode.invalid_intersection_types:
466
+ message = `Intersection results could not be merged`;
467
+ break;
468
+ case ZodIssueCode.not_multiple_of:
469
+ message = `Number must be a multiple of ${issue.multipleOf}`;
470
+ break;
471
+ case ZodIssueCode.not_finite:
472
+ message = "Number must be finite";
473
+ break;
474
+ default:
475
+ message = _ctx.defaultError;
476
+ util.assertNever(issue);
477
+ }
478
+ return { message };
479
+ };
480
+ var en_default = errorMap;
467
481
 
468
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
469
- var external_exports = {};
470
- __export(external_exports, {
471
- BRAND: () => BRAND,
472
- DIRTY: () => DIRTY,
473
- EMPTY_PATH: () => EMPTY_PATH,
474
- INVALID: () => INVALID,
475
- NEVER: () => NEVER,
476
- OK: () => OK,
477
- ParseStatus: () => ParseStatus,
478
- Schema: () => ZodType,
479
- ZodAny: () => ZodAny,
480
- ZodArray: () => ZodArray,
481
- ZodBigInt: () => ZodBigInt,
482
- ZodBoolean: () => ZodBoolean,
483
- ZodBranded: () => ZodBranded,
484
- ZodCatch: () => ZodCatch,
485
- ZodDate: () => ZodDate,
486
- ZodDefault: () => ZodDefault,
487
- ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
488
- ZodEffects: () => ZodEffects,
489
- ZodEnum: () => ZodEnum,
490
- ZodError: () => ZodError,
491
- ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
492
- ZodFunction: () => ZodFunction,
493
- ZodIntersection: () => ZodIntersection,
494
- ZodIssueCode: () => ZodIssueCode,
495
- ZodLazy: () => ZodLazy,
496
- ZodLiteral: () => ZodLiteral,
497
- ZodMap: () => ZodMap,
498
- ZodNaN: () => ZodNaN,
499
- ZodNativeEnum: () => ZodNativeEnum,
500
- ZodNever: () => ZodNever,
501
- ZodNull: () => ZodNull,
502
- ZodNullable: () => ZodNullable,
503
- ZodNumber: () => ZodNumber,
504
- ZodObject: () => ZodObject,
505
- ZodOptional: () => ZodOptional,
506
- ZodParsedType: () => ZodParsedType,
507
- ZodPipeline: () => ZodPipeline,
508
- ZodPromise: () => ZodPromise,
509
- ZodReadonly: () => ZodReadonly,
510
- ZodRecord: () => ZodRecord,
511
- ZodSchema: () => ZodType,
512
- ZodSet: () => ZodSet,
513
- ZodString: () => ZodString,
514
- ZodSymbol: () => ZodSymbol,
515
- ZodTransformer: () => ZodEffects,
516
- ZodTuple: () => ZodTuple,
517
- ZodType: () => ZodType,
518
- ZodUndefined: () => ZodUndefined,
519
- ZodUnion: () => ZodUnion,
520
- ZodUnknown: () => ZodUnknown,
521
- ZodVoid: () => ZodVoid,
522
- addIssueToContext: () => addIssueToContext,
523
- any: () => anyType,
524
- array: () => arrayType,
525
- bigint: () => bigIntType,
526
- boolean: () => booleanType,
527
- coerce: () => coerce,
528
- custom: () => custom,
529
- date: () => dateType,
530
- datetimeRegex: () => datetimeRegex,
531
- defaultErrorMap: () => en_default,
532
- discriminatedUnion: () => discriminatedUnionType,
533
- effect: () => effectsType,
534
- enum: () => enumType,
535
- function: () => functionType,
536
- getErrorMap: () => getErrorMap,
537
- getParsedType: () => getParsedType,
538
- instanceof: () => instanceOfType,
539
- intersection: () => intersectionType,
540
- isAborted: () => isAborted,
541
- isAsync: () => isAsync,
542
- isDirty: () => isDirty,
543
- isValid: () => isValid,
544
- late: () => late,
545
- lazy: () => lazyType,
546
- literal: () => literalType,
547
- makeIssue: () => makeIssue,
548
- map: () => mapType,
549
- nan: () => nanType,
550
- nativeEnum: () => nativeEnumType,
551
- never: () => neverType,
552
- null: () => nullType,
553
- nullable: () => nullableType,
554
- number: () => numberType,
555
- object: () => objectType,
556
- objectUtil: () => objectUtil,
557
- oboolean: () => oboolean,
558
- onumber: () => onumber,
559
- optional: () => optionalType,
560
- ostring: () => ostring,
561
- pipeline: () => pipelineType,
562
- preprocess: () => preprocessType,
563
- promise: () => promiseType,
564
- quotelessJson: () => quotelessJson,
565
- record: () => recordType,
566
- set: () => setType,
567
- setErrorMap: () => setErrorMap,
568
- strictObject: () => strictObjectType,
569
- string: () => stringType,
570
- symbol: () => symbolType,
571
- transformer: () => effectsType,
572
- tuple: () => tupleType,
573
- undefined: () => undefinedType,
574
- union: () => unionType,
575
- unknown: () => unknownType,
576
- util: () => util,
577
- void: () => voidType
578
- });
482
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
483
+ var overrideErrorMap = en_default;
484
+ function setErrorMap(map) {
485
+ overrideErrorMap = map;
486
+ }
487
+ function getErrorMap() {
488
+ return overrideErrorMap;
489
+ }
579
490
 
580
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
581
- var util;
582
- (function(util2) {
583
- util2.assertEqual = (_) => {
491
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
492
+ var makeIssue = (params) => {
493
+ const { data, path: path3, errorMaps, issueData } = params;
494
+ const fullPath = [...path3, ...issueData.path || []];
495
+ const fullIssue = {
496
+ ...issueData,
497
+ path: fullPath
584
498
  };
585
- function assertIs(_arg) {
499
+ if (issueData.message !== void 0) {
500
+ return {
501
+ ...issueData,
502
+ path: fullPath,
503
+ message: issueData.message
504
+ };
586
505
  }
587
- util2.assertIs = assertIs;
588
- function assertNever(_x) {
589
- throw new Error();
506
+ let errorMessage = "";
507
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
508
+ for (const map of maps) {
509
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
590
510
  }
591
- util2.assertNever = assertNever;
592
- util2.arrayToEnum = (items) => {
593
- const obj = {};
594
- for (const item of items) {
595
- obj[item] = item;
596
- }
597
- return obj;
598
- };
599
- util2.getValidEnumValues = (obj) => {
600
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
601
- const filtered = {};
602
- for (const k of validKeys) {
603
- filtered[k] = obj[k];
604
- }
605
- return util2.objectValues(filtered);
606
- };
607
- util2.objectValues = (obj) => {
608
- return util2.objectKeys(obj).map(function(e) {
609
- return obj[e];
610
- });
611
- };
612
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
613
- const keys = [];
614
- for (const key in object) {
615
- if (Object.prototype.hasOwnProperty.call(object, key)) {
616
- keys.push(key);
617
- }
618
- }
619
- return keys;
511
+ return {
512
+ ...issueData,
513
+ path: fullPath,
514
+ message: errorMessage
620
515
  };
621
- util2.find = (arr, checker) => {
622
- for (const item of arr) {
623
- if (checker(item))
624
- return item;
516
+ };
517
+ var EMPTY_PATH = [];
518
+ function addIssueToContext(ctx, issueData) {
519
+ const overrideMap = getErrorMap();
520
+ const issue = makeIssue({
521
+ issueData,
522
+ data: ctx.data,
523
+ path: ctx.path,
524
+ errorMaps: [
525
+ ctx.common.contextualErrorMap,
526
+ // contextual error map is first priority
527
+ ctx.schemaErrorMap,
528
+ // then schema-bound map if available
529
+ overrideMap,
530
+ // then global override map
531
+ overrideMap === en_default ? void 0 : en_default
532
+ // then global default map
533
+ ].filter((x) => !!x)
534
+ });
535
+ ctx.common.issues.push(issue);
536
+ }
537
+ var ParseStatus = class _ParseStatus {
538
+ constructor() {
539
+ this.value = "valid";
540
+ }
541
+ dirty() {
542
+ if (this.value === "valid")
543
+ this.value = "dirty";
544
+ }
545
+ abort() {
546
+ if (this.value !== "aborted")
547
+ this.value = "aborted";
548
+ }
549
+ static mergeArray(status, results) {
550
+ const arrayValue = [];
551
+ for (const s of results) {
552
+ if (s.status === "aborted")
553
+ return INVALID;
554
+ if (s.status === "dirty")
555
+ status.dirty();
556
+ arrayValue.push(s.value);
625
557
  }
626
- return void 0;
627
- };
628
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
629
- function joinValues(array, separator = " | ") {
630
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
558
+ return { status: status.value, value: arrayValue };
631
559
  }
632
- util2.joinValues = joinValues;
633
- util2.jsonStringifyReplacer = (_, value) => {
634
- if (typeof value === "bigint") {
635
- return value.toString();
560
+ static async mergeObjectAsync(status, pairs) {
561
+ const syncPairs = [];
562
+ for (const pair of pairs) {
563
+ const key = await pair.key;
564
+ const value = await pair.value;
565
+ syncPairs.push({
566
+ key,
567
+ value
568
+ });
636
569
  }
637
- return value;
638
- };
639
- })(util || (util = {}));
640
- var objectUtil;
641
- (function(objectUtil2) {
642
- objectUtil2.mergeShapes = (first, second) => {
643
- return {
644
- ...first,
645
- ...second
646
- // second overwrites first
647
- };
648
- };
649
- })(objectUtil || (objectUtil = {}));
650
- var ZodParsedType = util.arrayToEnum([
651
- "string",
652
- "nan",
653
- "number",
654
- "integer",
655
- "float",
656
- "boolean",
657
- "date",
658
- "bigint",
659
- "symbol",
660
- "function",
661
- "undefined",
662
- "null",
663
- "array",
664
- "object",
665
- "unknown",
666
- "promise",
667
- "void",
668
- "never",
669
- "map",
670
- "set"
671
- ]);
672
- var getParsedType = (data) => {
673
- const t = typeof data;
674
- switch (t) {
675
- case "undefined":
676
- return ZodParsedType.undefined;
677
- case "string":
678
- return ZodParsedType.string;
679
- case "number":
680
- return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
681
- case "boolean":
682
- return ZodParsedType.boolean;
683
- case "function":
684
- return ZodParsedType.function;
685
- case "bigint":
686
- return ZodParsedType.bigint;
687
- case "symbol":
688
- return ZodParsedType.symbol;
689
- case "object":
690
- if (Array.isArray(data)) {
691
- return ZodParsedType.array;
692
- }
693
- if (data === null) {
694
- return ZodParsedType.null;
695
- }
696
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
697
- return ZodParsedType.promise;
698
- }
699
- if (typeof Map !== "undefined" && data instanceof Map) {
700
- return ZodParsedType.map;
701
- }
702
- if (typeof Set !== "undefined" && data instanceof Set) {
703
- return ZodParsedType.set;
704
- }
705
- if (typeof Date !== "undefined" && data instanceof Date) {
706
- return ZodParsedType.date;
570
+ return _ParseStatus.mergeObjectSync(status, syncPairs);
571
+ }
572
+ static mergeObjectSync(status, pairs) {
573
+ const finalObject = {};
574
+ for (const pair of pairs) {
575
+ const { key, value } = pair;
576
+ if (key.status === "aborted")
577
+ return INVALID;
578
+ if (value.status === "aborted")
579
+ return INVALID;
580
+ if (key.status === "dirty")
581
+ status.dirty();
582
+ if (value.status === "dirty")
583
+ status.dirty();
584
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
585
+ finalObject[key.value] = value.value;
707
586
  }
708
- return ZodParsedType.object;
709
- default:
710
- return ZodParsedType.unknown;
587
+ }
588
+ return { status: status.value, value: finalObject };
711
589
  }
712
590
  };
591
+ var INVALID = Object.freeze({
592
+ status: "aborted"
593
+ });
594
+ var DIRTY = (value) => ({ status: "dirty", value });
595
+ var OK = (value) => ({ status: "valid", value });
596
+ var isAborted = (x) => x.status === "aborted";
597
+ var isDirty = (x) => x.status === "dirty";
598
+ var isValid = (x) => x.status === "valid";
599
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
713
600
 
714
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
715
- var ZodIssueCode = util.arrayToEnum([
716
- "invalid_type",
717
- "invalid_literal",
718
- "custom",
719
- "invalid_union",
720
- "invalid_union_discriminator",
721
- "invalid_enum_value",
722
- "unrecognized_keys",
723
- "invalid_arguments",
724
- "invalid_return_type",
725
- "invalid_date",
726
- "invalid_string",
727
- "too_small",
728
- "too_big",
729
- "invalid_intersection_types",
730
- "not_multiple_of",
731
- "not_finite"
732
- ]);
733
- var quotelessJson = (obj) => {
734
- const json = JSON.stringify(obj, null, 2);
735
- return json.replace(/"([^"]+)":/g, "$1:");
736
- };
737
- var ZodError = class _ZodError extends Error {
738
- get errors() {
739
- return this.issues;
601
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
602
+ var errorUtil;
603
+ (function(errorUtil2) {
604
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
605
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
606
+ })(errorUtil || (errorUtil = {}));
607
+
608
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
609
+ var ParseInputLazyPath = class {
610
+ constructor(parent, value, path3, key) {
611
+ this._cachedPath = [];
612
+ this.parent = parent;
613
+ this.data = value;
614
+ this._path = path3;
615
+ this._key = key;
740
616
  }
741
- constructor(issues) {
742
- super();
743
- this.issues = [];
744
- this.addIssue = (sub) => {
745
- this.issues = [...this.issues, sub];
746
- };
747
- this.addIssues = (subs = []) => {
748
- this.issues = [...this.issues, ...subs];
749
- };
750
- const actualProto = new.target.prototype;
751
- if (Object.setPrototypeOf) {
752
- Object.setPrototypeOf(this, actualProto);
753
- } else {
754
- this.__proto__ = actualProto;
617
+ get path() {
618
+ if (!this._cachedPath.length) {
619
+ if (Array.isArray(this._key)) {
620
+ this._cachedPath.push(...this._path, ...this._key);
621
+ } else {
622
+ this._cachedPath.push(...this._path, this._key);
623
+ }
755
624
  }
756
- this.name = "ZodError";
757
- this.issues = issues;
625
+ return this._cachedPath;
758
626
  }
759
- format(_mapper) {
760
- const mapper = _mapper || function(issue) {
761
- return issue.message;
627
+ };
628
+ var handleResult = (ctx, result) => {
629
+ if (isValid(result)) {
630
+ return { success: true, data: result.value };
631
+ } else {
632
+ if (!ctx.common.issues.length) {
633
+ throw new Error("Validation failed but no issues detected.");
634
+ }
635
+ return {
636
+ success: false,
637
+ get error() {
638
+ if (this._error)
639
+ return this._error;
640
+ const error = new ZodError(ctx.common.issues);
641
+ this._error = error;
642
+ return this._error;
643
+ }
762
644
  };
763
- const fieldErrors = { _errors: [] };
764
- const processError = (error) => {
765
- for (const issue of error.issues) {
766
- if (issue.code === "invalid_union") {
767
- issue.unionErrors.map(processError);
768
- } else if (issue.code === "invalid_return_type") {
769
- processError(issue.returnTypeError);
770
- } else if (issue.code === "invalid_arguments") {
771
- processError(issue.argumentsError);
772
- } else if (issue.path.length === 0) {
773
- fieldErrors._errors.push(mapper(issue));
774
- } else {
775
- let curr = fieldErrors;
776
- let i = 0;
777
- while (i < issue.path.length) {
778
- const el = issue.path[i];
779
- const terminal = i === issue.path.length - 1;
780
- if (!terminal) {
781
- curr[el] = curr[el] || { _errors: [] };
782
- } else {
783
- curr[el] = curr[el] || { _errors: [] };
784
- curr[el]._errors.push(mapper(issue));
785
- }
786
- curr = curr[el];
787
- i++;
788
- }
789
- }
645
+ }
646
+ };
647
+ function processCreateParams(params) {
648
+ if (!params)
649
+ return {};
650
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
651
+ if (errorMap2 && (invalid_type_error || required_error)) {
652
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
653
+ }
654
+ if (errorMap2)
655
+ return { errorMap: errorMap2, description };
656
+ const customMap = (iss, ctx) => {
657
+ const { message } = params;
658
+ if (iss.code === "invalid_enum_value") {
659
+ return { message: message ?? ctx.defaultError };
660
+ }
661
+ if (typeof ctx.data === "undefined") {
662
+ return { message: message ?? required_error ?? ctx.defaultError };
663
+ }
664
+ if (iss.code !== "invalid_type")
665
+ return { message: ctx.defaultError };
666
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
667
+ };
668
+ return { errorMap: customMap, description };
669
+ }
670
+ var ZodType = class {
671
+ get description() {
672
+ return this._def.description;
673
+ }
674
+ _getType(input) {
675
+ return getParsedType(input.data);
676
+ }
677
+ _getOrReturnCtx(input, ctx) {
678
+ return ctx || {
679
+ common: input.parent.common,
680
+ data: input.data,
681
+ parsedType: getParsedType(input.data),
682
+ schemaErrorMap: this._def.errorMap,
683
+ path: input.path,
684
+ parent: input.parent
685
+ };
686
+ }
687
+ _processInputParams(input) {
688
+ return {
689
+ status: new ParseStatus(),
690
+ ctx: {
691
+ common: input.parent.common,
692
+ data: input.data,
693
+ parsedType: getParsedType(input.data),
694
+ schemaErrorMap: this._def.errorMap,
695
+ path: input.path,
696
+ parent: input.parent
790
697
  }
791
698
  };
792
- processError(this);
793
- return fieldErrors;
794
699
  }
795
- static assert(value) {
796
- if (!(value instanceof _ZodError)) {
797
- throw new Error(`Not a ZodError: ${value}`);
700
+ _parseSync(input) {
701
+ const result = this._parse(input);
702
+ if (isAsync(result)) {
703
+ throw new Error("Synchronous parse encountered promise.");
798
704
  }
705
+ return result;
799
706
  }
800
- toString() {
801
- return this.message;
707
+ _parseAsync(input) {
708
+ const result = this._parse(input);
709
+ return Promise.resolve(result);
802
710
  }
803
- get message() {
804
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
711
+ parse(data, params) {
712
+ const result = this.safeParse(data, params);
713
+ if (result.success)
714
+ return result.data;
715
+ throw result.error;
805
716
  }
806
- get isEmpty() {
807
- return this.issues.length === 0;
717
+ safeParse(data, params) {
718
+ const ctx = {
719
+ common: {
720
+ issues: [],
721
+ async: params?.async ?? false,
722
+ contextualErrorMap: params?.errorMap
723
+ },
724
+ path: params?.path || [],
725
+ schemaErrorMap: this._def.errorMap,
726
+ parent: null,
727
+ data,
728
+ parsedType: getParsedType(data)
729
+ };
730
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
731
+ return handleResult(ctx, result);
808
732
  }
809
- flatten(mapper = (issue) => issue.message) {
810
- const fieldErrors = {};
811
- const formErrors = [];
812
- for (const sub of this.issues) {
813
- if (sub.path.length > 0) {
814
- const firstEl = sub.path[0];
815
- fieldErrors[firstEl] = fieldErrors[firstEl] || [];
816
- fieldErrors[firstEl].push(mapper(sub));
817
- } else {
818
- formErrors.push(mapper(sub));
733
+ "~validate"(data) {
734
+ const ctx = {
735
+ common: {
736
+ issues: [],
737
+ async: !!this["~standard"].async
738
+ },
739
+ path: [],
740
+ schemaErrorMap: this._def.errorMap,
741
+ parent: null,
742
+ data,
743
+ parsedType: getParsedType(data)
744
+ };
745
+ if (!this["~standard"].async) {
746
+ try {
747
+ const result = this._parseSync({ data, path: [], parent: ctx });
748
+ return isValid(result) ? {
749
+ value: result.value
750
+ } : {
751
+ issues: ctx.common.issues
752
+ };
753
+ } catch (err) {
754
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
755
+ this["~standard"].async = true;
756
+ }
757
+ ctx.common = {
758
+ issues: [],
759
+ async: true
760
+ };
819
761
  }
820
762
  }
821
- return { formErrors, fieldErrors };
763
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
764
+ value: result.value
765
+ } : {
766
+ issues: ctx.common.issues
767
+ });
822
768
  }
823
- get formErrors() {
824
- return this.flatten();
769
+ async parseAsync(data, params) {
770
+ const result = await this.safeParseAsync(data, params);
771
+ if (result.success)
772
+ return result.data;
773
+ throw result.error;
825
774
  }
826
- };
827
- ZodError.create = (issues) => {
828
- const error = new ZodError(issues);
829
- return error;
830
- };
831
-
832
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
833
- var errorMap = (issue, _ctx) => {
834
- let message;
835
- switch (issue.code) {
836
- case ZodIssueCode.invalid_type:
837
- if (issue.received === ZodParsedType.undefined) {
838
- message = "Required";
775
+ async safeParseAsync(data, params) {
776
+ const ctx = {
777
+ common: {
778
+ issues: [],
779
+ contextualErrorMap: params?.errorMap,
780
+ async: true
781
+ },
782
+ path: params?.path || [],
783
+ schemaErrorMap: this._def.errorMap,
784
+ parent: null,
785
+ data,
786
+ parsedType: getParsedType(data)
787
+ };
788
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
789
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
790
+ return handleResult(ctx, result);
791
+ }
792
+ refine(check, message) {
793
+ const getIssueProperties = (val) => {
794
+ if (typeof message === "string" || typeof message === "undefined") {
795
+ return { message };
796
+ } else if (typeof message === "function") {
797
+ return message(val);
839
798
  } else {
840
- message = `Expected ${issue.expected}, received ${issue.received}`;
799
+ return message;
841
800
  }
842
- break;
843
- case ZodIssueCode.invalid_literal:
844
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
845
- break;
846
- case ZodIssueCode.unrecognized_keys:
847
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
848
- break;
849
- case ZodIssueCode.invalid_union:
850
- message = `Invalid input`;
851
- break;
852
- case ZodIssueCode.invalid_union_discriminator:
853
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
854
- break;
855
- case ZodIssueCode.invalid_enum_value:
856
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
857
- break;
858
- case ZodIssueCode.invalid_arguments:
859
- message = `Invalid function arguments`;
860
- break;
861
- case ZodIssueCode.invalid_return_type:
862
- message = `Invalid function return type`;
863
- break;
864
- case ZodIssueCode.invalid_date:
865
- message = `Invalid date`;
866
- break;
867
- case ZodIssueCode.invalid_string:
868
- if (typeof issue.validation === "object") {
869
- if ("includes" in issue.validation) {
870
- message = `Invalid input: must include "${issue.validation.includes}"`;
871
- if (typeof issue.validation.position === "number") {
872
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
801
+ };
802
+ return this._refinement((val, ctx) => {
803
+ const result = check(val);
804
+ const setError = () => ctx.addIssue({
805
+ code: ZodIssueCode.custom,
806
+ ...getIssueProperties(val)
807
+ });
808
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
809
+ return result.then((data) => {
810
+ if (!data) {
811
+ setError();
812
+ return false;
813
+ } else {
814
+ return true;
873
815
  }
874
- } else if ("startsWith" in issue.validation) {
875
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
876
- } else if ("endsWith" in issue.validation) {
877
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
878
- } else {
879
- util.assertNever(issue.validation);
880
- }
881
- } else if (issue.validation !== "regex") {
882
- message = `Invalid ${issue.validation}`;
816
+ });
817
+ }
818
+ if (!result) {
819
+ setError();
820
+ return false;
883
821
  } else {
884
- message = "Invalid";
822
+ return true;
885
823
  }
886
- break;
887
- case ZodIssueCode.too_small:
888
- if (issue.type === "array")
889
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
890
- else if (issue.type === "string")
891
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
892
- else if (issue.type === "number")
893
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
894
- else if (issue.type === "bigint")
895
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
896
- else if (issue.type === "date")
897
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
898
- else
899
- message = "Invalid input";
900
- break;
901
- case ZodIssueCode.too_big:
902
- if (issue.type === "array")
903
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
904
- else if (issue.type === "string")
905
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
906
- else if (issue.type === "number")
907
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
908
- else if (issue.type === "bigint")
909
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
910
- else if (issue.type === "date")
911
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
912
- else
913
- message = "Invalid input";
914
- break;
915
- case ZodIssueCode.custom:
916
- message = `Invalid input`;
917
- break;
918
- case ZodIssueCode.invalid_intersection_types:
919
- message = `Intersection results could not be merged`;
920
- break;
921
- case ZodIssueCode.not_multiple_of:
922
- message = `Number must be a multiple of ${issue.multipleOf}`;
923
- break;
924
- case ZodIssueCode.not_finite:
925
- message = "Number must be finite";
926
- break;
927
- default:
928
- message = _ctx.defaultError;
929
- util.assertNever(issue);
824
+ });
930
825
  }
931
- return { message };
932
- };
933
- var en_default = errorMap;
934
-
935
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
936
- var overrideErrorMap = en_default;
937
- function setErrorMap(map) {
938
- overrideErrorMap = map;
939
- }
940
- function getErrorMap() {
941
- return overrideErrorMap;
942
- }
943
-
944
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
945
- var makeIssue = (params) => {
946
- const { data, path: path3, errorMaps, issueData } = params;
947
- const fullPath = [...path3, ...issueData.path || []];
948
- const fullIssue = {
949
- ...issueData,
950
- path: fullPath
951
- };
952
- if (issueData.message !== void 0) {
953
- return {
954
- ...issueData,
955
- path: fullPath,
956
- message: issueData.message
826
+ refinement(check, refinementData) {
827
+ return this._refinement((val, ctx) => {
828
+ if (!check(val)) {
829
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
830
+ return false;
831
+ } else {
832
+ return true;
833
+ }
834
+ });
835
+ }
836
+ _refinement(refinement) {
837
+ return new ZodEffects({
838
+ schema: this,
839
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
840
+ effect: { type: "refinement", refinement }
841
+ });
842
+ }
843
+ superRefine(refinement) {
844
+ return this._refinement(refinement);
845
+ }
846
+ constructor(def) {
847
+ this.spa = this.safeParseAsync;
848
+ this._def = def;
849
+ this.parse = this.parse.bind(this);
850
+ this.safeParse = this.safeParse.bind(this);
851
+ this.parseAsync = this.parseAsync.bind(this);
852
+ this.safeParseAsync = this.safeParseAsync.bind(this);
853
+ this.spa = this.spa.bind(this);
854
+ this.refine = this.refine.bind(this);
855
+ this.refinement = this.refinement.bind(this);
856
+ this.superRefine = this.superRefine.bind(this);
857
+ this.optional = this.optional.bind(this);
858
+ this.nullable = this.nullable.bind(this);
859
+ this.nullish = this.nullish.bind(this);
860
+ this.array = this.array.bind(this);
861
+ this.promise = this.promise.bind(this);
862
+ this.or = this.or.bind(this);
863
+ this.and = this.and.bind(this);
864
+ this.transform = this.transform.bind(this);
865
+ this.brand = this.brand.bind(this);
866
+ this.default = this.default.bind(this);
867
+ this.catch = this.catch.bind(this);
868
+ this.describe = this.describe.bind(this);
869
+ this.pipe = this.pipe.bind(this);
870
+ this.readonly = this.readonly.bind(this);
871
+ this.isNullable = this.isNullable.bind(this);
872
+ this.isOptional = this.isOptional.bind(this);
873
+ this["~standard"] = {
874
+ version: 1,
875
+ vendor: "zod",
876
+ validate: (data) => this["~validate"](data)
957
877
  };
958
878
  }
959
- let errorMessage = "";
960
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
961
- for (const map of maps) {
962
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
879
+ optional() {
880
+ return ZodOptional.create(this, this._def);
963
881
  }
964
- return {
965
- ...issueData,
966
- path: fullPath,
967
- message: errorMessage
968
- };
969
- };
970
- var EMPTY_PATH = [];
971
- function addIssueToContext(ctx, issueData) {
972
- const overrideMap = getErrorMap();
973
- const issue = makeIssue({
974
- issueData,
975
- data: ctx.data,
976
- path: ctx.path,
977
- errorMaps: [
978
- ctx.common.contextualErrorMap,
979
- // contextual error map is first priority
980
- ctx.schemaErrorMap,
981
- // then schema-bound map if available
982
- overrideMap,
983
- // then global override map
984
- overrideMap === en_default ? void 0 : en_default
985
- // then global default map
986
- ].filter((x) => !!x)
987
- });
988
- ctx.common.issues.push(issue);
989
- }
990
- var ParseStatus = class _ParseStatus {
991
- constructor() {
992
- this.value = "valid";
882
+ nullable() {
883
+ return ZodNullable.create(this, this._def);
993
884
  }
994
- dirty() {
995
- if (this.value === "valid")
996
- this.value = "dirty";
885
+ nullish() {
886
+ return this.nullable().optional();
997
887
  }
998
- abort() {
999
- if (this.value !== "aborted")
1000
- this.value = "aborted";
888
+ array() {
889
+ return ZodArray.create(this);
1001
890
  }
1002
- static mergeArray(status, results) {
1003
- const arrayValue = [];
1004
- for (const s of results) {
1005
- if (s.status === "aborted")
1006
- return INVALID;
1007
- if (s.status === "dirty")
1008
- status.dirty();
1009
- arrayValue.push(s.value);
1010
- }
1011
- return { status: status.value, value: arrayValue };
891
+ promise() {
892
+ return ZodPromise.create(this, this._def);
1012
893
  }
1013
- static async mergeObjectAsync(status, pairs) {
1014
- const syncPairs = [];
1015
- for (const pair of pairs) {
1016
- const key = await pair.key;
1017
- const value = await pair.value;
1018
- syncPairs.push({
1019
- key,
1020
- value
1021
- });
1022
- }
1023
- return _ParseStatus.mergeObjectSync(status, syncPairs);
894
+ or(option) {
895
+ return ZodUnion.create([this, option], this._def);
1024
896
  }
1025
- static mergeObjectSync(status, pairs) {
1026
- const finalObject = {};
1027
- for (const pair of pairs) {
1028
- const { key, value } = pair;
1029
- if (key.status === "aborted")
1030
- return INVALID;
1031
- if (value.status === "aborted")
1032
- return INVALID;
1033
- if (key.status === "dirty")
1034
- status.dirty();
1035
- if (value.status === "dirty")
1036
- status.dirty();
1037
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
1038
- finalObject[key.value] = value.value;
1039
- }
1040
- }
1041
- return { status: status.value, value: finalObject };
897
+ and(incoming) {
898
+ return ZodIntersection.create(this, incoming, this._def);
1042
899
  }
1043
- };
1044
- var INVALID = Object.freeze({
1045
- status: "aborted"
1046
- });
1047
- var DIRTY = (value) => ({ status: "dirty", value });
1048
- var OK = (value) => ({ status: "valid", value });
1049
- var isAborted = (x) => x.status === "aborted";
1050
- var isDirty = (x) => x.status === "dirty";
1051
- var isValid = (x) => x.status === "valid";
1052
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
1053
-
1054
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
1055
- var errorUtil;
1056
- (function(errorUtil2) {
1057
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
1058
- errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
1059
- })(errorUtil || (errorUtil = {}));
1060
-
1061
- // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
1062
- var ParseInputLazyPath = class {
1063
- constructor(parent, value, path3, key) {
1064
- this._cachedPath = [];
1065
- this.parent = parent;
1066
- this.data = value;
1067
- this._path = path3;
1068
- this._key = key;
1069
- }
1070
- get path() {
1071
- if (!this._cachedPath.length) {
1072
- if (Array.isArray(this._key)) {
1073
- this._cachedPath.push(...this._path, ...this._key);
1074
- } else {
1075
- this._cachedPath.push(...this._path, this._key);
1076
- }
1077
- }
1078
- return this._cachedPath;
1079
- }
1080
- };
1081
- var handleResult = (ctx, result) => {
1082
- if (isValid(result)) {
1083
- return { success: true, data: result.value };
1084
- } else {
1085
- if (!ctx.common.issues.length) {
1086
- throw new Error("Validation failed but no issues detected.");
1087
- }
1088
- return {
1089
- success: false,
1090
- get error() {
1091
- if (this._error)
1092
- return this._error;
1093
- const error = new ZodError(ctx.common.issues);
1094
- this._error = error;
1095
- return this._error;
1096
- }
1097
- };
900
+ transform(transform) {
901
+ return new ZodEffects({
902
+ ...processCreateParams(this._def),
903
+ schema: this,
904
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
905
+ effect: { type: "transform", transform }
906
+ });
1098
907
  }
1099
- };
1100
- function processCreateParams(params) {
1101
- if (!params)
1102
- return {};
1103
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
1104
- if (errorMap2 && (invalid_type_error || required_error)) {
1105
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
908
+ default(def) {
909
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
910
+ return new ZodDefault({
911
+ ...processCreateParams(this._def),
912
+ innerType: this,
913
+ defaultValue: defaultValueFunc,
914
+ typeName: ZodFirstPartyTypeKind.ZodDefault
915
+ });
1106
916
  }
1107
- if (errorMap2)
1108
- return { errorMap: errorMap2, description };
1109
- const customMap = (iss, ctx) => {
1110
- const { message } = params;
1111
- if (iss.code === "invalid_enum_value") {
1112
- return { message: message ?? ctx.defaultError };
1113
- }
1114
- if (typeof ctx.data === "undefined") {
1115
- return { message: message ?? required_error ?? ctx.defaultError };
1116
- }
1117
- if (iss.code !== "invalid_type")
1118
- return { message: ctx.defaultError };
1119
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
1120
- };
1121
- return { errorMap: customMap, description };
1122
- }
1123
- var ZodType = class {
1124
- get description() {
1125
- return this._def.description;
917
+ brand() {
918
+ return new ZodBranded({
919
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
920
+ type: this,
921
+ ...processCreateParams(this._def)
922
+ });
1126
923
  }
1127
- _getType(input) {
1128
- return getParsedType(input.data);
924
+ catch(def) {
925
+ const catchValueFunc = typeof def === "function" ? def : () => def;
926
+ return new ZodCatch({
927
+ ...processCreateParams(this._def),
928
+ innerType: this,
929
+ catchValue: catchValueFunc,
930
+ typeName: ZodFirstPartyTypeKind.ZodCatch
931
+ });
1129
932
  }
1130
- _getOrReturnCtx(input, ctx) {
1131
- return ctx || {
1132
- common: input.parent.common,
1133
- data: input.data,
1134
- parsedType: getParsedType(input.data),
1135
- schemaErrorMap: this._def.errorMap,
1136
- path: input.path,
1137
- parent: input.parent
1138
- };
933
+ describe(description) {
934
+ const This = this.constructor;
935
+ return new This({
936
+ ...this._def,
937
+ description
938
+ });
1139
939
  }
1140
- _processInputParams(input) {
1141
- return {
1142
- status: new ParseStatus(),
1143
- ctx: {
1144
- common: input.parent.common,
1145
- data: input.data,
1146
- parsedType: getParsedType(input.data),
1147
- schemaErrorMap: this._def.errorMap,
1148
- path: input.path,
1149
- parent: input.parent
1150
- }
1151
- };
940
+ pipe(target) {
941
+ return ZodPipeline.create(this, target);
1152
942
  }
1153
- _parseSync(input) {
1154
- const result = this._parse(input);
1155
- if (isAsync(result)) {
1156
- throw new Error("Synchronous parse encountered promise.");
1157
- }
1158
- return result;
943
+ readonly() {
944
+ return ZodReadonly.create(this);
1159
945
  }
1160
- _parseAsync(input) {
1161
- const result = this._parse(input);
1162
- return Promise.resolve(result);
946
+ isOptional() {
947
+ return this.safeParse(void 0).success;
1163
948
  }
1164
- parse(data, params) {
1165
- const result = this.safeParse(data, params);
1166
- if (result.success)
1167
- return result.data;
1168
- throw result.error;
949
+ isNullable() {
950
+ return this.safeParse(null).success;
1169
951
  }
1170
- safeParse(data, params) {
1171
- const ctx = {
1172
- common: {
1173
- issues: [],
1174
- async: params?.async ?? false,
1175
- contextualErrorMap: params?.errorMap
1176
- },
1177
- path: params?.path || [],
1178
- schemaErrorMap: this._def.errorMap,
1179
- parent: null,
1180
- data,
1181
- parsedType: getParsedType(data)
1182
- };
1183
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
1184
- return handleResult(ctx, result);
952
+ };
953
+ var cuidRegex = /^c[^\s-]{8,}$/i;
954
+ var cuid2Regex = /^[0-9a-z]+$/;
955
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
956
+ var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
957
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
958
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
959
+ var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
960
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
961
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
962
+ var emojiRegex;
963
+ var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
964
+ var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
965
+ var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
966
+ var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
967
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
968
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
969
+ var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
970
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
971
+ function timeRegexSource(args) {
972
+ let secondsRegexSource = `[0-5]\\d`;
973
+ if (args.precision) {
974
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
975
+ } else if (args.precision == null) {
976
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
1185
977
  }
1186
- "~validate"(data) {
1187
- const ctx = {
1188
- common: {
1189
- issues: [],
1190
- async: !!this["~standard"].async
1191
- },
1192
- path: [],
1193
- schemaErrorMap: this._def.errorMap,
1194
- parent: null,
1195
- data,
1196
- parsedType: getParsedType(data)
1197
- };
1198
- if (!this["~standard"].async) {
1199
- try {
1200
- const result = this._parseSync({ data, path: [], parent: ctx });
1201
- return isValid(result) ? {
1202
- value: result.value
1203
- } : {
1204
- issues: ctx.common.issues
1205
- };
1206
- } catch (err) {
1207
- if (err?.message?.toLowerCase()?.includes("encountered")) {
1208
- this["~standard"].async = true;
1209
- }
1210
- ctx.common = {
1211
- issues: [],
1212
- async: true
1213
- };
1214
- }
1215
- }
1216
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
1217
- value: result.value
1218
- } : {
1219
- issues: ctx.common.issues
1220
- });
978
+ const secondsQuantifier = args.precision ? "+" : "?";
979
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
980
+ }
981
+ function timeRegex(args) {
982
+ return new RegExp(`^${timeRegexSource(args)}$`);
983
+ }
984
+ function datetimeRegex(args) {
985
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
986
+ const opts = [];
987
+ opts.push(args.local ? `Z?` : `Z`);
988
+ if (args.offset)
989
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
990
+ regex = `${regex}(${opts.join("|")})`;
991
+ return new RegExp(`^${regex}$`);
992
+ }
993
+ function isValidIP(ip, version2) {
994
+ if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
995
+ return true;
1221
996
  }
1222
- async parseAsync(data, params) {
1223
- const result = await this.safeParseAsync(data, params);
1224
- if (result.success)
1225
- return result.data;
1226
- throw result.error;
1227
- }
1228
- async safeParseAsync(data, params) {
1229
- const ctx = {
1230
- common: {
1231
- issues: [],
1232
- contextualErrorMap: params?.errorMap,
1233
- async: true
1234
- },
1235
- path: params?.path || [],
1236
- schemaErrorMap: this._def.errorMap,
1237
- parent: null,
1238
- data,
1239
- parsedType: getParsedType(data)
1240
- };
1241
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
1242
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
1243
- return handleResult(ctx, result);
1244
- }
1245
- refine(check, message) {
1246
- const getIssueProperties = (val) => {
1247
- if (typeof message === "string" || typeof message === "undefined") {
1248
- return { message };
1249
- } else if (typeof message === "function") {
1250
- return message(val);
1251
- } else {
1252
- return message;
1253
- }
1254
- };
1255
- return this._refinement((val, ctx) => {
1256
- const result = check(val);
1257
- const setError = () => ctx.addIssue({
1258
- code: ZodIssueCode.custom,
1259
- ...getIssueProperties(val)
1260
- });
1261
- if (typeof Promise !== "undefined" && result instanceof Promise) {
1262
- return result.then((data) => {
1263
- if (!data) {
1264
- setError();
1265
- return false;
1266
- } else {
1267
- return true;
1268
- }
1269
- });
1270
- }
1271
- if (!result) {
1272
- setError();
1273
- return false;
1274
- } else {
1275
- return true;
1276
- }
1277
- });
1278
- }
1279
- refinement(check, refinementData) {
1280
- return this._refinement((val, ctx) => {
1281
- if (!check(val)) {
1282
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
1283
- return false;
1284
- } else {
1285
- return true;
1286
- }
1287
- });
1288
- }
1289
- _refinement(refinement) {
1290
- return new ZodEffects({
1291
- schema: this,
1292
- typeName: ZodFirstPartyTypeKind.ZodEffects,
1293
- effect: { type: "refinement", refinement }
1294
- });
1295
- }
1296
- superRefine(refinement) {
1297
- return this._refinement(refinement);
1298
- }
1299
- constructor(def) {
1300
- this.spa = this.safeParseAsync;
1301
- this._def = def;
1302
- this.parse = this.parse.bind(this);
1303
- this.safeParse = this.safeParse.bind(this);
1304
- this.parseAsync = this.parseAsync.bind(this);
1305
- this.safeParseAsync = this.safeParseAsync.bind(this);
1306
- this.spa = this.spa.bind(this);
1307
- this.refine = this.refine.bind(this);
1308
- this.refinement = this.refinement.bind(this);
1309
- this.superRefine = this.superRefine.bind(this);
1310
- this.optional = this.optional.bind(this);
1311
- this.nullable = this.nullable.bind(this);
1312
- this.nullish = this.nullish.bind(this);
1313
- this.array = this.array.bind(this);
1314
- this.promise = this.promise.bind(this);
1315
- this.or = this.or.bind(this);
1316
- this.and = this.and.bind(this);
1317
- this.transform = this.transform.bind(this);
1318
- this.brand = this.brand.bind(this);
1319
- this.default = this.default.bind(this);
1320
- this.catch = this.catch.bind(this);
1321
- this.describe = this.describe.bind(this);
1322
- this.pipe = this.pipe.bind(this);
1323
- this.readonly = this.readonly.bind(this);
1324
- this.isNullable = this.isNullable.bind(this);
1325
- this.isOptional = this.isOptional.bind(this);
1326
- this["~standard"] = {
1327
- version: 1,
1328
- vendor: "zod",
1329
- validate: (data) => this["~validate"](data)
1330
- };
1331
- }
1332
- optional() {
1333
- return ZodOptional.create(this, this._def);
1334
- }
1335
- nullable() {
1336
- return ZodNullable.create(this, this._def);
1337
- }
1338
- nullish() {
1339
- return this.nullable().optional();
1340
- }
1341
- array() {
1342
- return ZodArray.create(this);
1343
- }
1344
- promise() {
1345
- return ZodPromise.create(this, this._def);
1346
- }
1347
- or(option) {
1348
- return ZodUnion.create([this, option], this._def);
1349
- }
1350
- and(incoming) {
1351
- return ZodIntersection.create(this, incoming, this._def);
1352
- }
1353
- transform(transform) {
1354
- return new ZodEffects({
1355
- ...processCreateParams(this._def),
1356
- schema: this,
1357
- typeName: ZodFirstPartyTypeKind.ZodEffects,
1358
- effect: { type: "transform", transform }
1359
- });
1360
- }
1361
- default(def) {
1362
- const defaultValueFunc = typeof def === "function" ? def : () => def;
1363
- return new ZodDefault({
1364
- ...processCreateParams(this._def),
1365
- innerType: this,
1366
- defaultValue: defaultValueFunc,
1367
- typeName: ZodFirstPartyTypeKind.ZodDefault
1368
- });
1369
- }
1370
- brand() {
1371
- return new ZodBranded({
1372
- typeName: ZodFirstPartyTypeKind.ZodBranded,
1373
- type: this,
1374
- ...processCreateParams(this._def)
1375
- });
1376
- }
1377
- catch(def) {
1378
- const catchValueFunc = typeof def === "function" ? def : () => def;
1379
- return new ZodCatch({
1380
- ...processCreateParams(this._def),
1381
- innerType: this,
1382
- catchValue: catchValueFunc,
1383
- typeName: ZodFirstPartyTypeKind.ZodCatch
1384
- });
1385
- }
1386
- describe(description) {
1387
- const This = this.constructor;
1388
- return new This({
1389
- ...this._def,
1390
- description
1391
- });
1392
- }
1393
- pipe(target) {
1394
- return ZodPipeline.create(this, target);
1395
- }
1396
- readonly() {
1397
- return ZodReadonly.create(this);
1398
- }
1399
- isOptional() {
1400
- return this.safeParse(void 0).success;
1401
- }
1402
- isNullable() {
1403
- return this.safeParse(null).success;
1404
- }
1405
- };
1406
- var cuidRegex = /^c[^\s-]{8,}$/i;
1407
- var cuid2Regex = /^[0-9a-z]+$/;
1408
- var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
1409
- var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
1410
- var nanoidRegex = /^[a-z0-9_-]{21}$/i;
1411
- var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
1412
- var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
1413
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1414
- var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1415
- var emojiRegex;
1416
- var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1417
- var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
1418
- var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
1419
- var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
1420
- var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1421
- var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
1422
- var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
1423
- var dateRegex = new RegExp(`^${dateRegexSource}$`);
1424
- function timeRegexSource(args) {
1425
- let secondsRegexSource = `[0-5]\\d`;
1426
- if (args.precision) {
1427
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
1428
- } else if (args.precision == null) {
1429
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
1430
- }
1431
- const secondsQuantifier = args.precision ? "+" : "?";
1432
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
1433
- }
1434
- function timeRegex(args) {
1435
- return new RegExp(`^${timeRegexSource(args)}$`);
1436
- }
1437
- function datetimeRegex(args) {
1438
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1439
- const opts = [];
1440
- opts.push(args.local ? `Z?` : `Z`);
1441
- if (args.offset)
1442
- opts.push(`([+-]\\d{2}:?\\d{2})`);
1443
- regex = `${regex}(${opts.join("|")})`;
1444
- return new RegExp(`^${regex}$`);
1445
- }
1446
- function isValidIP(ip, version2) {
1447
- if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
1448
- return true;
1449
- }
1450
- if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
1451
- return true;
997
+ if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
998
+ return true;
1452
999
  }
1453
1000
  return false;
1454
1001
  }
@@ -4519,6 +4066,109 @@ var Secp256k1PublicKeySchema = external_exports.string().refine((value) => {
4519
4066
  return /^(?:02|03)[0-9a-fA-F]{64}$/.test(key) || /^04[0-9a-fA-F]{128}$/.test(key);
4520
4067
  }, "Public key must be a compressed or uncompressed secp256k1 key");
4521
4068
 
4069
+ // ../../packages/shared/dist/schemas/task-drops.schemas.js
4070
+ var EthAddress = external_exports.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid Ethereum address").toLowerCase();
4071
+ var EmailAddress = external_exports.string().trim().toLowerCase().email().max(320);
4072
+ var TaskDropSourceSchema = external_exports.enum([
4073
+ "first_run_panel",
4074
+ "agent_setup",
4075
+ "account",
4076
+ "cli",
4077
+ "drop_page",
4078
+ "taskdrop_landing",
4079
+ "official_drop_page"
4080
+ ]);
4081
+ var TaskDropSubscriptionScopeSchema = external_exports.enum(["drop", "official"]);
4082
+ var TaskDropCreateInlineSchema = external_exports.object({
4083
+ name: external_exports.string().trim().min(1).max(80),
4084
+ description: external_exports.string().trim().max(500).optional()
4085
+ });
4086
+ var TaskDropSubscribeInputSchema = external_exports.object({
4087
+ taskDropId: external_exports.string().min(1),
4088
+ email: EmailAddress,
4089
+ walletAddress: EthAddress.optional(),
4090
+ source: TaskDropSourceSchema.optional().default("drop_page")
4091
+ });
4092
+ var TaskDropSubscribeResponseSchema = external_exports.object({
4093
+ subscribed: external_exports.boolean(),
4094
+ alreadySubscribed: external_exports.boolean(),
4095
+ email: EmailAddress,
4096
+ taskDropId: external_exports.string(),
4097
+ scope: external_exports.literal("drop")
4098
+ });
4099
+ var TaskDropOfficialSubscribeInputSchema = external_exports.object({
4100
+ email: EmailAddress,
4101
+ walletAddress: EthAddress.optional(),
4102
+ source: TaskDropSourceSchema.optional().default("taskdrop_landing")
4103
+ });
4104
+ var TaskDropOfficialSubscribeResponseSchema = external_exports.object({
4105
+ subscribed: external_exports.boolean(),
4106
+ alreadySubscribed: external_exports.boolean(),
4107
+ email: EmailAddress,
4108
+ scope: external_exports.literal("official")
4109
+ });
4110
+ var TaskDropStatusInputSchema = external_exports.object({
4111
+ taskDropId: external_exports.string().min(1),
4112
+ email: EmailAddress
4113
+ });
4114
+ var TaskDropStatusResponseSchema = external_exports.object({
4115
+ subscribed: external_exports.boolean(),
4116
+ taskDropId: external_exports.string(),
4117
+ scope: TaskDropSubscriptionScopeSchema.nullable()
4118
+ });
4119
+ var TaskDropOfficialStatusInputSchema = external_exports.object({
4120
+ email: EmailAddress
4121
+ });
4122
+ var TaskDropOfficialStatusResponseSchema = external_exports.object({
4123
+ subscribed: external_exports.boolean(),
4124
+ scope: external_exports.literal("official").nullable()
4125
+ });
4126
+ var TaskDropAnnouncementInputSchema = external_exports.object({
4127
+ taskDropId: external_exports.string().min(1)
4128
+ });
4129
+ var TaskDropAnnouncementResponseSchema = external_exports.object({
4130
+ taskDropId: external_exports.string().min(1),
4131
+ announcedAt: external_exports.string().datetime(),
4132
+ alreadyAnnounced: external_exports.boolean(),
4133
+ sent: external_exports.number().int().nonnegative(),
4134
+ failed: external_exports.number().int().nonnegative(),
4135
+ pending: external_exports.number().int().nonnegative(),
4136
+ total: external_exports.number().int().nonnegative()
4137
+ });
4138
+ var TaskDropListByOwnerInputSchema = external_exports.object({
4139
+ ownerAddress: EthAddress
4140
+ });
4141
+ var TaskDropGetInputSchema = external_exports.object({
4142
+ taskDropId: external_exports.string().min(1)
4143
+ });
4144
+ var TaskDropSummarySchema = external_exports.object({
4145
+ id: external_exports.string().min(1),
4146
+ ownerAddress: EthAddress,
4147
+ officialWalletAddress: EthAddress,
4148
+ isOfficial: external_exports.boolean(),
4149
+ name: external_exports.string().min(1).max(80),
4150
+ description: external_exports.string().max(500).nullable(),
4151
+ createdAt: external_exports.string().datetime(),
4152
+ announcedAt: external_exports.string().datetime().nullable()
4153
+ }).refine((drop) => drop.officialWalletAddress === drop.ownerAddress, {
4154
+ message: "officialWalletAddress must match ownerAddress",
4155
+ path: ["officialWalletAddress"]
4156
+ });
4157
+ var TaskDropTaskSchema = external_exports.object({
4158
+ id: external_exports.string().min(1),
4159
+ description: external_exports.string(),
4160
+ reward: external_exports.string().regex(/^\d+$/),
4161
+ status: external_exports.string().min(1),
4162
+ mode: external_exports.string().min(1),
4163
+ tags: external_exports.array(external_exports.string()),
4164
+ createdAt: external_exports.string().datetime(),
4165
+ expiryTime: external_exports.string().datetime()
4166
+ });
4167
+ var TaskDropPageDataSchema = external_exports.object({
4168
+ drop: TaskDropSummarySchema,
4169
+ tasks: external_exports.array(TaskDropTaskSchema)
4170
+ });
4171
+
4522
4172
  // ../../packages/shared/dist/schemas/task.schemas.js
4523
4173
  var TaskMode = external_exports.enum(["bounty", "claim", "pitch", "benchmark", "auction"]);
4524
4174
  var TaskStatus = external_exports.enum([
@@ -4565,7 +4215,21 @@ var PendingActionSchema = external_exports.object({
4565
4215
  requiresPayment: external_exports.boolean().optional(),
4566
4216
  paymentAmount: external_exports.string().nullable().optional(),
4567
4217
  availableAfter: external_exports.string().nullable().optional(),
4568
- availableUntil: external_exports.string().nullable().optional()
4218
+ availableUntil: external_exports.string().nullable().optional(),
4219
+ targetWorker: external_exports.string().nullable().optional()
4220
+ });
4221
+ var TaskAwardSchema = external_exports.object({
4222
+ workerAddress: external_exports.string(),
4223
+ workerAgentId: external_exports.string().nullable(),
4224
+ workerActorType: external_exports.enum(["agent", "human"]),
4225
+ rank: external_exports.number().int().positive(),
4226
+ isPrimary: external_exports.boolean(),
4227
+ grossAmount: external_exports.string(),
4228
+ workerPayment: external_exports.string(),
4229
+ platformFee: external_exports.string(),
4230
+ settlementTxHash: external_exports.string(),
4231
+ settledAt: external_exports.string(),
4232
+ rating: external_exports.number().min(0).max(100).nullable()
4569
4233
  });
4570
4234
  var TaskCreateSchema = external_exports.object({
4571
4235
  description: external_exports.string().min(1, "Description is required").max(2e3, "Description is too long"),
@@ -4589,8 +4253,17 @@ var TaskCreateSchema = external_exports.object({
4589
4253
  evaluatorFeeBps: external_exports.number().min(0).max(1e4).optional(),
4590
4254
  evaluationWindowHours: external_exports.number().positive().optional(),
4591
4255
  appealWindowHours: external_exports.number().positive().optional(),
4592
- disputeResolver: external_exports.string().optional()
4256
+ disputeResolver: external_exports.string().optional(),
4257
+ taskDropId: external_exports.string().min(1).optional(),
4258
+ taskDropCreate: TaskDropCreateInlineSchema.optional()
4593
4259
  }).superRefine((input, ctx) => {
4260
+ if (input.taskDropId && input.taskDropCreate) {
4261
+ ctx.addIssue({
4262
+ code: external_exports.ZodIssueCode.custom,
4263
+ path: ["taskDropId"],
4264
+ message: "Provide taskDropId or taskDropCreate, not both"
4265
+ });
4266
+ }
4594
4267
  if (input.mode !== "auction")
4595
4268
  return;
4596
4269
  const toBaseUnits = (value) => value !== void 0 && /^[0-9]+$/.test(value) ? BigInt(value) : null;
@@ -4655,8 +4328,6 @@ var TaskResponseSchema = external_exports.object({
4655
4328
  expiryTime: external_exports.string(),
4656
4329
  status: TaskStatus,
4657
4330
  tags: external_exports.array(external_exports.string()),
4658
- worker: external_exports.string().nullable(),
4659
- rating: external_exports.number().min(0).max(100).nullable(),
4660
4331
  mode: TaskMode,
4661
4332
  stakeRequired: external_exports.boolean(),
4662
4333
  stakeBps: external_exports.number(),
@@ -4669,6 +4340,14 @@ var TaskResponseSchema = external_exports.object({
4669
4340
  claimedAt: external_exports.string().nullable(),
4670
4341
  platformFeeBps: external_exports.number(),
4671
4342
  submissionCount: external_exports.number().optional().default(0),
4343
+ awardCount: external_exports.number().int().nonnegative().optional(),
4344
+ // Read-time projection of the rank-1 task_awards row -- not a separately
4345
+ // written field, so it cannot drift out of sync the way the old worker/
4346
+ // rating compatibility fields could (see ADR-0006). null before settlement.
4347
+ primaryAward: external_exports.object({
4348
+ workerAddress: external_exports.string(),
4349
+ rating: external_exports.number().min(0).max(100).nullable()
4350
+ }).nullable().optional(),
4672
4351
  pitchCount: external_exports.number().optional().default(0),
4673
4352
  requesterAgentId: external_exports.string().nullable().optional(),
4674
4353
  requesterActorType: external_exports.enum(["agent", "human"]).optional(),
@@ -4699,6 +4378,11 @@ var TaskResponseSchema = external_exports.object({
4699
4378
  netReward: external_exports.string().nullable().optional(),
4700
4379
  pendingActions: PendingActionSchema.array().optional(),
4701
4380
  selfAward: external_exports.boolean().nullable().optional(),
4381
+ taskDropId: external_exports.string().nullable().optional(),
4382
+ taskDrop: external_exports.object({
4383
+ id: external_exports.string(),
4384
+ name: external_exports.string()
4385
+ }).nullable().optional(),
4702
4386
  hooks: external_exports.array(external_exports.string()).optional()
4703
4387
  });
4704
4388
  var TaskListInputSchema = external_exports.object({
@@ -4730,6 +4414,7 @@ var TaskInboxResponseSchema = external_exports.object({
4730
4414
  });
4731
4415
  var TaskDetailResponseSchema = TaskResponseSchema.extend({
4732
4416
  pendingActions: PendingActionSchema.array(),
4417
+ awards: TaskAwardSchema.array().optional(),
4733
4418
  dreamsPerUsdc: external_exports.string().optional(),
4734
4419
  bonusBps: external_exports.number().optional(),
4735
4420
  estimatedUsdBonusValue: external_exports.string().optional(),
@@ -5056,10 +4741,10 @@ var BidResponseSchema = external_exports.object({
5056
4741
  });
5057
4742
 
5058
4743
  // ../../packages/shared/dist/schemas/wallet.schemas.js
5059
- var EthAddress = external_exports.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid Ethereum address");
4744
+ var EthAddress2 = external_exports.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid Ethereum address");
5060
4745
  var SetWithdrawalAddressInputSchema = external_exports.object({
5061
- walletAddress: EthAddress,
5062
- withdrawalAddress: EthAddress,
4746
+ walletAddress: EthAddress2,
4747
+ withdrawalAddress: EthAddress2,
5063
4748
  signature: external_exports.string().min(1)
5064
4749
  });
5065
4750
  var SetWithdrawalAddressOutputSchema = external_exports.object({
@@ -5084,7 +4769,7 @@ var AuthorizationSchema = external_exports.object({
5084
4769
  nonce: external_exports.string()
5085
4770
  });
5086
4771
  var WithdrawInputSchema = external_exports.object({
5087
- from: EthAddress,
4772
+ from: EthAddress2,
5088
4773
  amountBaseUnits: external_exports.string().min(1),
5089
4774
  authorization: AuthorizationSchema,
5090
4775
  signature: external_exports.string().min(1)
@@ -5098,8 +4783,8 @@ var DreamsBalanceOutputSchema = external_exports.object({
5098
4783
  claimableBaseUnits: external_exports.string()
5099
4784
  });
5100
4785
  var WithdrawDreamsInputSchema = external_exports.object({
5101
- workerAddress: EthAddress,
5102
- destination: EthAddress,
4786
+ workerAddress: EthAddress2,
4787
+ destination: EthAddress2,
5103
4788
  nonce: external_exports.string().min(1),
5104
4789
  validBefore: external_exports.string().min(1),
5105
4790
  signature: external_exports.string().min(1)
@@ -5346,6 +5031,78 @@ var ResolveDisputeInputSchema = external_exports.object({
5346
5031
  });
5347
5032
  var EvaluatorTimeoutInputSchema = external_exports.object({ taskId: external_exports.string() });
5348
5033
 
5034
+ // ../../packages/shared/dist/schemas/legal.schemas.js
5035
+ var LegalDocumentTypeSchema = external_exports.enum([
5036
+ "terms_of_service",
5037
+ "privacy_policy",
5038
+ "risk_disclosure",
5039
+ "acceptable_use_policy"
5040
+ ]);
5041
+ var LegalDocumentSlugSchema = external_exports.enum(["terms", "privacy", "risks", "acceptable-use"]);
5042
+ var LegalSha256DigestSchema = external_exports.string().regex(/^sha256:[a-f0-9]{64}$/);
5043
+ var LegalBundleDocumentSchema = external_exports.object({
5044
+ contentHash: LegalSha256DigestSchema,
5045
+ slug: LegalDocumentSlugSchema,
5046
+ summary: external_exports.string(),
5047
+ title: external_exports.string(),
5048
+ type: LegalDocumentTypeSchema,
5049
+ url: external_exports.string().url(),
5050
+ version: external_exports.string()
5051
+ });
5052
+ var LegalBundleSchema = external_exports.object({
5053
+ acceptanceAvailable: external_exports.boolean(),
5054
+ acceptanceStatement: external_exports.string(),
5055
+ bundleDigest: LegalSha256DigestSchema,
5056
+ documents: external_exports.array(LegalBundleDocumentSchema),
5057
+ effectiveAt: external_exports.string().nullable(),
5058
+ enforcementEnabled: external_exports.boolean(),
5059
+ privyAppId: external_exports.string().nullable(),
5060
+ publishedAt: external_exports.string(),
5061
+ status: external_exports.enum(["draft", "approved"]),
5062
+ version: external_exports.string()
5063
+ });
5064
+ var LegalSubjectTypeSchema = external_exports.enum(["privy_user", "wallet"]);
5065
+ var LegalStatusResponseSchema = external_exports.object({
5066
+ accepted: external_exports.boolean(),
5067
+ bundle: LegalBundleSchema,
5068
+ receipt: external_exports.string().optional(),
5069
+ subjectType: LegalSubjectTypeSchema.optional()
5070
+ });
5071
+ var LegalWalletAddressSchema = external_exports.string().regex(/^0x[a-fA-F0-9]{40}$/);
5072
+ var LegalAffirmationsSchema = external_exports.object({
5073
+ acknowledgedRisk: external_exports.literal(true),
5074
+ agreedToAcceptableUse: external_exports.literal(true),
5075
+ agreedToTerms: external_exports.literal(true),
5076
+ receivedPrivacyNotice: external_exports.literal(true)
5077
+ });
5078
+ var LegalChallengeInputSchema = external_exports.object({
5079
+ walletAddress: LegalWalletAddressSchema
5080
+ });
5081
+ var LegalChallengeResponseSchema = external_exports.object({
5082
+ bundle: LegalBundleSchema,
5083
+ expiresAt: external_exports.string(),
5084
+ issuedAt: external_exports.string(),
5085
+ message: external_exports.string(),
5086
+ nonce: external_exports.string().uuid(),
5087
+ walletAddress: LegalWalletAddressSchema
5088
+ });
5089
+ var LegalAcceptanceBundleSchema = external_exports.object({
5090
+ bundleDigest: LegalSha256DigestSchema,
5091
+ bundleVersion: external_exports.string().max(128)
5092
+ });
5093
+ var LegalWalletAcceptanceInputSchema = LegalAffirmationsSchema.merge(LegalAcceptanceBundleSchema).extend({
5094
+ nonce: external_exports.string().uuid(),
5095
+ signature: external_exports.string().regex(/^0x[a-fA-F0-9]{128}(?:[a-fA-F0-9]{2})?$/),
5096
+ walletAddress: LegalWalletAddressSchema
5097
+ });
5098
+ var LegalWebAcceptanceInputSchema = LegalAffirmationsSchema.merge(LegalAcceptanceBundleSchema);
5099
+ var LegalAcceptanceResponseSchema = external_exports.object({
5100
+ acceptedAt: external_exports.string(),
5101
+ bundleDigest: LegalSha256DigestSchema,
5102
+ bundleVersion: external_exports.string(),
5103
+ receipt: external_exports.string()
5104
+ });
5105
+
5349
5106
  // ../../packages/shared/dist/platform.constants.js
5350
5107
  var USDC_DECIMALS = 6;
5351
5108
 
@@ -5611,42 +5368,1112 @@ function modInverse(a, n) {
5611
5368
  [t, nextT] = [nextT, t - q * nextT];
5612
5369
  [r, nextR] = [nextR, r - q * nextR];
5613
5370
  }
5614
- if (r !== 1)
5615
- return 0;
5616
- return (t % n + n) % n;
5617
- }
5618
- var MIX_K_INV = modInverse(MIX_K, N);
5371
+ if (r !== 1)
5372
+ return 0;
5373
+ return (t % n + n) % n;
5374
+ }
5375
+ var MIX_K_INV = modInverse(MIX_K, N);
5376
+
5377
+ // ../../packages/shared/dist/lib/dreams.js
5378
+ var USDC_DECIMALS2 = 6n;
5379
+ var DREAMS_DECIMALS = 18n;
5380
+ var USDC_SCALE = 10n ** USDC_DECIMALS2;
5381
+ var DREAMS_SCALE = 10n ** DREAMS_DECIMALS;
5382
+ function dreamsToUsd(dreamsBaseUnits, dreamsPerUsdc) {
5383
+ const dreams = BigInt(dreamsBaseUnits);
5384
+ const rate = BigInt(dreamsPerUsdc);
5385
+ if (dreams <= 0n || rate <= 0n)
5386
+ return "0";
5387
+ return (dreams * USDC_SCALE / rate).toString();
5388
+ }
5389
+ function formatDreams(baseUnits) {
5390
+ const value = BigInt(baseUnits);
5391
+ const negative = value < 0n;
5392
+ const abs = negative ? -value : value;
5393
+ const whole = abs / DREAMS_SCALE;
5394
+ const frac = abs % DREAMS_SCALE;
5395
+ const fracStr = frac.toString().padStart(18, "0").replace(/0+$/, "");
5396
+ const sign = negative ? "-" : "";
5397
+ return fracStr.length > 0 ? `${sign}${whole}.${fracStr}` : `${sign}${whole}`;
5398
+ }
5399
+
5400
+ // ../../packages/shared/dist/lib/authMessages.js
5401
+ function buildSelectWorkerMessage(taskId, pitchId, workerAddress) {
5402
+ return `taskmarket:select-worker:${taskId}:${pitchId}:${workerAddress.toLowerCase()}`;
5403
+ }
5404
+
5405
+ // ../../packages/shared/dist/legal.js
5406
+ var LEGAL_RECEIPT_HEADER = "X-Taskmarket-Legal-Receipt";
5407
+ function buildLegalReceiptHeaders(receipt) {
5408
+ return receipt ? { [LEGAL_RECEIPT_HEADER]: receipt } : {};
5409
+ }
5410
+ var LEGAL_ENTITY = {
5411
+ registeredName: "Daydreams AI",
5412
+ jurisdiction: "[JURISDICTION OF INCORPORATION]",
5413
+ registeredAddress: "[REGISTERED ADDRESS]",
5414
+ legalNoticeEmail: "[LEGAL NOTICE EMAIL]"
5415
+ };
5416
+ var LEGAL_ACCEPTANCE_STATEMENT = "I agree to the Terms of Service and Acceptable Use Policy, acknowledge the Risk Disclosure, and confirm that I have been given the Privacy Policy.";
5417
+ var VERSION = "2026-07-draft-2";
5418
+ var EFFECTIVE_AT = null;
5419
+ var DRAFT_NOTICE = `> Draft for counsel review. This policy is not approved or active. The contracting entity details, launch jurisdictions, operating-model statements, and counsel decisions in square brackets must be completed and verified before activation.`;
5420
+ var POLICY_DATE_LINES = `Published: 15 July 2026
5421
+
5422
+ Effective date: ${EFFECTIVE_AT ?? "[COUNSEL TO APPROVE EFFECTIVE DATE]"}`;
5423
+ var termsOfService = {
5424
+ type: "terms_of_service",
5425
+ title: "Terms of Service",
5426
+ slug: "terms",
5427
+ version: VERSION,
5428
+ summary: "The contract governing access to Taskmarket and participation in its task marketplace.",
5429
+ markdown: `# Taskmarket Terms of Service
5430
+
5431
+ Version ${VERSION}
5432
+
5433
+ ${POLICY_DATE_LINES}
5434
+
5435
+ ${DRAFT_NOTICE}
5436
+
5437
+ These Terms of Service (the "Terms") are a binding agreement between you and ${LEGAL_ENTITY.registeredName}, a company registered in ${LEGAL_ENTITY.jurisdiction}, with its registered office at ${LEGAL_ENTITY.registeredAddress} ("Taskmarket", "we", "us", or "our"). They govern your access to and use of Taskmarket websites, APIs, command-line tools, smart-contract interfaces, relayers, communications services, and related software (collectively, the "Services").
5438
+
5439
+ ## 1. Acceptance and authority
5440
+
5441
+ By selecting the acceptance control, signing the Taskmarket legal-acceptance message, submitting an acceptance through an authorized integration, or using a feature that requires acceptance, you agree to these Terms and the Acceptable Use Policy and acknowledge the Privacy Policy and Risk Disclosure. If you act for a company, DAO, agent operator, principal, or other person, you represent that you have authority to bind that person. "You" includes that person and every software agent you authorize to use the Services.
5442
+
5443
+ You must be legally capable of entering this agreement, be at least 18 years old or the age of majority where you live, and not be prohibited from using the Services by law. You may not accept on behalf of an unidentified principal or allow an autonomous agent to accept unless a human or legal person has authorized the acceptance.
5444
+
5445
+ ## 2. Platform role and regulatory perimeter
5446
+
5447
+ Taskmarket provides software and infrastructure through which requesters can publish funded tasks and workers can discover, perform, submit, evaluate, or dispute work. Some actions are recorded or settled using smart contracts and digital assets on public blockchains. Taskmarket-operated interfaces may prepare or relay participant-authorized transactions, sponsor gas, collect disclosed platform fees, or integrate third-party identity, wallet, fiat-onramp, storage, messaging, RPC, or payment-facilitation services.
5448
+
5449
+ Unless Taskmarket expressly agrees otherwise in a separate signed writing, Taskmarket is not the requester, worker, employer, employee, partner, joint venturer, fiduciary, trustee, professional adviser, or agent of a marketplace participant and is not a party to a participant contract described in section 3. Taskmarket does not take title to task deliverables merely by operating the Services. A third-party provider's services are governed by its own terms, and Taskmarket does not control public blockchains or independently deployed smart contracts.
5450
+
5451
+ References to "escrow" describe technical locking and release conditions implemented by the applicable smart contract. They do not promise a regulated trust, bank, deposit, custody, money-transmission, payment, or escrow service, deposit insurance, or chargeback rights. A label or disclaimer in these Terms does not determine the regulatory classification of Taskmarket, a participant, or an activity. [COUNSEL TO CONFIRM THE CUSTODY, MONEY-TRANSMISSION, PAYMENT-SERVICE, VIRTUAL-ASSET, FINANCIAL-SERVICE, AND FIAT-ONRAMP ANALYSIS FOR EVERY LAUNCH JURISDICTION AND THE DEPLOYED OPERATING MODEL.]
5452
+
5453
+ ## 3. Task records and participant contracts
5454
+
5455
+ A "Task Record" is the version of a task's description, mode, reward or pricing rule, platform fee, deadlines, eligibility rules, acceptance or evaluation criteria, evaluator and dispute settings, intellectual-property terms, confidentiality requirements, linked materials, and other disclosed conditions presented when a participant takes the relevant action, together with the applicable onchain state and transaction prompt. Requesters must make the Task Record complete and internally consistent. Participants must preserve a copy of any offchain terms they rely on.
5456
+
5457
+ Each Task Record and the actions taken under it form a direct contract between the requester and each worker to the extent a contract is created under applicable law (a "Participant Contract"). Depending on the task mode, a worker manifests willingness to contract by claiming or accepting a task, submitting a bid or pitch, or submitting work to an open bounty or benchmark. The Participant Contract forms when the worker claims or accepts the task, the requester selects the worker's bid or pitch, or the worker submits to an open task, subject to applicable law. A requester's publication funds and offers the task subject to its disclosed mode; selection, acceptance, rejection, evaluation, appeal, cancellation, expiry, and payment rights are governed by the Task Record and protocol state. [COUNSEL TO CONFIRM CONTRACT-FORMATION EVENTS FOR EVERY SUPPORTED TASK MODE AGAINST THE PRODUCTION INTERFACE AND SMART CONTRACTS.]
5458
+
5459
+ The requester promises to fund and administer the task, apply the disclosed criteria in good faith, avoid material changes after worker commitment except as the Task Record and law permit, and authorize payment when the protocol conditions are satisfied. The worker promises to perform and submit the work in accordance with the Task Record and to deliver the disclosed rights, licences, provenance, and supporting materials. Evaluators and dispute resolvers are bound by their disclosed mandate and must apply the stated criteria impartially and in good faith.
5460
+
5461
+ If records conflict, mandatory law controls first. As between participants, the verified onchain state and signed transaction control settlement mechanics; the Task Record controls the promised scope and quality of work; and these Terms supply general rules. A smart-contract result does not extinguish a separate legal right or remedy that cannot lawfully be excluded. Taskmarket is not responsible for enforcing Participant Contracts outside the technical functions it expressly provides.
5462
+
5463
+ ## 4. Accounts, wallets, agents, and security
5464
+
5465
+ You are responsible for all wallets, credentials, devices, API tokens, private keys, agent configurations, and instructions used under your control. You must keep them secure, promptly revoke compromised credentials, and ensure that automated activity remains within the authority you granted. We may treat a valid cryptographic signature, authenticated session, API token, or legal-acceptance receipt as evidence that the associated action was authorized, subject to applicable law.
5466
+
5467
+ You must provide accurate information and must not impersonate another person, conceal the real operator of an agent when disclosure is required, or transfer access to a prohibited person. Loss of a key or credential may make assets or data irrecoverable. Taskmarket does not promise to restore access or reverse blockchain transactions.
5468
+
5469
+ ## 5. Marketplace responsibilities and worker status
5470
+
5471
+ Requesters are responsible for lawful task descriptions, sufficient specifications, funding, evaluation criteria, permissions, and timely decisions. Workers are responsible for determining whether they can lawfully and competently perform a task, for the accuracy and safety of submissions, and for delivering all promised rights and materials. Evaluators and dispute resolvers must act within their disclosed role and apply the stated criteria in good faith.
5472
+
5473
+ You must independently assess counterparties and outputs. You may not rely on rankings, identities, badges, agent metadata, reputation scores, automated checks, or platform displays as endorsements. You are responsible for human review where an output could affect rights, safety, finances, employment, credit, housing, health, legal matters, critical infrastructure, or other high-impact decisions.
5474
+
5475
+ Participants ordinarily act as independent businesses or contractors, not as Taskmarket employees. That description does not override the legal classification produced by the actual relationship. Requesters and workers are responsible for determining and complying with any employment, contractor, labour-hire, digital-platform-work, minimum-pay, working-time, workplace-safety, insurance, payroll, withholding, superannuation, benefit, licensing, or collective-right obligations that apply. Taskmarket will provide any rights, notices, records, consultation, deactivation process, or regulator cooperation that mandatory platform-work law requires. [COUNSEL TO ASSESS WORKER CLASSIFICATION AND DIGITAL LABOUR PLATFORM DUTIES IN EVERY LAUNCH JURISDICTION.]
5476
+
5477
+ If a participant acts as a trader, business, consumer, or small business, it must accurately disclose that status where the Services request it. A trader must provide all legally required identity, contact, pricing, cancellation, guarantee, and pre-contract information to its counterparty. Participants may not use Taskmarket to evade consumer, worker, tax, or professional obligations.
5478
+
5479
+ ## 6. Funding, fees, settlement, and taxes
5480
+
5481
+ Displayed rewards, platform fees, gas sponsorship, facilitator charges, evaluator compensation, worker stakes, rejection or dispute charges, and settlement rules may vary by task, mode, or network. Before authorizing an action, you must review the asset, amount, recipient, network, platform fee, third-party fee, exchange-rate basis, and conditions for release, refund, forfeiture, or expiry. The Task Record or transaction prompt controls task-specific economics if it conflicts with a general description in these Terms.
5482
+
5483
+ Task funding may be held and released by a smart contract according to its state rather than by Taskmarket. Blockchain transactions may be final once submitted. Smart-contract conditions may release, split, return, freeze, forfeit, or make funds unavailable without a manual remedy from Taskmarket. Fiat onramps, stablecoins, wallets, facilitators, and exchanges are independent services and may impose separate identity checks, fees, limits, reversals, freezes, or terms.
5484
+
5485
+ Taskmarket may screen, reject, delay, freeze, block, or report an interface, relay, wallet, payment, or withdrawal where required by law, a sanctions obligation, a binding order, or a provider restriction. Taskmarket will not intentionally retain or redirect participant assets except as the protocol, a participant authorization, or applicable law permits. [COUNSEL TO DEFINE REQUIRED CUSTOMER DUE DILIGENCE, SANCTIONS SCREENING, RECORDKEEPING, REPORTING, ASSET-BLOCKING, LICENSING, AND COMPLAINT CONTROLS BEFORE ACTIVATION.]
5486
+
5487
+ You are responsible for all taxes, reporting, withholding, invoices, registrations, and currency-conversion consequences arising from your activity. Amounts described in a fiat currency are informational unless expressly guaranteed. Stablecoins may lose value or become unavailable.
5488
+
5489
+ ## 7. Protocol disputes and existing positions
5490
+
5491
+ Taskmarket may provide protocol-based acceptance, rejection, appeal, evaluator, timeout, cancellation, refund, or dispute-resolution functions. Those functions are limited to their disclosed technical rules and are not a court or arbitration service unless an approved policy expressly says otherwise. You must observe all onchain and interface deadlines and retain supporting evidence. A protocol result may determine smart-contract settlement but does not prevent a participant from pursuing a non-waivable legal remedy against its counterparty.
5492
+
5493
+ If a new version of these Terms is required and you decline it, we may restrict new marketplace activity while preserving available public reads and designated exit or recovery actions. The availability of an exit action depends on the protocol state and applicable law; it is not a guarantee that every position can be unwound.
5494
+
5495
+ ## 8. Intellectual property and submissions
5496
+
5497
+ Taskmarket and its licensors retain rights in the Services, branding, interfaces, documentation, and software except for open-source components governed by their licenses. We grant you a limited, revocable, non-exclusive, non-transferable right to use the Services in accordance with these Terms.
5498
+
5499
+ As between marketplace participants, ownership and licensing of task inputs and outputs are determined by the Task Record, the Participant Contract, and applicable law. Unless a Task Record expressly provides a different rule, each participant retains what it owned before the task and the worker retains ownership of new deliverables; the worker grants the requester only a non-exclusive licence reasonably necessary to inspect and evaluate the submission. Any assignment or broader licence takes effect only to the extent stated in the Task Record and permitted by law, and [COUNSEL TO CONFIRM WHETHER IT IS CONDITIONED ON FULL PAYMENT]. Moral rights and similar rights are not waived except through a valid express waiver or consent.
5500
+
5501
+ You represent that you have all rights and permissions needed to upload, process, disclose, and license content and that you will provide required attribution, open-source notices, provenance, and usage restrictions. You grant Taskmarket a worldwide, non-exclusive licence to host, transmit, reproduce, transform, and display content solely as needed to operate, secure, and improve the Services, resolve complaints, and comply with law. This operational licence ends when no longer needed, subject to backups, evidence preservation, public records, and legal retention.
5502
+
5503
+ Taskmarket may operate an intellectual-property complaint and counter-notice process and may restrict disputed content while reviewing a complaint. [COUNSEL TO DEFINE THE APPLICABLE COPYRIGHT, TRADEMARK, REPEAT-INFRINGER, COUNTER-NOTICE, AND DESIGNATED-AGENT PROCESS FOR LAUNCH JURISDICTIONS.]
5504
+
5505
+ ## 9. Confidentiality and public blockchains
5506
+
5507
+ The Services do not create a general duty of confidentiality between participants. A Task Record must expressly identify confidential information, permitted recipients and uses, security requirements, and the duration of any confidentiality obligation. Do not place confidential, personal, export-controlled, privileged, or restricted information in public task fields, signatures, hashes, transaction calldata, content-addressed storage, or other permanent systems. Public blockchain information may be visible indefinitely and cannot generally be deleted by Taskmarket. A hash can still reveal information or become personal data when combined with other information.
5508
+
5509
+ ## 10. Compliance, sanctions, and acceptable use
5510
+
5511
+ You must comply with all laws that apply to you, including sanctions, export controls, anti-money-laundering obligations, anti-bribery rules, consumer and marketplace laws, intellectual-property laws, privacy laws, and rules governing automated decision-making. You may not use the Services from, for, or on behalf of a sanctioned jurisdiction, blocked person, or prohibited transaction. You must comply with the Acceptable Use Policy.
5512
+
5513
+ You must provide information reasonably required for identity, age, trader-status, source-of-funds, sanctions, export-control, tax, fraud, or other lawful checks. We may screen addresses, identities, locations, counterparties, content, or activity; request information; restrict access; reject or delay relaying; preserve records; block assets where legally required and technically possible; or report conduct where reasonably necessary for security, legal compliance, or platform integrity. Screening is not a representation that any participant or transaction is lawful.
5514
+
5515
+ ## 11. Mandatory rights, complaints, suspension, and termination
5516
+
5517
+ Nothing in these Terms excludes, restricts, or modifies mandatory consumer, small-business, worker, or contractor rights; statutory guarantees; cooling-off or cancellation rights; unfair-terms protections; privacy or payment rights; or regulator or court remedies. If a prohibited exclusion would otherwise apply, these Terms operate only to the maximum extent permitted by law. You may contact ${LEGAL_ENTITY.legalNoticeEmail} about a payment, safety, moderation, privacy, intellectual-property, deactivation, or other complaint. [COUNSEL AND PRODUCT TO DEFINE JURISDICTION-SPECIFIC COMPLAINT CATEGORIES, RESPONSE TARGETS, EXTERNAL ESCALATION, AND REQUIRED OMBUDSMAN OR REGULATOR DETAILS.]
5518
+
5519
+ You may stop using the Services at any time. We may limit, suspend, or terminate access; refuse or remove content; revoke platform credentials; or stop operating any feature where reasonably necessary for legal compliance, security, maintenance, abuse prevention, or material breach. Where feasible and lawful, we will preserve designated exit functions for existing positions, but smart-contract and third-party constraints may limit what we can do.
5520
+
5521
+ Where required by law, we will give reasons, advance notice, an opportunity to respond, and access to an internal or external review process before or after moderation, suspension, deactivation, or termination. Immediate action may be necessary for urgent harm, security, sanctions, fraud, illegality, or a binding order. The Acceptable Use Policy describes the general enforcement process.
5522
+
5523
+ Sections that by their nature should survive will survive, including ownership, payment, risk allocation, liability, indemnity, records, disputes, and notices.
5524
+
5525
+ ## 12. Disclaimers
5526
+
5527
+ THE SERVICES ARE PROVIDED "AS IS" AND "AS AVAILABLE". TO THE MAXIMUM EXTENT PERMITTED BY LAW, TASKMARKET DISCLAIMS ALL EXPRESS, IMPLIED, AND STATUTORY WARRANTIES, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, ACCURACY, SECURITY, AVAILABILITY, AND WARRANTIES ARISING FROM COURSE OF DEALING. TASKMARKET DOES NOT WARRANT THAT CODE, SMART CONTRACTS, AGENTS, OUTPUTS, PAYMENTS, DATA, OR THIRD-PARTY SERVICES ARE ERROR-FREE, SAFE, LAWFUL, OR AVAILABLE.
5528
+
5529
+ Nothing in these Terms excludes a warranty, guarantee, right, or remedy that cannot lawfully be excluded.
5530
+
5531
+ ## 13. Limitation of liability
5532
+
5533
+ TO THE MAXIMUM EXTENT PERMITTED BY LAW, TASKMARKET AND ITS AFFILIATES, PERSONNEL, AND SUPPLIERS WILL NOT BE LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, PUNITIVE, OR CONSEQUENTIAL LOSS; LOST PROFITS, REVENUE, DATA, GOODWILL, OPPORTUNITY, OR DIGITAL ASSETS; OR LOSS ARISING FROM KEYS, AGENTS, OUTPUTS, COUNTERPARTIES, SMART CONTRACTS, NETWORKS, FORKS, OR THIRD-PARTY SERVICES.
5534
+
5535
+ TASKMARKET'S AGGREGATE LIABILITY ARISING OUT OF THE SERVICES WILL NOT EXCEED THE GREATER OF (A) FEES YOU PAID DIRECTLY TO TASKMARKET DURING THE SIX MONTHS BEFORE THE EVENT GIVING RISE TO LIABILITY OR (B) [LIABILITY CAP TO BE APPROVED BY COUNSEL]. These limits apply across all theories of liability and do not apply where prohibited by law.
5536
+
5537
+ ## 14. Indemnity
5538
+
5539
+ To the extent permitted by law, you will defend, indemnify, and hold harmless Taskmarket and its affiliates and personnel from third-party claims, losses, and reasonable costs arising from your tasks, submissions, agents, content, breach of these Terms, infringement, unlawful conduct, or failure to pay taxes. This obligation does not apply to the extent caused by a protected party's fraud, wilful misconduct, or liability that cannot be excluded.
5540
+
5541
+ ## 15. Changes, electronic communications, and records
5542
+
5543
+ We may update these Terms. Material changes will receive a new version and effective date, and we may require fresh assent before new activity. An acceptance record identifies the exact document version and content hash presented. Continuing to use ungated public features does not by itself record assent to a new version.
5544
+
5545
+ You consent to receive agreements, disclosures, receipts, and notices electronically where law permits. A click, authenticated request, wallet signature, agent action within granted authority, or other electronic record may evidence assent or authorization, but does not bind a person who did not authorize it. You are responsible for keeping contact details current and retaining copies of Task Records, transaction prompts, and notices. Taskmarket may retain versioned policies, content hashes, signatures, session evidence, timestamps, IP addresses, user agents, and related audit records as described in the Privacy Policy.
5546
+
5547
+ ## 16. Governing law and legal disputes
5548
+
5549
+ These Terms are governed by the laws of [GOVERNING LAW JURISDICTION], excluding conflict-of-law rules. The courts of [EXCLUSIVE FORUM] have exclusive jurisdiction, subject to any mandatory consumer rights and any dispute process counsel adds before approval. [COUNSEL TO INSERT ANY ARBITRATION, CLASS-ACTION, OR CONSUMER-SPECIFIC TERMS.]
5550
+
5551
+ ## 17. General
5552
+
5553
+ These Terms, the Acceptable Use Policy, the Risk Disclosure, the applicable Task Record, and any expressly incorporated participant terms are the entire agreement about their subject matter. The Privacy Policy is a notice and does not form a contract except where applicable law provides otherwise. If a provision is unenforceable, it will be enforced to the maximum lawful extent and the rest remains effective. A failure to enforce is not a waiver. You may not assign these Terms without our consent; we may assign them as part of a reorganization, financing, or transfer of the Services, subject to law. Neither party is liable for delay caused by an event beyond its reasonable control, but this does not excuse payment, asset-protection, or mandatory legal obligations. Headings are for convenience only.
5554
+
5555
+ ## 18. Notices and contact
5556
+
5557
+ Legal notices to Taskmarket must be sent to ${LEGAL_ENTITY.legalNoticeEmail} and, where required, to ${LEGAL_ENTITY.registeredAddress}. We may send operational or legal notices through the Services, to your registered contact, or by another lawful method.
5558
+ `
5559
+ };
5560
+ var privacyPolicy = {
5561
+ type: "privacy_policy",
5562
+ title: "Privacy Policy",
5563
+ slug: "privacy",
5564
+ version: VERSION,
5565
+ summary: "How Taskmarket collects, uses, shares, retains, and protects personal information.",
5566
+ markdown: `# Taskmarket Privacy Policy
5567
+
5568
+ Version ${VERSION}
5569
+
5570
+ ${POLICY_DATE_LINES}
5571
+
5572
+ ${DRAFT_NOTICE}
5573
+
5574
+ This Privacy Policy explains how ${LEGAL_ENTITY.registeredName}, registered in ${LEGAL_ENTITY.jurisdiction} at ${LEGAL_ENTITY.registeredAddress} ("Taskmarket", "we", "us", or "our"), handles personal information when you use the Services. Taskmarket is the controller, APP entity, business, or other organization responsible for the processing described here to the extent the applicable law assigns that role. Marketplace participants are independently responsible for personal information they place in tasks, submissions, evaluations, or agent workflows unless a written data-processing agreement says otherwise. [COUNSEL TO CONFIRM TASKMARKET'S PRIVACY ROLE FOR EACH DATA FLOW AND LAUNCH JURISDICTION.]
5575
+
5576
+ ## 1. Information we collect
5577
+
5578
+ We may collect:
5579
+
5580
+ - **Account and contact data:** Privy user identifier, email address, social-login details made available to us, wallet addresses, usernames, organization details, and support communications.
5581
+ - **Wallet and blockchain data:** public addresses, signatures, transactions, task and payment events, token balances needed for a feature, contract interactions, and information derived from public ledgers.
5582
+ - **Marketplace content:** task descriptions, bids, pitches, proofs, submissions, evaluations, disputes, ratings, files, messages, agent profiles, public keys, and metadata. Content may contain personal information supplied by you or another participant.
5583
+ - **Technical and usage data:** IP address, device and browser information, timestamps, request identifiers, logs, pages and commands used, error reports, security events, and cookie or similar-technology data.
5584
+ - **Acceptance evidence:** policy versions and content hashes, acceptance method, timestamp, wallet signature or authenticated Privy session identifier, receipt hash, IP address, and user agent.
5585
+ - **Compliance data:** screening results, risk indicators, country or region inferred from technical data, and information reasonably needed to investigate abuse or meet legal obligations.
5586
+ - **Sensitive or regulated data:** identity-verification records, government identifiers, sanctions matches, precise location, or other sensitive information only where a feature or legal obligation requires it. Do not include health, biometric, financial-account, government-identifier, criminal-record, or other sensitive data in marketplace content unless the Task Record expressly permits it and a lawful basis and safeguards are in place.
5587
+
5588
+ We obtain information from you, your authorized agents and integrations, identity and wallet providers, counterparties, public blockchains, service providers, and publicly available sources. Where required, we provide a contextual collection notice at or before collection explaining the data, purpose, recipients, consequences of not providing it, and applicable choices. This Policy does not replace a collection notice required for a particular feature or jurisdiction.
5589
+
5590
+ ## 2. Why we use information
5591
+
5592
+ We use information to provide and administer the Services; authenticate users and agents; create and display marketplace records; facilitate contract interactions, payments, communications, and support; maintain acceptance evidence; prevent fraud and security incidents; debug and improve the Services; enforce policies; perform sanctions and compliance checks where implemented; comply with law; establish or defend legal claims; and communicate material service or policy changes.
5593
+
5594
+ Where a legal basis is required, we rely as applicable on performance of a contract, legitimate interests in operating and securing the marketplace, compliance with legal obligations, protection of vital interests, consent for a specific optional purpose, or another basis available under local law. [COUNSEL AND PRODUCT TO COMPLETE A PURPOSE-BY-PURPOSE DATA INVENTORY AND LAWFUL-BASIS ASSESSMENT.] You may withdraw consent for future processing where consent is the basis, without affecting earlier processing. The Privacy Policy is a notice and is not itself blanket consent to every use of information. We will not use personal information for a materially incompatible purpose without another lawful basis and any notice or consent the law requires.
5595
+
5596
+ ## 3. Public and immutable information
5597
+
5598
+ Wallet addresses, transactions, signatures, hashes, task events, and other data placed on a public blockchain are available to anyone and may be copied, analyzed, or retained by independent parties. We do not control public networks and generally cannot alter or erase their records. Avoid submitting personal or confidential information onchain. Offchain deletion requests do not remove independent blockchain records.
5599
+
5600
+ ## 4. How we disclose information
5601
+
5602
+ We may disclose information:
5603
+
5604
+ - to other marketplace participants and the public where a feature is public or disclosure is needed to perform a task;
5605
+ - to cloud, database, storage, authentication, wallet, RPC, blockchain, payment-facilitation, email, security, analytics, and support providers acting for us;
5606
+ - to professional advisers, auditors, insurers, investors, and transaction counterparties under appropriate duties;
5607
+ - to authorities or other parties when reasonably necessary to comply with law, enforce rights, protect safety or security, or investigate abuse; and
5608
+ - in connection with a merger, financing, reorganization, insolvency, or transfer of all or part of the business.
5609
+
5610
+ Public blockchains and independently operated protocols are not our processors and may use data for their own purposes. Before activation, Taskmarket must publish and maintain a service-provider register covering material authentication, wallet, cloud, database, storage, RPC, fiat-onramp, payment, email, security, analytics, and support providers, their purposes, and processing locations. [PRODUCT AND COUNSEL TO COMPLETE AND APPROVE THAT REGISTER.] We do not sell personal information for money. [COUNSEL TO CONFIRM WHETHER ANY ADVERTISING, ANALYTICS, ONCHAIN ENRICHMENT, OR PROVIDER ACTIVITY IS A "SALE," "SHARE," OR TARGETED ADVERTISING UNDER APPLICABLE US STATE LAW.]
5611
+
5612
+ ## 5. International transfers
5613
+
5614
+ The Services and our providers may process information in countries other than yours. Before launch, Taskmarket will identify relevant origin and destination countries and, where required, use recognized transfer safeguards, perform transfer-risk assessments, and make required disclosures. Safeguards may include adequacy decisions, contractual clauses, or another lawful mechanism. Public blockchain data is globally accessible and cannot be limited to a selected processing location. [COUNSEL TO APPROVE THE INTERNATIONAL-TRANSFER MECHANISM AND COUNTRY DISCLOSURES.]
5615
+
5616
+ ## 6. Retention and deletion
5617
+
5618
+ We retain information only for as long as reasonably needed for the purposes above, including the life of an account or marketplace position and an appropriate period afterward. We may retain acceptance evidence, transaction and accounting records, security logs, dispute materials, and compliance records for the applicable limitation, tax, anti-fraud, sanctions, or regulatory period. Retention depends on the data's sensitivity, purpose, legal requirements, and risk. Before activation, Taskmarket must adopt and implement a documented retention schedule.
5619
+
5620
+ [PRODUCT AND COUNSEL TO APPROVE A DOCUMENTED RETENTION SCHEDULE WITH A SPECIFIC PERIOD OR OBJECTIVE CRITERION FOR EACH DATA CATEGORY, INCLUDING ACCOUNTS, AUTHENTICATION, WALLET DATA, MARKETPLACE CONTENT, UPLOADS, ACCEPTANCE EVIDENCE, PAYMENT RECORDS, LOGS, SUPPORT, SCREENING, DISPUTES, AND BACKUPS.] When a period expires, we delete, de-identify, or securely isolate the information unless preservation is required by law, a legal hold, security investigation, or an unresolved position or dispute. Account deletion does not necessarily delete public content, records needed to complete or defend a transaction, or data outside our control. Public blockchain and content-addressed records may persist indefinitely.
5621
+
5622
+ ## 7. Security and incident response
5623
+
5624
+ We use administrative, technical, and organizational measures designed to protect information, including access controls, encryption where appropriate, credential hashing, logging, environment separation, vendor review, backup controls, vulnerability management, and incident response proportionate to the risk. No system, wallet, transmission, or storage method is completely secure. You are responsible for securing your keys, devices, integrations, and agent instructions and for avoiding sensitive data in public fields.
5625
+
5626
+ We maintain a process to identify, contain, investigate, remediate, document, and learn from suspected breaches. Where a breach is an eligible data breach or otherwise legally notifiable, we will notify affected people and the competent regulator within the time and with the information required by applicable law. [PRODUCT AND COUNSEL TO APPROVE THE INCIDENT-RESPONSE PLAN, RESPONSIBLE CONTACTS, PROVIDER ESCALATIONS, AND JURISDICTION-SPECIFIC ASSESSMENT AND NOTIFICATION DEADLINES.]
5627
+
5628
+ ## 8. Your choices and rights
5629
+
5630
+ Depending on where you live, you may have rights to access, correct, delete, restrict, object to, or receive a portable copy of personal information; withdraw consent; opt out of certain sale, sharing, profiling, or targeted advertising; and complain to a privacy or data-protection authority. You may also have a right not to be discriminated against for exercising a right.
5631
+
5632
+ Send requests to ${LEGAL_ENTITY.legalNoticeEmail}. We may verify your identity and authority, refuse or limit a request where permitted, and retain information that law or compelling legitimate interests require. If you use an authorized agent, we may require proof of authorization. We will respond within the period required by the law that applies to the request and explain applicable appeal rights. [COUNSEL AND PRODUCT TO DEFINE VERIFIED REQUEST INTAKE, SEARCH, EXPORT, CORRECTION, DELETION, RESTRICTION, OBJECTION, APPEAL, AND RECORDKEEPING PROCEDURES.] Requests cannot require us to alter a public blockchain or data controlled solely by another participant, but we will address offchain copies and links within our control as applicable law requires.
5633
+
5634
+ ## 9. Cookies and tracking technologies
5635
+
5636
+ We and our authentication and infrastructure providers may use cookies, local storage, or similar technologies for login sessions, security, preferences, legal-acceptance receipts, and service operation. We will not deploy non-essential analytics, advertising, or cross-context tracking before obtaining consent where required. [PRODUCT AND COUNSEL TO COMPLETE A COOKIE AND SDK INVENTORY, IDENTIFY EACH PROVIDER, PURPOSE, DATA, DURATION, AND CLASSIFICATION, IMPLEMENT WITHDRAWAL AND REGION-SPECIFIC CONSENT CONTROLS, AND PUBLISH THE RESULTING COOKIE NOTICE BEFORE APPROVAL.]
5637
+
5638
+ ## 10. Automated systems
5639
+
5640
+ We may use automated tools to detect abuse, prioritize security review, calculate public marketplace metrics, or screen activity. These tools may be inaccurate. Taskmarket does not intend to make solely automated decisions producing legal or similarly significant effects about individuals unless disclosed with safeguards required by law. Before using personal information for such a decision, Taskmarket will assess the system, document the information and decision types, provide any required explanation and human review, and publish disclosures required by applicable law. Marketplace participants control their own agents and evaluations and are independently responsible for their processing.
5641
+
5642
+ ## 11. Children
5643
+
5644
+ The Services are not directed to children under 18, and we do not knowingly permit them to enter marketplace transactions. Contact us if you believe a child provided personal information so we can investigate and take appropriate action.
5645
+
5646
+ ## 12. Third-party services
5647
+
5648
+ The Services may link to or interoperate with wallets, authentication providers, fiat onramps, payment facilitators, blockchains, storage networks, websites, and agents controlled by others. Their privacy practices are governed by their own notices, not this Policy. Taskmarket will use contracts and diligence required by applicable law for providers processing personal information on its behalf, but cannot control an independent participant, provider, or public network.
5649
+
5650
+ ## 13. Accountability and privacy by design
5651
+
5652
+ Taskmarket will maintain records of material data flows, purposes, lawful bases where required, providers, transfers, retention, security controls, rights requests, and incidents. New features involving sensitive information, systematic monitoring, large-scale profiling, financial activity, agent evaluation, or other high risk will receive a privacy and legal assessment before launch. This Policy describes practices; it does not replace the internal procedures and systems required to comply with privacy law.
5653
+
5654
+ ## 14. Changes
5655
+
5656
+ We may update this Policy. We will publish the new version and effective date and provide additional notice where required. If a change requires consent under law, we will request it separately. Material legal-bundle changes may require a fresh Taskmarket acknowledgement.
5657
+
5658
+ ## 15. Contact and region-specific disclosures
5659
+
5660
+ - Privacy questions and requests: ${LEGAL_ENTITY.legalNoticeEmail}
5661
+ - Postal address: ${LEGAL_ENTITY.registeredAddress}
5662
+ - Representative or data protection officer: [INSERT IF REQUIRED]
5663
+ - Relevant supervisory authority details: [INSERT AFTER JURISDICTION REVIEW]
5664
+ - Region-specific rights, collection notices, financial incentives, and appeals: [INSERT FOR EACH LAUNCH JURISDICTION]
5665
+ `
5666
+ };
5667
+ var riskDisclosure = {
5668
+ type: "risk_disclosure",
5669
+ title: "Risk Disclosure",
5670
+ slug: "risks",
5671
+ version: VERSION,
5672
+ summary: "Material technical, financial, marketplace, legal, and autonomous-agent risks.",
5673
+ markdown: `# Taskmarket Risk Disclosure
5674
+
5675
+ Version ${VERSION}
5676
+
5677
+ ${POLICY_DATE_LINES}
5678
+
5679
+ ${DRAFT_NOTICE}
5680
+
5681
+ Taskmarket involves experimental software, autonomous agents, public blockchains, smart contracts, cryptographic credentials, and digital assets. It is not suitable for every person or use case. This disclosure highlights material risks but cannot identify every risk. You should obtain independent legal, tax, financial, security, and technical advice appropriate to your circumstances.
5682
+
5683
+ ## 1. Smart-contract and protocol risk
5684
+
5685
+ Smart contracts may contain defects, behave unexpectedly, be upgraded, pause, become unavailable, or be exploited. Transaction ordering, reorganization, congestion, gas pricing, RPC failures, chain forks, validator behavior, and dependencies may delay or change outcomes. A transaction shown as pending or successful in an interface may later fail or be reorganized. Code and onchain state, not a summary in the interface, determine protocol execution.
5686
+
5687
+ ## 2. Irreversibility and loss
5688
+
5689
+ Blockchain signatures and transactions are generally irreversible. Funds sent to an incorrect address, network, contract, or task may be permanently lost. Deadlines can expire without notice, and a missed acceptance, appeal, evaluation, timeout, or withdrawal step may change who receives funds. Taskmarket may be technically unable to stop or reverse an executed transaction.
5690
+
5691
+ ## 3. Stablecoin, token, and market risk
5692
+
5693
+ USDC and any reward token are issued or governed by third parties. They may deviate from their reference value, be frozen, blacklisted, upgraded, redeemed on changed terms, lose liquidity, or become illegal or unavailable in a jurisdiction. Token prices and exchange rates can move rapidly. A displayed fiat equivalent is not guaranteed. Gas sponsorship, facilitator availability, and fee levels may change.
5694
+
5695
+ ## 4. Wallet and credential risk
5696
+
5697
+ Anyone who controls your private key, device key, session, API token, or agent runtime may act through it. Malware, phishing, prompt injection, compromised dependencies, insecure backups, exposed environment variables, or operator error can cause unauthorized tasks, signatures, disclosures, or loss. Embedded and external wallets have distinct custody and recovery models. Review them before use.
5698
+
5699
+ ## 5. Autonomous-agent risk
5700
+
5701
+ Agents can hallucinate, misunderstand instructions, exceed authority, expose secrets, infringe rights, produce unsafe code, manipulate other agents, or take economically irrational actions. Agent outputs may be inaccurate, biased, malicious, or unsuitable for production. An agent can be induced by untrusted task content or files to disregard its operator's instructions. Apply least privilege, spending limits, sandboxing, monitoring, and human review proportionate to the impact.
5702
+
5703
+ ## 6. Marketplace and counterparty risk
5704
+
5705
+ Participants may be anonymous, pseudonymous, unavailable, unqualified, or dishonest. Identity records, wallet history, rankings, and reputation signals can be incomplete, manipulated, or associated with a compromised key. A requester may provide unlawful or defective materials. A worker may submit plagiarized, insecure, or unusable work. Evaluation is subjective, and protocol dispute mechanisms may not provide a legally enforceable or satisfactory remedy.
5706
+
5707
+ ## 7. Escrow and settlement risk
5708
+
5709
+ "Escrow" is a description of technical smart-contract conditions and does not guarantee legal trust, custody, deposit protection, chargeback rights, or recovery. Funds may be locked, split, released, refunded, or stranded according to contract state. Relayers and payment facilitators may reject, delay, or incorrectly process requests. The legal classification of a payment or facilitation activity can vary by jurisdiction and may impose obligations on Taskmarket or participants.
5710
+
5711
+ Fiat onramps, embedded wallets, stablecoin issuers, payment facilitators, RPC providers, and relayers may require identity checks, impose limits, decline a transaction, freeze an account or asset, reverse an offchain leg, become insolvent, or stop supporting a jurisdiction. Taskmarket may be unable to complete a transaction or recover value held or controlled by one of those providers.
5712
+
5713
+ ## 8. Legal, regulatory, sanctions, and tax risk
5714
+
5715
+ Laws governing digital assets, money transmission, marketplaces, employment, digital platform work, consumer protection, sanctions, export controls, AI, privacy, intellectual property, and taxation are evolving and differ across jurisdictions. A regulator or court may restrict the Services, characterize Taskmarket or a participant differently from these documents, require licensing, registration, employment benefits, refunds, disclosures, reporting, or tax withholding, invalidate a contract term, or order assets or access blocked. Sanctions and fraud screening may produce false positives, delay lawful activity, or fail to identify prohibited activity. You remain responsible for your own compliance and taxes, but this does not transfer a legal obligation that applicable law places on Taskmarket.
5716
+
5717
+ ## 9. Data and confidentiality risk
5718
+
5719
+ Public blockchain records and content-addressed data may be permanent, globally visible, and correlated with your identity. Encryption may be implemented incorrectly or later weakened. Files and agent outputs may contain malware, personal information, confidential material, or hidden instructions. Never assume a task, message, proof, hash, or submission is private merely because the interface does not prominently display it.
5720
+
5721
+ ## 10. Availability and change risk
5722
+
5723
+ The Services may experience downtime, data loss, rate limits, discontinued features, incompatible updates, or third-party failures. Open-source software may change without notice. Taskmarket may restrict a region, wallet, task, or action for legal or security reasons. Exit functions can depend on current protocol state and are not guaranteed to remain available in every circumstance.
5724
+
5725
+ ## 11. No advice or guarantee
5726
+
5727
+ Information, metrics, rankings, examples, documentation, and agent-generated content are not legal, tax, financial, investment, cybersecurity, or professional advice. Taskmarket does not recommend a participant, task, token, strategy, or output and does not guarantee profit, payment, quality, compliance, recovery, or fitness for purpose.
5728
+
5729
+ ## 12. Acknowledgement
5730
+
5731
+ By acknowledging this Risk Disclosure, you confirm that you understand that you can lose funds, data, rights, time, and access; that autonomous and blockchain systems may fail; that counterparties may not perform; and that you are able to bear the risks of the activities you authorize. An acknowledgement is not a waiver of rights that cannot lawfully be waived.
5732
+ `
5733
+ };
5734
+ var acceptableUsePolicy = {
5735
+ type: "acceptable_use_policy",
5736
+ title: "Acceptable Use Policy",
5737
+ slug: "acceptable-use",
5738
+ version: VERSION,
5739
+ summary: "Rules protecting people, systems, markets, and the lawful operation of Taskmarket.",
5740
+ markdown: `# Taskmarket Acceptable Use Policy
5741
+
5742
+ Version ${VERSION}
5743
+
5744
+ ${POLICY_DATE_LINES}
5745
+
5746
+ ${DRAFT_NOTICE}
5747
+
5748
+ This Acceptable Use Policy (the "AUP") forms part of the Taskmarket Terms of Service. It applies to every user, operator, requester, worker, evaluator, resolver, integration, and autonomous agent using the Services. You are responsible for configuring and supervising your agents so that they comply.
5749
+
5750
+ ## 1. Illegal and regulated activity
5751
+
5752
+ You may not use Taskmarket to request, facilitate, conceal, promote, or perform activity that violates applicable law. This includes money laundering, terrorist financing, sanctions evasion, bribery, fraud, trafficking, illegal gambling, unlicensed financial services, unlawful securities activity, tax evasion, or trade in prohibited goods or services. You may not transact with a blocked person or for a prohibited jurisdiction or purpose.
5753
+
5754
+ Do not offer regulated legal, medical, financial, employment, credit, housing, insurance, or other high-impact services unless every required authorization, professional duty, disclosure, safeguard, and human review is in place.
5755
+
5756
+ You must provide accurate information and reasonably cooperate with lawful identity, age, trader-status, source-of-funds, wallet or counterparty screening, sanctions, export-control, fraud, tax, or licensing checks. You may not structure activity, use another wallet or agent, conceal a principal or beneficiary, or route through a third party to evade a restriction, reporting duty, or compliance control.
5757
+
5758
+ ## 2. Harm, exploitation, and dangerous services
5759
+
5760
+ You may not create or accept tasks that facilitate violence, abuse, exploitation, stalking, extortion, doxxing, non-consensual intimate content, child sexual abuse material, human trafficking, or credible threats. You may not develop biological, chemical, radiological, nuclear, or weapons capabilities intended to cause harm, or provide operational instructions that materially enable such harm.
5761
+
5762
+ ## 3. Cybersecurity abuse
5763
+
5764
+ You may perform security research only with clear authorization and within the authorized scope. You may not deploy malware or ransomware; steal credentials or tokens; conduct phishing, credential stuffing, denial-of-service, destructive exploitation, botnet activity, unauthorized access, covert persistence, data exfiltration, or supply-chain compromise; or evade security controls. Proof-of-concept work must be contained and must not expose unrelated systems or data.
5765
+
5766
+ ## 4. Privacy, surveillance, and identity
5767
+
5768
+ You may not unlawfully collect, infer, buy, sell, expose, or process personal information; conduct covert surveillance; identify an anonymous person without a lawful basis; create deceptive biometric or identity systems; impersonate another person; or submit confidential, privileged, health, financial, authentication, or government-identifier data without authority and appropriate safeguards.
5769
+
5770
+ ## 5. Intellectual property and deceptive content
5771
+
5772
+ You may not infringe intellectual-property, confidentiality, publicity, database, or contractual rights; submit plagiarized work; remove provenance or rights information; create deceptive endorsements; or falsely represent the source, authorship, testing, security, or capabilities of an output. Synthetic or modified media must be disclosed where non-disclosure would mislead or violate law.
5773
+
5774
+ An intellectual-property complaint must identify the protected work or right, the challenged material, the complainant's authority, contact details, a good-faith basis, and any statement required by applicable law. Affected users may submit a counter-notice where available. False, abusive, or retaliatory complaints violate this AUP. [COUNSEL TO DEFINE THE DESIGNATED CONTACT, REPEAT-INFRINGER STANDARD, COUNTER-NOTICE PROCESS, RESTORATION TIMELINE, AND JURISDICTION-SPECIFIC FORMALITIES.]
5775
+
5776
+ ## 6. Market and platform integrity
5777
+
5778
+ You may not manipulate ratings, bids, rankings, disputes, rewards, identities, task outcomes, or token markets; collude to extract rewards; create sham tasks or submissions; use multiple identities to evade controls; exploit another participant's mistake in bad faith; spam; scrape in a way that degrades the Services; bypass rate limits or access controls; probe secrets; or interfere with Taskmarket, its smart contracts, relayers, facilitators, communications, or other users.
5779
+
5780
+ You may not submit a task or file whose primary purpose is to prompt-inject, deceive, compromise, or redirect an agent outside the disclosed task. Security testing of agent defenses requires explicit scope and containment.
5781
+
5782
+ ## 7. Resource and communications abuse
5783
+
5784
+ Do not send unsolicited bulk messages, deceptive email, malicious attachments, or communications that violate anti-spam or marketing laws. Do not consume disproportionate infrastructure, automate abusive retries, or use the Services to mine cryptocurrency or proxy unrelated traffic without written authorization.
5785
+
5786
+ ## 8. Required safeguards
5787
+
5788
+ You must use permissions and data proportionate to the task; disclose material constraints and hazards; validate inputs and outputs; protect credentials; inspect third-party files; maintain lawful records; stop an agent that behaves unexpectedly; and provide human oversight for high-impact or irreversible actions. If you discover a vulnerability, avoid unnecessary access or harm and report it to ${LEGAL_ENTITY.legalNoticeEmail}.
5789
+
5790
+ ## 9. Enforcement, reporting, and appeals
5791
+
5792
+ We may investigate, preserve evidence, remove content, reject relaying, rate-limit, suspend credentials, restrict wallets or regions, notify affected parties, or report conduct to service providers or authorities. We may act on reasonable risk indicators without first proving a legal violation. Where feasible and lawful, enforcement will be calibrated to the risk and will not intentionally prevent designated withdrawal, refund, cancellation, data-access, deletion, or logout functions needed to protect existing rights.
5793
+
5794
+ You must cooperate with reasonable investigations and must not retaliate against a reporter. Evasion or attempted evasion is a separate violation.
5795
+
5796
+ Report suspected violations to ${LEGAL_ENTITY.legalNoticeEmail} with the relevant task, wallet, transaction, message, and supporting facts. Do not include unnecessary sensitive data. [COUNSEL AND PRODUCT TO DEFINE AN ENFORCEMENT APPEAL PROCESS, RESPONSE TARGETS, AND REQUIRED ILLEGAL-CONTENT REPORTING CHANNELS FOR EACH LAUNCH JURISDICTION.]
5797
+
5798
+ Unless immediate action or legal restrictions prevent it, Taskmarket will provide the affected person with the nature and basis of a material restriction and access to a notice and appeal process. Review will be performed by a person or system with appropriate independence and authority, and the outcome and available external escalation will be communicated where required. [COUNSEL AND PRODUCT TO DEFINE NOTICE CONTENT, ENFORCEMENT LEVELS, PRESERVATION RULES, REVIEW INDEPENDENCE, RESPONSE TARGETS, REPEAT-VIOLATION RULES, EXTERNAL REDRESS, TRANSPARENCY REPORTING, AND REQUIRED ILLEGAL-CONTENT CHANNELS FOR EACH LAUNCH JURISDICTION.]
5799
+ `
5800
+ };
5801
+ function buildWalletLegalAcceptanceMessage(input) {
5802
+ const documentLines = input.documents.map((document) => `- ${document.title} (${document.version}): ${document.contentHash}`).join("\n");
5803
+ return `Taskmarket legal acceptance
5804
+
5805
+ Wallet: ${input.walletAddress}
5806
+ Bundle: ${input.bundleVersion}
5807
+ Issued at: ${input.issuedAt}
5808
+ Expires at: ${input.expiresAt}
5809
+ Nonce: ${input.nonce}
5810
+
5811
+ Documents:
5812
+ ${documentLines}
5813
+
5814
+ ${LEGAL_ACCEPTANCE_STATEMENT}`;
5815
+ }
5816
+
5817
+ // src/commands/init.ts
5818
+ import { privateKeyToAccount as privateKeyToAccount3 } from "viem/accounts";
5819
+
5820
+ // src/lib/keystore.ts
5821
+ import { createCipheriv, createDecipheriv, randomBytes } from "crypto";
5822
+ import { promises as fs } from "fs";
5823
+ import os from "os";
5824
+ import path from "path";
5825
+ import { privateKeyToAccount } from "viem/accounts";
5826
+ function getKeystorePath() {
5827
+ return path.join(os.homedir(), ".taskmarket", "keystore.json");
5828
+ }
5829
+ function generateKeypair() {
5830
+ const keyBytes = randomBytes(32);
5831
+ const privateKey = "0x" + keyBytes.toString("hex");
5832
+ const account = privateKeyToAccount(privateKey);
5833
+ return { privateKey, address: account.address };
5834
+ }
5835
+ function encryptPrivateKey(deviceEncryptionKeyHex, privateKey) {
5836
+ const key = Buffer.from(deviceEncryptionKeyHex, "hex");
5837
+ const iv = randomBytes(12);
5838
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
5839
+ const plaintext = Buffer.from(privateKey, "utf8");
5840
+ const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
5841
+ const tag = cipher.getAuthTag();
5842
+ return Buffer.concat([iv, tag, encrypted]).toString("hex");
5843
+ }
5844
+ function decryptPrivateKey(deviceEncryptionKeyHex, encryptedHex) {
5845
+ const key = Buffer.from(deviceEncryptionKeyHex, "hex");
5846
+ const data = Buffer.from(encryptedHex, "hex");
5847
+ const iv = data.subarray(0, 12);
5848
+ const tag = data.subarray(12, 28);
5849
+ const ciphertext = data.subarray(28);
5850
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
5851
+ decipher.setAuthTag(tag);
5852
+ const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
5853
+ return decrypted.toString("utf8");
5854
+ }
5855
+ async function saveKeystore(keystore, keystorePath) {
5856
+ const p = keystorePath ?? getKeystorePath();
5857
+ await fs.mkdir(path.dirname(p), { recursive: true });
5858
+ await fs.writeFile(p, JSON.stringify(keystore, null, 2), "utf8");
5859
+ }
5860
+ async function loadKeystore(keystorePath) {
5861
+ const p = keystorePath ?? getKeystorePath();
5862
+ let data;
5863
+ try {
5864
+ data = await fs.readFile(p, "utf8");
5865
+ } catch {
5866
+ throw new Error(`Keystore not found at ${p}. Run 'taskmarket init' first.`);
5867
+ }
5868
+ return JSON.parse(data);
5869
+ }
5870
+ async function keystoreExists(keystorePath) {
5871
+ const p = keystorePath ?? getKeystorePath();
5872
+ try {
5873
+ await fs.access(p);
5874
+ return true;
5875
+ } catch {
5876
+ return false;
5877
+ }
5878
+ }
5879
+
5880
+ // src/lib/api.ts
5881
+ var API_URL = process.env.TASKMARKET_API_URL ?? "https://api.taskmarket.dev";
5882
+ var API_ORIGIN = new URL(API_URL).origin;
5883
+ function legalReceiptHeadersForKeystore(keystore, path3, method) {
5884
+ const canSend = keystore.legalAcceptanceApiOrigin === API_ORIGIN && (method === "POST" || path3 === "/api/legal/status");
5885
+ return canSend ? buildLegalReceiptHeaders(keystore.legalAcceptanceReceipt) : {};
5886
+ }
5887
+ async function legalReceiptHeaders(path3, method) {
5888
+ try {
5889
+ const keystore = await loadKeystore();
5890
+ return legalReceiptHeadersForKeystore(keystore, path3, method);
5891
+ } catch {
5892
+ return {};
5893
+ }
5894
+ }
5895
+ async function apiGet(path3, options) {
5896
+ const legalHeaders = await legalReceiptHeaders(path3, "GET");
5897
+ const res = await fetch(`${API_URL}${path3}`, {
5898
+ method: "GET",
5899
+ redirect: "error",
5900
+ headers: {
5901
+ "Content-Type": "application/json",
5902
+ ...legalHeaders,
5903
+ ...options?.headers ?? {}
5904
+ }
5905
+ });
5906
+ const body = await res.json();
5907
+ if (!res.ok) {
5908
+ throw new Error(`GET ${path3} failed (${res.status}): ${JSON.stringify(body)}`);
5909
+ }
5910
+ return body;
5911
+ }
5912
+ async function apiPost(path3, body) {
5913
+ const legalHeaders = await legalReceiptHeaders(path3, "POST");
5914
+ const res = await fetch(`${API_URL}${path3}`, {
5915
+ method: "POST",
5916
+ redirect: "error",
5917
+ headers: { "Content-Type": "application/json", ...legalHeaders },
5918
+ body: JSON.stringify(body)
5919
+ });
5920
+ const result = await res.json();
5921
+ if (!res.ok) {
5922
+ throw new Error(`POST ${path3} failed (${res.status}): ${JSON.stringify(result)}`);
5923
+ }
5924
+ return result;
5925
+ }
5926
+
5927
+ // src/lib/output.ts
5928
+ function printResult(data) {
5929
+ console.log(JSON.stringify({ ok: true, data }));
5930
+ }
5931
+ function printError(message) {
5932
+ process.stderr.write(JSON.stringify({ ok: false, error: message }) + "\n");
5933
+ process.exit(1);
5934
+ }
5935
+
5936
+ // src/lib/agent.ts
5937
+ async function pollAgentId(address, maxWaitMs = 6e4) {
5938
+ const interval = 3e3;
5939
+ const deadline = Date.now() + maxWaitMs;
5940
+ while (Date.now() < deadline) {
5941
+ await new Promise((r) => setTimeout(r, interval));
5942
+ try {
5943
+ const res = await fetch(`${API_URL}/api/identity/status?address=${address}`);
5944
+ if (res.ok) {
5945
+ const data = await res.json();
5946
+ if (data.agentId) return data.agentId;
5947
+ }
5948
+ } catch {
5949
+ }
5950
+ }
5951
+ return null;
5952
+ }
5953
+
5954
+ // src/lib/device-registration.ts
5955
+ async function registerDevice(input) {
5956
+ const response = await fetch(`${API_URL}/api/devices`, {
5957
+ body: JSON.stringify({ publicKey: input.publicKey, walletAddress: input.walletAddress }),
5958
+ headers: {
5959
+ "Content-Type": "application/json",
5960
+ ...buildLegalReceiptHeaders(input.legalReceipt)
5961
+ },
5962
+ method: "POST",
5963
+ redirect: "error"
5964
+ });
5965
+ if (!response.ok) {
5966
+ const text = await response.text().catch(() => "");
5967
+ throw new Error(`Device registration failed (${response.status}): ${text}`);
5968
+ }
5969
+ return await response.json();
5970
+ }
5971
+
5972
+ // src/lib/encryption.ts
5973
+ import { createECDH, hkdfSync, createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes2 } from "crypto";
5974
+ var VERSION2 = 1;
5975
+ var EPH_PUB_LEN = 65;
5976
+ var IV_LEN = 12;
5977
+ var TAG_LEN = 16;
5978
+ var HEADER_LEN = 1 + EPH_PUB_LEN + IV_LEN + TAG_LEN;
5979
+ function ecdhSharedSecret(privateKeyHex, otherPubKeyHex) {
5980
+ const ecdh = createECDH("secp256k1");
5981
+ ecdh.setPrivateKey(Buffer.from(privateKeyHex.replace(/^0x/, ""), "hex"));
5982
+ const shared = ecdh.computeSecret(Buffer.from(otherPubKeyHex, "hex"));
5983
+ return shared;
5984
+ }
5985
+ function hkdfKey(sharedSecret) {
5986
+ return Buffer.from(hkdfSync("sha256", sharedSecret, Buffer.alloc(0), "taskmarket-ecies-v1", 32));
5987
+ }
5988
+ function aesGcmEncrypt(key, iv, plaintext) {
5989
+ const cipher = createCipheriv2("aes-256-gcm", key, iv);
5990
+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
5991
+ const tag = cipher.getAuthTag();
5992
+ return { ciphertext, tag };
5993
+ }
5994
+ function aesGcmDecrypt(key, iv, tag, ciphertext) {
5995
+ const decipher = createDecipheriv2("aes-256-gcm", key, iv);
5996
+ decipher.setAuthTag(tag);
5997
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
5998
+ }
5999
+ function derivePublicKey(privateKeyHex) {
6000
+ const ecdh = createECDH("secp256k1");
6001
+ ecdh.setPrivateKey(Buffer.from(privateKeyHex.replace(/^0x/, ""), "hex"));
6002
+ return ecdh.getPublicKey(void 0, "uncompressed").toString("hex");
6003
+ }
6004
+ function deriveCompressedPublicKey(privateKeyHex) {
6005
+ const ecdh = createECDH("secp256k1");
6006
+ ecdh.setPrivateKey(Buffer.from(privateKeyHex.replace(/^0x/, ""), "hex"));
6007
+ return ecdh.getPublicKey(void 0, "compressed").toString("hex");
6008
+ }
6009
+ function encryptForRecipient(fileBuffer, recipientPubKeyHex) {
6010
+ const ephEcdh = createECDH("secp256k1");
6011
+ ephEcdh.generateKeys();
6012
+ const ephPubKey = ephEcdh.getPublicKey(void 0, "uncompressed");
6013
+ const ephPrivKeyHex = ephEcdh.getPrivateKey("hex");
6014
+ const shared = ecdhSharedSecret(ephPrivKeyHex, recipientPubKeyHex);
6015
+ const aesKey = hkdfKey(shared);
6016
+ const iv = randomBytes2(IV_LEN);
6017
+ const { ciphertext, tag } = aesGcmEncrypt(aesKey, iv, fileBuffer);
6018
+ return Buffer.concat([Buffer.from([VERSION2]), ephPubKey, iv, tag, ciphertext]);
6019
+ }
6020
+ function decryptWithPrivateKey(fileBuffer, privateKeyHex) {
6021
+ if (fileBuffer.length < HEADER_LEN + 1) {
6022
+ throw new Error("Decryption failed: invalid key or corrupted file");
6023
+ }
6024
+ const version2 = fileBuffer[0];
6025
+ if (version2 !== VERSION2) {
6026
+ throw new Error(`Decryption failed: unsupported file version 0x${version2.toString(16)}`);
6027
+ }
6028
+ const ephPubKeyHex = fileBuffer.subarray(1, 1 + EPH_PUB_LEN).toString("hex");
6029
+ const iv = fileBuffer.subarray(1 + EPH_PUB_LEN, 1 + EPH_PUB_LEN + IV_LEN);
6030
+ const tag = fileBuffer.subarray(1 + EPH_PUB_LEN + IV_LEN, 1 + EPH_PUB_LEN + IV_LEN + TAG_LEN);
6031
+ const ciphertext = fileBuffer.subarray(1 + EPH_PUB_LEN + IV_LEN + TAG_LEN);
6032
+ const shared = ecdhSharedSecret(privateKeyHex, ephPubKeyHex);
6033
+ const aesKey = hkdfKey(shared);
6034
+ try {
6035
+ return aesGcmDecrypt(aesKey, iv, tag, ciphertext);
6036
+ } catch {
6037
+ throw new Error("Decryption failed: invalid key or corrupted file");
6038
+ }
6039
+ }
6040
+
6041
+ // src/commands/legal/index.ts
6042
+ import { Command } from "commander";
6043
+ import { createInterface } from "readline/promises";
6044
+
6045
+ // src/lib/signer.ts
6046
+ import { privateKeyToAccount as privateKeyToAccount2 } from "viem/accounts";
6047
+ import { toHex } from "viem";
6048
+ async function fetchDeviceKey(deviceId, apiToken, keyServerUrl) {
6049
+ const base = keyServerUrl ?? API_URL;
6050
+ const res = await fetch(`${base}/api/devices/${deviceId}/key`, {
6051
+ method: "POST",
6052
+ headers: { "Content-Type": "application/json" },
6053
+ body: JSON.stringify({ deviceId, apiToken })
6054
+ });
6055
+ if (!res.ok) {
6056
+ const text = await res.text().catch(() => "");
6057
+ throw new Error(`Failed to fetch device key (${res.status}): ${text}`);
6058
+ }
6059
+ const data = await res.json();
6060
+ return data.deviceEncryptionKey;
6061
+ }
6062
+ async function signTypedData(typedData, keystore) {
6063
+ const account = await createWalletAccountFromKeystore(keystore);
6064
+ const sig = await account.signTypedData(typedData);
6065
+ return sig;
6066
+ }
6067
+ async function signMessage(message, keystore) {
6068
+ const account = await createWalletAccountFromKeystore(keystore);
6069
+ const sig = await account.signMessage({ message });
6070
+ return sig;
6071
+ }
6072
+ async function createWalletAccountFromKeystore(keystore) {
6073
+ const dek = await fetchDeviceKey(keystore.deviceId, keystore.apiToken, keystore.keyServerUrl);
6074
+ const privateKey = decryptPrivateKey(dek, keystore.encryptedKey);
6075
+ return privateKeyToAccount2(privateKey);
6076
+ }
6077
+ async function getWalletAddress() {
6078
+ const keystore = await loadKeystore();
6079
+ return keystore.walletAddress;
6080
+ }
6081
+ async function createTransferAuthorization(accept, keystore) {
6082
+ const now = Math.floor(Date.now() / 1e3);
6083
+ const authorization = {
6084
+ from: keystore.walletAddress,
6085
+ to: accept.payTo,
6086
+ value: accept.amount,
6087
+ validAfter: String(now - 60),
6088
+ validBefore: String(now + accept.maxTimeoutSeconds),
6089
+ nonce: toHex(crypto.getRandomValues(new Uint8Array(32)))
6090
+ };
6091
+ const signature = await signTypedData(
6092
+ {
6093
+ domain: accept.extra.eip712.domain,
6094
+ types: accept.extra.eip712.types,
6095
+ primaryType: accept.extra.eip712.primaryType,
6096
+ message: authorization
6097
+ },
6098
+ keystore
6099
+ );
6100
+ return { authorization, signature };
6101
+ }
6102
+
6103
+ // src/commands/legal/index.ts
6104
+ var affirmations = {
6105
+ acknowledgedRisk: true,
6106
+ agreedToAcceptableUse: true,
6107
+ agreedToTerms: true,
6108
+ receivedPrivacyNotice: true
6109
+ };
6110
+ async function confirmAcceptance(bundle, assumeYes) {
6111
+ const documentList = bundle.documents.map(
6112
+ (document) => `- ${document.title} (${document.version})
6113
+ ${document.url}
6114
+ ${document.contentHash}`
6115
+ ).join("\n");
6116
+ process.stderr.write(
6117
+ `
6118
+ Review the Taskmarket legal bundle before accepting:
6119
+ ${documentList}
6120
+
6121
+ ${bundle.acceptanceStatement}
6122
+
6123
+ `
6124
+ );
6125
+ if (assumeYes) return;
6126
+ if (!process.stdin.isTTY) {
6127
+ throw new Error("Interactive confirmation is unavailable. Re-run with --yes after review.");
6128
+ }
6129
+ const prompt = createInterface({ input: process.stdin, output: process.stderr });
6130
+ try {
6131
+ const answer = await prompt.question("Type I AGREE to sign this acceptance: ");
6132
+ if (answer.trim() !== "I AGREE") {
6133
+ throw new Error("Legal acceptance was not confirmed");
6134
+ }
6135
+ } finally {
6136
+ prompt.close();
6137
+ }
6138
+ }
6139
+ function bundleEvidence(bundle) {
6140
+ return JSON.stringify({
6141
+ acceptanceStatement: bundle.acceptanceStatement,
6142
+ bundleDigest: bundle.bundleDigest,
6143
+ documents: bundle.documents.map(({ contentHash, title, type, version: version2 }) => ({
6144
+ contentHash,
6145
+ title,
6146
+ type,
6147
+ version: version2
6148
+ })),
6149
+ version: bundle.version
6150
+ });
6151
+ }
6152
+ function validateLegalChallenge(reviewedBundle, challenge, expectedWalletAddress) {
6153
+ if (challenge.bundle.version !== reviewedBundle.version || bundleEvidence(challenge.bundle) !== bundleEvidence(reviewedBundle)) {
6154
+ throw new Error("The legal bundle changed while acceptance was in progress. Review it again.");
6155
+ }
6156
+ if (challenge.walletAddress.toLowerCase() !== expectedWalletAddress.toLowerCase()) {
6157
+ throw new Error("The legal acceptance challenge is for a different wallet.");
6158
+ }
6159
+ const expectedMessage = buildWalletLegalAcceptanceMessage({
6160
+ bundleVersion: challenge.bundle.version,
6161
+ documents: challenge.bundle.documents,
6162
+ expiresAt: challenge.expiresAt,
6163
+ issuedAt: challenge.issuedAt,
6164
+ nonce: challenge.nonce,
6165
+ walletAddress: challenge.walletAddress
6166
+ });
6167
+ if (challenge.message !== expectedMessage) {
6168
+ throw new Error("The legal acceptance challenge does not match the reviewed bundle.");
6169
+ }
6170
+ }
6171
+ async function acceptLegalBundle(options) {
6172
+ const bundle = LegalBundleSchema.parse(options.bundle ?? await apiGet("/api/legal/current"));
6173
+ if (!bundle.acceptanceAvailable) {
6174
+ throw new Error("The current legal bundle is a counsel-review draft and cannot be accepted.");
6175
+ }
6176
+ await confirmAcceptance(bundle, options.assumeYes);
6177
+ const challenge = LegalChallengeResponseSchema.parse(
6178
+ await apiPost("/api/legal/challenge", {
6179
+ walletAddress: options.walletAddress
6180
+ })
6181
+ );
6182
+ validateLegalChallenge(bundle, challenge, options.walletAddress);
6183
+ const signature = await options.signMessage(challenge.message);
6184
+ const result = LegalAcceptanceResponseSchema.parse(
6185
+ await apiPost("/api/legal/accept/wallet", {
6186
+ ...affirmations,
6187
+ bundleDigest: bundle.bundleDigest,
6188
+ bundleVersion: bundle.version,
6189
+ nonce: challenge.nonce,
6190
+ signature,
6191
+ walletAddress: options.walletAddress
6192
+ })
6193
+ );
6194
+ if (result.bundleDigest !== bundle.bundleDigest || result.bundleVersion !== bundle.version) {
6195
+ throw new Error("The server returned a receipt for a different legal bundle.");
6196
+ }
6197
+ return result;
6198
+ }
6199
+ var statusCommand = new Command("status").description("Show whether this CLI has accepted the current legal bundle").action(async () => {
6200
+ const keystore = await loadKeystore();
6201
+ const status = LegalStatusResponseSchema.parse(await apiGet("/api/legal/status"));
6202
+ if (status.receipt) {
6203
+ await saveKeystore({
6204
+ ...keystore,
6205
+ legalAcceptanceApiOrigin: API_ORIGIN,
6206
+ legalAcceptanceBundleVersion: status.bundle.version,
6207
+ legalAcceptanceReceipt: status.receipt
6208
+ });
6209
+ }
6210
+ printResult({
6211
+ accepted: status.accepted,
6212
+ bundleDigest: status.bundle.bundleDigest,
6213
+ bundleVersion: status.bundle.version,
6214
+ enforcementEnabled: status.bundle.enforcementEnabled,
6215
+ status: status.bundle.status,
6216
+ documents: status.bundle.documents.map(({ title, url, version: version2 }) => ({
6217
+ title,
6218
+ url,
6219
+ version: version2
6220
+ }))
6221
+ });
6222
+ });
6223
+ var acceptCommand = new Command("accept").description("Review and sign the current Taskmarket legal bundle").option(
6224
+ "--yes",
6225
+ "Confirm acceptance non-interactively after the operator has reviewed every policy"
6226
+ ).action(async (options) => {
6227
+ const keystore = await loadKeystore();
6228
+ const result = await acceptLegalBundle({
6229
+ assumeYes: Boolean(options.yes),
6230
+ signMessage: (message) => signMessage(message, keystore),
6231
+ walletAddress: keystore.walletAddress
6232
+ });
6233
+ await saveKeystore({
6234
+ ...keystore,
6235
+ legalAcceptanceApiOrigin: API_ORIGIN,
6236
+ legalAcceptanceBundleVersion: result.bundleVersion,
6237
+ legalAcceptanceReceipt: result.receipt
6238
+ });
6239
+ printResult({
6240
+ accepted: true,
6241
+ acceptedAt: result.acceptedAt,
6242
+ bundleDigest: result.bundleDigest,
6243
+ bundleVersion: result.bundleVersion,
6244
+ walletAddress: keystore.walletAddress
6245
+ });
6246
+ });
6247
+ var legalCommand = new Command("legal").description(
6248
+ "Review and manage versioned Taskmarket legal acceptance"
6249
+ );
6250
+ legalCommand.addCommand(statusCommand);
6251
+ legalCommand.addCommand(acceptCommand);
6252
+
6253
+ // src/commands/init.ts
6254
+ function sanitizeEmailUsername(agentId, suffix) {
6255
+ const maxBase = 30 - 1 - suffix.length;
6256
+ if (maxBase < 2) return null;
6257
+ const base = agentId.toLowerCase().replace(/[^a-z0-9]/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "").slice(0, maxBase).replace(/-+$/, "");
6258
+ if (base.length < 2) return null;
6259
+ const candidate = `${base}-${suffix}`;
6260
+ return /^[a-z0-9][a-z0-9-]{1,28}[a-z0-9]$/.test(candidate) ? candidate : null;
6261
+ }
6262
+ async function tryRegisterEmail(deviceId, apiToken, username, explicit) {
6263
+ try {
6264
+ const reg = await apiPost("/api/emails/register", {
6265
+ deviceId,
6266
+ apiToken,
6267
+ username
6268
+ });
6269
+ return reg.emailAddress;
6270
+ } catch (err) {
6271
+ if (explicit) {
6272
+ const msg = err instanceof Error ? err.message : String(err);
6273
+ process.stderr.write(
6274
+ JSON.stringify({
6275
+ ok: false,
6276
+ error: `Email registration failed: ${msg}. Run: taskmarket email register --username ${username}`
6277
+ }) + "\n"
6278
+ );
6279
+ }
6280
+ return null;
6281
+ }
6282
+ }
6283
+ var initCommand = new Command2("init").description("Create and register a new agent wallet (safe to re-run)").option(
6284
+ "--email <username>",
6285
+ "Claim a custom email username (default: auto-generated from agent ID)"
6286
+ ).option(
6287
+ "--yes",
6288
+ "Confirm legal acceptance non-interactively after reviewing every current policy"
6289
+ ).action(async (opts) => {
6290
+ if (opts.email) {
6291
+ const check = await apiGet(
6292
+ `/api/emails/check-username?username=${encodeURIComponent(opts.email)}`
6293
+ );
6294
+ if (!check.available) {
6295
+ printError(`Email username "${opts.email}" is not available.`);
6296
+ }
6297
+ }
6298
+ if (await keystoreExists()) {
6299
+ const keystore = await loadKeystore();
6300
+ let agentId2 = keystore.agentId;
6301
+ if (!agentId2) {
6302
+ agentId2 = await pollAgentId(keystore.walletAddress);
6303
+ if (agentId2) {
6304
+ await saveKeystore({ ...keystore, agentId: agentId2 });
6305
+ }
6306
+ }
6307
+ let networkInfo2;
6308
+ try {
6309
+ const response = await apiGet("/trpc/network.info");
6310
+ networkInfo2 = response.result.data;
6311
+ } catch {
6312
+ }
6313
+ let emailAddress2 = null;
6314
+ try {
6315
+ const existing = await apiGet(`/api/agents/stats?address=${keystore.walletAddress}`);
6316
+ emailAddress2 = existing.emailAddress ?? null;
6317
+ } catch {
6318
+ }
6319
+ if (!emailAddress2) {
6320
+ const username2 = opts.email ?? (agentId2 && networkInfo2 ? sanitizeEmailUsername(agentId2, String(networkInfo2.chainId)) : null);
6321
+ if (username2) {
6322
+ emailAddress2 = await tryRegisterEmail(
6323
+ keystore.deviceId,
6324
+ keystore.apiToken,
6325
+ username2,
6326
+ !!opts.email
6327
+ );
6328
+ }
6329
+ }
6330
+ printResult({
6331
+ address: keystore.walletAddress,
6332
+ agentId: agentId2,
6333
+ network: networkInfo2?.networkName,
6334
+ chainId: networkInfo2?.chainId,
6335
+ emailAddress: emailAddress2
6336
+ });
6337
+ return;
6338
+ }
6339
+ const { privateKey, address } = generateKeypair();
6340
+ const publicKey = deriveCompressedPublicKey(privateKey);
6341
+ const legalBundle = LegalBundleSchema.parse(await apiGet("/api/legal/current"));
6342
+ const legalAcceptance = legalBundle.enforcementEnabled ? await acceptLegalBundle({
6343
+ assumeYes: Boolean(opts.yes),
6344
+ bundle: legalBundle,
6345
+ signMessage: (message) => privateKeyToAccount3(privateKey).signMessage({ message }),
6346
+ walletAddress: address
6347
+ }) : void 0;
6348
+ const {
6349
+ deviceId,
6350
+ apiToken,
6351
+ deviceEncryptionKey,
6352
+ agentId: initialAgentId
6353
+ } = await registerDevice({
6354
+ legalReceipt: legalAcceptance?.receipt,
6355
+ publicKey,
6356
+ walletAddress: address
6357
+ });
6358
+ const encryptedKey = encryptPrivateKey(deviceEncryptionKey, privateKey);
6359
+ let agentId = initialAgentId;
6360
+ await saveKeystore({
6361
+ encryptedKey,
6362
+ walletAddress: address,
6363
+ deviceId,
6364
+ apiToken,
6365
+ agentId,
6366
+ keyServerUrl: API_URL,
6367
+ ...legalAcceptance ? {
6368
+ legalAcceptanceApiOrigin: API_ORIGIN,
6369
+ legalAcceptanceBundleVersion: legalAcceptance.bundleVersion,
6370
+ legalAcceptanceReceipt: legalAcceptance.receipt
6371
+ } : {}
6372
+ });
6373
+ if (!agentId) {
6374
+ agentId = await pollAgentId(address);
6375
+ if (agentId) {
6376
+ const keystore = await loadKeystore();
6377
+ await saveKeystore({ ...keystore, agentId });
6378
+ }
6379
+ }
6380
+ let networkInfo;
6381
+ try {
6382
+ const response = await apiGet("/trpc/network.info");
6383
+ networkInfo = response.result.data;
6384
+ } catch {
6385
+ }
6386
+ const username = opts.email ?? (agentId && networkInfo ? sanitizeEmailUsername(agentId, String(networkInfo.chainId)) : null);
6387
+ const emailAddress = username ? await tryRegisterEmail(deviceId, apiToken, username, !!opts.email) : null;
6388
+ printResult({
6389
+ address,
6390
+ agentId,
6391
+ network: networkInfo?.networkName,
6392
+ chainId: networkInfo?.chainId,
6393
+ emailAddress
6394
+ });
6395
+ });
5619
6396
 
5620
- // ../../packages/shared/dist/lib/dreams.js
5621
- var USDC_DECIMALS2 = 6n;
5622
- var DREAMS_DECIMALS = 18n;
5623
- var USDC_SCALE = 10n ** USDC_DECIMALS2;
5624
- var DREAMS_SCALE = 10n ** DREAMS_DECIMALS;
5625
- function dreamsToUsd(dreamsBaseUnits, dreamsPerUsdc) {
5626
- const dreams = BigInt(dreamsBaseUnits);
5627
- const rate = BigInt(dreamsPerUsdc);
5628
- if (dreams <= 0n || rate <= 0n)
5629
- return "0";
5630
- return (dreams * USDC_SCALE / rate).toString();
5631
- }
5632
- function formatDreams(baseUnits) {
5633
- const value = BigInt(baseUnits);
5634
- const negative = value < 0n;
5635
- const abs = negative ? -value : value;
5636
- const whole = abs / DREAMS_SCALE;
5637
- const frac = abs % DREAMS_SCALE;
5638
- const fracStr = frac.toString().padStart(18, "0").replace(/0+$/, "");
5639
- const sign = negative ? "-" : "";
5640
- return fracStr.length > 0 ? `${sign}${whole}.${fracStr}` : `${sign}${whole}`;
5641
- }
6397
+ // src/commands/address.ts
6398
+ import { Command as Command3 } from "commander";
6399
+ var addressCommand = new Command3("address").description("Print the wallet address").action(async () => {
6400
+ const keystore = await loadKeystore();
6401
+ printResult({ address: keystore.walletAddress });
6402
+ });
5642
6403
 
5643
- // ../../packages/shared/dist/lib/authMessages.js
5644
- function buildSelectWorkerMessage(taskId, pitchId, workerAddress) {
5645
- return `taskmarket:select-worker:${taskId}:${pitchId}:${workerAddress.toLowerCase()}`;
6404
+ // src/commands/identity.ts
6405
+ import { Command as Command4 } from "commander";
6406
+
6407
+ // src/lib/x402.ts
6408
+ async function x402Post(path3, body) {
6409
+ const url = `${API_URL}${path3}`;
6410
+ const keystore = await loadKeystore();
6411
+ const legalHeaders = legalReceiptHeadersForKeystore(keystore, path3, "POST");
6412
+ const r1 = await fetch(url, {
6413
+ method: "POST",
6414
+ redirect: "error",
6415
+ headers: { "Content-Type": "application/json", ...legalHeaders },
6416
+ body: JSON.stringify(body)
6417
+ });
6418
+ if (r1.status !== 402) {
6419
+ if (r1.ok) {
6420
+ return r1.json();
6421
+ }
6422
+ const text = await r1.text().catch(() => "");
6423
+ throw new Error(`POST ${path3} failed (${r1.status}): ${text}`);
6424
+ }
6425
+ const requirements = await r1.json();
6426
+ if (!requirements.accepts || requirements.accepts.length === 0) {
6427
+ throw new Error("No payment methods accepted by server");
6428
+ }
6429
+ const accept = requirements.accepts[0];
6430
+ const { authorization, signature } = await createTransferAuthorization(accept, keystore);
6431
+ const paymentPayload = {
6432
+ x402Version: 2,
6433
+ resource: requirements.resource,
6434
+ accepted: {
6435
+ scheme: accept.scheme,
6436
+ network: accept.network,
6437
+ amount: accept.amount,
6438
+ asset: accept.asset,
6439
+ payTo: accept.payTo,
6440
+ maxTimeoutSeconds: accept.maxTimeoutSeconds,
6441
+ extra: accept.extra
6442
+ },
6443
+ payload: { authorization, signature }
6444
+ };
6445
+ const r2 = await fetch(url, {
6446
+ method: "POST",
6447
+ redirect: "error",
6448
+ headers: {
6449
+ "Content-Type": "application/json",
6450
+ ...legalHeaders,
6451
+ "PAYMENT-SIGNATURE": Buffer.from(JSON.stringify(paymentPayload)).toString("base64")
6452
+ },
6453
+ body: JSON.stringify(body)
6454
+ });
6455
+ const result = await r2.json();
6456
+ if (!r2.ok) {
6457
+ throw new Error(`POST ${path3} failed after payment (${r2.status}): ${JSON.stringify(result)}`);
6458
+ }
6459
+ return result;
5646
6460
  }
5647
6461
 
6462
+ // src/commands/identity.ts
6463
+ var identityCommand = new Command4("identity").description("Manage agent identity");
6464
+ identityCommand.command("register").description("Register ERC-8004 agent identity (costs 0.001 USDC)").action(async () => {
6465
+ const result = await x402Post("/api/identity/register", {});
6466
+ printResult({ agentId: result.agentId });
6467
+ });
6468
+ identityCommand.command("status").description("Check identity registration status").action(async () => {
6469
+ const keystore = await loadKeystore();
6470
+ const result = await apiGet(`/api/identity/status?address=${keystore.walletAddress}`);
6471
+ printResult({ registered: result.registered, agentId: result.agentId });
6472
+ });
6473
+
5648
6474
  // src/commands/stats.ts
5649
- var statsCommand = new Command4("stats").description("View agent statistics").option("--address <addr>", "Wallet address (defaults to own wallet)").option("--agent <agentId>", "Agent ID (alternative to --address)").action(async (opts) => {
6475
+ import { Command as Command5 } from "commander";
6476
+ var statsCommand = new Command5("stats").description("View agent statistics").option("--address <addr>", "Wallet address (defaults to own wallet)").option("--agent <agentId>", "Agent ID (alternative to --address)").action(async (opts) => {
5650
6477
  let address = opts.address;
5651
6478
  if (!address) {
5652
6479
  const keystore = await loadKeystore();
@@ -5692,10 +6519,10 @@ var statsCommand = new Command4("stats").description("View agent statistics").op
5692
6519
  });
5693
6520
 
5694
6521
  // src/commands/task/index.ts
5695
- import { Command as Command35 } from "commander";
6522
+ import { Command as Command36 } from "commander";
5696
6523
 
5697
6524
  // src/commands/task/create.ts
5698
- import { Command as Command5 } from "commander";
6525
+ import { Command as Command6 } from "commander";
5699
6526
 
5700
6527
  // src/lib/usdc.ts
5701
6528
  var USDC_BASE_UNITS = 10n ** BigInt(USDC_DECIMALS);
@@ -5718,7 +6545,7 @@ function usdcToBaseUnits(value, options = {}) {
5718
6545
  }
5719
6546
 
5720
6547
  // src/commands/task/create.ts
5721
- var createCmd = new Command5("create").description("Create a new task (costs reward amount in USDC)").requiredOption("--description <text>", "Task description").requiredOption("--reward <usdc>", "Reward in USDC (e.g. 5 for 5 USDC)").requiredOption("--duration <hours>", "Task duration in hours").option("--mode <mode>", "Task mode: bounty, claim, pitch, benchmark, auction", "bounty").option("--tags <tags>", "Comma-separated tags").option("--pitch-deadline <hours>", "Pitch deadline in hours from now (pitch mode only)").option("--bid-deadline <hours>", "Bid deadline in hours from now (auction mode only)").option("--max-price <usdc>", "Maximum bid price in USDC (required for auction mode)").option(
6548
+ var createCmd = new Command6("create").description("Create a new task (costs reward amount in USDC)").requiredOption("--description <text>", "Task description").requiredOption("--reward <usdc>", "Reward in USDC (e.g. 5 for 5 USDC)").requiredOption("--duration <hours>", "Task duration in hours").option("--mode <mode>", "Task mode: bounty, claim, pitch, benchmark, auction", "bounty").option("--tags <tags>", "Comma-separated tags").option("--pitch-deadline <hours>", "Pitch deadline in hours from now (pitch mode only)").option("--bid-deadline <hours>", "Bid deadline in hours from now (auction mode only)").option("--max-price <usdc>", "Maximum bid price in USDC (required for auction mode)").option(
5722
6549
  "--auction-type <type>",
5723
6550
  "Auction subtype: dutch, english, reverse_dutch, reverse_english (required for auction mode)"
5724
6551
  ).option(
@@ -5872,8 +6699,8 @@ var createCmd = new Command5("create").description("Create a new task (costs rew
5872
6699
  );
5873
6700
 
5874
6701
  // src/commands/task/search.ts
5875
- import { Command as Command6 } from "commander";
5876
- var listCmd = new Command6("list").alias("search").description("List available tasks").option("--status <status>", "Filter by status (e.g. open)", "open").option("--mode <mode>", "Filter by mode (bounty, claim, pitch, benchmark, auction)").option(
6702
+ import { Command as Command7 } from "commander";
6703
+ var listCmd = new Command7("list").alias("search").description("List available tasks").option("--status <status>", "Filter by status (e.g. open)", "open").option("--mode <mode>", "Filter by mode (bounty, claim, pitch, benchmark, auction)").option(
5877
6704
  "--auction-type <type>",
5878
6705
  "Filter auction tasks by subtype (dutch, english, reverse_dutch, reverse_english)"
5879
6706
  ).option("--tags <tags>", "Comma-separated tags to filter by").option("--skill <skill>", "Filter by skill tag (comma-separated, alias for --tags)").option("--reward-min <n>", "Minimum reward in USDC").option("--reward-max <n>", "Maximum reward in USDC").option("--deadline-hours <n>", "Only tasks expiring within this many hours").option("--limit <n>", "Maximum results to return", "20").option("--cursor <cursor>", "Cursor from previous page (nextCursor in JSON output)").action(
@@ -5897,8 +6724,8 @@ var listCmd = new Command6("list").alias("search").description("List available t
5897
6724
  );
5898
6725
 
5899
6726
  // src/commands/task/get.ts
5900
- import { Command as Command7 } from "commander";
5901
- var getCmd = new Command7("get").description("Get task details").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6727
+ import { Command as Command8 } from "commander";
6728
+ var getCmd = new Command8("get").description("Get task details").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
5902
6729
  const task = await apiGet(`/api/tasks/${taskId}`);
5903
6730
  if (!task) {
5904
6731
  printError(`Task not found: ${taskId}`);
@@ -5907,7 +6734,7 @@ var getCmd = new Command7("get").description("Get task details").argument("<task
5907
6734
  });
5908
6735
 
5909
6736
  // src/commands/task/submit.ts
5910
- import { Command as Command8, Option } from "commander";
6737
+ import { Command as Command9, Option } from "commander";
5911
6738
  import { promises as fsPromises } from "fs";
5912
6739
  import { basename, extname } from "path";
5913
6740
  import { createHash } from "crypto";
@@ -5996,7 +6823,7 @@ function streamingPut(uploadUrl, data, mimeType, label) {
5996
6823
  stream.pipe(req);
5997
6824
  });
5998
6825
  }
5999
- var submitCmd = new Command8("submit").description("Submit work for a task").argument("<taskId>", "Task ID (0x-prefixed hex)").option("--file <path>", "Path to a submission file (repeatable)", collectFile, []).addOption(
6826
+ var submitCmd = new Command9("submit").description("Submit work for a task").argument("<taskId>", "Task ID (0x-prefixed hex)").option("--file <path>", "Path to a submission file (repeatable)", collectFile, []).addOption(
6000
6827
  new Option("--role <role>", "Artifact role applied to all files").choices(["preview", "source", "final", "attachment"]).default("attachment")
6001
6828
  ).action(async (taskId, opts) => {
6002
6829
  try {
@@ -6053,8 +6880,8 @@ var submitCmd = new Command8("submit").description("Submit work for a task").arg
6053
6880
  });
6054
6881
 
6055
6882
  // src/commands/task/accept.ts
6056
- import { Command as Command9 } from "commander";
6057
- var acceptCmd = new Command9("accept").description("Accept a submission (costs 0.001 USDC)").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--worker <addr>", "Worker wallet address").action(async (taskId, opts) => {
6883
+ import { Command as Command10 } from "commander";
6884
+ var acceptCmd = new Command10("accept").description("Accept a submission (costs 0.001 USDC)").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--worker <addr>", "Worker wallet address").action(async (taskId, opts) => {
6058
6885
  const task = await apiGet(`/api/tasks/${taskId}`);
6059
6886
  if (!task) {
6060
6887
  printError("Task not found");
@@ -6085,7 +6912,7 @@ var acceptCmd = new Command9("accept").description("Accept a submission (costs 0
6085
6912
  });
6086
6913
 
6087
6914
  // src/commands/task/accept-submissions.ts
6088
- import { Command as Command10 } from "commander";
6915
+ import { Command as Command11 } from "commander";
6089
6916
  function parseWinner(spec) {
6090
6917
  const parts = spec.split(":");
6091
6918
  if (parts.length < 2 || parts.length > 3) {
@@ -6104,7 +6931,7 @@ function parseWinner(spec) {
6104
6931
  const submissionId = submissionIdStr ? submissionIdStr : void 0;
6105
6932
  return { worker, share, ...submissionId !== void 0 && { submissionId } };
6106
6933
  }
6107
- var acceptSubmissionsCmd = new Command10("accept-submissions").description(
6934
+ var acceptSubmissionsCmd = new Command11("accept-submissions").description(
6108
6935
  "Accept N submissions for a Bounty/Benchmark task with explicit share basis points (costs 0.001 USDC).\nShares must sum to 10000. The contract resolves each deliverable from on-chain submission history.\n\nFor ranked payouts, pass winners in rank order \u2014 workers[0] is the primary winner.\n\nTo pin a specific submission version, append the submission ID as a third field.\n\nExamples:\n task accept-submissions 0x\u2026 --winner 0xAlice:5000 --winner 0xBob:3000 --winner 0xCarol:2000\n task accept-submissions 0x\u2026 --winner 0xAlice:5000:sub_abc123 --winner 0xBob:5000:sub_def456"
6109
6936
  ).argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption(
6110
6937
  "--winner <spec...>",
@@ -6127,8 +6954,8 @@ var acceptSubmissionsCmd = new Command10("accept-submissions").description(
6127
6954
  });
6128
6955
 
6129
6956
  // src/commands/task/rate.ts
6130
- import { Command as Command11 } from "commander";
6131
- var rateCmd = new Command11("rate").description("Rate a worker (costs 0.001 USDC)").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--worker <addr>", "Worker wallet address").requiredOption("--rating <n>", "Rating 0-100").option("--feedback <text>", "Optional feedback text").action(async (taskId, opts) => {
6957
+ import { Command as Command12 } from "commander";
6958
+ var rateCmd = new Command12("rate").description("Rate a worker (costs 0.001 USDC)").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--worker <addr>", "Worker wallet address").requiredOption("--rating <n>", "Rating 0-100").option("--feedback <text>", "Optional feedback text").action(async (taskId, opts) => {
6132
6959
  const rating = parseInt(opts.rating, 10);
6133
6960
  if (rating < 0 || rating > 100) {
6134
6961
  printError("Rating must be between 0 and 100");
@@ -6143,8 +6970,8 @@ var rateCmd = new Command11("rate").description("Rate a worker (costs 0.001 USDC
6143
6970
  });
6144
6971
 
6145
6972
  // src/commands/task/claim.ts
6146
- import { Command as Command12 } from "commander";
6147
- var claimCmd = new Command12("claim").description("Claim a task as a worker").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6973
+ import { Command as Command13 } from "commander";
6974
+ var claimCmd = new Command13("claim").description("Claim a task as a worker").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6148
6975
  const keystore = await loadKeystore();
6149
6976
  const message = `taskmarket:claim:${taskId}`;
6150
6977
  const signature = await signMessage(message, keystore);
@@ -6156,8 +6983,8 @@ var claimCmd = new Command12("claim").description("Claim a task as a worker").ar
6156
6983
  });
6157
6984
 
6158
6985
  // src/commands/task/pitch.ts
6159
- import { Command as Command13 } from "commander";
6160
- var pitchCmd = new Command13("pitch").description("Submit a pitch for a task (costs 0.001 USDC, anchors hash on-chain)").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--text <text>", "Pitch text").option("--duration <hours>", "Estimated duration in hours").action(async (taskId, opts) => {
6986
+ import { Command as Command14 } from "commander";
6987
+ var pitchCmd = new Command14("pitch").description("Submit a pitch for a task (costs 0.001 USDC, anchors hash on-chain)").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--text <text>", "Pitch text").option("--duration <hours>", "Estimated duration in hours").action(async (taskId, opts) => {
6161
6988
  const keystore = await loadKeystore();
6162
6989
  const signature = await signMessage(`taskmarket:pitch:${taskId}`, keystore);
6163
6990
  const result = await x402Post(`/api/tasks/${taskId}/pitches`, {
@@ -6171,8 +6998,8 @@ var pitchCmd = new Command13("pitch").description("Submit a pitch for a task (co
6171
6998
  });
6172
6999
 
6173
7000
  // src/commands/task/pitches.ts
6174
- import { Command as Command14 } from "commander";
6175
- var pitchesCmd = new Command14("pitches").description("List pitches for a task").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
7001
+ import { Command as Command15 } from "commander";
7002
+ var pitchesCmd = new Command15("pitches").description("List pitches for a task").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6176
7003
  try {
6177
7004
  printResult(await apiGet(`/api/tasks/${taskId}/pitches`));
6178
7005
  } catch (err) {
@@ -6181,8 +7008,8 @@ var pitchesCmd = new Command14("pitches").description("List pitches for a task")
6181
7008
  });
6182
7009
 
6183
7010
  // src/commands/task/select-worker.ts
6184
- import { Command as Command15 } from "commander";
6185
- var selectWorkerCmd = new Command15("select-worker").description("Select a worker from pitches (requester only)").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--pitch <pitchId>", "Pitch ID to select").requiredOption("--worker <address>", "Worker wallet address to assign").action(async (taskId, opts) => {
7011
+ import { Command as Command16 } from "commander";
7012
+ var selectWorkerCmd = new Command16("select-worker").description("Select a worker from pitches (requester only)").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--pitch <pitchId>", "Pitch ID to select").requiredOption("--worker <address>", "Worker wallet address to assign").action(async (taskId, opts) => {
6186
7013
  const keystore = await loadKeystore();
6187
7014
  const message = buildSelectWorkerMessage(taskId, opts.pitch, opts.worker);
6188
7015
  const signature = await signMessage(message, keystore);
@@ -6196,8 +7023,8 @@ var selectWorkerCmd = new Command15("select-worker").description("Select a worke
6196
7023
  });
6197
7024
 
6198
7025
  // src/commands/task/proof.ts
6199
- import { Command as Command16 } from "commander";
6200
- var proofCmd = new Command16("proof").description("Submit a benchmark proof (costs 0.001 USDC, anchors hash on-chain)").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--data <data>", "Proof data").requiredOption("--type <type>", "Proof type").option("--metric <val>", "Metric value").action(async (taskId, opts) => {
7026
+ import { Command as Command17 } from "commander";
7027
+ var proofCmd = new Command17("proof").description("Submit a benchmark proof (costs 0.001 USDC, anchors hash on-chain)").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--data <data>", "Proof data").requiredOption("--type <type>", "Proof type").option("--metric <val>", "Metric value").action(async (taskId, opts) => {
6201
7028
  const keystore = await loadKeystore();
6202
7029
  const signature = await signMessage(`taskmarket:proof:${taskId}`, keystore);
6203
7030
  const result = await x402Post(`/api/tasks/${taskId}/proofs`, {
@@ -6212,8 +7039,8 @@ var proofCmd = new Command16("proof").description("Submit a benchmark proof (cos
6212
7039
  });
6213
7040
 
6214
7041
  // src/commands/task/proofs.ts
6215
- import { Command as Command17 } from "commander";
6216
- var proofsCmd = new Command17("proofs").description("List proofs for a benchmark task").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
7042
+ import { Command as Command18 } from "commander";
7043
+ var proofsCmd = new Command18("proofs").description("List proofs for a benchmark task").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6217
7044
  try {
6218
7045
  printResult(await apiGet(`/api/tasks/${taskId}/proofs`));
6219
7046
  } catch (err) {
@@ -6222,8 +7049,8 @@ var proofsCmd = new Command17("proofs").description("List proofs for a benchmark
6222
7049
  });
6223
7050
 
6224
7051
  // src/commands/task/bid.ts
6225
- import { Command as Command18 } from "commander";
6226
- var bidCmd = new Command18("bid").description("Submit a bid on an auction task").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--price <usdc>", "Bid price in USDC (e.g. 3 or 1.5)").action(async (taskId, opts) => {
7052
+ import { Command as Command19 } from "commander";
7053
+ var bidCmd = new Command19("bid").description("Submit a bid on an auction task").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--price <usdc>", "Bid price in USDC (e.g. 3 or 1.5)").action(async (taskId, opts) => {
6227
7054
  let priceBaseUnits;
6228
7055
  try {
6229
7056
  priceBaseUnits = usdcToBaseUnits(opts.price);
@@ -6240,8 +7067,8 @@ var bidCmd = new Command18("bid").description("Submit a bid on an auction task")
6240
7067
  });
6241
7068
 
6242
7069
  // src/commands/task/auction-accept.ts
6243
- import { Command as Command19 } from "commander";
6244
- var auctionAcceptCmd = new Command19("auction-accept").description("Accept current clock price on a dutch or reverse_dutch auction task").argument("<taskId>", "Task ID (0x-prefixed hex)").option(
7070
+ import { Command as Command20 } from "commander";
7071
+ var auctionAcceptCmd = new Command20("auction-accept").description("Accept current clock price on a dutch or reverse_dutch auction task").argument("<taskId>", "Task ID (0x-prefixed hex)").option(
6245
7072
  "--min-price <usdc>",
6246
7073
  "Reject if current clock price is below this value (price floor guard)"
6247
7074
  ).action(async (taskId, opts) => {
@@ -6264,8 +7091,8 @@ var auctionAcceptCmd = new Command19("auction-accept").description("Accept curre
6264
7091
  });
6265
7092
 
6266
7093
  // src/commands/task/submissions.ts
6267
- import { Command as Command20 } from "commander";
6268
- var submissionsCmd = new Command20("submissions").description("List submissions for a task").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
7094
+ import { Command as Command21 } from "commander";
7095
+ var submissionsCmd = new Command21("submissions").description("List submissions for a task").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6269
7096
  let subs;
6270
7097
  try {
6271
7098
  subs = await apiGet(`/api/tasks/${taskId}/submissions`);
@@ -6277,8 +7104,8 @@ var submissionsCmd = new Command20("submissions").description("List submissions
6277
7104
  });
6278
7105
 
6279
7106
  // src/commands/task/select-winner.ts
6280
- import { Command as Command21 } from "commander";
6281
- var selectWinnerCmd = new Command21("select-winner").description("Permissionlessly finalize the lowest bidder after the auction deadline").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
7107
+ import { Command as Command22 } from "commander";
7108
+ var selectWinnerCmd = new Command22("select-winner").description("Permissionlessly finalize the lowest bidder after the auction deadline").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6282
7109
  let result;
6283
7110
  try {
6284
7111
  result = await apiPost(`/api/tasks/${taskId}/bids/select-winner`, {
@@ -6292,9 +7119,9 @@ var selectWinnerCmd = new Command21("select-winner").description("Permissionless
6292
7119
  });
6293
7120
 
6294
7121
  // src/commands/task/download.ts
6295
- import { Command as Command22 } from "commander";
7122
+ import { Command as Command23 } from "commander";
6296
7123
  import { writeFileSync } from "fs";
6297
- var downloadCmd = new Command22("download").description("Download a submission file (requester or worker)").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--submission <id>", "Submission ID (from `task submissions`)").option("--artifact <id>", "Artifact ID for multi-artifact submissions").option("--output <path>", "Save to file instead of printing to stdout").action(
7124
+ var downloadCmd = new Command23("download").description("Download a submission file (requester or worker)").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--submission <id>", "Submission ID (from `task submissions`)").option("--artifact <id>", "Artifact ID for multi-artifact submissions").option("--output <path>", "Save to file instead of printing to stdout").action(
6298
7125
  async (taskId, opts) => {
6299
7126
  const keystore = await loadKeystore();
6300
7127
  let presignedUrl;
@@ -6332,15 +7159,15 @@ var downloadCmd = new Command22("download").description("Download a submission f
6332
7159
  );
6333
7160
 
6334
7161
  // src/commands/task/cancel.ts
6335
- import { Command as Command23 } from "commander";
6336
- var cancelCmd = new Command23("cancel").description("Cancel an open task and refund the escrowed reward (costs 0.001 USDC)").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
7162
+ import { Command as Command24 } from "commander";
7163
+ var cancelCmd = new Command24("cancel").description("Cancel an open task and refund the escrowed reward (costs 0.001 USDC)").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6337
7164
  const result = await x402Post(`/api/tasks/${taskId}/cancel`, { taskId });
6338
7165
  printResult(result);
6339
7166
  });
6340
7167
 
6341
7168
  // src/commands/task/refund-expired.ts
6342
- import { Command as Command24 } from "commander";
6343
- var refundExpiredCmd = new Command24("refund-expired").description(
7169
+ import { Command as Command25 } from "commander";
7170
+ var refundExpiredCmd = new Command25("refund-expired").description(
6344
7171
  "Refund an expired task with no submissions back to the requester (costs 0.001 USDC)"
6345
7172
  ).argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6346
7173
  try {
@@ -6353,8 +7180,8 @@ var refundExpiredCmd = new Command24("refund-expired").description(
6353
7180
  });
6354
7181
 
6355
7182
  // src/commands/task/reject-submission.ts
6356
- import { Command as Command25 } from "commander";
6357
- var rejectSubmissionCmd = new Command25("reject-submission").description(
7183
+ import { Command as Command26 } from "commander";
7184
+ var rejectSubmissionCmd = new Command26("reject-submission").description(
6358
7185
  "Reject a spam or low-quality submission (costs 0.01 USDC relay fee). Once all submissions are rejected, the task can be cancelled to recover escrow."
6359
7186
  ).argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--worker <address>", "Worker address whose submission to reject").action(async (taskId, opts) => {
6360
7187
  try {
@@ -6370,7 +7197,7 @@ var rejectSubmissionCmd = new Command25("reject-submission").description(
6370
7197
  });
6371
7198
 
6372
7199
  // src/commands/task/reject-all-submissions.ts
6373
- import { Command as Command26 } from "commander";
7200
+ import { Command as Command27 } from "commander";
6374
7201
  function activeSubmissionWorkers(submissions) {
6375
7202
  const workers = /* @__PURE__ */ new Map();
6376
7203
  for (const submission of submissions) {
@@ -6380,7 +7207,7 @@ function activeSubmissionWorkers(submissions) {
6380
7207
  }
6381
7208
  return [...workers.values()];
6382
7209
  }
6383
- var rejectAllSubmissionsCmd = new Command26("reject-all-submissions").description(
7210
+ var rejectAllSubmissionsCmd = new Command27("reject-all-submissions").description(
6384
7211
  "Reject every active submission on a bounty or benchmark task in one go. Lists active submissions, rejects each unique worker in sequence, then cancels the task. Use this to recover escrow when all submitted work is unsuitable."
6385
7212
  ).argument("<taskId>", "Task ID (0x-prefixed hex)").option("--no-cancel", "Reject all submissions but do not cancel the task afterward").action(async (taskId, opts) => {
6386
7213
  let submissions;
@@ -6428,8 +7255,8 @@ var rejectAllSubmissionsCmd = new Command26("reject-all-submissions").descriptio
6428
7255
  });
6429
7256
 
6430
7257
  // src/commands/task/my-submissions.ts
6431
- import { Command as Command27 } from "commander";
6432
- var mySubmissionsCmd = new Command27("my-submissions").description("List all submissions made by your wallet across all tasks.").option("--address <address>", "Wallet address to query (defaults to own wallet from keystore)").action(async (opts) => {
7258
+ import { Command as Command28 } from "commander";
7259
+ var mySubmissionsCmd = new Command28("my-submissions").description("List all submissions made by your wallet across all tasks.").option("--address <address>", "Wallet address to query (defaults to own wallet from keystore)").action(async (opts) => {
6433
7260
  try {
6434
7261
  let address = opts.address;
6435
7262
  if (!address) {
@@ -6447,8 +7274,8 @@ var mySubmissionsCmd = new Command27("my-submissions").description("List all sub
6447
7274
  });
6448
7275
 
6449
7276
  // src/commands/task/update.ts
6450
- import { Command as Command28 } from "commander";
6451
- var updateCmd = new Command28("update").description("Update an open task (costs 0.001 USDC plus any reward increase)").argument("<taskId>", "Task ID (0x-prefixed hex)").option("--reward <usdc>", 'New reward in USDC (human units, e.g. "50")').option("--extend-expiry <seconds>", "Extend expiry by this many seconds").option("--bid-deadline <iso>", "New bid deadline (ISO 8601)").option("--pitch-deadline <iso>", "New pitch deadline (ISO 8601)").option("--auction-floor-price <usdc>", "New auction floor price in USDC").option("--auction-start-price <usdc>", "New auction start price in USDC").option("--description <text>", "New description").option("--tags <csv>", "New tags (comma-separated)").option("--metric-description <text>", "New metric description").action(
7277
+ import { Command as Command29 } from "commander";
7278
+ var updateCmd = new Command29("update").description("Update an open task (costs 0.001 USDC plus any reward increase)").argument("<taskId>", "Task ID (0x-prefixed hex)").option("--reward <usdc>", 'New reward in USDC (human units, e.g. "50")').option("--extend-expiry <seconds>", "Extend expiry by this many seconds").option("--bid-deadline <iso>", "New bid deadline (ISO 8601)").option("--pitch-deadline <iso>", "New pitch deadline (ISO 8601)").option("--auction-floor-price <usdc>", "New auction floor price in USDC").option("--auction-start-price <usdc>", "New auction start price in USDC").option("--description <text>", "New description").option("--tags <csv>", "New tags (comma-separated)").option("--metric-description <text>", "New metric description").action(
6452
7279
  async (taskId, opts) => {
6453
7280
  const body = { taskId };
6454
7281
  if (opts.reward !== void 0) {
@@ -6531,8 +7358,8 @@ var updateCmd = new Command28("update").description("Update an open task (costs
6531
7358
  );
6532
7359
 
6533
7360
  // src/commands/task/forfeit.ts
6534
- import { Command as Command29 } from "commander";
6535
- var forfeitCmd = new Command29("forfeit").description("Reclaim a claim-mode task whose worker's claim has expired (requester only)").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
7361
+ import { Command as Command30 } from "commander";
7362
+ var forfeitCmd = new Command30("forfeit").description("Reclaim a claim-mode task whose worker's claim has expired (requester only)").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6536
7363
  try {
6537
7364
  const keystore = await loadKeystore();
6538
7365
  const message = `taskmarket:forfeit:${taskId}`;
@@ -6549,8 +7376,8 @@ var forfeitCmd = new Command29("forfeit").description("Reclaim a claim-mode task
6549
7376
  });
6550
7377
 
6551
7378
  // src/commands/task/evaluate.ts
6552
- import { Command as Command30 } from "commander";
6553
- var evaluateCmd = new Command30("evaluate").description("Submit an evaluation verdict for a task in Review state").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--verdict <type>", "Verdict: approve, reject, or partial").option("--score <n>", "Score 0-1000 (default: 1000)", "1000").option("--confidence <n>", "Confidence 0-1000 (default: 1000)", "1000").option("--evidence-hash <hash>", "Evidence hash (32-byte hex)").option(
7379
+ import { Command as Command31 } from "commander";
7380
+ var evaluateCmd = new Command31("evaluate").description("Submit an evaluation verdict for a task in Review state").argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--verdict <type>", "Verdict: approve, reject, or partial").option("--score <n>", "Score 0-1000 (default: 1000)", "1000").option("--confidence <n>", "Confidence 0-1000 (default: 1000)", "1000").option("--evidence-hash <hash>", "Evidence hash (32-byte hex)").option(
6554
7381
  "--award <worker:amount:rank>",
6555
7382
  "Award entry (repeatable): worker:amountUSDC:rank",
6556
7383
  collect,
@@ -6613,28 +7440,28 @@ function collect(val, prev) {
6613
7440
  }
6614
7441
 
6615
7442
  // src/commands/task/appeal.ts
6616
- import { Command as Command31 } from "commander";
6617
- var appealCmd = new Command31("appeal").description("Appeal an evaluator verdict while in Appealing state").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
7443
+ import { Command as Command32 } from "commander";
7444
+ var appealCmd = new Command32("appeal").description("Appeal an evaluator verdict while in Appealing state").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6618
7445
  const result = await x402Post(`/api/tasks/${taskId}/appeal`, { taskId });
6619
7446
  printResult({ txHash: result.txHash });
6620
7447
  });
6621
7448
 
6622
7449
  // src/commands/task/evaluator-timeout.ts
6623
- import { Command as Command32 } from "commander";
6624
- var evaluatorTimeoutCmd = new Command32("evaluator-timeout").description("Trigger evaluator timeout after the evaluation window expires (requester only)").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
7450
+ import { Command as Command33 } from "commander";
7451
+ var evaluatorTimeoutCmd = new Command33("evaluator-timeout").description("Trigger evaluator timeout after the evaluation window expires (requester only)").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6625
7452
  const result = await x402Post(`/api/tasks/${taskId}/evaluator-timeout`, { taskId });
6626
7453
  printResult({ txHash: result.txHash });
6627
7454
  });
6628
7455
 
6629
7456
  // src/commands/task/finalize-verdict.ts
6630
- import { Command as Command33 } from "commander";
6631
- var finalizeVerdictCmd = new Command33("finalize-verdict").description("Finalize an evaluator verdict after the appeal window expires (permissionless)").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
7457
+ import { Command as Command34 } from "commander";
7458
+ var finalizeVerdictCmd = new Command34("finalize-verdict").description("Finalize an evaluator verdict after the appeal window expires (permissionless)").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6632
7459
  const result = await apiPost(`/api/tasks/${taskId}/finalize-verdict`, { taskId });
6633
7460
  printResult({ txHash: result.txHash });
6634
7461
  });
6635
7462
 
6636
7463
  // src/commands/task/resolve-dispute.ts
6637
- import { Command as Command34 } from "commander";
7464
+ import { Command as Command35 } from "commander";
6638
7465
  function parseAward(spec) {
6639
7466
  const parts = spec.split(":");
6640
7467
  if (parts.length !== 3) {
@@ -6655,7 +7482,7 @@ function parseAward(spec) {
6655
7482
  rank
6656
7483
  };
6657
7484
  }
6658
- var resolveDisputeCmd = new Command34("resolve-dispute").description(
7485
+ var resolveDisputeCmd = new Command35("resolve-dispute").description(
6659
7486
  "Resolve a disputed task as the designated dispute resolver (X402 required).\n\nExamples:\n task resolve-dispute 0x\u2026 --verdict approve --award 0xAlice:5:1\n task resolve-dispute 0x\u2026 --verdict partial --award 0xAlice:3:1 --award 0xBob:2:2"
6660
7487
  ).argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--verdict <type>", "Verdict type: approve or partial").requiredOption(
6661
7488
  "--award <spec...>",
@@ -6681,7 +7508,7 @@ var resolveDisputeCmd = new Command34("resolve-dispute").description(
6681
7508
  });
6682
7509
 
6683
7510
  // src/commands/task/index.ts
6684
- var taskCommand = new Command35("task").description("Manage tasks");
7511
+ var taskCommand = new Command36("task").description("Manage tasks");
6685
7512
  taskCommand.addCommand(createCmd);
6686
7513
  taskCommand.addCommand(listCmd);
6687
7514
  taskCommand.addCommand(getCmd);
@@ -6714,8 +7541,8 @@ taskCommand.addCommand(finalizeVerdictCmd);
6714
7541
  taskCommand.addCommand(resolveDisputeCmd);
6715
7542
 
6716
7543
  // src/commands/agents.ts
6717
- import { Command as Command36 } from "commander";
6718
- var agentsCommand = new Command36("agents").description("Browse the agent directory").option("--sort <order>", "Sort order: reputation or tasks", "reputation").option("--skill <tag>", "Filter by skill tag").option("--search <query>", "Search by agentId or wallet address").option("--limit <n>", "Maximum results to return", "20").action(async (opts) => {
7544
+ import { Command as Command37 } from "commander";
7545
+ var agentsCommand = new Command37("agents").description("Browse the agent directory").option("--sort <order>", "Sort order: reputation or tasks", "reputation").option("--skill <tag>", "Filter by skill tag").option("--search <query>", "Search by agentId or wallet address").option("--limit <n>", "Maximum results to return", "20").action(async (opts) => {
6719
7546
  const params = new URLSearchParams();
6720
7547
  if (opts.sort) params.set("sort", opts.sort);
6721
7548
  if (opts.skill) params.set("skill", opts.skill);
@@ -6726,8 +7553,8 @@ var agentsCommand = new Command36("agents").description("Browse the agent direct
6726
7553
  });
6727
7554
 
6728
7555
  // src/commands/inbox.ts
6729
- import { Command as Command37 } from "commander";
6730
- var inboxCommand = new Command37("inbox").description("Show tasks you created and tasks you are working on").action(async () => {
7556
+ import { Command as Command38 } from "commander";
7557
+ var inboxCommand = new Command38("inbox").description("Show tasks you created and tasks you are working on").action(async () => {
6731
7558
  let address;
6732
7559
  try {
6733
7560
  address = await getWalletAddress();
@@ -6753,8 +7580,8 @@ var inboxCommand = new Command37("inbox").description("Show tasks you created an
6753
7580
  });
6754
7581
 
6755
7582
  // src/commands/deposit.ts
6756
- import { Command as Command38 } from "commander";
6757
- var depositCommand = new Command38("deposit").description("Show wallet address and network info for funding").action(async () => {
7583
+ import { Command as Command39 } from "commander";
7584
+ var depositCommand = new Command39("deposit").description("Show wallet address and network info for funding").action(async () => {
6758
7585
  let address;
6759
7586
  try {
6760
7587
  address = await getWalletAddress();
@@ -6781,11 +7608,11 @@ var depositCommand = new Command38("deposit").description("Show wallet address a
6781
7608
  });
6782
7609
 
6783
7610
  // src/commands/wallet/index.ts
6784
- import { Command as Command44 } from "commander";
7611
+ import { Command as Command45 } from "commander";
6785
7612
 
6786
7613
  // src/commands/wallet/balance.ts
6787
- import { Command as Command39 } from "commander";
6788
- var walletBalanceCommand = new Command39("balance").description("Show USDC balance").option("--address <addr>", "Address to check (defaults to own wallet)").action(async (opts) => {
7614
+ import { Command as Command40 } from "commander";
7615
+ var walletBalanceCommand = new Command40("balance").description("Show USDC balance").option("--address <addr>", "Address to check (defaults to own wallet)").action(async (opts) => {
6789
7616
  let address = opts.address;
6790
7617
  if (!address) {
6791
7618
  const keystore = await loadKeystore();
@@ -6796,9 +7623,9 @@ var walletBalanceCommand = new Command39("balance").description("Show USDC balan
6796
7623
  });
6797
7624
 
6798
7625
  // src/commands/wallet/import.ts
6799
- import { Command as Command40 } from "commander";
6800
- import { createInterface } from "readline";
6801
- import { privateKeyToAccount as privateKeyToAccount3 } from "viem/accounts";
7626
+ import { Command as Command41 } from "commander";
7627
+ import { createInterface as createInterface2 } from "readline";
7628
+ import { privateKeyToAccount as privateKeyToAccount4 } from "viem/accounts";
6802
7629
  function normalizePrivateKey(raw) {
6803
7630
  const hex = raw.startsWith("0x") ? raw.slice(2) : raw;
6804
7631
  if (!/^[0-9a-fA-F]{64}$/.test(hex)) {
@@ -6808,7 +7635,7 @@ function normalizePrivateKey(raw) {
6808
7635
  }
6809
7636
  function promptHiddenInput(prompt) {
6810
7637
  return new Promise((resolve) => {
6811
- const rl = createInterface({
7638
+ const rl = createInterface2({
6812
7639
  input: process.stdin,
6813
7640
  output: process.stdout,
6814
7641
  terminal: true
@@ -6831,7 +7658,10 @@ function promptHiddenInput(prompt) {
6831
7658
  });
6832
7659
  });
6833
7660
  }
6834
- var walletImportCommand = new Command40("import").description("Import an existing private key as the agent wallet").option("--key <privateKey>", "Private key to import (64 hex chars, with or without 0x prefix)").action(async (opts) => {
7661
+ var walletImportCommand = new Command41("import").description("Import an existing private key as the agent wallet").option("--key <privateKey>", "Private key to import (64 hex chars, with or without 0x prefix)").option(
7662
+ "--yes",
7663
+ "Confirm legal acceptance non-interactively after reviewing every current policy"
7664
+ ).action(async (opts) => {
6835
7665
  if (await keystoreExists()) {
6836
7666
  const keystore = await loadKeystore();
6837
7667
  printResult({ address: keystore.walletAddress, agentId: keystore.agentId });
@@ -6850,24 +7680,26 @@ var walletImportCommand = new Command40("import").description("Import an existin
6850
7680
  keySource = "prompt";
6851
7681
  }
6852
7682
  const privateKey = normalizePrivateKey(rawKey);
6853
- const account = privateKeyToAccount3(privateKey);
7683
+ const account = privateKeyToAccount4(privateKey);
6854
7684
  const address = account.address;
6855
7685
  const publicKey = deriveCompressedPublicKey(privateKey);
6856
- const res = await fetch(`${API_URL}/api/devices`, {
6857
- method: "POST",
6858
- headers: { "Content-Type": "application/json" },
6859
- body: JSON.stringify({ walletAddress: address, publicKey })
6860
- });
6861
- if (!res.ok) {
6862
- const text = await res.text().catch(() => "");
6863
- throw new Error(`Device registration failed (${res.status}): ${text}`);
6864
- }
7686
+ const legalBundle = LegalBundleSchema.parse(await apiGet("/api/legal/current"));
7687
+ const legalAcceptance = legalBundle.enforcementEnabled ? await acceptLegalBundle({
7688
+ assumeYes: Boolean(opts.yes),
7689
+ bundle: legalBundle,
7690
+ signMessage: (message) => account.signMessage({ message }),
7691
+ walletAddress: address
7692
+ }) : void 0;
6865
7693
  const {
6866
7694
  deviceId,
6867
7695
  apiToken,
6868
7696
  deviceEncryptionKey,
6869
7697
  agentId: initialAgentId
6870
- } = await res.json();
7698
+ } = await registerDevice({
7699
+ legalReceipt: legalAcceptance?.receipt,
7700
+ publicKey,
7701
+ walletAddress: address
7702
+ });
6871
7703
  const encryptedKey = encryptPrivateKey(deviceEncryptionKey, privateKey);
6872
7704
  let agentId = initialAgentId;
6873
7705
  await saveKeystore({
@@ -6876,7 +7708,12 @@ var walletImportCommand = new Command40("import").description("Import an existin
6876
7708
  deviceId,
6877
7709
  apiToken,
6878
7710
  agentId,
6879
- keyServerUrl: API_URL
7711
+ keyServerUrl: API_URL,
7712
+ ...legalAcceptance ? {
7713
+ legalAcceptanceApiOrigin: API_ORIGIN,
7714
+ legalAcceptanceBundleVersion: legalAcceptance.bundleVersion,
7715
+ legalAcceptanceReceipt: legalAcceptance.receipt
7716
+ } : {}
6880
7717
  });
6881
7718
  if (!agentId) {
6882
7719
  agentId = await pollAgentId(address);
@@ -6896,11 +7733,11 @@ var walletImportCommand = new Command40("import").description("Import an existin
6896
7733
  });
6897
7734
 
6898
7735
  // src/commands/wallet/set-withdrawal-address.ts
6899
- import { Command as Command41 } from "commander";
7736
+ import { Command as Command42 } from "commander";
6900
7737
  function isValidAddress(addr) {
6901
7738
  return /^0x[a-fA-F0-9]{40}$/.test(addr);
6902
7739
  }
6903
- var setWithdrawalAddressCommand = new Command41("set-withdrawal-address").description("Set a withdrawal address for USDC withdrawals (one-time, free)").argument("<address>", "Ethereum address to receive withdrawals").action(async (address) => {
7740
+ var setWithdrawalAddressCommand = new Command42("set-withdrawal-address").description("Set a withdrawal address for USDC withdrawals (one-time, free)").argument("<address>", "Ethereum address to receive withdrawals").action(async (address) => {
6904
7741
  if (!isValidAddress(address)) {
6905
7742
  printError("Invalid Ethereum address: must be 0x followed by 40 hex characters");
6906
7743
  }
@@ -6922,8 +7759,8 @@ var setWithdrawalAddressCommand = new Command41("set-withdrawal-address").descri
6922
7759
  });
6923
7760
 
6924
7761
  // src/commands/wallet/publish-key.ts
6925
- import { Command as Command42 } from "commander";
6926
- var publishKeyCommand = new Command42("publish-key").description("Publish your secp256k1 public key so others can encrypt files for you").action(async () => {
7762
+ import { Command as Command43 } from "commander";
7763
+ var publishKeyCommand = new Command43("publish-key").description("Publish your secp256k1 public key so others can encrypt files for you").action(async () => {
6927
7764
  let keystore;
6928
7765
  try {
6929
7766
  keystore = await loadKeystore();
@@ -6942,13 +7779,13 @@ var publishKeyCommand = new Command42("publish-key").description("Publish your s
6942
7779
  });
6943
7780
 
6944
7781
  // src/commands/wallet/withdraw-dreams.ts
6945
- import { Command as Command43 } from "commander";
7782
+ import { Command as Command44 } from "commander";
6946
7783
  import { toHex as toHex2 } from "viem";
6947
7784
  var AUTHORIZATION_VALIDITY_SECONDS = 300;
6948
7785
  function isValidAddress2(addr) {
6949
7786
  return /^0x[a-fA-F0-9]{40}$/.test(addr);
6950
7787
  }
6951
- var withdrawDreamsCommand = new Command43("withdraw-dreams").description("Withdraw accumulated DREAMS rewards to the withdrawal address").option("--destination <addr>", "Destination address (defaults to registered withdrawal address)").action(async (opts) => {
7788
+ var withdrawDreamsCommand = new Command44("withdraw-dreams").description("Withdraw accumulated DREAMS rewards to the withdrawal address").option("--destination <addr>", "Destination address (defaults to registered withdrawal address)").action(async (opts) => {
6952
7789
  let keystore;
6953
7790
  try {
6954
7791
  keystore = await loadKeystore();
@@ -6993,7 +7830,7 @@ var withdrawDreamsCommand = new Command43("withdraw-dreams").description("Withdr
6993
7830
  });
6994
7831
 
6995
7832
  // src/commands/wallet/index.ts
6996
- var walletCommand = new Command44("wallet").description("Wallet management commands");
7833
+ var walletCommand = new Command45("wallet").description("Wallet management commands");
6997
7834
  walletCommand.addCommand(walletBalanceCommand);
6998
7835
  walletCommand.addCommand(walletImportCommand);
6999
7836
  walletCommand.addCommand(setWithdrawalAddressCommand);
@@ -7001,7 +7838,7 @@ walletCommand.addCommand(publishKeyCommand);
7001
7838
  walletCommand.addCommand(withdrawDreamsCommand);
7002
7839
 
7003
7840
  // src/commands/withdraw.ts
7004
- import { Command as Command45 } from "commander";
7841
+ import { Command as Command46 } from "commander";
7005
7842
  import { toHex as toHex3 } from "viem";
7006
7843
  var USDC_TYPES = {
7007
7844
  TransferWithAuthorization: [
@@ -7013,7 +7850,7 @@ var USDC_TYPES = {
7013
7850
  { name: "nonce", type: "bytes32" }
7014
7851
  ]
7015
7852
  };
7016
- var withdrawCommand = new Command45("withdraw").description("Withdraw USDC to the registered withdrawal address").argument("<amount>", "Amount in USDC (e.g. 5 for 5 USDC)").action(async (amount) => {
7853
+ var withdrawCommand = new Command46("withdraw").description("Withdraw USDC to the registered withdrawal address").argument("<amount>", "Amount in USDC (e.g. 5 for 5 USDC)").action(async (amount) => {
7017
7854
  const parsed = parseFloat(amount);
7018
7855
  if (isNaN(parsed) || parsed <= 0) {
7019
7856
  printError("Invalid amount: must be a positive number (e.g. 5 for 5 USDC)");
@@ -7063,9 +7900,9 @@ var withdrawCommand = new Command45("withdraw").description("Withdraw USDC to th
7063
7900
  });
7064
7901
 
7065
7902
  // src/commands/encrypt.ts
7066
- import { Command as Command46 } from "commander";
7903
+ import { Command as Command47 } from "commander";
7067
7904
  import { promises as fs2 } from "fs";
7068
- var encryptCommand = new Command46("encrypt").description("Encrypt a file with ECIES using wallet keys").argument("<file>", "Path to the file to encrypt").option("--recipient <address>", "Recipient wallet address (default: self)").option("--output <path>", "Output path (default: <file>.enc)").action(async (file, opts) => {
7905
+ var encryptCommand = new Command47("encrypt").description("Encrypt a file with ECIES using wallet keys").argument("<file>", "Path to the file to encrypt").option("--recipient <address>", "Recipient wallet address (default: self)").option("--output <path>", "Output path (default: <file>.enc)").action(async (file, opts) => {
7069
7906
  let plaintext;
7070
7907
  try {
7071
7908
  plaintext = await fs2.readFile(file);
@@ -7114,9 +7951,9 @@ var encryptCommand = new Command46("encrypt").description("Encrypt a file with E
7114
7951
  });
7115
7952
 
7116
7953
  // src/commands/decrypt.ts
7117
- import { Command as Command47 } from "commander";
7954
+ import { Command as Command48 } from "commander";
7118
7955
  import { promises as fs3 } from "fs";
7119
- var decryptCommand = new Command47("decrypt").description("Decrypt a file using your wallet key").argument("<file>", "Path to the encrypted file").option("--output <path>", "Output path (default: strips .enc, otherwise appends .dec)").action(async (file, opts) => {
7956
+ var decryptCommand = new Command48("decrypt").description("Decrypt a file using your wallet key").argument("<file>", "Path to the encrypted file").option("--output <path>", "Output path (default: strips .enc, otherwise appends .dec)").action(async (file, opts) => {
7120
7957
  let ciphertext;
7121
7958
  try {
7122
7959
  ciphertext = await fs3.readFile(file);
@@ -7154,13 +7991,13 @@ var decryptCommand = new Command47("decrypt").description("Decrypt a file using
7154
7991
  });
7155
7992
 
7156
7993
  // src/commands/xmtp.ts
7157
- import { Command as Command48 } from "commander";
7994
+ import { Command as Command49 } from "commander";
7158
7995
 
7159
7996
  // src/lib/xmtp-client.ts
7160
7997
  import os2 from "os";
7161
7998
  import path2 from "path";
7162
7999
  import { randomUUID as randomUUID2, hkdfSync as hkdfSync2 } from "crypto";
7163
- import { privateKeyToAccount as privateKeyToAccount4 } from "viem/accounts";
8000
+ import { privateKeyToAccount as privateKeyToAccount5 } from "viem/accounts";
7164
8001
 
7165
8002
  // src/lib/xmtp-envelope.ts
7166
8003
  import { randomUUID } from "crypto";
@@ -7719,7 +8556,7 @@ async function createProductionClient(input) {
7719
8556
  } else if (input.keystore) {
7720
8557
  const dek = await fetchDeviceKey(input.keystore.deviceId, input.keystore.apiToken);
7721
8558
  const privateKey = decryptPrivateKey(dek, input.keystore.encryptedKey);
7722
- const account = privateKeyToAccount4(privateKey);
8559
+ const account = privateKeyToAccount5(privateKey);
7723
8560
  signer = {
7724
8561
  type: "EOA",
7725
8562
  getIdentifier: () => ({ identifier: account.address.toLowerCase(), identifierKind: 0 }),
@@ -7918,7 +8755,7 @@ function getDefaultQueryTimeoutMs() {
7918
8755
  }
7919
8756
  return Math.floor(parsed);
7920
8757
  }
7921
- var xmtpCommand = new Command48("xmtp").description("Manage XMTP messaging for this agent");
8758
+ var xmtpCommand = new Command49("xmtp").description("Manage XMTP messaging for this agent");
7922
8759
  xmtpCommand.command("init").description("Initialize XMTP client and register installation metadata with backend").action(async () => {
7923
8760
  const keystore = await loadKeystore();
7924
8761
  const client = await createXmtpClient({
@@ -8146,7 +8983,7 @@ xmtpCommand.command("purge").description("Revoke stale XMTP installations that h
8146
8983
  });
8147
8984
 
8148
8985
  // src/commands/daemon.ts
8149
- import { Command as Command49 } from "commander";
8986
+ import { Command as Command50 } from "commander";
8150
8987
  function diffTaskStatuses(prev, next) {
8151
8988
  const changes = [];
8152
8989
  for (const [taskId, newStatus] of next) {
@@ -8174,7 +9011,7 @@ function sleepOrAbort(ms, signal) {
8174
9011
  });
8175
9012
  }
8176
9013
  var MAX_SEEN_TASK_IDS = 2e3;
8177
- var daemonCommand = new Command49("daemon").description("Long-running agent daemon: XMTP stream, heartbeats, and task polling").option("--heartbeat-interval <ms>", "Heartbeat interval in milliseconds", "1800000").option("--inbox-interval <ms>", "Inbox poll interval in milliseconds", "15000").option("--task-interval <ms>", "New task poll interval in milliseconds", "15000").option(
9014
+ var daemonCommand = new Command50("daemon").description("Long-running agent daemon: XMTP stream, heartbeats, and task polling").option("--heartbeat-interval <ms>", "Heartbeat interval in milliseconds", "1800000").option("--inbox-interval <ms>", "Inbox poll interval in milliseconds", "15000").option("--task-interval <ms>", "New task poll interval in milliseconds", "15000").option(
8178
9015
  "--auction-poll-interval <ms>",
8179
9016
  "Poll interval for clock-based auction tasks (dutch/reverse_dutch) in milliseconds",
8180
9017
  "15000"
@@ -8495,11 +9332,11 @@ var daemonCommand = new Command49("daemon").description("Long-running agent daem
8495
9332
  );
8496
9333
 
8497
9334
  // src/commands/email/index.ts
8498
- import { Command as Command58 } from "commander";
9335
+ import { Command as Command59 } from "commander";
8499
9336
 
8500
9337
  // src/commands/email/register.ts
8501
- import { Command as Command50 } from "commander";
8502
- var registerCommand = new Command50("register").description("Register an email address for this agent").requiredOption("--username <name>", "Desired username (e.g. myagent)").action(async (opts) => {
9338
+ import { Command as Command51 } from "commander";
9339
+ var registerCommand = new Command51("register").description("Register an email address for this agent").requiredOption("--username <name>", "Desired username (e.g. myagent)").action(async (opts) => {
8503
9340
  const check = await apiGet(
8504
9341
  `/api/emails/check-username?username=${encodeURIComponent(opts.username)}`
8505
9342
  );
@@ -8516,8 +9353,8 @@ var registerCommand = new Command50("register").description("Register an email a
8516
9353
  });
8517
9354
 
8518
9355
  // src/commands/email/inbox.ts
8519
- import { Command as Command51 } from "commander";
8520
- var inboxCommand2 = new Command51("inbox").description("List emails in your inbox").option("--limit <n>", "Number of emails to return", "20").option("--unread", "Show only unread emails").action(async (opts) => {
9356
+ import { Command as Command52 } from "commander";
9357
+ var inboxCommand2 = new Command52("inbox").description("List emails in your inbox").option("--limit <n>", "Number of emails to return", "20").option("--unread", "Show only unread emails").action(async (opts) => {
8521
9358
  const keystore = await loadKeystore();
8522
9359
  const params = new URLSearchParams({
8523
9360
  deviceId: keystore.deviceId,
@@ -8532,8 +9369,8 @@ var inboxCommand2 = new Command51("inbox").description("List emails in your inbo
8532
9369
  });
8533
9370
 
8534
9371
  // src/commands/email/read.ts
8535
- import { Command as Command52 } from "commander";
8536
- var readCommand = new Command52("read").description("Read an email by ID (marks it as read)").argument("<id>", "Email ID").action(async (id) => {
9372
+ import { Command as Command53 } from "commander";
9373
+ var readCommand = new Command53("read").description("Read an email by ID (marks it as read)").argument("<id>", "Email ID").action(async (id) => {
8537
9374
  const keystore = await loadKeystore();
8538
9375
  const params = new URLSearchParams({
8539
9376
  deviceId: keystore.deviceId,
@@ -8545,8 +9382,8 @@ var readCommand = new Command52("read").description("Read an email by ID (marks
8545
9382
  });
8546
9383
 
8547
9384
  // src/commands/email/send.ts
8548
- import { Command as Command53 } from "commander";
8549
- var sendCommand = new Command53("send").description("Send an email").requiredOption("--to <address>", "Recipient email address").requiredOption("--subject <subject>", "Email subject").requiredOption("--body <text>", "Email body text").action(async (opts) => {
9385
+ import { Command as Command54 } from "commander";
9386
+ var sendCommand = new Command54("send").description("Send an email").requiredOption("--to <address>", "Recipient email address").requiredOption("--subject <subject>", "Email subject").requiredOption("--body <text>", "Email body text").action(async (opts) => {
8550
9387
  const keystore = await loadKeystore();
8551
9388
  const result = await apiPost("/api/emails/send", {
8552
9389
  deviceId: keystore.deviceId,
@@ -8559,8 +9396,8 @@ var sendCommand = new Command53("send").description("Send an email").requiredOpt
8559
9396
  });
8560
9397
 
8561
9398
  // src/commands/email/reply.ts
8562
- import { Command as Command54 } from "commander";
8563
- var replyCommand = new Command54("reply").description("Reply to an email").argument("<id>", "Email ID to reply to").requiredOption("--body <text>", "Reply body text").action(async (id, opts) => {
9399
+ import { Command as Command55 } from "commander";
9400
+ var replyCommand = new Command55("reply").description("Reply to an email").argument("<id>", "Email ID to reply to").requiredOption("--body <text>", "Reply body text").action(async (id, opts) => {
8564
9401
  const keystore = await loadKeystore();
8565
9402
  const params = new URLSearchParams({
8566
9403
  deviceId: keystore.deviceId,
@@ -8582,8 +9419,8 @@ var replyCommand = new Command54("reply").description("Reply to an email").argum
8582
9419
  });
8583
9420
 
8584
9421
  // src/commands/email/delete.ts
8585
- import { Command as Command55 } from "commander";
8586
- var deleteCommand = new Command55("delete").description("Delete an email by ID").argument("<id>", "Email ID").action(async (id) => {
9422
+ import { Command as Command56 } from "commander";
9423
+ var deleteCommand = new Command56("delete").description("Delete an email by ID").argument("<id>", "Email ID").action(async (id) => {
8587
9424
  const keystore = await loadKeystore();
8588
9425
  const result = await apiPost("/api/emails/delete", {
8589
9426
  deviceId: keystore.deviceId,
@@ -8594,15 +9431,15 @@ var deleteCommand = new Command55("delete").description("Delete an email by ID")
8594
9431
  });
8595
9432
 
8596
9433
  // src/commands/email/address.ts
8597
- import { Command as Command56 } from "commander";
8598
- var addressCommand2 = new Command56("address").description("Show your registered email address").action(async () => {
9434
+ import { Command as Command57 } from "commander";
9435
+ var addressCommand2 = new Command57("address").description("Show your registered email address").action(async () => {
8599
9436
  const keystore = await loadKeystore();
8600
9437
  const result = await apiGet(`/api/agents/stats?address=${keystore.walletAddress}`);
8601
9438
  printResult({ emailAddress: result.emailAddress ?? null });
8602
9439
  });
8603
9440
 
8604
9441
  // src/commands/email/mark-read.ts
8605
- import { Command as Command57 } from "commander";
9442
+ import { Command as Command58 } from "commander";
8606
9443
  async function setReadStatus(id, read) {
8607
9444
  const keystore = await loadKeystore();
8608
9445
  const result = await apiPost("/api/emails/mark-read", {
@@ -8613,12 +9450,12 @@ async function setReadStatus(id, read) {
8613
9450
  });
8614
9451
  printResult({ id: result.id, isRead: result.isRead });
8615
9452
  }
8616
- var markReadCommand = new Command57("mark-read").description("Mark an email as read or unread").argument("<id>", "Email ID").option("--unread", "Mark as unread instead of read").action(async (id, opts) => {
9453
+ var markReadCommand = new Command58("mark-read").description("Mark an email as read or unread").argument("<id>", "Email ID").option("--unread", "Mark as unread instead of read").action(async (id, opts) => {
8617
9454
  await setReadStatus(id, !opts.unread);
8618
9455
  });
8619
9456
 
8620
9457
  // src/commands/email/index.ts
8621
- var emailCommand = new Command58("email").description("Email management commands");
9458
+ var emailCommand = new Command59("email").description("Email management commands");
8622
9459
  emailCommand.addCommand(registerCommand);
8623
9460
  emailCommand.addCommand(inboxCommand2);
8624
9461
  emailCommand.addCommand(readCommand);
@@ -8629,11 +9466,11 @@ emailCommand.addCommand(addressCommand2);
8629
9466
  emailCommand.addCommand(markReadCommand);
8630
9467
 
8631
9468
  // src/commands/requester/index.ts
8632
- import { Command as Command60 } from "commander";
9469
+ import { Command as Command61 } from "commander";
8633
9470
 
8634
9471
  // src/commands/requester/stats.ts
8635
- import { Command as Command59 } from "commander";
8636
- var requesterStatsCmd = new Command59("stats").description("Get requester reputation stats for an address").argument("<address>", "Wallet address of the requester").action(async (address) => {
9472
+ import { Command as Command60 } from "commander";
9473
+ var requesterStatsCmd = new Command60("stats").description("Get requester reputation stats for an address").argument("<address>", "Wallet address of the requester").action(async (address) => {
8637
9474
  if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
8638
9475
  printError("Address must be a 0x-prefixed 20-byte hex string");
8639
9476
  process.exit(1);
@@ -8649,12 +9486,12 @@ var requesterStatsCmd = new Command59("stats").description("Get requester reputa
8649
9486
  });
8650
9487
 
8651
9488
  // src/commands/requester/index.ts
8652
- var requesterCmd = new Command60("requester").description("Requester reputation commands").addCommand(requesterStatsCmd);
9489
+ var requesterCmd = new Command61("requester").description("Requester reputation commands").addCommand(requesterStatsCmd);
8653
9490
 
8654
9491
  // src/index.ts
8655
9492
  var require2 = createRequire(import.meta.url);
8656
9493
  var { version } = require2("../package.json");
8657
- var program = new Command61();
9494
+ var program = new Command62();
8658
9495
  program.name("taskmarket").description("Taskmarket CLI for AI agents").version(version);
8659
9496
  program.addCommand(initCommand);
8660
9497
  program.addCommand(walletCommand);
@@ -8672,6 +9509,7 @@ program.addCommand(xmtpCommand);
8672
9509
  program.addCommand(daemonCommand);
8673
9510
  program.addCommand(emailCommand);
8674
9511
  program.addCommand(requesterCmd);
9512
+ program.addCommand(legalCommand);
8675
9513
  program.parseAsync(process.argv).catch((err) => {
8676
9514
  process.stderr.write(JSON.stringify({ ok: false, error: err.message }) + "\n");
8677
9515
  process.exit(1);