@swarm-tips/client 0.4.8 → 0.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent.js CHANGED
@@ -10,10 +10,10 @@ import { SwarmClient, } from "./swarm/index.js";
10
10
  import { verifyVow } from "./vow/verify.js";
11
11
  /** Default EVM gas price ceiling (`maxFeePerGas` = 50 gwei). */
12
12
  export const DEFAULT_MAX_NETWORK_FEE_WEI = 50000000000n;
13
- /** Recoupable SOL advance (`0.0031 SOL` = `3_100_000` lamports = `3_000_000` rent + `100_000` first-task gas budget) fronted by `/agent/onboard`. */
14
- export const ONBOARD_ADVANCE_LAMPORTS = 3_100_000;
15
- /** Minimum SOL balance (`0.003 SOL` = `3_000_000` lamports) required for self-paid `AgentState` initialization + lifecycle fees. */
16
- export const MIN_SELF_PAID_SOLANA_BALANCE_LAMPORTS = 3_000_000;
13
+ /** Recoupable SOL advance (`0.0026 SOL` = `2_600_000` lamports) fronted by proof-gated onboarding / `/agent/onboard`. */
14
+ export const ONBOARD_ADVANCE_LAMPORTS = 2_600_000;
15
+ /** Minimum SOL balance (`0.00255 SOL` = `2_550_000` lamports) required for self-paid `AgentState` initialization + lifecycle fees. */
16
+ export const MIN_SELF_PAID_SOLANA_BALANCE_LAMPORTS = 2_550_000;
17
17
  /** Minimum SOL balance (`50_000` lamports) required for standalone post-claim `submit_work` fee payment. */
18
18
  const MIN_POST_CLAIM_SUBMIT_SOLANA_BALANCE_LAMPORTS = 50_000;
