@lucid-agents/taskmarket 1.3.0 → 1.5.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 +2463 -1559
  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
  }
@@ -4507,6 +4054,7 @@ var coerce = {
4507
4054
  var NEVER = INVALID;
4508
4055
 
4509
4056
  // ../../packages/shared/dist/schemas/common.schemas.js
4057
+ var EthAddressSchema = external_exports.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid Ethereum address");
4510
4058
  var UsdcBaseUnitsSchema = external_exports.string().regex(/^[0-9]+$/, "Amount must be a non-negative integer in USDC base units");
4511
4059
  var PositiveUsdcBaseUnitsSchema = UsdcBaseUnitsSchema.refine(
4512
4060
  // The refine still runs when the regex check has already failed; skip the
@@ -4518,9 +4066,122 @@ var Secp256k1PublicKeySchema = external_exports.string().refine((value) => {
4518
4066
  const key = value.replace(/^0x/, "");
4519
4067
  return /^(?:02|03)[0-9a-fA-F]{64}$/.test(key) || /^04[0-9a-fA-F]{128}$/.test(key);
4520
4068
  }, "Public key must be a compressed or uncompressed secp256k1 key");
4069
+ function csvArrayQueryParam(schema = external_exports.string()) {
4070
+ return external_exports.preprocess((value) => {
4071
+ if (value === void 0 || value === "")
4072
+ return void 0;
4073
+ if (Array.isArray(value))
4074
+ return value;
4075
+ return String(value).split(",").map((v) => v.trim()).filter(Boolean);
4076
+ }, external_exports.array(schema).optional());
4077
+ }
4078
+
4079
+ // ../../packages/shared/dist/schemas/task-drops.schemas.js
4080
+ var EthAddress = external_exports.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid Ethereum address").toLowerCase();
4081
+ var EmailAddress = external_exports.string().trim().toLowerCase().email().max(320);
4082
+ var TaskDropSourceSchema = external_exports.enum([
4083
+ "first_run_panel",
4084
+ "agent_setup",
4085
+ "account",
4086
+ "cli",
4087
+ "drop_page",
4088
+ "taskdrop_landing",
4089
+ "official_drop_page"
4090
+ ]);
4091
+ var TaskDropSubscriptionScopeSchema = external_exports.enum(["drop", "official"]);
4092
+ var TaskDropCreateInlineSchema = external_exports.object({
4093
+ name: external_exports.string().trim().min(1).max(80),
4094
+ description: external_exports.string().trim().max(500).optional()
4095
+ });
4096
+ var TaskDropSubscribeInputSchema = external_exports.object({
4097
+ taskDropId: external_exports.string().min(1),
4098
+ email: EmailAddress,
4099
+ walletAddress: EthAddress.optional(),
4100
+ source: TaskDropSourceSchema.optional().default("drop_page")
4101
+ });
4102
+ var TaskDropSubscribeResponseSchema = external_exports.object({
4103
+ subscribed: external_exports.boolean(),
4104
+ alreadySubscribed: external_exports.boolean(),
4105
+ email: EmailAddress,
4106
+ taskDropId: external_exports.string(),
4107
+ scope: external_exports.literal("drop")
4108
+ });
4109
+ var TaskDropOfficialSubscribeInputSchema = external_exports.object({
4110
+ email: EmailAddress,
4111
+ walletAddress: EthAddress.optional(),
4112
+ source: TaskDropSourceSchema.optional().default("taskdrop_landing")
4113
+ });
4114
+ var TaskDropOfficialSubscribeResponseSchema = external_exports.object({
4115
+ subscribed: external_exports.boolean(),
4116
+ alreadySubscribed: external_exports.boolean(),
4117
+ email: EmailAddress,
4118
+ scope: external_exports.literal("official")
4119
+ });
4120
+ var TaskDropStatusInputSchema = external_exports.object({
4121
+ taskDropId: external_exports.string().min(1),
4122
+ email: EmailAddress
4123
+ });
4124
+ var TaskDropStatusResponseSchema = external_exports.object({
4125
+ subscribed: external_exports.boolean(),
4126
+ taskDropId: external_exports.string(),
4127
+ scope: TaskDropSubscriptionScopeSchema.nullable()
4128
+ });
4129
+ var TaskDropOfficialStatusInputSchema = external_exports.object({
4130
+ email: EmailAddress
4131
+ });
4132
+ var TaskDropOfficialStatusResponseSchema = external_exports.object({
4133
+ subscribed: external_exports.boolean(),
4134
+ scope: external_exports.literal("official").nullable()
4135
+ });
4136
+ var TaskDropAnnouncementInputSchema = external_exports.object({
4137
+ taskDropId: external_exports.string().min(1)
4138
+ });
4139
+ var TaskDropAnnouncementResponseSchema = external_exports.object({
4140
+ taskDropId: external_exports.string().min(1),
4141
+ announcedAt: external_exports.string().datetime(),
4142
+ alreadyAnnounced: external_exports.boolean(),
4143
+ sent: external_exports.number().int().nonnegative(),
4144
+ failed: external_exports.number().int().nonnegative(),
4145
+ pending: external_exports.number().int().nonnegative(),
4146
+ total: external_exports.number().int().nonnegative()
4147
+ });
4148
+ var TaskDropListByOwnerInputSchema = external_exports.object({
4149
+ ownerAddress: EthAddress
4150
+ });
4151
+ var TaskDropGetInputSchema = external_exports.object({
4152
+ taskDropId: external_exports.string().min(1)
4153
+ });
4154
+ var TaskDropSummarySchema = external_exports.object({
4155
+ id: external_exports.string().min(1),
4156
+ ownerAddress: EthAddress,
4157
+ officialWalletAddress: EthAddress,
4158
+ isOfficial: external_exports.boolean(),
4159
+ name: external_exports.string().min(1).max(80),
4160
+ description: external_exports.string().max(500).nullable(),
4161
+ createdAt: external_exports.string().datetime(),
4162
+ announcedAt: external_exports.string().datetime().nullable()
4163
+ }).refine((drop) => drop.officialWalletAddress === drop.ownerAddress, {
4164
+ message: "officialWalletAddress must match ownerAddress",
4165
+ path: ["officialWalletAddress"]
4166
+ });
4167
+ var TaskDropTaskSchema = external_exports.object({
4168
+ id: external_exports.string().min(1),
4169
+ description: external_exports.string(),
4170
+ reward: external_exports.string().regex(/^\d+$/),
4171
+ status: external_exports.string().min(1),
4172
+ mode: external_exports.string().min(1),
4173
+ tags: external_exports.array(external_exports.string()),
4174
+ createdAt: external_exports.string().datetime(),
4175
+ expiryTime: external_exports.string().datetime()
4176
+ });
4177
+ var TaskDropPageDataSchema = external_exports.object({
4178
+ drop: TaskDropSummarySchema,
4179
+ tasks: external_exports.array(TaskDropTaskSchema)
4180
+ });
4521
4181
 
4522
4182
  // ../../packages/shared/dist/schemas/task.schemas.js
4523
4183
  var TaskMode = external_exports.enum(["bounty", "claim", "pitch", "benchmark", "auction"]);
4184
+ var TaskVisibility = external_exports.enum(["unlisted", "public"]);
4524
4185
  var TaskStatus = external_exports.enum([
4525
4186
  "open",
4526
4187
  "claimed",
@@ -4565,7 +4226,21 @@ var PendingActionSchema = external_exports.object({
4565
4226
  requiresPayment: external_exports.boolean().optional(),
4566
4227
  paymentAmount: external_exports.string().nullable().optional(),
4567
4228
  availableAfter: external_exports.string().nullable().optional(),
4568
- availableUntil: external_exports.string().nullable().optional()
4229
+ availableUntil: external_exports.string().nullable().optional(),
4230
+ targetWorker: external_exports.string().nullable().optional()
4231
+ });
4232
+ var TaskAwardSchema = external_exports.object({
4233
+ workerAddress: external_exports.string(),
4234
+ workerAgentId: external_exports.string().nullable(),
4235
+ workerActorType: external_exports.enum(["agent", "human"]),
4236
+ rank: external_exports.number().int().positive(),
4237
+ isPrimary: external_exports.boolean(),
4238
+ grossAmount: external_exports.string(),
4239
+ workerPayment: external_exports.string(),
4240
+ platformFee: external_exports.string(),
4241
+ settlementTxHash: external_exports.string(),
4242
+ settledAt: external_exports.string(),
4243
+ rating: external_exports.number().min(0).max(100).nullable()
4569
4244
  });
4570
4245
  var TaskCreateSchema = external_exports.object({
4571
4246
  description: external_exports.string().min(1, "Description is required").max(2e3, "Description is too long"),
@@ -4573,6 +4248,7 @@ var TaskCreateSchema = external_exports.object({
4573
4248
  duration: external_exports.number().positive("Duration must be positive"),
4574
4249
  tags: external_exports.array(external_exports.string()).max(10, "Maximum 10 tags allowed"),
4575
4250
  mode: TaskMode.optional().default("bounty"),
4251
+ taskVisibility: TaskVisibility.optional().default("public"),
4576
4252
  stakeRequired: external_exports.boolean().optional().default(false),
4577
4253
  stakeBps: external_exports.number().min(0).max(1e4).optional().default(0),
4578
4254
  pitchDeadline: external_exports.number().positive().optional(),
@@ -4589,8 +4265,17 @@ var TaskCreateSchema = external_exports.object({
4589
4265
  evaluatorFeeBps: external_exports.number().min(0).max(1e4).optional(),
4590
4266
  evaluationWindowHours: external_exports.number().positive().optional(),
4591
4267
  appealWindowHours: external_exports.number().positive().optional(),
4592
- disputeResolver: external_exports.string().optional()
4268
+ disputeResolver: external_exports.string().optional(),
4269
+ taskDropId: external_exports.string().min(1).optional(),
4270
+ taskDropCreate: TaskDropCreateInlineSchema.optional()
4593
4271
  }).superRefine((input, ctx) => {
4272
+ if (input.taskDropId && input.taskDropCreate) {
4273
+ ctx.addIssue({
4274
+ code: external_exports.ZodIssueCode.custom,
4275
+ path: ["taskDropId"],
4276
+ message: "Provide taskDropId or taskDropCreate, not both"
4277
+ });
4278
+ }
4594
4279
  if (input.mode !== "auction")
4595
4280
  return;
4596
4281
  const toBaseUnits = (value) => value !== void 0 && /^[0-9]+$/.test(value) ? BigInt(value) : null;
@@ -4655,9 +4340,8 @@ var TaskResponseSchema = external_exports.object({
4655
4340
  expiryTime: external_exports.string(),
4656
4341
  status: TaskStatus,
4657
4342
  tags: external_exports.array(external_exports.string()),
4658
- worker: external_exports.string().nullable(),
4659
- rating: external_exports.number().min(0).max(100).nullable(),
4660
4343
  mode: TaskMode,
4344
+ taskVisibility: TaskVisibility.optional().default("public"),
4661
4345
  stakeRequired: external_exports.boolean(),
4662
4346
  stakeBps: external_exports.number(),
4663
4347
  pitchDeadline: external_exports.string().nullable(),
@@ -4669,6 +4353,14 @@ var TaskResponseSchema = external_exports.object({
4669
4353
  claimedAt: external_exports.string().nullable(),
4670
4354
  platformFeeBps: external_exports.number(),
4671
4355
  submissionCount: external_exports.number().optional().default(0),
4356
+ awardCount: external_exports.number().int().nonnegative().optional(),
4357
+ // Read-time projection of the rank-1 task_awards row -- not a separately
4358
+ // written field, so it cannot drift out of sync the way the old worker/
4359
+ // rating compatibility fields could (see ADR-0006). null before settlement.
4360
+ primaryAward: external_exports.object({
4361
+ workerAddress: external_exports.string(),
4362
+ rating: external_exports.number().min(0).max(100).nullable()
4363
+ }).nullable().optional(),
4672
4364
  pitchCount: external_exports.number().optional().default(0),
4673
4365
  requesterAgentId: external_exports.string().nullable().optional(),
4674
4366
  requesterActorType: external_exports.enum(["agent", "human"]).optional(),
@@ -4699,6 +4391,11 @@ var TaskResponseSchema = external_exports.object({
4699
4391
  netReward: external_exports.string().nullable().optional(),
4700
4392
  pendingActions: PendingActionSchema.array().optional(),
4701
4393
  selfAward: external_exports.boolean().nullable().optional(),
4394
+ taskDropId: external_exports.string().nullable().optional(),
4395
+ taskDrop: external_exports.object({
4396
+ id: external_exports.string(),
4397
+ name: external_exports.string()
4398
+ }).nullable().optional(),
4702
4399
  hooks: external_exports.array(external_exports.string()).optional()
4703
4400
  });
4704
4401
  var TaskListInputSchema = external_exports.object({
@@ -4708,7 +4405,7 @@ var TaskListInputSchema = external_exports.object({
4708
4405
  mode: external_exports.enum(["ALL", "bounty", "claim", "pitch", "benchmark", "auction"]).optional().default("ALL"),
4709
4406
  auctionType: AuctionType.optional(),
4710
4407
  requesterActorType: external_exports.enum(["agent", "human"]).optional(),
4711
- tags: external_exports.array(external_exports.string()).optional(),
4408
+ tags: csvArrayQueryParam(),
4712
4409
  minReward: external_exports.string().optional(),
4713
4410
  maxReward: external_exports.string().optional(),
4714
4411
  deadlineHours: external_exports.number().int().positive().optional(),
@@ -4722,7 +4419,12 @@ var TaskListResponseSchema = external_exports.object({
4722
4419
  hasMore: external_exports.boolean()
4723
4420
  });
4724
4421
  var TaskInboxInputSchema = external_exports.object({
4725
- address: external_exports.string()
4422
+ address: external_exports.string(),
4423
+ // Optional proof that the caller owns `address`: a signature over
4424
+ // `taskmarket:inbox:<address>` (see ADR-0015). When present and valid, the
4425
+ // response additionally includes that address's own unlisted tasks; otherwise
4426
+ // behavior is unchanged (public tasks only, same as today, for any address).
4427
+ signature: external_exports.string().optional()
4726
4428
  });
4727
4429
  var TaskInboxResponseSchema = external_exports.object({
4728
4430
  asRequester: external_exports.array(TaskResponseSchema),
@@ -4730,6 +4432,7 @@ var TaskInboxResponseSchema = external_exports.object({
4730
4432
  });
4731
4433
  var TaskDetailResponseSchema = TaskResponseSchema.extend({
4732
4434
  pendingActions: PendingActionSchema.array(),
4435
+ awards: TaskAwardSchema.array().optional(),
4733
4436
  dreamsPerUsdc: external_exports.string().optional(),
4734
4437
  bonusBps: external_exports.number().optional(),
4735
4438
  estimatedUsdBonusValue: external_exports.string().optional(),
@@ -5056,10 +4759,9 @@ var BidResponseSchema = external_exports.object({
5056
4759
  });
5057
4760
 
5058
4761
  // ../../packages/shared/dist/schemas/wallet.schemas.js
5059
- var EthAddress = external_exports.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid Ethereum address");
5060
4762
  var SetWithdrawalAddressInputSchema = external_exports.object({
5061
- walletAddress: EthAddress,
5062
- withdrawalAddress: EthAddress,
4763
+ walletAddress: EthAddressSchema,
4764
+ withdrawalAddress: EthAddressSchema,
5063
4765
  signature: external_exports.string().min(1)
5064
4766
  });
5065
4767
  var SetWithdrawalAddressOutputSchema = external_exports.object({
@@ -5084,7 +4786,7 @@ var AuthorizationSchema = external_exports.object({
5084
4786
  nonce: external_exports.string()
5085
4787
  });
5086
4788
  var WithdrawInputSchema = external_exports.object({
5087
- from: EthAddress,
4789
+ from: EthAddressSchema,
5088
4790
  amountBaseUnits: external_exports.string().min(1),
5089
4791
  authorization: AuthorizationSchema,
5090
4792
  signature: external_exports.string().min(1)
@@ -5098,8 +4800,8 @@ var DreamsBalanceOutputSchema = external_exports.object({
5098
4800
  claimableBaseUnits: external_exports.string()
5099
4801
  });
5100
4802
  var WithdrawDreamsInputSchema = external_exports.object({
5101
- workerAddress: EthAddress,
5102
- destination: EthAddress,
4803
+ workerAddress: EthAddressSchema,
4804
+ destination: EthAddressSchema,
5103
4805
  nonce: external_exports.string().min(1),
5104
4806
  validBefore: external_exports.string().min(1),
5105
4807
  signature: external_exports.string().min(1)
@@ -5118,7 +4820,6 @@ var ExchangeRateOutputSchema = external_exports.object({
5118
4820
  });
5119
4821
 
5120
4822
  // ../../packages/shared/dist/schemas/xmtp.schemas.js
5121
- var EthereumAddressSchema = external_exports.string().regex(/^0x[a-fA-F0-9]{40}$/);
5122
4823
  var XmtpPolicySchema = external_exports.enum(["allow", "deny", "quarantine"]);
5123
4824
  var XmtpPolicyModeSchema = external_exports.enum(["allowlist", "open"]);
5124
4825
  var AgentMessageEnvelopeSchema = external_exports.object({
@@ -5127,7 +4828,7 @@ var AgentMessageEnvelopeSchema = external_exports.object({
5127
4828
  requestId: external_exports.string().uuid(),
5128
4829
  replyToRequestId: external_exports.string().uuid().nullable().optional(),
5129
4830
  senderInboxId: external_exports.string().min(1),
5130
- senderAddress: EthereumAddressSchema,
4831
+ senderAddress: EthAddressSchema,
5131
4832
  sentAt: external_exports.string().datetime(),
5132
4833
  deadlineMs: external_exports.number().int().positive().optional(),
5133
4834
  payload: external_exports.record(external_exports.string(), external_exports.unknown())
@@ -5191,13 +4892,13 @@ var XmtpPeerPolicyListOutputSchema = external_exports.object({
5191
4892
  }))
5192
4893
  });
5193
4894
  var XmtpResolvePeerInputSchema = external_exports.object({
5194
- address: EthereumAddressSchema.optional(),
4895
+ address: EthAddressSchema.optional(),
5195
4896
  agentId: external_exports.string().min(1).optional()
5196
4897
  }).refine((value) => Boolean(value.address || value.agentId), {
5197
4898
  message: "Either address or agentId is required"
5198
4899
  });
5199
4900
  var XmtpResolvePeerOutputSchema = external_exports.object({
5200
- address: EthereumAddressSchema.nullable(),
4901
+ address: EthAddressSchema.nullable(),
5201
4902
  inboxId: external_exports.string().nullable()
5202
4903
  });
5203
4904
 
@@ -5346,6 +5047,78 @@ var ResolveDisputeInputSchema = external_exports.object({
5346
5047
  });
5347
5048
  var EvaluatorTimeoutInputSchema = external_exports.object({ taskId: external_exports.string() });
5348
5049
 
5050
+ // ../../packages/shared/dist/schemas/legal.schemas.js
5051
+ var LegalDocumentTypeSchema = external_exports.enum([
5052
+ "terms_of_service",
5053
+ "privacy_policy",
5054
+ "risk_disclosure",
5055
+ "acceptable_use_policy"
5056
+ ]);
5057
+ var LegalDocumentSlugSchema = external_exports.enum(["terms", "privacy", "risks", "acceptable-use"]);
5058
+ var LegalSha256DigestSchema = external_exports.string().regex(/^sha256:[a-f0-9]{64}$/);
5059
+ var LegalBundleDocumentSchema = external_exports.object({
5060
+ contentHash: LegalSha256DigestSchema,
5061
+ slug: LegalDocumentSlugSchema,
5062
+ summary: external_exports.string(),
5063
+ title: external_exports.string(),
5064
+ type: LegalDocumentTypeSchema,
5065
+ url: external_exports.string().url(),
5066
+ version: external_exports.string()
5067
+ });
5068
+ var LegalBundleSchema = external_exports.object({
5069
+ acceptanceAvailable: external_exports.boolean(),
5070
+ acceptanceStatement: external_exports.string(),
5071
+ bundleDigest: LegalSha256DigestSchema,
5072
+ documents: external_exports.array(LegalBundleDocumentSchema),
5073
+ effectiveAt: external_exports.string().nullable(),
5074
+ enforcementEnabled: external_exports.boolean(),
5075
+ privyAppId: external_exports.string().nullable(),
5076
+ publishedAt: external_exports.string(),
5077
+ status: external_exports.enum(["draft", "approved"]),
5078
+ version: external_exports.string()
5079
+ });
5080
+ var LegalSubjectTypeSchema = external_exports.enum(["privy_user", "wallet"]);
5081
+ var LegalStatusResponseSchema = external_exports.object({
5082
+ accepted: external_exports.boolean(),
5083
+ bundle: LegalBundleSchema,
5084
+ receipt: external_exports.string().optional(),
5085
+ subjectType: LegalSubjectTypeSchema.optional()
5086
+ });
5087
+ var LegalWalletAddressSchema = EthAddressSchema;
5088
+ var LegalAffirmationsSchema = external_exports.object({
5089
+ acknowledgedRisk: external_exports.literal(true),
5090
+ agreedToAcceptableUse: external_exports.literal(true),
5091
+ agreedToTerms: external_exports.literal(true),
5092
+ receivedPrivacyNotice: external_exports.literal(true)
5093
+ });
5094
+ var LegalChallengeInputSchema = external_exports.object({
5095
+ walletAddress: LegalWalletAddressSchema
5096
+ });
5097
+ var LegalChallengeResponseSchema = external_exports.object({
5098
+ bundle: LegalBundleSchema,
5099
+ expiresAt: external_exports.string(),
5100
+ issuedAt: external_exports.string(),
5101
+ message: external_exports.string(),
5102
+ nonce: external_exports.string().uuid(),
5103
+ walletAddress: LegalWalletAddressSchema
5104
+ });
5105
+ var LegalAcceptanceBundleSchema = external_exports.object({
5106
+ bundleDigest: LegalSha256DigestSchema,
5107
+ bundleVersion: external_exports.string().max(128)
5108
+ });
5109
+ var LegalWalletAcceptanceInputSchema = LegalAffirmationsSchema.merge(LegalAcceptanceBundleSchema).extend({
5110
+ nonce: external_exports.string().uuid(),
5111
+ signature: external_exports.string().regex(/^0x[a-fA-F0-9]{128}(?:[a-fA-F0-9]{2})?$/),
5112
+ walletAddress: LegalWalletAddressSchema
5113
+ });
5114
+ var LegalWebAcceptanceInputSchema = LegalAffirmationsSchema.merge(LegalAcceptanceBundleSchema);
5115
+ var LegalAcceptanceResponseSchema = external_exports.object({
5116
+ acceptedAt: external_exports.string(),
5117
+ bundleDigest: LegalSha256DigestSchema,
5118
+ bundleVersion: external_exports.string(),
5119
+ receipt: external_exports.string()
5120
+ });
5121
+
5349
5122
  // ../../packages/shared/dist/platform.constants.js
5350
5123
  var USDC_DECIMALS = 6;
5351
5124
 
@@ -5611,42 +5384,1144 @@ function modInverse(a, n) {
5611
5384
  [t, nextT] = [nextT, t - q * nextT];
5612
5385
  [r, nextR] = [nextR, r - q * nextR];
5613
5386
  }
5614
- if (r !== 1)
5615
- return 0;
5616
- return (t % n + n) % n;
5617
- }
5618
- var MIX_K_INV = modInverse(MIX_K, N);
5387
+ if (r !== 1)
5388
+ return 0;
5389
+ return (t % n + n) % n;
5390
+ }
5391
+ var MIX_K_INV = modInverse(MIX_K, N);
5392
+
5393
+ // ../../packages/shared/dist/lib/dreams.js
5394
+ var USDC_DECIMALS2 = 6n;
5395
+ var DREAMS_DECIMALS = 18n;
5396
+ var USDC_SCALE = 10n ** USDC_DECIMALS2;
5397
+ var DREAMS_SCALE = 10n ** DREAMS_DECIMALS;
5398
+ function dreamsToUsd(dreamsBaseUnits, dreamsPerUsdc) {
5399
+ const dreams = BigInt(dreamsBaseUnits);
5400
+ const rate = BigInt(dreamsPerUsdc);
5401
+ if (dreams <= 0n || rate <= 0n)
5402
+ return "0";
5403
+ return (dreams * USDC_SCALE / rate).toString();
5404
+ }
5405
+ function formatDreams(baseUnits) {
5406
+ const value = BigInt(baseUnits);
5407
+ const negative = value < 0n;
5408
+ const abs = negative ? -value : value;
5409
+ const whole = abs / DREAMS_SCALE;
5410
+ const frac = abs % DREAMS_SCALE;
5411
+ const fracStr = frac.toString().padStart(18, "0").replace(/0+$/, "");
5412
+ const sign = negative ? "-" : "";
5413
+ return fracStr.length > 0 ? `${sign}${whole}.${fracStr}` : `${sign}${whole}`;
5414
+ }
5415
+
5416
+ // ../../packages/shared/dist/lib/authMessages.js
5417
+ function buildSelectWorkerMessage(taskId, pitchId, workerAddress) {
5418
+ return `taskmarket:select-worker:${taskId}:${pitchId}:${workerAddress.toLowerCase()}`;
5419
+ }
5420
+ function buildInboxSelfAuthMessage(address) {
5421
+ return `taskmarket:inbox:${address.toLowerCase()}`;
5422
+ }
5423
+ function buildMyBidsMessage(address) {
5424
+ return `taskmarket:my-bids:${address.toLowerCase()}`;
5425
+ }
5426
+ function buildSubmitMessage(taskId) {
5427
+ return `taskmarket:submit:${taskId}`;
5428
+ }
5429
+ function buildClaimMessage(taskId) {
5430
+ return `taskmarket:claim:${taskId}`;
5431
+ }
5432
+ function buildForfeitMessage(taskId) {
5433
+ return `taskmarket:forfeit:${taskId}`;
5434
+ }
5435
+ function buildSetWithdrawalAddressMessage(withdrawalAddress) {
5436
+ return `taskmarket:set-withdrawal-address:${withdrawalAddress.toLowerCase()}`;
5437
+ }
5438
+ function buildWithdrawDreamsMessage(destination, nonce, validBefore) {
5439
+ return `taskmarket:withdraw-dreams:${destination.toLowerCase()}:${nonce}:${validBefore}`;
5440
+ }
5441
+ function buildDeviceRegisterMessage(walletAddress) {
5442
+ return `taskmarket:device-register:${walletAddress.toLowerCase()}`;
5443
+ }
5444
+
5445
+ // ../../packages/shared/dist/legal.js
5446
+ var LEGAL_RECEIPT_HEADER = "X-Taskmarket-Legal-Receipt";
5447
+ function buildLegalReceiptHeaders(receipt) {
5448
+ return receipt ? { [LEGAL_RECEIPT_HEADER]: receipt } : {};
5449
+ }
5450
+ var LEGAL_ENTITY = {
5451
+ registeredName: "Daydreams AI",
5452
+ jurisdiction: "[JURISDICTION OF INCORPORATION]",
5453
+ registeredAddress: "[REGISTERED ADDRESS]",
5454
+ legalNoticeEmail: "[LEGAL NOTICE EMAIL]"
5455
+ };
5456
+ 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.";
5457
+ var VERSION = "2026-07-draft-2";
5458
+ var EFFECTIVE_AT = null;
5459
+ 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.`;
5460
+ var POLICY_DATE_LINES = `Published: 15 July 2026
5461
+
5462
+ Effective date: ${EFFECTIVE_AT ?? "[COUNSEL TO APPROVE EFFECTIVE DATE]"}`;
5463
+ var termsOfService = {
5464
+ type: "terms_of_service",
5465
+ title: "Terms of Service",
5466
+ slug: "terms",
5467
+ version: VERSION,
5468
+ summary: "The contract governing access to Taskmarket and participation in its task marketplace.",
5469
+ markdown: `# Taskmarket Terms of Service
5470
+
5471
+ Version ${VERSION}
5472
+
5473
+ ${POLICY_DATE_LINES}
5474
+
5475
+ ${DRAFT_NOTICE}
5476
+
5477
+ 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").
5478
+
5479
+ ## 1. Acceptance and authority
5480
+
5481
+ 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.
5482
+
5483
+ 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.
5484
+
5485
+ ## 2. Platform role and regulatory perimeter
5486
+
5487
+ 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.
5488
+
5489
+ 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.
5490
+
5491
+ 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.]
5492
+
5493
+ ## 3. Task records and participant contracts
5494
+
5495
+ 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.
5496
+
5497
+ 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.]
5498
+
5499
+ 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.
5500
+
5501
+ 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.
5502
+
5503
+ ## 4. Accounts, wallets, agents, and security
5504
+
5505
+ 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.
5506
+
5507
+ 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.
5508
+
5509
+ ## 5. Marketplace responsibilities and worker status
5510
+
5511
+ 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.
5512
+
5513
+ 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.
5514
+
5515
+ 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.]
5516
+
5517
+ 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.
5518
+
5519
+ ## 6. Funding, fees, settlement, and taxes
5520
+
5521
+ 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.
5522
+
5523
+ 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.
5524
+
5525
+ 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.]
5526
+
5527
+ 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.
5528
+
5529
+ ## 7. Protocol disputes and existing positions
5530
+
5531
+ 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.
5532
+
5533
+ 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.
5534
+
5535
+ ## 8. Intellectual property and submissions
5536
+
5537
+ 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.
5538
+
5539
+ 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.
5540
+
5541
+ 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.
5542
+
5543
+ 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.]
5544
+
5545
+ ## 9. Confidentiality and public blockchains
5546
+
5547
+ 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.
5548
+
5549
+ ## 10. Compliance, sanctions, and acceptable use
5550
+
5551
+ 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.
5552
+
5553
+ 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.
5554
+
5555
+ ## 11. Mandatory rights, complaints, suspension, and termination
5556
+
5557
+ 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.]
5558
+
5559
+ 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.
5560
+
5561
+ 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.
5562
+
5563
+ Sections that by their nature should survive will survive, including ownership, payment, risk allocation, liability, indemnity, records, disputes, and notices.
5564
+
5565
+ ## 12. Disclaimers
5566
+
5567
+ 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.
5568
+
5569
+ Nothing in these Terms excludes a warranty, guarantee, right, or remedy that cannot lawfully be excluded.
5570
+
5571
+ ## 13. Limitation of liability
5572
+
5573
+ 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.
5574
+
5575
+ 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.
5576
+
5577
+ ## 14. Indemnity
5578
+
5579
+ 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.
5580
+
5581
+ ## 15. Changes, electronic communications, and records
5582
+
5583
+ 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.
5584
+
5585
+ 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.
5586
+
5587
+ ## 16. Governing law and legal disputes
5588
+
5589
+ 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.]
5590
+
5591
+ ## 17. General
5592
+
5593
+ 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.
5594
+
5595
+ ## 18. Notices and contact
5596
+
5597
+ 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.
5598
+ `
5599
+ };
5600
+ var privacyPolicy = {
5601
+ type: "privacy_policy",
5602
+ title: "Privacy Policy",
5603
+ slug: "privacy",
5604
+ version: VERSION,
5605
+ summary: "How Taskmarket collects, uses, shares, retains, and protects personal information.",
5606
+ markdown: `# Taskmarket Privacy Policy
5607
+
5608
+ Version ${VERSION}
5609
+
5610
+ ${POLICY_DATE_LINES}
5611
+
5612
+ ${DRAFT_NOTICE}
5613
+
5614
+ 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.]
5615
+
5616
+ ## 1. Information we collect
5617
+
5618
+ We may collect:
5619
+
5620
+ - **Account and contact data:** Privy user identifier, email address, social-login details made available to us, wallet addresses, usernames, organization details, and support communications.
5621
+ - **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.
5622
+ - **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.
5623
+ - **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.
5624
+ - **Acceptance evidence:** policy versions and content hashes, acceptance method, timestamp, wallet signature or authenticated Privy session identifier, receipt hash, IP address, and user agent.
5625
+ - **Compliance data:** screening results, risk indicators, country or region inferred from technical data, and information reasonably needed to investigate abuse or meet legal obligations.
5626
+ - **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.
5627
+
5628
+ 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.
5629
+
5630
+ ## 2. Why we use information
5631
+
5632
+ 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.
5633
+
5634
+ 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.
5635
+
5636
+ ## 3. Public and immutable information
5637
+
5638
+ 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.
5639
+
5640
+ ## 4. How we disclose information
5641
+
5642
+ We may disclose information:
5643
+
5644
+ - to other marketplace participants and the public where a feature is public or disclosure is needed to perform a task;
5645
+ - to cloud, database, storage, authentication, wallet, RPC, blockchain, payment-facilitation, email, security, analytics, and support providers acting for us;
5646
+ - to professional advisers, auditors, insurers, investors, and transaction counterparties under appropriate duties;
5647
+ - to authorities or other parties when reasonably necessary to comply with law, enforce rights, protect safety or security, or investigate abuse; and
5648
+ - in connection with a merger, financing, reorganization, insolvency, or transfer of all or part of the business.
5649
+
5650
+ 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.]
5651
+
5652
+ ## 5. International transfers
5653
+
5654
+ 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.]
5655
+
5656
+ ## 6. Retention and deletion
5657
+
5658
+ 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.
5659
+
5660
+ [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.
5661
+
5662
+ ## 7. Security and incident response
5663
+
5664
+ 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.
5665
+
5666
+ 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.]
5667
+
5668
+ ## 8. Your choices and rights
5669
+
5670
+ 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.
5671
+
5672
+ 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.
5673
+
5674
+ ## 9. Cookies and tracking technologies
5675
+
5676
+ 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.]
5677
+
5678
+ ## 10. Automated systems
5679
+
5680
+ 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.
5681
+
5682
+ ## 11. Children
5683
+
5684
+ 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.
5685
+
5686
+ ## 12. Third-party services
5687
+
5688
+ 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.
5689
+
5690
+ ## 13. Accountability and privacy by design
5691
+
5692
+ 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.
5693
+
5694
+ ## 14. Changes
5695
+
5696
+ 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.
5697
+
5698
+ ## 15. Contact and region-specific disclosures
5699
+
5700
+ - Privacy questions and requests: ${LEGAL_ENTITY.legalNoticeEmail}
5701
+ - Postal address: ${LEGAL_ENTITY.registeredAddress}
5702
+ - Representative or data protection officer: [INSERT IF REQUIRED]
5703
+ - Relevant supervisory authority details: [INSERT AFTER JURISDICTION REVIEW]
5704
+ - Region-specific rights, collection notices, financial incentives, and appeals: [INSERT FOR EACH LAUNCH JURISDICTION]
5705
+ `
5706
+ };
5707
+ var riskDisclosure = {
5708
+ type: "risk_disclosure",
5709
+ title: "Risk Disclosure",
5710
+ slug: "risks",
5711
+ version: VERSION,
5712
+ summary: "Material technical, financial, marketplace, legal, and autonomous-agent risks.",
5713
+ markdown: `# Taskmarket Risk Disclosure
5714
+
5715
+ Version ${VERSION}
5716
+
5717
+ ${POLICY_DATE_LINES}
5718
+
5719
+ ${DRAFT_NOTICE}
5720
+
5721
+ 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.
5722
+
5723
+ ## 1. Smart-contract and protocol risk
5724
+
5725
+ 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.
5726
+
5727
+ ## 2. Irreversibility and loss
5728
+
5729
+ 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.
5730
+
5731
+ ## 3. Stablecoin, token, and market risk
5732
+
5733
+ 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.
5734
+
5735
+ ## 4. Wallet and credential risk
5736
+
5737
+ 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.
5738
+
5739
+ ## 5. Autonomous-agent risk
5740
+
5741
+ 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.
5742
+
5743
+ ## 6. Marketplace and counterparty risk
5744
+
5745
+ 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.
5746
+
5747
+ ## 7. Escrow and settlement risk
5748
+
5749
+ "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.
5750
+
5751
+ 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.
5752
+
5753
+ ## 8. Legal, regulatory, sanctions, and tax risk
5754
+
5755
+ 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.
5756
+
5757
+ ## 9. Data and confidentiality risk
5758
+
5759
+ 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.
5760
+
5761
+ ## 10. Availability and change risk
5762
+
5763
+ 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.
5764
+
5765
+ ## 11. No advice or guarantee
5766
+
5767
+ 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.
5768
+
5769
+ ## 12. Acknowledgement
5770
+
5771
+ 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.
5772
+ `
5773
+ };
5774
+ var acceptableUsePolicy = {
5775
+ type: "acceptable_use_policy",
5776
+ title: "Acceptable Use Policy",
5777
+ slug: "acceptable-use",
5778
+ version: VERSION,
5779
+ summary: "Rules protecting people, systems, markets, and the lawful operation of Taskmarket.",
5780
+ markdown: `# Taskmarket Acceptable Use Policy
5781
+
5782
+ Version ${VERSION}
5783
+
5784
+ ${POLICY_DATE_LINES}
5785
+
5786
+ ${DRAFT_NOTICE}
5787
+
5788
+ 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.
5789
+
5790
+ ## 1. Illegal and regulated activity
5791
+
5792
+ 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.
5793
+
5794
+ 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.
5795
+
5796
+ 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.
5797
+
5798
+ ## 2. Harm, exploitation, and dangerous services
5799
+
5800
+ 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.
5801
+
5802
+ ## 3. Cybersecurity abuse
5803
+
5804
+ 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.
5805
+
5806
+ ## 4. Privacy, surveillance, and identity
5807
+
5808
+ 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.
5809
+
5810
+ ## 5. Intellectual property and deceptive content
5811
+
5812
+ 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.
5813
+
5814
+ 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.]
5815
+
5816
+ ## 6. Market and platform integrity
5817
+
5818
+ 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.
5819
+
5820
+ 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.
5821
+
5822
+ ## 7. Resource and communications abuse
5823
+
5824
+ 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.
5825
+
5826
+ ## 8. Required safeguards
5827
+
5828
+ 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}.
5829
+
5830
+ ## 9. Enforcement, reporting, and appeals
5831
+
5832
+ 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.
5833
+
5834
+ You must cooperate with reasonable investigations and must not retaliate against a reporter. Evasion or attempted evasion is a separate violation.
5835
+
5836
+ 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.]
5837
+
5838
+ 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.]
5839
+ `
5840
+ };
5841
+ function buildWalletLegalAcceptanceMessage(input) {
5842
+ const documentLines = input.documents.map((document) => `- ${document.title} (${document.version}): ${document.contentHash}`).join("\n");
5843
+ return `Taskmarket legal acceptance
5844
+
5845
+ Wallet: ${input.walletAddress}
5846
+ Bundle: ${input.bundleVersion}
5847
+ Issued at: ${input.issuedAt}
5848
+ Expires at: ${input.expiresAt}
5849
+ Nonce: ${input.nonce}
5850
+
5851
+ Documents:
5852
+ ${documentLines}
5853
+
5854
+ ${LEGAL_ACCEPTANCE_STATEMENT}`;
5855
+ }
5856
+
5857
+ // src/commands/init.ts
5858
+ import { privateKeyToAccount as privateKeyToAccount3 } from "viem/accounts";
5859
+
5860
+ // src/lib/keystore.ts
5861
+ import { createCipheriv, createDecipheriv, randomBytes } from "crypto";
5862
+ import { promises as fs } from "fs";
5863
+ import os from "os";
5864
+ import path from "path";
5865
+ import { privateKeyToAccount } from "viem/accounts";
5866
+ function getKeystorePath() {
5867
+ return path.join(os.homedir(), ".taskmarket", "keystore.json");
5868
+ }
5869
+ function generateKeypair() {
5870
+ const keyBytes = randomBytes(32);
5871
+ const privateKey = "0x" + keyBytes.toString("hex");
5872
+ const account = privateKeyToAccount(privateKey);
5873
+ return { privateKey, address: account.address };
5874
+ }
5875
+ function encryptPrivateKey(deviceEncryptionKeyHex, privateKey) {
5876
+ const key = Buffer.from(deviceEncryptionKeyHex, "hex");
5877
+ const iv = randomBytes(12);
5878
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
5879
+ const plaintext = Buffer.from(privateKey, "utf8");
5880
+ const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
5881
+ const tag = cipher.getAuthTag();
5882
+ return Buffer.concat([iv, tag, encrypted]).toString("hex");
5883
+ }
5884
+ function decryptPrivateKey(deviceEncryptionKeyHex, encryptedHex) {
5885
+ const key = Buffer.from(deviceEncryptionKeyHex, "hex");
5886
+ const data = Buffer.from(encryptedHex, "hex");
5887
+ const iv = data.subarray(0, 12);
5888
+ const tag = data.subarray(12, 28);
5889
+ const ciphertext = data.subarray(28);
5890
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
5891
+ decipher.setAuthTag(tag);
5892
+ const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
5893
+ return decrypted.toString("utf8");
5894
+ }
5895
+ async function saveKeystore(keystore, keystorePath) {
5896
+ const p = keystorePath ?? getKeystorePath();
5897
+ await fs.mkdir(path.dirname(p), { recursive: true });
5898
+ await fs.writeFile(p, JSON.stringify(keystore, null, 2), "utf8");
5899
+ }
5900
+ async function loadKeystore(keystorePath) {
5901
+ const p = keystorePath ?? getKeystorePath();
5902
+ let data;
5903
+ try {
5904
+ data = await fs.readFile(p, "utf8");
5905
+ } catch {
5906
+ throw new Error(`Keystore not found at ${p}. Run 'taskmarket init' first.`);
5907
+ }
5908
+ return JSON.parse(data);
5909
+ }
5910
+ async function keystoreExists(keystorePath) {
5911
+ const p = keystorePath ?? getKeystorePath();
5912
+ try {
5913
+ await fs.access(p);
5914
+ return true;
5915
+ } catch {
5916
+ return false;
5917
+ }
5918
+ }
5919
+
5920
+ // src/lib/api.ts
5921
+ var API_URL = process.env.TASKMARKET_API_URL ?? "https://api.taskmarket.dev";
5922
+ var API_ORIGIN = new URL(API_URL).origin;
5923
+ function legalReceiptHeadersForKeystore(keystore, path3, method) {
5924
+ const canSend = keystore.legalAcceptanceApiOrigin === API_ORIGIN && (method === "POST" || path3 === "/api/legal/status");
5925
+ return canSend ? buildLegalReceiptHeaders(keystore.legalAcceptanceReceipt) : {};
5926
+ }
5927
+ async function legalReceiptHeaders(path3, method) {
5928
+ try {
5929
+ const keystore = await loadKeystore();
5930
+ return legalReceiptHeadersForKeystore(keystore, path3, method);
5931
+ } catch {
5932
+ return {};
5933
+ }
5934
+ }
5935
+ async function apiGet(path3, options) {
5936
+ const legalHeaders = await legalReceiptHeaders(path3, "GET");
5937
+ const res = await fetch(`${API_URL}${path3}`, {
5938
+ method: "GET",
5939
+ redirect: "error",
5940
+ headers: {
5941
+ "Content-Type": "application/json",
5942
+ ...legalHeaders,
5943
+ ...options?.headers ?? {}
5944
+ }
5945
+ });
5946
+ const body = await res.json();
5947
+ if (!res.ok) {
5948
+ throw new Error(`GET ${path3} failed (${res.status}): ${JSON.stringify(body)}`);
5949
+ }
5950
+ return body;
5951
+ }
5952
+ async function apiPost(path3, body) {
5953
+ const legalHeaders = await legalReceiptHeaders(path3, "POST");
5954
+ const res = await fetch(`${API_URL}${path3}`, {
5955
+ method: "POST",
5956
+ redirect: "error",
5957
+ headers: { "Content-Type": "application/json", ...legalHeaders },
5958
+ body: JSON.stringify(body)
5959
+ });
5960
+ const result = await res.json();
5961
+ if (!res.ok) {
5962
+ throw new Error(`POST ${path3} failed (${res.status}): ${JSON.stringify(result)}`);
5963
+ }
5964
+ return result;
5965
+ }
5966
+
5967
+ // src/lib/output.ts
5968
+ function printResult(data) {
5969
+ console.log(JSON.stringify({ ok: true, data }));
5970
+ }
5971
+ function printError(message) {
5972
+ process.stderr.write(JSON.stringify({ ok: false, error: message }) + "\n");
5973
+ process.exit(1);
5974
+ }
5975
+
5976
+ // src/lib/agent.ts
5977
+ async function pollAgentId(address, maxWaitMs = 6e4) {
5978
+ const interval = 3e3;
5979
+ const deadline = Date.now() + maxWaitMs;
5980
+ while (Date.now() < deadline) {
5981
+ await new Promise((r) => setTimeout(r, interval));
5982
+ try {
5983
+ const res = await fetch(`${API_URL}/api/identity/status?address=${address}`);
5984
+ if (res.ok) {
5985
+ const data = await res.json();
5986
+ if (data.agentId) return data.agentId;
5987
+ }
5988
+ } catch {
5989
+ }
5990
+ }
5991
+ return null;
5992
+ }
5993
+
5994
+ // src/lib/device-registration.ts
5995
+ async function registerDevice(input) {
5996
+ const response = await fetch(`${API_URL}/api/devices`, {
5997
+ body: JSON.stringify({
5998
+ publicKey: input.publicKey,
5999
+ signature: input.signature,
6000
+ walletAddress: input.walletAddress
6001
+ }),
6002
+ headers: {
6003
+ "Content-Type": "application/json",
6004
+ ...buildLegalReceiptHeaders(input.legalReceipt)
6005
+ },
6006
+ method: "POST",
6007
+ redirect: "error"
6008
+ });
6009
+ if (!response.ok) {
6010
+ const text = await response.text().catch(() => "");
6011
+ throw new Error(`Device registration failed (${response.status}): ${text}`);
6012
+ }
6013
+ return await response.json();
6014
+ }
6015
+
6016
+ // src/lib/encryption.ts
6017
+ import { createECDH, hkdfSync, createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes2 } from "crypto";
6018
+ var VERSION2 = 1;
6019
+ var EPH_PUB_LEN = 65;
6020
+ var IV_LEN = 12;
6021
+ var TAG_LEN = 16;
6022
+ var HEADER_LEN = 1 + EPH_PUB_LEN + IV_LEN + TAG_LEN;
6023
+ function ecdhSharedSecret(privateKeyHex, otherPubKeyHex) {
6024
+ const ecdh = createECDH("secp256k1");
6025
+ ecdh.setPrivateKey(Buffer.from(privateKeyHex.replace(/^0x/, ""), "hex"));
6026
+ const shared = ecdh.computeSecret(Buffer.from(otherPubKeyHex, "hex"));
6027
+ return shared;
6028
+ }
6029
+ function hkdfKey(sharedSecret) {
6030
+ return Buffer.from(hkdfSync("sha256", sharedSecret, Buffer.alloc(0), "taskmarket-ecies-v1", 32));
6031
+ }
6032
+ function aesGcmEncrypt(key, iv, plaintext) {
6033
+ const cipher = createCipheriv2("aes-256-gcm", key, iv);
6034
+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
6035
+ const tag = cipher.getAuthTag();
6036
+ return { ciphertext, tag };
6037
+ }
6038
+ function aesGcmDecrypt(key, iv, tag, ciphertext) {
6039
+ const decipher = createDecipheriv2("aes-256-gcm", key, iv);
6040
+ decipher.setAuthTag(tag);
6041
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
6042
+ }
6043
+ function derivePublicKey(privateKeyHex) {
6044
+ const ecdh = createECDH("secp256k1");
6045
+ ecdh.setPrivateKey(Buffer.from(privateKeyHex.replace(/^0x/, ""), "hex"));
6046
+ return ecdh.getPublicKey(void 0, "uncompressed").toString("hex");
6047
+ }
6048
+ function deriveCompressedPublicKey(privateKeyHex) {
6049
+ const ecdh = createECDH("secp256k1");
6050
+ ecdh.setPrivateKey(Buffer.from(privateKeyHex.replace(/^0x/, ""), "hex"));
6051
+ return ecdh.getPublicKey(void 0, "compressed").toString("hex");
6052
+ }
6053
+ function encryptForRecipient(fileBuffer, recipientPubKeyHex) {
6054
+ const ephEcdh = createECDH("secp256k1");
6055
+ ephEcdh.generateKeys();
6056
+ const ephPubKey = ephEcdh.getPublicKey(void 0, "uncompressed");
6057
+ const ephPrivKeyHex = ephEcdh.getPrivateKey("hex");
6058
+ const shared = ecdhSharedSecret(ephPrivKeyHex, recipientPubKeyHex);
6059
+ const aesKey = hkdfKey(shared);
6060
+ const iv = randomBytes2(IV_LEN);
6061
+ const { ciphertext, tag } = aesGcmEncrypt(aesKey, iv, fileBuffer);
6062
+ return Buffer.concat([Buffer.from([VERSION2]), ephPubKey, iv, tag, ciphertext]);
6063
+ }
6064
+ function decryptWithPrivateKey(fileBuffer, privateKeyHex) {
6065
+ if (fileBuffer.length < HEADER_LEN + 1) {
6066
+ throw new Error("Decryption failed: invalid key or corrupted file");
6067
+ }
6068
+ const version2 = fileBuffer[0];
6069
+ if (version2 !== VERSION2) {
6070
+ throw new Error(`Decryption failed: unsupported file version 0x${version2.toString(16)}`);
6071
+ }
6072
+ const ephPubKeyHex = fileBuffer.subarray(1, 1 + EPH_PUB_LEN).toString("hex");
6073
+ const iv = fileBuffer.subarray(1 + EPH_PUB_LEN, 1 + EPH_PUB_LEN + IV_LEN);
6074
+ const tag = fileBuffer.subarray(1 + EPH_PUB_LEN + IV_LEN, 1 + EPH_PUB_LEN + IV_LEN + TAG_LEN);
6075
+ const ciphertext = fileBuffer.subarray(1 + EPH_PUB_LEN + IV_LEN + TAG_LEN);
6076
+ const shared = ecdhSharedSecret(privateKeyHex, ephPubKeyHex);
6077
+ const aesKey = hkdfKey(shared);
6078
+ try {
6079
+ return aesGcmDecrypt(aesKey, iv, tag, ciphertext);
6080
+ } catch {
6081
+ throw new Error("Decryption failed: invalid key or corrupted file");
6082
+ }
6083
+ }
6084
+
6085
+ // src/commands/legal/index.ts
6086
+ import { Command } from "commander";
6087
+ import { createInterface } from "readline/promises";
6088
+
6089
+ // src/lib/signer.ts
6090
+ import { privateKeyToAccount as privateKeyToAccount2 } from "viem/accounts";
6091
+ import { toHex } from "viem";
6092
+ async function fetchDeviceKey(deviceId, apiToken, keyServerUrl) {
6093
+ const base = keyServerUrl ?? API_URL;
6094
+ const res = await fetch(`${base}/api/devices/${deviceId}/key`, {
6095
+ method: "POST",
6096
+ headers: { "Content-Type": "application/json" },
6097
+ body: JSON.stringify({ deviceId, apiToken })
6098
+ });
6099
+ if (!res.ok) {
6100
+ const text = await res.text().catch(() => "");
6101
+ throw new Error(`Failed to fetch device key (${res.status}): ${text}`);
6102
+ }
6103
+ const data = await res.json();
6104
+ return data.deviceEncryptionKey;
6105
+ }
6106
+ async function signTypedData(typedData, keystore) {
6107
+ const account = await createWalletAccountFromKeystore(keystore);
6108
+ const sig = await account.signTypedData(typedData);
6109
+ return sig;
6110
+ }
6111
+ async function signMessage(message, keystore) {
6112
+ const account = await createWalletAccountFromKeystore(keystore);
6113
+ const sig = await account.signMessage({ message });
6114
+ return sig;
6115
+ }
6116
+ async function createWalletAccountFromKeystore(keystore) {
6117
+ const dek = await fetchDeviceKey(keystore.deviceId, keystore.apiToken, keystore.keyServerUrl);
6118
+ const privateKey = decryptPrivateKey(dek, keystore.encryptedKey);
6119
+ return privateKeyToAccount2(privateKey);
6120
+ }
6121
+ async function getWalletAddress() {
6122
+ const keystore = await loadKeystore();
6123
+ return keystore.walletAddress;
6124
+ }
6125
+ async function createTransferAuthorization(accept, keystore) {
6126
+ const now = Math.floor(Date.now() / 1e3);
6127
+ const authorization = {
6128
+ from: keystore.walletAddress,
6129
+ to: accept.payTo,
6130
+ value: accept.amount,
6131
+ validAfter: String(now - 60),
6132
+ validBefore: String(now + accept.maxTimeoutSeconds),
6133
+ nonce: toHex(crypto.getRandomValues(new Uint8Array(32)))
6134
+ };
6135
+ const signature = await signTypedData(
6136
+ {
6137
+ domain: accept.extra.eip712.domain,
6138
+ types: accept.extra.eip712.types,
6139
+ primaryType: accept.extra.eip712.primaryType,
6140
+ message: authorization
6141
+ },
6142
+ keystore
6143
+ );
6144
+ return { authorization, signature };
6145
+ }
6146
+
6147
+ // src/commands/legal/index.ts
6148
+ var affirmations = {
6149
+ acknowledgedRisk: true,
6150
+ agreedToAcceptableUse: true,
6151
+ agreedToTerms: true,
6152
+ receivedPrivacyNotice: true
6153
+ };
6154
+ async function confirmAcceptance(bundle, assumeYes) {
6155
+ const documentList = bundle.documents.map(
6156
+ (document) => `- ${document.title} (${document.version})
6157
+ ${document.url}
6158
+ ${document.contentHash}`
6159
+ ).join("\n");
6160
+ process.stderr.write(
6161
+ `
6162
+ Review the Taskmarket legal bundle before accepting:
6163
+ ${documentList}
6164
+
6165
+ ${bundle.acceptanceStatement}
6166
+
6167
+ `
6168
+ );
6169
+ if (assumeYes) return;
6170
+ if (!process.stdin.isTTY) {
6171
+ throw new Error("Interactive confirmation is unavailable. Re-run with --yes after review.");
6172
+ }
6173
+ const prompt = createInterface({ input: process.stdin, output: process.stderr });
6174
+ try {
6175
+ const answer = await prompt.question("Type I AGREE to sign this acceptance: ");
6176
+ if (answer.trim() !== "I AGREE") {
6177
+ throw new Error("Legal acceptance was not confirmed");
6178
+ }
6179
+ } finally {
6180
+ prompt.close();
6181
+ }
6182
+ }
6183
+ function bundleEvidence(bundle) {
6184
+ return JSON.stringify({
6185
+ acceptanceStatement: bundle.acceptanceStatement,
6186
+ bundleDigest: bundle.bundleDigest,
6187
+ documents: bundle.documents.map(({ contentHash, title, type, version: version2 }) => ({
6188
+ contentHash,
6189
+ title,
6190
+ type,
6191
+ version: version2
6192
+ })),
6193
+ version: bundle.version
6194
+ });
6195
+ }
6196
+ function validateLegalChallenge(reviewedBundle, challenge, expectedWalletAddress) {
6197
+ if (challenge.bundle.version !== reviewedBundle.version || bundleEvidence(challenge.bundle) !== bundleEvidence(reviewedBundle)) {
6198
+ throw new Error("The legal bundle changed while acceptance was in progress. Review it again.");
6199
+ }
6200
+ if (challenge.walletAddress.toLowerCase() !== expectedWalletAddress.toLowerCase()) {
6201
+ throw new Error("The legal acceptance challenge is for a different wallet.");
6202
+ }
6203
+ const expectedMessage = buildWalletLegalAcceptanceMessage({
6204
+ bundleVersion: challenge.bundle.version,
6205
+ documents: challenge.bundle.documents,
6206
+ expiresAt: challenge.expiresAt,
6207
+ issuedAt: challenge.issuedAt,
6208
+ nonce: challenge.nonce,
6209
+ walletAddress: challenge.walletAddress
6210
+ });
6211
+ if (challenge.message !== expectedMessage) {
6212
+ throw new Error("The legal acceptance challenge does not match the reviewed bundle.");
6213
+ }
6214
+ }
6215
+ async function acceptLegalBundle(options) {
6216
+ const bundle = LegalBundleSchema.parse(options.bundle ?? await apiGet("/api/legal/current"));
6217
+ if (!bundle.acceptanceAvailable) {
6218
+ throw new Error("The current legal bundle is a counsel-review draft and cannot be accepted.");
6219
+ }
6220
+ await confirmAcceptance(bundle, options.assumeYes);
6221
+ const challenge = LegalChallengeResponseSchema.parse(
6222
+ await apiPost("/api/legal/challenge", {
6223
+ walletAddress: options.walletAddress
6224
+ })
6225
+ );
6226
+ validateLegalChallenge(bundle, challenge, options.walletAddress);
6227
+ const signature = await options.signMessage(challenge.message);
6228
+ const result = LegalAcceptanceResponseSchema.parse(
6229
+ await apiPost("/api/legal/accept/wallet", {
6230
+ ...affirmations,
6231
+ bundleDigest: bundle.bundleDigest,
6232
+ bundleVersion: bundle.version,
6233
+ nonce: challenge.nonce,
6234
+ signature,
6235
+ walletAddress: options.walletAddress
6236
+ })
6237
+ );
6238
+ if (result.bundleDigest !== bundle.bundleDigest || result.bundleVersion !== bundle.version) {
6239
+ throw new Error("The server returned a receipt for a different legal bundle.");
6240
+ }
6241
+ return result;
6242
+ }
6243
+ var statusCommand = new Command("status").description("Show whether this CLI has accepted the current legal bundle").action(async () => {
6244
+ const keystore = await loadKeystore();
6245
+ const status = LegalStatusResponseSchema.parse(await apiGet("/api/legal/status"));
6246
+ if (status.receipt) {
6247
+ await saveKeystore({
6248
+ ...keystore,
6249
+ legalAcceptanceApiOrigin: API_ORIGIN,
6250
+ legalAcceptanceBundleVersion: status.bundle.version,
6251
+ legalAcceptanceReceipt: status.receipt
6252
+ });
6253
+ }
6254
+ printResult({
6255
+ accepted: status.accepted,
6256
+ bundleDigest: status.bundle.bundleDigest,
6257
+ bundleVersion: status.bundle.version,
6258
+ enforcementEnabled: status.bundle.enforcementEnabled,
6259
+ status: status.bundle.status,
6260
+ documents: status.bundle.documents.map(({ title, url, version: version2 }) => ({
6261
+ title,
6262
+ url,
6263
+ version: version2
6264
+ }))
6265
+ });
6266
+ });
6267
+ var acceptCommand = new Command("accept").description("Review and sign the current Taskmarket legal bundle").option(
6268
+ "--yes",
6269
+ "Confirm acceptance non-interactively after the operator has reviewed every policy"
6270
+ ).action(async (options) => {
6271
+ const keystore = await loadKeystore();
6272
+ const result = await acceptLegalBundle({
6273
+ assumeYes: Boolean(options.yes),
6274
+ signMessage: (message) => signMessage(message, keystore),
6275
+ walletAddress: keystore.walletAddress
6276
+ });
6277
+ await saveKeystore({
6278
+ ...keystore,
6279
+ legalAcceptanceApiOrigin: API_ORIGIN,
6280
+ legalAcceptanceBundleVersion: result.bundleVersion,
6281
+ legalAcceptanceReceipt: result.receipt
6282
+ });
6283
+ printResult({
6284
+ accepted: true,
6285
+ acceptedAt: result.acceptedAt,
6286
+ bundleDigest: result.bundleDigest,
6287
+ bundleVersion: result.bundleVersion,
6288
+ walletAddress: keystore.walletAddress
6289
+ });
6290
+ });
6291
+ var legalCommand = new Command("legal").description(
6292
+ "Review and manage versioned Taskmarket legal acceptance"
6293
+ );
6294
+ legalCommand.addCommand(statusCommand);
6295
+ legalCommand.addCommand(acceptCommand);
6296
+
6297
+ // src/commands/init.ts
6298
+ function sanitizeEmailUsername(agentId, suffix) {
6299
+ const maxBase = 30 - 1 - suffix.length;
6300
+ if (maxBase < 2) return null;
6301
+ const base = agentId.toLowerCase().replace(/[^a-z0-9]/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "").slice(0, maxBase).replace(/-+$/, "");
6302
+ if (base.length < 2) return null;
6303
+ const candidate = `${base}-${suffix}`;
6304
+ return /^[a-z0-9][a-z0-9-]{1,28}[a-z0-9]$/.test(candidate) ? candidate : null;
6305
+ }
6306
+ async function tryRegisterEmail(deviceId, apiToken, username, explicit) {
6307
+ try {
6308
+ const reg = await apiPost("/api/emails/register", {
6309
+ deviceId,
6310
+ apiToken,
6311
+ username
6312
+ });
6313
+ return reg.emailAddress;
6314
+ } catch (err) {
6315
+ if (explicit) {
6316
+ const msg = err instanceof Error ? err.message : String(err);
6317
+ process.stderr.write(
6318
+ JSON.stringify({
6319
+ ok: false,
6320
+ error: `Email registration failed: ${msg}. Run: taskmarket email register --username ${username}`
6321
+ }) + "\n"
6322
+ );
6323
+ }
6324
+ return null;
6325
+ }
6326
+ }
6327
+ var initCommand = new Command2("init").description("Create and register a new agent wallet (safe to re-run)").option(
6328
+ "--email <username>",
6329
+ "Claim a custom email username (default: auto-generated from agent ID)"
6330
+ ).option(
6331
+ "--yes",
6332
+ "Confirm legal acceptance non-interactively after reviewing every current policy"
6333
+ ).action(async (opts) => {
6334
+ if (opts.email) {
6335
+ const check = await apiGet(
6336
+ `/api/emails/check-username?username=${encodeURIComponent(opts.email)}`
6337
+ );
6338
+ if (!check.available) {
6339
+ printError(`Email username "${opts.email}" is not available.`);
6340
+ }
6341
+ }
6342
+ if (await keystoreExists()) {
6343
+ const keystore = await loadKeystore();
6344
+ let agentId2 = keystore.agentId;
6345
+ if (!agentId2) {
6346
+ agentId2 = await pollAgentId(keystore.walletAddress);
6347
+ if (agentId2) {
6348
+ await saveKeystore({ ...keystore, agentId: agentId2 });
6349
+ }
6350
+ }
6351
+ let networkInfo2;
6352
+ try {
6353
+ const response = await apiGet("/trpc/network.info");
6354
+ networkInfo2 = response.result.data;
6355
+ } catch {
6356
+ }
6357
+ let emailAddress2 = null;
6358
+ try {
6359
+ const existing = await apiGet(`/api/agents/stats?address=${keystore.walletAddress}`);
6360
+ emailAddress2 = existing.emailAddress ?? null;
6361
+ } catch {
6362
+ }
6363
+ if (!emailAddress2) {
6364
+ const username2 = opts.email ?? (agentId2 && networkInfo2 ? sanitizeEmailUsername(agentId2, String(networkInfo2.chainId)) : null);
6365
+ if (username2) {
6366
+ emailAddress2 = await tryRegisterEmail(
6367
+ keystore.deviceId,
6368
+ keystore.apiToken,
6369
+ username2,
6370
+ !!opts.email
6371
+ );
6372
+ }
6373
+ }
6374
+ printResult({
6375
+ address: keystore.walletAddress,
6376
+ agentId: agentId2,
6377
+ network: networkInfo2?.networkName,
6378
+ chainId: networkInfo2?.chainId,
6379
+ emailAddress: emailAddress2
6380
+ });
6381
+ return;
6382
+ }
6383
+ const { privateKey, address } = generateKeypair();
6384
+ const publicKey = deriveCompressedPublicKey(privateKey);
6385
+ const legalBundle = LegalBundleSchema.parse(await apiGet("/api/legal/current"));
6386
+ const legalAcceptance = legalBundle.enforcementEnabled ? await acceptLegalBundle({
6387
+ assumeYes: Boolean(opts.yes),
6388
+ bundle: legalBundle,
6389
+ signMessage: (message) => privateKeyToAccount3(privateKey).signMessage({ message }),
6390
+ walletAddress: address
6391
+ }) : void 0;
6392
+ const deviceRegisterSignature = await privateKeyToAccount3(
6393
+ privateKey
6394
+ ).signMessage({ message: buildDeviceRegisterMessage(address) });
6395
+ const {
6396
+ deviceId,
6397
+ apiToken,
6398
+ deviceEncryptionKey,
6399
+ agentId: initialAgentId
6400
+ } = await registerDevice({
6401
+ legalReceipt: legalAcceptance?.receipt,
6402
+ publicKey,
6403
+ signature: deviceRegisterSignature,
6404
+ walletAddress: address
6405
+ });
6406
+ const encryptedKey = encryptPrivateKey(deviceEncryptionKey, privateKey);
6407
+ let agentId = initialAgentId;
6408
+ await saveKeystore({
6409
+ encryptedKey,
6410
+ walletAddress: address,
6411
+ deviceId,
6412
+ apiToken,
6413
+ agentId,
6414
+ keyServerUrl: API_URL,
6415
+ ...legalAcceptance ? {
6416
+ legalAcceptanceApiOrigin: API_ORIGIN,
6417
+ legalAcceptanceBundleVersion: legalAcceptance.bundleVersion,
6418
+ legalAcceptanceReceipt: legalAcceptance.receipt
6419
+ } : {}
6420
+ });
6421
+ if (!agentId) {
6422
+ agentId = await pollAgentId(address);
6423
+ if (agentId) {
6424
+ const keystore = await loadKeystore();
6425
+ await saveKeystore({ ...keystore, agentId });
6426
+ }
6427
+ }
6428
+ let networkInfo;
6429
+ try {
6430
+ const response = await apiGet("/trpc/network.info");
6431
+ networkInfo = response.result.data;
6432
+ } catch {
6433
+ }
6434
+ const username = opts.email ?? (agentId && networkInfo ? sanitizeEmailUsername(agentId, String(networkInfo.chainId)) : null);
6435
+ const emailAddress = username ? await tryRegisterEmail(deviceId, apiToken, username, !!opts.email) : null;
6436
+ printResult({
6437
+ address,
6438
+ agentId,
6439
+ network: networkInfo?.networkName,
6440
+ chainId: networkInfo?.chainId,
6441
+ emailAddress
6442
+ });
6443
+ });
5619
6444
 
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
- }
6445
+ // src/commands/address.ts
6446
+ import { Command as Command3 } from "commander";
6447
+ var addressCommand = new Command3("address").description("Print the wallet address").action(async () => {
6448
+ const keystore = await loadKeystore();
6449
+ printResult({ address: keystore.walletAddress });
6450
+ });
5642
6451
 
5643
- // ../../packages/shared/dist/lib/authMessages.js
5644
- function buildSelectWorkerMessage(taskId, pitchId, workerAddress) {
5645
- return `taskmarket:select-worker:${taskId}:${pitchId}:${workerAddress.toLowerCase()}`;
6452
+ // src/commands/identity.ts
6453
+ import { Command as Command4 } from "commander";
6454
+
6455
+ // src/lib/x402.ts
6456
+ async function x402Post(path3, body) {
6457
+ const url = `${API_URL}${path3}`;
6458
+ const keystore = await loadKeystore();
6459
+ const legalHeaders = legalReceiptHeadersForKeystore(keystore, path3, "POST");
6460
+ const r1 = await fetch(url, {
6461
+ method: "POST",
6462
+ redirect: "error",
6463
+ headers: { "Content-Type": "application/json", ...legalHeaders },
6464
+ body: JSON.stringify(body)
6465
+ });
6466
+ if (r1.status !== 402) {
6467
+ if (r1.ok) {
6468
+ return r1.json();
6469
+ }
6470
+ const text = await r1.text().catch(() => "");
6471
+ throw new Error(`POST ${path3} failed (${r1.status}): ${text}`);
6472
+ }
6473
+ const requirements = await r1.json();
6474
+ if (!requirements.accepts || requirements.accepts.length === 0) {
6475
+ throw new Error("No payment methods accepted by server");
6476
+ }
6477
+ const accept = requirements.accepts[0];
6478
+ const { authorization, signature } = await createTransferAuthorization(accept, keystore);
6479
+ const paymentPayload = {
6480
+ x402Version: 2,
6481
+ resource: requirements.resource,
6482
+ accepted: {
6483
+ scheme: accept.scheme,
6484
+ network: accept.network,
6485
+ amount: accept.amount,
6486
+ asset: accept.asset,
6487
+ payTo: accept.payTo,
6488
+ maxTimeoutSeconds: accept.maxTimeoutSeconds,
6489
+ extra: accept.extra
6490
+ },
6491
+ payload: { authorization, signature }
6492
+ };
6493
+ const r2 = await fetch(url, {
6494
+ method: "POST",
6495
+ redirect: "error",
6496
+ headers: {
6497
+ "Content-Type": "application/json",
6498
+ ...legalHeaders,
6499
+ "PAYMENT-SIGNATURE": Buffer.from(JSON.stringify(paymentPayload)).toString("base64")
6500
+ },
6501
+ body: JSON.stringify(body)
6502
+ });
6503
+ const result = await r2.json();
6504
+ if (!r2.ok) {
6505
+ throw new Error(`POST ${path3} failed after payment (${r2.status}): ${JSON.stringify(result)}`);
6506
+ }
6507
+ return result;
5646
6508
  }
5647
6509
 
6510
+ // src/commands/identity.ts
6511
+ var identityCommand = new Command4("identity").description("Manage agent identity");
6512
+ identityCommand.command("register").description("Register ERC-8004 agent identity (costs 0.001 USDC)").action(async () => {
6513
+ const result = await x402Post("/api/identity/register", {});
6514
+ printResult({ agentId: result.agentId });
6515
+ });
6516
+ identityCommand.command("status").description("Check identity registration status").action(async () => {
6517
+ const keystore = await loadKeystore();
6518
+ const result = await apiGet(`/api/identity/status?address=${keystore.walletAddress}`);
6519
+ printResult({ registered: result.registered, agentId: result.agentId });
6520
+ });
6521
+
5648
6522
  // 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) => {
6523
+ import { Command as Command5 } from "commander";
6524
+ 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
6525
  let address = opts.address;
5651
6526
  if (!address) {
5652
6527
  const keystore = await loadKeystore();
@@ -5692,10 +6567,10 @@ var statsCommand = new Command4("stats").description("View agent statistics").op
5692
6567
  });
5693
6568
 
5694
6569
  // src/commands/task/index.ts
5695
- import { Command as Command35 } from "commander";
6570
+ import { Command as Command36 } from "commander";
5696
6571
 
5697
6572
  // src/commands/task/create.ts
5698
- import { Command as Command5 } from "commander";
6573
+ import { Command as Command6 } from "commander";
5699
6574
 
5700
6575
  // src/lib/usdc.ts
5701
6576
  var USDC_BASE_UNITS = 10n ** BigInt(USDC_DECIMALS);
@@ -5718,7 +6593,11 @@ function usdcToBaseUnits(value, options = {}) {
5718
6593
  }
5719
6594
 
5720
6595
  // 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(
6596
+ 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(
6597
+ "--task-visibility <mode>",
6598
+ "Task visibility: public (default) or unlisted. Unlisted only hides a task from Taskmarket's own listings/search/SEO -- it stays permanently visible on the public blockchain to anyone with the link, reading the contract directly, or running their own indexer. Not a privacy feature.",
6599
+ "public"
6600
+ ).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
6601
  "--auction-type <type>",
5723
6602
  "Auction subtype: dutch, english, reverse_dutch, reverse_english (required for auction mode)"
5724
6603
  ).option(
@@ -5744,6 +6623,9 @@ var createCmd = new Command5("create").description("Create a new task (costs rew
5744
6623
  if (!Number.isFinite(duration) || duration <= 0) {
5745
6624
  return void printError("--duration must be a positive number of hours");
5746
6625
  }
6626
+ if (opts.taskVisibility !== "public" && opts.taskVisibility !== "unlisted") {
6627
+ return void printError("--task-visibility must be one of: public, unlisted");
6628
+ }
5747
6629
  if (opts.mode === "auction") {
5748
6630
  if (!opts.maxPrice) {
5749
6631
  return void printError("--max-price is required for auction mode");
@@ -5787,6 +6669,7 @@ var createCmd = new Command5("create").description("Create a new task (costs rew
5787
6669
  reward: rewardBaseUnits,
5788
6670
  duration,
5789
6671
  mode: opts.mode,
6672
+ taskVisibility: opts.taskVisibility,
5790
6673
  tags,
5791
6674
  stakeRequired: false,
5792
6675
  stakeBps: 0
@@ -5872,8 +6755,8 @@ var createCmd = new Command5("create").description("Create a new task (costs rew
5872
6755
  );
5873
6756
 
5874
6757
  // 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(
6758
+ import { Command as Command7 } from "commander";
6759
+ 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
6760
  "--auction-type <type>",
5878
6761
  "Filter auction tasks by subtype (dutch, english, reverse_dutch, reverse_english)"
5879
6762
  ).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 +6780,8 @@ var listCmd = new Command6("list").alias("search").description("List available t
5897
6780
  );
5898
6781
 
5899
6782
  // 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) => {
6783
+ import { Command as Command8 } from "commander";
6784
+ var getCmd = new Command8("get").description("Get task details").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
5902
6785
  const task = await apiGet(`/api/tasks/${taskId}`);
5903
6786
  if (!task) {
5904
6787
  printError(`Task not found: ${taskId}`);
@@ -5907,7 +6790,7 @@ var getCmd = new Command7("get").description("Get task details").argument("<task
5907
6790
  });
5908
6791
 
5909
6792
  // src/commands/task/submit.ts
5910
- import { Command as Command8, Option } from "commander";
6793
+ import { Command as Command9, Option } from "commander";
5911
6794
  import { promises as fsPromises } from "fs";
5912
6795
  import { basename, extname } from "path";
5913
6796
  import { createHash } from "crypto";
@@ -5996,7 +6879,7 @@ function streamingPut(uploadUrl, data, mimeType, label) {
5996
6879
  stream.pipe(req);
5997
6880
  });
5998
6881
  }
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(
6882
+ 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
6883
  new Option("--role <role>", "Artifact role applied to all files").choices(["preview", "source", "final", "attachment"]).default("attachment")
6001
6884
  ).action(async (taskId, opts) => {
6002
6885
  try {
@@ -6004,7 +6887,7 @@ var submitCmd = new Command8("submit").description("Submit work for a task").arg
6004
6887
  printError("--file is required");
6005
6888
  }
6006
6889
  const keystore = await loadKeystore();
6007
- const signature = await signMessage(`taskmarket:submit:${taskId}`, keystore);
6890
+ const signature = await signMessage(buildSubmitMessage(taskId), keystore);
6008
6891
  const artifactInputs = await Promise.all(
6009
6892
  opts.file.map(async (filePath) => {
6010
6893
  const mimeType = mimeTypeForPath(filePath);
@@ -6053,8 +6936,8 @@ var submitCmd = new Command8("submit").description("Submit work for a task").arg
6053
6936
  });
6054
6937
 
6055
6938
  // 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) => {
6939
+ import { Command as Command10 } from "commander";
6940
+ 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
6941
  const task = await apiGet(`/api/tasks/${taskId}`);
6059
6942
  if (!task) {
6060
6943
  printError("Task not found");
@@ -6085,7 +6968,7 @@ var acceptCmd = new Command9("accept").description("Accept a submission (costs 0
6085
6968
  });
6086
6969
 
6087
6970
  // src/commands/task/accept-submissions.ts
6088
- import { Command as Command10 } from "commander";
6971
+ import { Command as Command11 } from "commander";
6089
6972
  function parseWinner(spec) {
6090
6973
  const parts = spec.split(":");
6091
6974
  if (parts.length < 2 || parts.length > 3) {
@@ -6104,7 +6987,7 @@ function parseWinner(spec) {
6104
6987
  const submissionId = submissionIdStr ? submissionIdStr : void 0;
6105
6988
  return { worker, share, ...submissionId !== void 0 && { submissionId } };
6106
6989
  }
6107
- var acceptSubmissionsCmd = new Command10("accept-submissions").description(
6990
+ var acceptSubmissionsCmd = new Command11("accept-submissions").description(
6108
6991
  "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
6992
  ).argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption(
6110
6993
  "--winner <spec...>",
@@ -6127,8 +7010,8 @@ var acceptSubmissionsCmd = new Command10("accept-submissions").description(
6127
7010
  });
6128
7011
 
6129
7012
  // 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) => {
7013
+ import { Command as Command12 } from "commander";
7014
+ 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
7015
  const rating = parseInt(opts.rating, 10);
6133
7016
  if (rating < 0 || rating > 100) {
6134
7017
  printError("Rating must be between 0 and 100");
@@ -6143,10 +7026,10 @@ var rateCmd = new Command11("rate").description("Rate a worker (costs 0.001 USDC
6143
7026
  });
6144
7027
 
6145
7028
  // 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) => {
7029
+ import { Command as Command13 } from "commander";
7030
+ var claimCmd = new Command13("claim").description("Claim a task as a worker").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6148
7031
  const keystore = await loadKeystore();
6149
- const message = `taskmarket:claim:${taskId}`;
7032
+ const message = buildClaimMessage(taskId);
6150
7033
  const signature = await signMessage(message, keystore);
6151
7034
  const result = await apiPost(`/api/tasks/${taskId}/claim`, {
6152
7035
  workerAddress: keystore.walletAddress,
@@ -6156,8 +7039,8 @@ var claimCmd = new Command12("claim").description("Claim a task as a worker").ar
6156
7039
  });
6157
7040
 
6158
7041
  // 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) => {
7042
+ import { Command as Command14 } from "commander";
7043
+ 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
7044
  const keystore = await loadKeystore();
6162
7045
  const signature = await signMessage(`taskmarket:pitch:${taskId}`, keystore);
6163
7046
  const result = await x402Post(`/api/tasks/${taskId}/pitches`, {
@@ -6171,8 +7054,8 @@ var pitchCmd = new Command13("pitch").description("Submit a pitch for a task (co
6171
7054
  });
6172
7055
 
6173
7056
  // 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) => {
7057
+ import { Command as Command15 } from "commander";
7058
+ var pitchesCmd = new Command15("pitches").description("List pitches for a task").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6176
7059
  try {
6177
7060
  printResult(await apiGet(`/api/tasks/${taskId}/pitches`));
6178
7061
  } catch (err) {
@@ -6181,8 +7064,8 @@ var pitchesCmd = new Command14("pitches").description("List pitches for a task")
6181
7064
  });
6182
7065
 
6183
7066
  // 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) => {
7067
+ import { Command as Command16 } from "commander";
7068
+ 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
7069
  const keystore = await loadKeystore();
6187
7070
  const message = buildSelectWorkerMessage(taskId, opts.pitch, opts.worker);
6188
7071
  const signature = await signMessage(message, keystore);
@@ -6196,8 +7079,8 @@ var selectWorkerCmd = new Command15("select-worker").description("Select a worke
6196
7079
  });
6197
7080
 
6198
7081
  // 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) => {
7082
+ import { Command as Command17 } from "commander";
7083
+ 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
7084
  const keystore = await loadKeystore();
6202
7085
  const signature = await signMessage(`taskmarket:proof:${taskId}`, keystore);
6203
7086
  const result = await x402Post(`/api/tasks/${taskId}/proofs`, {
@@ -6212,8 +7095,8 @@ var proofCmd = new Command16("proof").description("Submit a benchmark proof (cos
6212
7095
  });
6213
7096
 
6214
7097
  // 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) => {
7098
+ import { Command as Command18 } from "commander";
7099
+ var proofsCmd = new Command18("proofs").description("List proofs for a benchmark task").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6217
7100
  try {
6218
7101
  printResult(await apiGet(`/api/tasks/${taskId}/proofs`));
6219
7102
  } catch (err) {
@@ -6222,8 +7105,8 @@ var proofsCmd = new Command17("proofs").description("List proofs for a benchmark
6222
7105
  });
6223
7106
 
6224
7107
  // 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) => {
7108
+ import { Command as Command19 } from "commander";
7109
+ 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
7110
  let priceBaseUnits;
6228
7111
  try {
6229
7112
  priceBaseUnits = usdcToBaseUnits(opts.price);
@@ -6240,8 +7123,8 @@ var bidCmd = new Command18("bid").description("Submit a bid on an auction task")
6240
7123
  });
6241
7124
 
6242
7125
  // 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(
7126
+ import { Command as Command20 } from "commander";
7127
+ 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
7128
  "--min-price <usdc>",
6246
7129
  "Reject if current clock price is below this value (price floor guard)"
6247
7130
  ).action(async (taskId, opts) => {
@@ -6264,8 +7147,8 @@ var auctionAcceptCmd = new Command19("auction-accept").description("Accept curre
6264
7147
  });
6265
7148
 
6266
7149
  // 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) => {
7150
+ import { Command as Command21 } from "commander";
7151
+ var submissionsCmd = new Command21("submissions").description("List submissions for a task").argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6269
7152
  let subs;
6270
7153
  try {
6271
7154
  subs = await apiGet(`/api/tasks/${taskId}/submissions`);
@@ -6277,8 +7160,8 @@ var submissionsCmd = new Command20("submissions").description("List submissions
6277
7160
  });
6278
7161
 
6279
7162
  // 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) => {
7163
+ import { Command as Command22 } from "commander";
7164
+ 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
7165
  let result;
6283
7166
  try {
6284
7167
  result = await apiPost(`/api/tasks/${taskId}/bids/select-winner`, {
@@ -6292,9 +7175,9 @@ var selectWinnerCmd = new Command21("select-winner").description("Permissionless
6292
7175
  });
6293
7176
 
6294
7177
  // src/commands/task/download.ts
6295
- import { Command as Command22 } from "commander";
7178
+ import { Command as Command23 } from "commander";
6296
7179
  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(
7180
+ 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
7181
  async (taskId, opts) => {
6299
7182
  const keystore = await loadKeystore();
6300
7183
  let presignedUrl;
@@ -6332,15 +7215,15 @@ var downloadCmd = new Command22("download").description("Download a submission f
6332
7215
  );
6333
7216
 
6334
7217
  // 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) => {
7218
+ import { Command as Command24 } from "commander";
7219
+ 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
7220
  const result = await x402Post(`/api/tasks/${taskId}/cancel`, { taskId });
6338
7221
  printResult(result);
6339
7222
  });
6340
7223
 
6341
7224
  // src/commands/task/refund-expired.ts
6342
- import { Command as Command24 } from "commander";
6343
- var refundExpiredCmd = new Command24("refund-expired").description(
7225
+ import { Command as Command25 } from "commander";
7226
+ var refundExpiredCmd = new Command25("refund-expired").description(
6344
7227
  "Refund an expired task with no submissions back to the requester (costs 0.001 USDC)"
6345
7228
  ).argument("<taskId>", "Task ID (0x-prefixed hex)").action(async (taskId) => {
6346
7229
  try {
@@ -6353,8 +7236,8 @@ var refundExpiredCmd = new Command24("refund-expired").description(
6353
7236
  });
6354
7237
 
6355
7238
  // src/commands/task/reject-submission.ts
6356
- import { Command as Command25 } from "commander";
6357
- var rejectSubmissionCmd = new Command25("reject-submission").description(
7239
+ import { Command as Command26 } from "commander";
7240
+ var rejectSubmissionCmd = new Command26("reject-submission").description(
6358
7241
  "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
7242
  ).argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--worker <address>", "Worker address whose submission to reject").action(async (taskId, opts) => {
6360
7243
  try {
@@ -6370,7 +7253,7 @@ var rejectSubmissionCmd = new Command25("reject-submission").description(
6370
7253
  });
6371
7254
 
6372
7255
  // src/commands/task/reject-all-submissions.ts
6373
- import { Command as Command26 } from "commander";
7256
+ import { Command as Command27 } from "commander";
6374
7257
  function activeSubmissionWorkers(submissions) {
6375
7258
  const workers = /* @__PURE__ */ new Map();
6376
7259
  for (const submission of submissions) {
@@ -6380,7 +7263,7 @@ function activeSubmissionWorkers(submissions) {
6380
7263
  }
6381
7264
  return [...workers.values()];
6382
7265
  }
6383
- var rejectAllSubmissionsCmd = new Command26("reject-all-submissions").description(
7266
+ var rejectAllSubmissionsCmd = new Command27("reject-all-submissions").description(
6384
7267
  "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
7268
  ).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
7269
  let submissions;
@@ -6428,8 +7311,8 @@ var rejectAllSubmissionsCmd = new Command26("reject-all-submissions").descriptio
6428
7311
  });
6429
7312
 
6430
7313
  // 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) => {
7314
+ import { Command as Command28 } from "commander";
7315
+ 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
7316
  try {
6434
7317
  let address = opts.address;
6435
7318
  if (!address) {
@@ -6447,8 +7330,8 @@ var mySubmissionsCmd = new Command27("my-submissions").description("List all sub
6447
7330
  });
6448
7331
 
6449
7332
  // 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(
7333
+ import { Command as Command29 } from "commander";
7334
+ 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
7335
  async (taskId, opts) => {
6453
7336
  const body = { taskId };
6454
7337
  if (opts.reward !== void 0) {
@@ -6531,11 +7414,11 @@ var updateCmd = new Command28("update").description("Update an open task (costs
6531
7414
  );
6532
7415
 
6533
7416
  // 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) => {
7417
+ import { Command as Command30 } from "commander";
7418
+ 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
7419
  try {
6537
7420
  const keystore = await loadKeystore();
6538
- const message = `taskmarket:forfeit:${taskId}`;
7421
+ const message = buildForfeitMessage(taskId);
6539
7422
  const signature = await signMessage(message, keystore);
6540
7423
  const result = await apiPost(`/api/tasks/${taskId}/forfeit`, {
6541
7424
  taskId,
@@ -6549,8 +7432,8 @@ var forfeitCmd = new Command29("forfeit").description("Reclaim a claim-mode task
6549
7432
  });
6550
7433
 
6551
7434
  // 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(
7435
+ import { Command as Command31 } from "commander";
7436
+ 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
7437
  "--award <worker:amount:rank>",
6555
7438
  "Award entry (repeatable): worker:amountUSDC:rank",
6556
7439
  collect,
@@ -6613,28 +7496,28 @@ function collect(val, prev) {
6613
7496
  }
6614
7497
 
6615
7498
  // 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) => {
7499
+ import { Command as Command32 } from "commander";
7500
+ 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
7501
  const result = await x402Post(`/api/tasks/${taskId}/appeal`, { taskId });
6619
7502
  printResult({ txHash: result.txHash });
6620
7503
  });
6621
7504
 
6622
7505
  // 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) => {
7506
+ import { Command as Command33 } from "commander";
7507
+ 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
7508
  const result = await x402Post(`/api/tasks/${taskId}/evaluator-timeout`, { taskId });
6626
7509
  printResult({ txHash: result.txHash });
6627
7510
  });
6628
7511
 
6629
7512
  // 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) => {
7513
+ import { Command as Command34 } from "commander";
7514
+ 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
7515
  const result = await apiPost(`/api/tasks/${taskId}/finalize-verdict`, { taskId });
6633
7516
  printResult({ txHash: result.txHash });
6634
7517
  });
6635
7518
 
6636
7519
  // src/commands/task/resolve-dispute.ts
6637
- import { Command as Command34 } from "commander";
7520
+ import { Command as Command35 } from "commander";
6638
7521
  function parseAward(spec) {
6639
7522
  const parts = spec.split(":");
6640
7523
  if (parts.length !== 3) {
@@ -6655,7 +7538,7 @@ function parseAward(spec) {
6655
7538
  rank
6656
7539
  };
6657
7540
  }
6658
- var resolveDisputeCmd = new Command34("resolve-dispute").description(
7541
+ var resolveDisputeCmd = new Command35("resolve-dispute").description(
6659
7542
  "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
7543
  ).argument("<taskId>", "Task ID (0x-prefixed hex)").requiredOption("--verdict <type>", "Verdict type: approve or partial").requiredOption(
6661
7544
  "--award <spec...>",
@@ -6681,7 +7564,7 @@ var resolveDisputeCmd = new Command34("resolve-dispute").description(
6681
7564
  });
6682
7565
 
6683
7566
  // src/commands/task/index.ts
6684
- var taskCommand = new Command35("task").description("Manage tasks");
7567
+ var taskCommand = new Command36("task").description("Manage tasks");
6685
7568
  taskCommand.addCommand(createCmd);
6686
7569
  taskCommand.addCommand(listCmd);
6687
7570
  taskCommand.addCommand(getCmd);
@@ -6714,8 +7597,8 @@ taskCommand.addCommand(finalizeVerdictCmd);
6714
7597
  taskCommand.addCommand(resolveDisputeCmd);
6715
7598
 
6716
7599
  // 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) => {
7600
+ import { Command as Command37 } from "commander";
7601
+ 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
7602
  const params = new URLSearchParams();
6720
7603
  if (opts.sort) params.set("sort", opts.sort);
6721
7604
  if (opts.skill) params.set("skill", opts.skill);
@@ -6726,35 +7609,41 @@ var agentsCommand = new Command36("agents").description("Browse the agent direct
6726
7609
  });
6727
7610
 
6728
7611
  // 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 () => {
6731
- let address;
7612
+ import { Command as Command38 } from "commander";
7613
+ var inboxCommand = new Command38("inbox").description("Show tasks you created and tasks you are working on").action(async () => {
7614
+ let keystore;
6732
7615
  try {
6733
- address = await getWalletAddress();
7616
+ keystore = await loadKeystore();
6734
7617
  } catch (err) {
6735
7618
  const msg = err instanceof Error ? err.message : "No keystore found. Run `taskmarket init` first.";
6736
7619
  printError(msg);
6737
7620
  }
6738
- const taskResult = await apiGet(
6739
- `/api/agents/inbox?address=${encodeURIComponent(address)}`
6740
- );
6741
- let pendingBids = [];
7621
+ const address = keystore.walletAddress;
7622
+ let account;
6742
7623
  try {
6743
- const keystore = await loadKeystore();
6744
- if (keystore.deviceId && keystore.apiToken) {
6745
- const params = new URLSearchParams({ deviceId: keystore.deviceId });
6746
- pendingBids = await apiGet(`/api/bids/my?${params.toString()}`, {
6747
- headers: { "x-taskmarket-api-token": keystore.apiToken }
6748
- });
6749
- }
7624
+ account = await createWalletAccountFromKeystore(keystore);
6750
7625
  } catch {
6751
7626
  }
7627
+ const [signature, bidsSignature] = await Promise.all([
7628
+ account?.signMessage({ message: buildInboxSelfAuthMessage(address) }).catch(() => void 0),
7629
+ account?.signMessage({ message: buildMyBidsMessage(address) }).catch(() => void 0)
7630
+ ]);
7631
+ const inboxParams = new URLSearchParams({ address });
7632
+ if (signature) inboxParams.set("signature", signature);
7633
+ const bidParams = new URLSearchParams({ address });
7634
+ if (bidsSignature) bidParams.set("signature", bidsSignature);
7635
+ const [taskResult, pendingBids] = await Promise.all([
7636
+ apiGet(`/api/agents/inbox?${inboxParams.toString()}`),
7637
+ bidsSignature ? apiGet(`/api/bids/my?${bidParams.toString()}`).catch(
7638
+ () => []
7639
+ ) : Promise.resolve([])
7640
+ ]);
6752
7641
  printResult({ ...taskResult, pendingBids });
6753
7642
  });
6754
7643
 
6755
7644
  // 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 () => {
7645
+ import { Command as Command39 } from "commander";
7646
+ var depositCommand = new Command39("deposit").description("Show wallet address and network info for funding").action(async () => {
6758
7647
  let address;
6759
7648
  try {
6760
7649
  address = await getWalletAddress();
@@ -6781,11 +7670,11 @@ var depositCommand = new Command38("deposit").description("Show wallet address a
6781
7670
  });
6782
7671
 
6783
7672
  // src/commands/wallet/index.ts
6784
- import { Command as Command44 } from "commander";
7673
+ import { Command as Command45 } from "commander";
6785
7674
 
6786
7675
  // 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) => {
7676
+ import { Command as Command40 } from "commander";
7677
+ var walletBalanceCommand = new Command40("balance").description("Show USDC balance").option("--address <addr>", "Address to check (defaults to own wallet)").action(async (opts) => {
6789
7678
  let address = opts.address;
6790
7679
  if (!address) {
6791
7680
  const keystore = await loadKeystore();
@@ -6796,9 +7685,9 @@ var walletBalanceCommand = new Command39("balance").description("Show USDC balan
6796
7685
  });
6797
7686
 
6798
7687
  // 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";
7688
+ import { Command as Command41 } from "commander";
7689
+ import { createInterface as createInterface2 } from "readline";
7690
+ import { privateKeyToAccount as privateKeyToAccount4 } from "viem/accounts";
6802
7691
  function normalizePrivateKey(raw) {
6803
7692
  const hex = raw.startsWith("0x") ? raw.slice(2) : raw;
6804
7693
  if (!/^[0-9a-fA-F]{64}$/.test(hex)) {
@@ -6808,7 +7697,7 @@ function normalizePrivateKey(raw) {
6808
7697
  }
6809
7698
  function promptHiddenInput(prompt) {
6810
7699
  return new Promise((resolve) => {
6811
- const rl = createInterface({
7700
+ const rl = createInterface2({
6812
7701
  input: process.stdin,
6813
7702
  output: process.stdout,
6814
7703
  terminal: true
@@ -6831,7 +7720,10 @@ function promptHiddenInput(prompt) {
6831
7720
  });
6832
7721
  });
6833
7722
  }
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) => {
7723
+ 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(
7724
+ "--yes",
7725
+ "Confirm legal acceptance non-interactively after reviewing every current policy"
7726
+ ).action(async (opts) => {
6835
7727
  if (await keystoreExists()) {
6836
7728
  const keystore = await loadKeystore();
6837
7729
  printResult({ address: keystore.walletAddress, agentId: keystore.agentId });
@@ -6850,24 +7742,30 @@ var walletImportCommand = new Command40("import").description("Import an existin
6850
7742
  keySource = "prompt";
6851
7743
  }
6852
7744
  const privateKey = normalizePrivateKey(rawKey);
6853
- const account = privateKeyToAccount3(privateKey);
7745
+ const account = privateKeyToAccount4(privateKey);
6854
7746
  const address = account.address;
6855
7747
  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 })
7748
+ const legalBundle = LegalBundleSchema.parse(await apiGet("/api/legal/current"));
7749
+ const legalAcceptance = legalBundle.enforcementEnabled ? await acceptLegalBundle({
7750
+ assumeYes: Boolean(opts.yes),
7751
+ bundle: legalBundle,
7752
+ signMessage: (message) => account.signMessage({ message }),
7753
+ walletAddress: address
7754
+ }) : void 0;
7755
+ const deviceRegisterSignature = await account.signMessage({
7756
+ message: buildDeviceRegisterMessage(address)
6860
7757
  });
6861
- if (!res.ok) {
6862
- const text = await res.text().catch(() => "");
6863
- throw new Error(`Device registration failed (${res.status}): ${text}`);
6864
- }
6865
7758
  const {
6866
7759
  deviceId,
6867
7760
  apiToken,
6868
7761
  deviceEncryptionKey,
6869
7762
  agentId: initialAgentId
6870
- } = await res.json();
7763
+ } = await registerDevice({
7764
+ legalReceipt: legalAcceptance?.receipt,
7765
+ publicKey,
7766
+ signature: deviceRegisterSignature,
7767
+ walletAddress: address
7768
+ });
6871
7769
  const encryptedKey = encryptPrivateKey(deviceEncryptionKey, privateKey);
6872
7770
  let agentId = initialAgentId;
6873
7771
  await saveKeystore({
@@ -6876,7 +7774,12 @@ var walletImportCommand = new Command40("import").description("Import an existin
6876
7774
  deviceId,
6877
7775
  apiToken,
6878
7776
  agentId,
6879
- keyServerUrl: API_URL
7777
+ keyServerUrl: API_URL,
7778
+ ...legalAcceptance ? {
7779
+ legalAcceptanceApiOrigin: API_ORIGIN,
7780
+ legalAcceptanceBundleVersion: legalAcceptance.bundleVersion,
7781
+ legalAcceptanceReceipt: legalAcceptance.receipt
7782
+ } : {}
6880
7783
  });
6881
7784
  if (!agentId) {
6882
7785
  agentId = await pollAgentId(address);
@@ -6896,11 +7799,11 @@ var walletImportCommand = new Command40("import").description("Import an existin
6896
7799
  });
6897
7800
 
6898
7801
  // src/commands/wallet/set-withdrawal-address.ts
6899
- import { Command as Command41 } from "commander";
7802
+ import { Command as Command42 } from "commander";
6900
7803
  function isValidAddress(addr) {
6901
7804
  return /^0x[a-fA-F0-9]{40}$/.test(addr);
6902
7805
  }
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) => {
7806
+ 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
7807
  if (!isValidAddress(address)) {
6905
7808
  printError("Invalid Ethereum address: must be 0x followed by 40 hex characters");
6906
7809
  }
@@ -6911,7 +7814,7 @@ var setWithdrawalAddressCommand = new Command41("set-withdrawal-address").descri
6911
7814
  printError("No keystore found. Run `taskmarket init` first.");
6912
7815
  }
6913
7816
  const walletAddress = keystore.walletAddress;
6914
- const message = `taskmarket:set-withdrawal-address:${address}`;
7817
+ const message = buildSetWithdrawalAddressMessage(address);
6915
7818
  const signature = await signMessage(message, keystore);
6916
7819
  const result = await apiPost("/api/wallet/set-withdrawal-address", {
6917
7820
  walletAddress,
@@ -6922,8 +7825,8 @@ var setWithdrawalAddressCommand = new Command41("set-withdrawal-address").descri
6922
7825
  });
6923
7826
 
6924
7827
  // 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 () => {
7828
+ import { Command as Command43 } from "commander";
7829
+ var publishKeyCommand = new Command43("publish-key").description("Publish your secp256k1 public key so others can encrypt files for you").action(async () => {
6927
7830
  let keystore;
6928
7831
  try {
6929
7832
  keystore = await loadKeystore();
@@ -6942,13 +7845,13 @@ var publishKeyCommand = new Command42("publish-key").description("Publish your s
6942
7845
  });
6943
7846
 
6944
7847
  // src/commands/wallet/withdraw-dreams.ts
6945
- import { Command as Command43 } from "commander";
7848
+ import { Command as Command44 } from "commander";
6946
7849
  import { toHex as toHex2 } from "viem";
6947
7850
  var AUTHORIZATION_VALIDITY_SECONDS = 300;
6948
7851
  function isValidAddress2(addr) {
6949
7852
  return /^0x[a-fA-F0-9]{40}$/.test(addr);
6950
7853
  }
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) => {
7854
+ 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
7855
  let keystore;
6953
7856
  try {
6954
7857
  keystore = await loadKeystore();
@@ -6973,7 +7876,7 @@ var withdrawDreamsCommand = new Command43("withdraw-dreams").description("Withdr
6973
7876
  }
6974
7877
  const nonce = toHex2(crypto.getRandomValues(new Uint8Array(32)));
6975
7878
  const validBefore = String(Math.floor(Date.now() / 1e3) + AUTHORIZATION_VALIDITY_SECONDS);
6976
- const message = `taskmarket:withdraw-dreams:${destination}:${nonce}:${validBefore}`;
7879
+ const message = buildWithdrawDreamsMessage(destination, nonce, validBefore);
6977
7880
  const signature = await signMessage(message, keystore);
6978
7881
  const result = await apiPost("/api/wallet/withdraw-dreams", {
6979
7882
  workerAddress,
@@ -6993,7 +7896,7 @@ var withdrawDreamsCommand = new Command43("withdraw-dreams").description("Withdr
6993
7896
  });
6994
7897
 
6995
7898
  // src/commands/wallet/index.ts
6996
- var walletCommand = new Command44("wallet").description("Wallet management commands");
7899
+ var walletCommand = new Command45("wallet").description("Wallet management commands");
6997
7900
  walletCommand.addCommand(walletBalanceCommand);
6998
7901
  walletCommand.addCommand(walletImportCommand);
6999
7902
  walletCommand.addCommand(setWithdrawalAddressCommand);
@@ -7001,7 +7904,7 @@ walletCommand.addCommand(publishKeyCommand);
7001
7904
  walletCommand.addCommand(withdrawDreamsCommand);
7002
7905
 
7003
7906
  // src/commands/withdraw.ts
7004
- import { Command as Command45 } from "commander";
7907
+ import { Command as Command46 } from "commander";
7005
7908
  import { toHex as toHex3 } from "viem";
7006
7909
  var USDC_TYPES = {
7007
7910
  TransferWithAuthorization: [
@@ -7013,7 +7916,7 @@ var USDC_TYPES = {
7013
7916
  { name: "nonce", type: "bytes32" }
7014
7917
  ]
7015
7918
  };
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) => {
7919
+ 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
7920
  const parsed = parseFloat(amount);
7018
7921
  if (isNaN(parsed) || parsed <= 0) {
7019
7922
  printError("Invalid amount: must be a positive number (e.g. 5 for 5 USDC)");
@@ -7063,9 +7966,9 @@ var withdrawCommand = new Command45("withdraw").description("Withdraw USDC to th
7063
7966
  });
7064
7967
 
7065
7968
  // src/commands/encrypt.ts
7066
- import { Command as Command46 } from "commander";
7969
+ import { Command as Command47 } from "commander";
7067
7970
  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) => {
7971
+ 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
7972
  let plaintext;
7070
7973
  try {
7071
7974
  plaintext = await fs2.readFile(file);
@@ -7114,9 +8017,9 @@ var encryptCommand = new Command46("encrypt").description("Encrypt a file with E
7114
8017
  });
7115
8018
 
7116
8019
  // src/commands/decrypt.ts
7117
- import { Command as Command47 } from "commander";
8020
+ import { Command as Command48 } from "commander";
7118
8021
  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) => {
8022
+ 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
8023
  let ciphertext;
7121
8024
  try {
7122
8025
  ciphertext = await fs3.readFile(file);
@@ -7154,13 +8057,13 @@ var decryptCommand = new Command47("decrypt").description("Decrypt a file using
7154
8057
  });
7155
8058
 
7156
8059
  // src/commands/xmtp.ts
7157
- import { Command as Command48 } from "commander";
8060
+ import { Command as Command49 } from "commander";
7158
8061
 
7159
8062
  // src/lib/xmtp-client.ts
7160
8063
  import os2 from "os";
7161
8064
  import path2 from "path";
7162
8065
  import { randomUUID as randomUUID2, hkdfSync as hkdfSync2 } from "crypto";
7163
- import { privateKeyToAccount as privateKeyToAccount4 } from "viem/accounts";
8066
+ import { privateKeyToAccount as privateKeyToAccount5 } from "viem/accounts";
7164
8067
 
7165
8068
  // src/lib/xmtp-envelope.ts
7166
8069
  import { randomUUID } from "crypto";
@@ -7719,7 +8622,7 @@ async function createProductionClient(input) {
7719
8622
  } else if (input.keystore) {
7720
8623
  const dek = await fetchDeviceKey(input.keystore.deviceId, input.keystore.apiToken);
7721
8624
  const privateKey = decryptPrivateKey(dek, input.keystore.encryptedKey);
7722
- const account = privateKeyToAccount4(privateKey);
8625
+ const account = privateKeyToAccount5(privateKey);
7723
8626
  signer = {
7724
8627
  type: "EOA",
7725
8628
  getIdentifier: () => ({ identifier: account.address.toLowerCase(), identifierKind: 0 }),
@@ -7918,7 +8821,7 @@ function getDefaultQueryTimeoutMs() {
7918
8821
  }
7919
8822
  return Math.floor(parsed);
7920
8823
  }
7921
- var xmtpCommand = new Command48("xmtp").description("Manage XMTP messaging for this agent");
8824
+ var xmtpCommand = new Command49("xmtp").description("Manage XMTP messaging for this agent");
7922
8825
  xmtpCommand.command("init").description("Initialize XMTP client and register installation metadata with backend").action(async () => {
7923
8826
  const keystore = await loadKeystore();
7924
8827
  const client = await createXmtpClient({
@@ -8146,7 +9049,7 @@ xmtpCommand.command("purge").description("Revoke stale XMTP installations that h
8146
9049
  });
8147
9050
 
8148
9051
  // src/commands/daemon.ts
8149
- import { Command as Command49 } from "commander";
9052
+ import { Command as Command50 } from "commander";
8150
9053
  function diffTaskStatuses(prev, next) {
8151
9054
  const changes = [];
8152
9055
  for (const [taskId, newStatus] of next) {
@@ -8174,7 +9077,7 @@ function sleepOrAbort(ms, signal) {
8174
9077
  });
8175
9078
  }
8176
9079
  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(
9080
+ 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
9081
  "--auction-poll-interval <ms>",
8179
9082
  "Poll interval for clock-based auction tasks (dutch/reverse_dutch) in milliseconds",
8180
9083
  "15000"
@@ -8495,11 +9398,11 @@ var daemonCommand = new Command49("daemon").description("Long-running agent daem
8495
9398
  );
8496
9399
 
8497
9400
  // src/commands/email/index.ts
8498
- import { Command as Command58 } from "commander";
9401
+ import { Command as Command59 } from "commander";
8499
9402
 
8500
9403
  // 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) => {
9404
+ import { Command as Command51 } from "commander";
9405
+ 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
9406
  const check = await apiGet(
8504
9407
  `/api/emails/check-username?username=${encodeURIComponent(opts.username)}`
8505
9408
  );
@@ -8516,8 +9419,8 @@ var registerCommand = new Command50("register").description("Register an email a
8516
9419
  });
8517
9420
 
8518
9421
  // 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) => {
9422
+ import { Command as Command52 } from "commander";
9423
+ 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
9424
  const keystore = await loadKeystore();
8522
9425
  const params = new URLSearchParams({
8523
9426
  deviceId: keystore.deviceId,
@@ -8532,8 +9435,8 @@ var inboxCommand2 = new Command51("inbox").description("List emails in your inbo
8532
9435
  });
8533
9436
 
8534
9437
  // 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) => {
9438
+ import { Command as Command53 } from "commander";
9439
+ var readCommand = new Command53("read").description("Read an email by ID (marks it as read)").argument("<id>", "Email ID").action(async (id) => {
8537
9440
  const keystore = await loadKeystore();
8538
9441
  const params = new URLSearchParams({
8539
9442
  deviceId: keystore.deviceId,
@@ -8545,8 +9448,8 @@ var readCommand = new Command52("read").description("Read an email by ID (marks
8545
9448
  });
8546
9449
 
8547
9450
  // 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) => {
9451
+ import { Command as Command54 } from "commander";
9452
+ 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
9453
  const keystore = await loadKeystore();
8551
9454
  const result = await apiPost("/api/emails/send", {
8552
9455
  deviceId: keystore.deviceId,
@@ -8559,8 +9462,8 @@ var sendCommand = new Command53("send").description("Send an email").requiredOpt
8559
9462
  });
8560
9463
 
8561
9464
  // 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) => {
9465
+ import { Command as Command55 } from "commander";
9466
+ 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
9467
  const keystore = await loadKeystore();
8565
9468
  const params = new URLSearchParams({
8566
9469
  deviceId: keystore.deviceId,
@@ -8582,8 +9485,8 @@ var replyCommand = new Command54("reply").description("Reply to an email").argum
8582
9485
  });
8583
9486
 
8584
9487
  // 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) => {
9488
+ import { Command as Command56 } from "commander";
9489
+ var deleteCommand = new Command56("delete").description("Delete an email by ID").argument("<id>", "Email ID").action(async (id) => {
8587
9490
  const keystore = await loadKeystore();
8588
9491
  const result = await apiPost("/api/emails/delete", {
8589
9492
  deviceId: keystore.deviceId,
@@ -8594,15 +9497,15 @@ var deleteCommand = new Command55("delete").description("Delete an email by ID")
8594
9497
  });
8595
9498
 
8596
9499
  // 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 () => {
9500
+ import { Command as Command57 } from "commander";
9501
+ var addressCommand2 = new Command57("address").description("Show your registered email address").action(async () => {
8599
9502
  const keystore = await loadKeystore();
8600
9503
  const result = await apiGet(`/api/agents/stats?address=${keystore.walletAddress}`);
8601
9504
  printResult({ emailAddress: result.emailAddress ?? null });
8602
9505
  });
8603
9506
 
8604
9507
  // src/commands/email/mark-read.ts
8605
- import { Command as Command57 } from "commander";
9508
+ import { Command as Command58 } from "commander";
8606
9509
  async function setReadStatus(id, read) {
8607
9510
  const keystore = await loadKeystore();
8608
9511
  const result = await apiPost("/api/emails/mark-read", {
@@ -8613,12 +9516,12 @@ async function setReadStatus(id, read) {
8613
9516
  });
8614
9517
  printResult({ id: result.id, isRead: result.isRead });
8615
9518
  }
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) => {
9519
+ 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
9520
  await setReadStatus(id, !opts.unread);
8618
9521
  });
8619
9522
 
8620
9523
  // src/commands/email/index.ts
8621
- var emailCommand = new Command58("email").description("Email management commands");
9524
+ var emailCommand = new Command59("email").description("Email management commands");
8622
9525
  emailCommand.addCommand(registerCommand);
8623
9526
  emailCommand.addCommand(inboxCommand2);
8624
9527
  emailCommand.addCommand(readCommand);
@@ -8629,11 +9532,11 @@ emailCommand.addCommand(addressCommand2);
8629
9532
  emailCommand.addCommand(markReadCommand);
8630
9533
 
8631
9534
  // src/commands/requester/index.ts
8632
- import { Command as Command60 } from "commander";
9535
+ import { Command as Command61 } from "commander";
8633
9536
 
8634
9537
  // 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) => {
9538
+ import { Command as Command60 } from "commander";
9539
+ var requesterStatsCmd = new Command60("stats").description("Get requester reputation stats for an address").argument("<address>", "Wallet address of the requester").action(async (address) => {
8637
9540
  if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
8638
9541
  printError("Address must be a 0x-prefixed 20-byte hex string");
8639
9542
  process.exit(1);
@@ -8649,12 +9552,12 @@ var requesterStatsCmd = new Command59("stats").description("Get requester reputa
8649
9552
  });
8650
9553
 
8651
9554
  // src/commands/requester/index.ts
8652
- var requesterCmd = new Command60("requester").description("Requester reputation commands").addCommand(requesterStatsCmd);
9555
+ var requesterCmd = new Command61("requester").description("Requester reputation commands").addCommand(requesterStatsCmd);
8653
9556
 
8654
9557
  // src/index.ts
8655
9558
  var require2 = createRequire(import.meta.url);
8656
9559
  var { version } = require2("../package.json");
8657
- var program = new Command61();
9560
+ var program = new Command62();
8658
9561
  program.name("taskmarket").description("Taskmarket CLI for AI agents").version(version);
8659
9562
  program.addCommand(initCommand);
8660
9563
  program.addCommand(walletCommand);
@@ -8672,6 +9575,7 @@ program.addCommand(xmtpCommand);
8672
9575
  program.addCommand(daemonCommand);
8673
9576
  program.addCommand(emailCommand);
8674
9577
  program.addCommand(requesterCmd);
9578
+ program.addCommand(legalCommand);
8675
9579
  program.parseAsync(process.argv).catch((err) => {
8676
9580
  process.stderr.write(JSON.stringify({ ok: false, error: err.message }) + "\n");
8677
9581
  process.exit(1);