19
19
  const DEFAULT_SOLANA_RPC = {
@@ -239,18 +239,14 @@ export class SwarmAgent {
239
239
  return self.shillbotClient.preflightTask(id, body, callOpts);
240
240
  },
241
241
  submitAndExecute: (id, contentId, opts) => self.executeClaimOrSubmit(id, "submit", contentId, opts),
242
- buildVerify: (id) => self.shillbotClient.buildVerify(id, {
242
+ buildVerify: (id, opts) => self.shillbotClient.buildVerify(id, {
243
243
  payer: self.auth.walletAddress,
244
244
  mcpBaseUrl: self.mcpUrl,
245
245
  network: self.network,
246
+ ...(opts?.attemptId ? { attemptId: opts.attemptId } : {}),
246
247
  }),
247
- async verifyAndExecute(id, opts) {
248
- const prepared = await self.tasks.buildVerify(id);
249
- return self.executePreparedAction(id, "verify", prepared, {
250
- connection: opts?.connection,
251
- payoutTo: opts?.payoutTo,
252
- });
253
- },
248
+ verify: (id, opts) => self.verifyTask(id, opts),
249
+ verifyAndExecute: (id, opts) => self.verifyTask(id, opts),
254
250
  buildFinalize: (id) => self.shillbotClient.buildFinalize(id),
255
251
  async finalizeAndExecute(id, opts) {
256
252
  const prepared = await self.tasks.buildFinalize(id);
@@ -371,7 +367,7 @@ export class SwarmAgent {
371
367
  },
372
368
  };
373
369
  }
374
- /** Bootstrap a zero-funds Solana agent wallet via recoupable Advance PDA fronting (`3_100_000` lamports). */
370
+ /** Bootstrap a zero-funds Solana agent wallet via recoupable Advance PDA fronting (`2_600_000` lamports). */
375
371
  onboard() {
376
372
  return this.shillbotClient.onboard();
377
373
  }
@@ -379,10 +375,19 @@ export class SwarmAgent {
379
375
  claimTask(id, opts) {
380
376
  return this.executeClaimOrSubmit(id, "claim", undefined, opts);
381
377
  }
382
- /** Submit work for a task and execute the prepared transaction (with automatic `$0` wallet onboarding when enabled). */
378
+ /** Submit work for a task and execute the prepared transaction (or return immediately on M2 202 Accepted open competition). */
383
379
  submitWork(id, contentId, opts) {
384
380
  return this.executeClaimOrSubmit(id, "submit", contentId, opts);
385
381
  }
382
+ /** Build, locally validate, sign, broadcast, and confirm a task verification transaction (including M2 1-tx Open->Verified bundles). */
383
+ async verifyTask(id, opts) {
384
+ const prepared = await this.tasks.buildVerify(id, opts?.attemptId ? { attemptId: opts.attemptId } : undefined);
385
+ return this.executePreparedAction(id, "verify", prepared, {
386
+ connection: opts?.connection,
387
+ feePayer: opts?.feePayer,
388
+ payoutTo: opts?.payoutTo,
389
+ });
390
+ }
386
391
  requireSigner() {
387
392
  if (!this.signer) {
388
393
  throw new SwarmClientError({
@@ -403,9 +408,17 @@ export class SwarmAgent {
403
408
  }
404
409
  const suffix = sponsorMode !== "none" ? `?sponsor=${encodeURIComponent(query)}` : "";
405
410
  const payload = {
406
- content_id: contentId ?? "",
407
411
  ...(opts?.extra ?? {}),
408
412
  };
413
+ if (opts?.proofLean !== undefined && payload.proof_lean === undefined) {
414
+ payload.proof_lean = opts.proofLean;
415
+ }
416
+ if (contentId !== undefined && contentId !== "") {
417
+ payload.content_id = contentId;
418
+ }
419
+ else if (payload.content_id === undefined && payload.proof_lean === undefined) {
420
+ payload.content_id = contentId ?? "";
421
+ }
409
422
  if (opts?.agentHarness && payload.agent_harness === undefined) {
410
423
  payload.agent_harness = opts.agentHarness;
411
424
  }
@@ -435,10 +448,23 @@ export class SwarmAgent {
435
448
  throw err;
436
449
  }
437
450
  }
451
+ // M2 Open-Competition off-chain submission (`202 Accepted`, $0 gas):
452
+ // return immediately without calling RPC, signing, broadcasting, or auto-onboarding prematurely.
453
+ if (action === "submit" &&
454
+ (prepared.open_competition === true || (!prepared.transaction && Boolean(prepared.attempt_id)))) {
455
+ return {
456
+ task_id: prepared.task_id ?? id,
457
+ signature: "",
458
+ ...(prepared.task_pda ? { task_pda: prepared.task_pda } : {}),
459
+ attempt_id: prepared.attempt_id,
460
+ open_competition: true,
461
+ status: prepared.status ?? "verifying",
462
+ };
463
+ }
438
464
  const connection = this.signer?.chain === "solana"
439
465
  ? (opts?.connection ?? new Connection(this.rpcUrl, "confirmed"))
440
466
  : opts?.connection;
441
- // When a Solana wallet holds less than MIN_SELF_PAID_SOLANA_BALANCE_LAMPORTS (3_000_000 lamports
467
+ // When a Solana wallet holds less than MIN_SELF_PAID_SOLANA_BALANCE_LAMPORTS (2_550_000 lamports
442
468
  // for claim / atomic claim+submit) or MIN_POST_CLAIM_SUBMIT_SOLANA_BALANCE_LAMPORTS (50_000 lamports
443
469
  // for standalone submit) and receives a self-paid HTTP 200 transaction, onboard once and re-request.
444
470
  if (prepared.transaction &&
@@ -525,14 +551,14 @@ export class SwarmAgent {
525
551
  /**
526
552
  * Resolve an authorized `payoutTo` pubkey (`P1-2` / `HIGH-02`):
527
553
  * - If caller explicitly passed `explicitPayoutTo`, return it verbatim.
528
- * - Otherwise, NEVER trust `advance_backer` from the API response alone:
529
- * 1. Verify `advancePda(advance_backer, walletAddress) === prepared.payout_to`.
530
- * 2. Fetch the PDA on-chain via `connection.getAccountInfo(derived, "confirmed")` and require:
554
+ * - Otherwise, NEVER trust `advance_backer` or `required_payout_to` from the API response alone:
555
+ * 1. When `advance_backer` is provided, verify `advancePda(advance_backer, walletAddress) === candidatePayoutTo`.
556
+ * 2. Fetch the PDA on-chain via `connection.getAccountInfo(candidatePk, "confirmed")` and require:
531
557
  * - account exists (`acct !== null && acct.lamports > 0`),
532
558
  * - `acct.owner.equals(EXTENSION_CREDIT_PROGRAM_ID)`,
533
559
  * - valid 113-byte `Advance` account (`sha256("account:Advance")[0..8]`) with
534
- * `backer === advance_backer`, `recipient === walletAddress`, and
535
- * `recouped_lamports < advance_lamports`.
560
+ * `recipient === walletAddress`, canonical `advancePda(decoded.backer, walletAddress) === candidatePk`,
561
+ * `backer === advance_backer` (when provided), and `recouped_lamports < advance_lamports`.
536
562
  * 3. On any mismatch or RPC error, return `undefined` so `validatePreparedTransaction`
537
563
  * rejects any `set_payout_to` fail-closed.
538
564
  */
@@ -540,17 +566,26 @@ export class SwarmAgent {
540
566
  if (explicitPayoutTo !== undefined) {
541
567
  return explicitPayoutTo;
542
568
  }
543
- if (!walletAddress || !prepared.payout_to || !prepared.advance_backer) {
569
+ const candidatePayoutTo = prepared.payout_to ?? prepared.required_payout_to ?? undefined;
570
+ if (!walletAddress || !candidatePayoutTo) {
544
571
  return undefined;
545
572
  }
546
573
  try {
547
- const expectedBacker = new PublicKey(prepared.advance_backer);
548
574
  const expectedRecipient = new PublicKey(walletAddress);
549
- const derived = advancePda(expectedBacker, expectedRecipient);
550
- if (derived.toBase58() !== prepared.payout_to) {
551
- return undefined;
575
+ let expectedBacker;
576
+ let candidatePk;
577
+ if (prepared.advance_backer) {
578
+ expectedBacker = new PublicKey(prepared.advance_backer);
579
+ const derived = advancePda(expectedBacker, expectedRecipient);
580
+ if (derived.toBase58() !== candidatePayoutTo) {
581
+ return undefined;
582
+ }
583
+ candidatePk = derived;
584
+ }
585
+ else {
586
+ candidatePk = new PublicKey(candidatePayoutTo);
552
587
  }
553
- const acct = await connection.getAccountInfo(derived, "confirmed");
588
+ const acct = await connection.getAccountInfo(candidatePk, "confirmed");
554
589
  if (!acct || acct.lamports <= 0) {
555
590
  return undefined;
556
591
  }
@@ -561,13 +596,16 @@ export class SwarmAgent {
561
596
  if (!decoded) {
562
597
  return undefined;
563
598
  }
564
- if (!decoded.backer.equals(expectedBacker) ||
565
- !decoded.recipient.equals(expectedRecipient) ||
599
+ if (expectedBacker && !decoded.backer.equals(expectedBacker)) {
600
+ return undefined;
601
+ }
602
+ if (!decoded.recipient.equals(expectedRecipient) ||
603
+ !advancePda(decoded.backer, expectedRecipient).equals(candidatePk) ||
566
604
  decoded.advanceLamports === 0n ||
567
605
  decoded.recoupedLamports >= decoded.advanceLamports) {
568
606
  return undefined;
569
607
  }
570
- return derived.toBase58();
608
+ return candidatePk.toBase58();
571
609
  }
572
610
  catch {
573
611
  return undefined;
@@ -647,7 +685,8 @@ export class SwarmAgent {
647
685
  };
648
686
  }
649
687
  async executeSolanaAction(id, action, prepared, signer, opts) {
650
- if (!prepared.transaction) {
688
+ const encodedTx = prepared.transaction || prepared.co_signed_transaction || "";
689
+ if (!encodedTx) {
651
690
  throw new SwarmClientError({
652
691
  code: "INVALID_RESPONSE",
653
692
  operation: `tasks.${action}AndExecute`,
@@ -655,7 +694,7 @@ export class SwarmAgent {
655
694
  });
656
695
  }
657
696
  if (action === "create") {
658
- const txEscrow = extractCreateEscrowLamports(prepared.transaction);
697
+ const txEscrow = extractCreateEscrowLamports(encodedTx);
659
698
  if (txEscrow !== undefined && txEscrow > this.maxEscrowSpendLamports) {
660
699
  throw new SwarmClientError({
661
700
  code: "SPEND_CAP_EXCEEDED",
@@ -667,7 +706,7 @@ export class SwarmAgent {
667
706
  // C9 Network Fee Cap check first so fee cap breaches report SPEND_CAP_EXCEEDED
668
707
  let preInspected;
669
708
  try {
670
- preInspected = inspectTransaction(prepared.transaction);
709
+ preInspected = inspectTransaction(encodedTx);
671
710
  }
672
711
  catch (err) {
673
712
  throw new SwarmClientError({
@@ -699,10 +738,10 @@ export class SwarmAgent {
699
738
  ? { escrowLamports: opts.expectedEscrowLamports }
700
739
  : {}),
701
740
  };
702
- validatePreparedTransaction(prepared.transaction, expected);
741
+ validatePreparedTransaction(encodedTx, expected);
703
742
  const signature = await signBroadcastPreparedTransaction({
704
743
  connection,
705
- transaction: prepared.transaction,
744
+ transaction: encodedTx,
706
745
  expected,
707
746
  sign: (tx) => signer.signTransaction(tx),
708
747
  });
@@ -716,15 +755,39 @@ export class SwarmAgent {
716
755
  signature,
717
756
  task_pda: prepared.task_pda,
718
757
  confirmation,
758
+ ...(prepared.attempt_id !== undefined ? { attempt_id: prepared.attempt_id } : {}),
759
+ ...(prepared.onboarded_advance_tx !== undefined
760
+ ? { onboarded_advance_tx: prepared.onboarded_advance_tx }
761
+ : {}),
719
762
  };
720
763
  }
721
764
  static adviseNextAction(task, nowMs = Date.now()) {
722
765
  const rawState = String(task.state ?? task.status ?? "").trim().toLowerCase();
723
766
  const rawPlatform = task.platform;
724
- const isOnChainAction = rawPlatform === 11 ||
725
- (typeof rawPlatform === "string" && rawPlatform.trim().toLowerCase() === "onchain_action");
767
+ const normalizedPlatform = typeof rawPlatform === "string" ? rawPlatform.trim().toLowerCase() : undefined;
768
+ const isOpenCompetition = rawPlatform === 10 ||
769
+ rawPlatform === 11 ||
770
+ normalizedPlatform === "10" ||
771
+ normalizedPlatform === "11" ||
772
+ normalizedPlatform === "lean_proof" ||
773
+ normalizedPlatform === "onchain_action";
726
774
  if (rawState === "open") {
727
- return { step: isOnChainAction ? "submit" : "claim" };
775
+ if (isOpenCompetition) {
776
+ const latestAttempt = task.my_latest_attempt && typeof task.my_latest_attempt === "object"
777
+ ? task.my_latest_attempt
778
+ : undefined;
779
+ const attemptStatus = typeof latestAttempt?.status === "string"
780
+ ? latestAttempt.status.trim().toLowerCase()
781
+ : "";
782
+ if (attemptStatus === "passed") {
783
+ return { step: "verify" };
784
+ }
785
+ if (attemptStatus === "verifying") {
786
+ return { step: "wait_attestation" };
787
+ }
788
+ return { step: "submit" };
789
+ }
790
+ return { step: "claim" };
728
791
  }
729
792
  if (rawState === "claimed") {
730
793
  return { step: "submit" };
@@ -8,6 +8,15 @@ export interface WalletTokenManagerOptions {
8
8
  fetch?: FetchLike;
9
9
  now?: () => number;
10
10
  }
11
+ /** Canonical server-issued auth challenge nonce format (`hex::encode([u8; 32])`, P2-25). */
12
+ export declare const AUTH_CHALLENGE_NONCE_RE: RegExp;
13
+ /**
14
+ * Validate a server-supplied auth challenge nonce before signing it.
15
+ * Rejects arbitrary strings (such as `swarm-attr-v1:...` referral messages or
16
+ * crafted off-chain authorizations) so a compromised API cannot turn wallet
17
+ * login into a blind-signing oracle.
18
+ */
19
+ export declare function validateAuthChallengeNonce(nonce: unknown, operation: string): string;
11
20
  /**
12
21
  * Non-custodial JWT manager backed by `game-api` wallet challenges:
13
22
  * - Solana: `POST /auth/challenge` + `POST /auth/verify` (Ed25519 detached bs58)
@@ -17,6 +17,31 @@ function parseJwtClaims(token) {
17
17
  }
18
18
  }
19
19
  const DEFAULT_OPAQUE_TTL_MS = 23 * 60 * 60 * 1_000;
20
+ /** Canonical server-issued auth challenge nonce format (`hex::encode([u8; 32])`, P2-25). */
21
+ export const AUTH_CHALLENGE_NONCE_RE = /^[0-9a-f]{64}$/;
22
+ /**
23
+ * Validate a server-supplied auth challenge nonce before signing it.
24
+ * Rejects arbitrary strings (such as `swarm-attr-v1:...` referral messages or
25
+ * crafted off-chain authorizations) so a compromised API cannot turn wallet
26
+ * login into a blind-signing oracle.
27
+ */
28
+ export function validateAuthChallengeNonce(nonce, operation) {
29
+ if (typeof nonce !== "string" || nonce.length === 0) {
30
+ throw new SwarmClientError({
31
+ code: "INVALID_RESPONSE",
32
+ operation,
33
+ message: "Auth challenge returned no nonce",
34
+ });
35
+ }
36
+ if (!AUTH_CHALLENGE_NONCE_RE.test(nonce)) {
37
+ throw new SwarmClientError({
38
+ code: "INVALID_RESPONSE",
39
+ operation,
40
+ message: "Auth challenge nonce must be 64 lowercase hex characters; refusing to sign arbitrary payload",
41
+ });
42
+ }
43
+ return nonce;
44
+ }
20
45
  /**
21
46
  * Non-custodial JWT manager backed by `game-api` wallet challenges:
22
47
  * - Solana: `POST /auth/challenge` + `POST /auth/verify` (Ed25519 detached bs58)
@@ -109,17 +134,11 @@ export class WalletTokenManager {
109
134
  const challenge = await this.http.post("/auth/challenge", {
110
135
  wallet: signer.address,
111
136
  });
112
- if (!challenge?.nonce) {
113
- throw new SwarmClientError({
114
- code: "INVALID_RESPONSE",
115
- operation: "auth.challenge",
116
- message: "Auth challenge returned no nonce",
117
- });
118
- }
119
- const sigBytes = await signer.signMessage(new TextEncoder().encode(challenge.nonce));
137
+ const nonce = validateAuthChallengeNonce(challenge?.nonce, "auth.challenge");
138
+ const sigBytes = await signer.signMessage(new TextEncoder().encode(nonce));
120
139
  const verified = await this.http.post("/auth/verify", {
121
140
  wallet: signer.address,
122
- nonce: challenge.nonce,
141
+ nonce,
123
142
  signature: bs58.encode(sigBytes),
124
143
  });
125
144
  if (!verified?.token) {
@@ -135,17 +154,11 @@ export class WalletTokenManager {
135
154
  const challenge = await this.http.post("/auth/evm/challenge", {
136
155
  wallet: signer.address,
137
156
  });
138
- if (!challenge?.nonce) {
139
- throw new SwarmClientError({
140
- code: "INVALID_RESPONSE",
141
- operation: "auth.evmChallenge",
142
- message: "EVM auth challenge returned no nonce",
143
- });
144
- }
145
- const signature = await signer.signMessage(challenge.nonce);
157
+ const nonce = validateAuthChallengeNonce(challenge?.nonce, "auth.evmChallenge");
158
+ const signature = await signer.signMessage(nonce);
146
159
  const verified = await this.http.post("/auth/evm/verify", {
147
160
  wallet: signer.address,
148
- nonce: challenge.nonce,
161
+ nonce,
149
162
  signature,
150
163
  });
151
164
  if (!verified?.token) {
@@ -34,6 +34,8 @@ export declare function extractLeanWorkspaceSpec(task: Record<string, unknown>,
34
34
  export declare function buildLeanWorkspaceFiles(task: Record<string, unknown>, taskId: string): Record<string, string>;
35
35
  /**
36
36
  * Materialize a Lean 4 prover workspace on disk. Refuses to overwrite any
37
- * existing non-empty target file unless `force === true`.
37
+ * existing non-empty target file unless `force === true`, and unconditionally
38
+ * refuses symbolic links (live or dangling) at the target directory or any
39
+ * destination file path even when `force === true`.
38
40
  */
39
41
  export declare function scaffoldLeanWorkspace(task: Record<string, unknown>, taskId: string, targetDir: string, force?: boolean): ScaffoldLeanWorkspaceResult;
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
1
+ import { closeSync, constants as fsConstants, lstatSync, mkdirSync, openSync, writeFileSync, } from "node:fs";
2
2
  import { join, resolve } from "node:path";
3
3
  import { CliUsageError } from "./keyfile.js";
4
4
  export const DEFAULT_LEAN_TOOLCHAINS = {
@@ -10,6 +10,11 @@ export const DEFAULT_LEAN_TOOLCHAINS = {
10
10
  export const DEFAULT_MATHLIB_REV_V2_V3 = "c5ea00351c28e24afc9f0f84379aa41082b1188f";
11
11
  export const DEFAULT_MATHLIB_REV_V4 = "51e6992efd06126df61a496bebf8f49482a4e129";
12
12
  export const DEFAULT_ZETA23_REV_V4 = "3635e74826a4c1fcece7d1cd2b6fa75e43a00510";
13
+ const LEAN_TOOLCHAIN_RE = /^leanprover\/lean4:v[0-9]+\.[0-9]+\.[0-9]+(-rc[0-9]+)?$/;
14
+ const GIT_COMMIT_SHA_RE = /^[0-9a-f]{40}$/;
15
+ const TASK_ID_RE = /^[A-Za-z0-9:._-]{1,128}$/;
16
+ const MODE_RE = /^[a-z0-9_-]{1,32}$/;
17
+ const IMPORT_IDENT_RE = /^[A-Za-z0-9_.]+$/;
13
18
  function parsePositiveIntDirective(statementLean, key) {
14
19
  const re = new RegExp(`^\\s*--\\s*swarm:${key}\\s*=\\s*(\\d+)\\s*$`, "m");
15
20
  const match = re.exec(statementLean);
@@ -26,13 +31,21 @@ function asLeanEnv(value) {
26
31
  ? value
27
32
  : undefined;
28
33
  }
29
- function nonEmptyString(value) {
30
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
31
- }
32
34
  function positiveInt(value) {
33
35
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
34
36
  }
37
+ function validateOptionalPattern(value, pattern, field, description) {
38
+ if (value === undefined || value === null)
39
+ return undefined;
40
+ if (typeof value !== "string" || !pattern.test(value)) {
41
+ throw new CliUsageError(`Invalid ${field} in task metadata: expected ${description}.`);
42
+ }
43
+ return value;
44
+ }
35
45
  export function extractLeanWorkspaceSpec(task, taskId) {
46
+ if (typeof taskId !== "string" || !TASK_ID_RE.test(taskId)) {
47
+ throw new CliUsageError(`Invalid task_id "${String(taskId)}": expected 1-128 characters matching [A-Za-z0-9:._-].`);
48
+ }
36
49
  if (task.platform !== 10) {
37
50
  throw new CliUsageError(`Task "${taskId}" is not a LeanProof task (platform=${String(task.platform)}, expected 10).`);
38
51
  }
@@ -42,27 +55,39 @@ export function extractLeanWorkspaceSpec(task, taskId) {
42
55
  }
43
56
  const env = asLeanEnv(task.lean_environment);
44
57
  const rawPolicy = positiveInt(env?.lean_policy) ?? positiveInt(task.lean_policy) ?? 1;
45
- const leanToolchain = nonEmptyString(env?.lean_toolchain) ??
58
+ const leanToolchain = validateOptionalPattern(env?.lean_toolchain, LEAN_TOOLCHAIN_RE, "lean_toolchain", "official leanprover/lean4:v<major>.<minor>.<patch>[-rc<N>] toolchain") ??
46
59
  DEFAULT_LEAN_TOOLCHAINS[rawPolicy] ??
47
60
  DEFAULT_LEAN_TOOLCHAINS[1];
48
61
  const defaultMode = rawPolicy === 4 ? "composable" : rawPolicy === 2 || rawPolicy === 3 ? "mathlib" : "self-contained";
49
- const mode = nonEmptyString(env?.mode) ?? defaultMode;
62
+ const mode = validateOptionalPattern(env?.mode, MODE_RE, "mode", "1-32 characters matching [a-z0-9_-]") ?? defaultMode;
50
63
  const defaultImports = rawPolicy === 4
51
64
  ? ["Mathlib", "Zeta23", "SwarmProofs"]
52
65
  : rawPolicy === 2 || rawPolicy === 3
53
66
  ? ["Mathlib"]
54
67
  : [];
55
- const importAllowlist = Array.isArray(env?.import_allowlist)
56
- ? env.import_allowlist.filter((item) => typeof item === "string" && item.trim().length > 0)
57
- : defaultImports;
58
- const mathlibRev = nonEmptyString(env?.mathlib_rev) ??
68
+ let importAllowlist;
69
+ if (env?.import_allowlist !== undefined && env?.import_allowlist !== null) {
70
+ if (!Array.isArray(env.import_allowlist)) {
71
+ throw new CliUsageError("Invalid import_allowlist in task metadata: expected array of Lean module names.");
72
+ }
73
+ importAllowlist = env.import_allowlist.map((item) => {
74
+ if (typeof item !== "string" || !IMPORT_IDENT_RE.test(item)) {
75
+ throw new CliUsageError(`Invalid import_allowlist entry "${String(item)}": expected Lean module identifier matching [A-Za-z0-9_.]+.`);
76
+ }
77
+ return item;
78
+ });
79
+ }
80
+ else {
81
+ importAllowlist = defaultImports;
82
+ }
83
+ const mathlibRev = validateOptionalPattern(env?.mathlib_rev, GIT_COMMIT_SHA_RE, "mathlib_rev", "40-character lowercase hex git commit SHA") ??
59
84
  (rawPolicy === 4
60
85
  ? DEFAULT_MATHLIB_REV_V4
61
86
  : rawPolicy === 2 || rawPolicy === 3
62
87
  ? DEFAULT_MATHLIB_REV_V2_V3
63
88
  : undefined);
64
- const zeta23Rev = nonEmptyString(env?.zeta23_rev) ?? (rawPolicy === 4 ? DEFAULT_ZETA23_REV_V4 : undefined);
65
- const swarmProofsRev = nonEmptyString(env?.swarm_proofs_rev);
89
+ const zeta23Rev = validateOptionalPattern(env?.zeta23_rev, GIT_COMMIT_SHA_RE, "zeta23_rev", "40-character lowercase hex git commit SHA") ?? (rawPolicy === 4 ? DEFAULT_ZETA23_REV_V4 : undefined);
90
+ const swarmProofsRev = validateOptionalPattern(env?.swarm_proofs_rev, GIT_COMMIT_SHA_RE, "swarm_proofs_rev", "40-character lowercase hex git commit SHA");
66
91
  const allowsDisproof = typeof env?.allows_disproof === "boolean"
67
92
  ? env.allows_disproof
68
93
  : hasBidirectionalDirective(statementLean);
@@ -191,19 +216,64 @@ export function buildLeanWorkspaceFiles(task, taskId) {
191
216
  "README.md": buildReadmeMd(spec),
192
217
  };
193
218
  }
219
+ function safeLstat(path) {
220
+ try {
221
+ return lstatSync(path);
222
+ }
223
+ catch (err) {
224
+ if (err?.code === "ENOENT")
225
+ return undefined;
226
+ throw err;
227
+ }
228
+ }
229
+ function writeFileNoFollow(dest, content) {
230
+ const noFollow = fsConstants.O_NOFOLLOW ?? 0;
231
+ const flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC | noFollow;
232
+ let fd;
233
+ try {
234
+ fd = openSync(dest, flags, 0o644);
235
+ }
236
+ catch (err) {
237
+ const code = err?.code;
238
+ if (code === "ELOOP" || code === "EMLINK") {
239
+ throw new CliUsageError(`Refusing to write through symbolic link at ${dest}.`);
240
+ }
241
+ throw err;
242
+ }
243
+ try {
244
+ writeFileSync(fd, content, "utf8");
245
+ }
246
+ finally {
247
+ closeSync(fd);
248
+ }
249
+ }
194
250
  /**
195
251
  * Materialize a Lean 4 prover workspace on disk. Refuses to overwrite any
196
- * existing non-empty target file unless `force === true`.
252
+ * existing non-empty target file unless `force === true`, and unconditionally
253
+ * refuses symbolic links (live or dangling) at the target directory or any
254
+ * destination file path even when `force === true`.
197
255
  */
198
256
  export function scaffoldLeanWorkspace(task, taskId, targetDir, force = false) {
199
257
  const spec = extractLeanWorkspaceSpec(task, taskId);
200
258
  const files = buildLeanWorkspaceFiles(task, taskId);
201
259
  const resolvedDir = resolve(targetDir);
260
+ const dirStat = safeLstat(resolvedDir);
261
+ if (dirStat) {
262
+ if (dirStat.isSymbolicLink()) {
263
+ throw new CliUsageError(`Refusing to scaffold into symbolic link directory: ${resolvedDir}.`);
264
+ }
265
+ if (!dirStat.isDirectory()) {
266
+ throw new CliUsageError(`Target path exists and is not a directory: ${resolvedDir}.`);
267
+ }
268
+ }
202
269
  const existingNonEmpty = [];
203
270
  for (const relName of Object.keys(files)) {
204
271
  const dest = join(resolvedDir, relName);
205
- if (existsSync(dest)) {
206
- const stat = statSync(dest);
272
+ const stat = safeLstat(dest);
273
+ if (stat) {
274
+ if (stat.isSymbolicLink()) {
275
+ throw new CliUsageError(`Refusing to write through symbolic link target file: ${dest}.`);
276
+ }
207
277
  if (stat.isDirectory() || stat.size > 0) {
208
278
  existingNonEmpty.push(relName);
209
279
  }
@@ -215,7 +285,12 @@ export function scaffoldLeanWorkspace(task, taskId, targetDir, force = false) {
215
285
  mkdirSync(resolvedDir, { recursive: true });
216
286
  const written = [];
217
287
  for (const [relName, content] of Object.entries(files)) {
218
- writeFileSync(join(resolvedDir, relName), content, "utf8");
288
+ const dest = join(resolvedDir, relName);
289
+ const postStat = safeLstat(dest);
290
+ if (postStat?.isSymbolicLink()) {
291
+ throw new CliUsageError(`Refusing to write through symbolic link target file: ${dest}.`);
292
+ }
293
+ writeFileNoFollow(dest, content);
219
294
  written.push(relName);
220
295
  }
221
296
  return {
package/dist/cli/swarm.js CHANGED
@@ -110,8 +110,8 @@ Commands:
110
110
  tasks init <id> [--dir <path>] [--force] (scaffold pinned Lean 4 workspace — zero auth / zero SOL)
111
111
  tasks check <id> <proof-file> [--compile] (static or remote compile preflight with diagnostics & compression metrics)
112
112
  tasks claim <id> [--payout-to <pubkey>] [--fee-payer <pubkey>] [--no-exec]
113
- tasks submit <id> (--content <str> | --proof-file <path>) [--harness <name>] [--model <name>] [--payout-to <pubkey>] [--fee-payer <pubkey>] [--no-exec]
114
- tasks verify <id> [--no-exec]
113
+ tasks submit <id> ([<content_id>] | --content <str> | --proof-file <path> | --proof-lean <src>) [--harness <name>] [--model <name>] [--payout-to <pubkey>] [--fee-payer <pubkey>] [--no-exec]
114
+ tasks verify <id> [--attempt-id <id>] [--payout-to <pubkey>] [--no-exec]
115
115
  tasks finalize <id> [--no-exec]
116
116
  tasks expire <id> [--no-exec] (client escrow refund past claim/submit deadline or past submitted_at + verification_timeout)
117
117
  proofs list [--limit N] [--policy N] (public verified Lean 4 proofs & prover leaderboard)
@@ -506,12 +506,16 @@ export async function runSwarmCli(argv, io = {}) {
506
506
  }
507
507
  if (sub === "submit") {
508
508
  const id = rest[0]?.trim();
509
- const content = getStringFlag(flags, "--content");
509
+ const content = getStringFlag(flags, "--content") ?? rest[1];
510
510
  const proofFile = getStringFlag(flags, "--proof-file");
511
+ const inlineProofLean = getStringFlag(flags, "--proof-lean");
511
512
  const harness = getStringFlag(flags, "--harness");
512
513
  const model = getStringFlag(flags, "--model");
513
- if (!id || (!content && !proofFile)) {
514
- throw new CliUsageError("Usage: swarm tasks submit <task_id> (--content <str> | --proof-file <path>) [--harness <name>] [--model <name>] [--payout-to <pubkey>] [--fee-payer <pubkey>] [--no-exec]");
514
+ if (proofFile && inlineProofLean !== undefined) {
515
+ throw new CliUsageError("Specify either --proof-file or --proof-lean, not both.");
516
+ }
517
+ if (!id || (!content && !proofFile && inlineProofLean === undefined)) {
518
+ throw new CliUsageError("Usage: swarm tasks submit <task_id> ([<content_id>] | --content <str> | --proof-file <path> | --proof-lean <src>) [--harness <name>] [--model <name>] [--payout-to <pubkey>] [--fee-payer <pubkey>] [--no-exec]");
515
519
  }
516
520
  let proofLean;
517
521
  if (proofFile) {
@@ -525,8 +529,23 @@ export async function runSwarmCli(argv, io = {}) {
525
529
  throw new CliUsageError(`Proof file ${proofFile} is empty.`);
526
530
  }
527
531
  }
532
+ else if (inlineProofLean !== undefined) {
533
+ if (!inlineProofLean.trim()) {
534
+ throw new CliUsageError("Flag --proof-lean must not be empty.");
535
+ }
536
+ proofLean = inlineProofLean;
537
+ }
528
538
  const payoutTo = getStringFlag(flags, "--payout-to");
529
539
  const feePayer = getStringFlag(flags, "--fee-payer");
540
+ const formatOpenCompetitionHuman = (res) => {
541
+ const targetId = res.task_id ?? id;
542
+ const attemptPart = res.attempt_id ? ` --attempt-id ${res.attempt_id}` : "";
543
+ stdout.write([
544
+ `Accepted (Open Competition — $0 gas) — task ${targetId}`,
545
+ `Attempt ID: ${res.attempt_id ?? "pending"} | Status: ${res.status ?? "verifying"}`,
546
+ `Next: poll \`swarm tasks get ${targetId}\`, then run \`swarm tasks verify ${targetId}${attemptPart}\` once passed.`,
547
+ ].join("\n") + "\n");
548
+ };
530
549
  if (noExec) {
531
550
  const submitBody = {
532
551
  content_id: content ?? "",
@@ -535,34 +554,45 @@ export async function runSwarmCli(argv, io = {}) {
535
554
  ...(model ? { model_family: model } : {}),
536
555
  };
537
556
  const res = await agent.tasks.submit(id, submitBody);
538
- writeOutput(stdout, jsonMode, res);
557
+ if (!jsonMode && res.open_competition === true) {
558
+ formatOpenCompetitionHuman(res);
559
+ }
560
+ else {
561
+ writeOutput(stdout, jsonMode, res);
562
+ }
539
563
  return 0;
540
564
  }
541
- const extra = {
542
- ...(proofLean !== undefined ? { proof_lean: proofLean } : {}),
543
- ...(harness ? { agent_harness: harness } : {}),
544
- ...(model ? { model_family: model } : {}),
545
- };
546
- const execOpts = payoutTo || feePayer || harness || model || Object.keys(extra).length > 0
565
+ const execOpts = payoutTo || feePayer || harness || model || proofLean !== undefined
547
566
  ? {
548
567
  ...(payoutTo ? { payoutTo } : {}),
549
568
  ...(feePayer ? { feePayer } : {}),
569
+ ...(proofLean !== undefined ? { proofLean } : {}),
550
570
  ...(harness ? { agentHarness: harness } : {}),
551
571
  ...(model ? { modelFamily: model } : {}),
552
- ...(Object.keys(extra).length > 0 ? { extra } : {}),
553
572
  }
554
573
  : undefined;
555
- const res = await agent.tasks.submitAndExecute(id, content ?? "", execOpts);
556
- writeOutput(stdout, jsonMode, res);
574
+ const res = await agent.tasks.submitAndExecute(id, content, execOpts);
575
+ if (!jsonMode && res.open_competition === true) {
576
+ formatOpenCompetitionHuman(res);
577
+ }
578
+ else {
579
+ writeOutput(stdout, jsonMode, res);
580
+ }
557
581
  return 0;
558
582
  }
559
583
  if (sub === "verify") {
560
- const id = rest[0];
561
- if (!id)
562
- throw new CliUsageError("Usage: swarm tasks verify <task_id> [--no-exec]");
584
+ const id = rest[0]?.trim();
585
+ if (!id) {
586
+ throw new CliUsageError("Usage: swarm tasks verify <task_id> [--attempt-id <id>] [--payout-to <pubkey>] [--no-exec]");
587
+ }
588
+ const attemptId = getStringFlag(flags, "--attempt-id")?.trim() || undefined;
589
+ const payoutTo = getStringFlag(flags, "--payout-to");
590
+ const verifyOpts = attemptId || payoutTo
591
+ ? { ...(attemptId ? { attemptId } : {}), ...(payoutTo ? { payoutTo } : {}) }
592
+ : undefined;
563
593
  const res = noExec
564
- ? await agent.tasks.buildVerify(id)
565
- : await agent.tasks.verifyAndExecute(id);
594
+ ? await agent.tasks.buildVerify(id, attemptId ? { attemptId } : undefined)
595
+ : await agent.tasks.verifyAndExecute(id, verifyOpts);
566
596
  writeOutput(stdout, jsonMode, res);
567
597
  return 0;
568
598
  }