@swarm-tips/client 0.4.7 → 0.4.9

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.
@@ -0,0 +1,231 @@
1
+ import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { CliUsageError } from "./keyfile.js";
4
+ export const DEFAULT_LEAN_TOOLCHAINS = {
5
+ 1: "leanprover/lean4:v4.31.0",
6
+ 2: "leanprover/lean4:v4.30.0",
7
+ 3: "leanprover/lean4:v4.30.0",
8
+ 4: "leanprover/lean4:v4.33.0-rc2",
9
+ };
10
+ export const DEFAULT_MATHLIB_REV_V2_V3 = "c5ea00351c28e24afc9f0f84379aa41082b1188f";
11
+ export const DEFAULT_MATHLIB_REV_V4 = "51e6992efd06126df61a496bebf8f49482a4e129";
12
+ export const DEFAULT_ZETA23_REV_V4 = "3635e74826a4c1fcece7d1cd2b6fa75e43a00510";
13
+ function parsePositiveIntDirective(statementLean, key) {
14
+ const re = new RegExp(`^\\s*--\\s*swarm:${key}\\s*=\\s*(\\d+)\\s*$`, "m");
15
+ const match = re.exec(statementLean);
16
+ if (!match)
17
+ return undefined;
18
+ const parsed = Number(match[1]);
19
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
20
+ }
21
+ function hasBidirectionalDirective(statementLean) {
22
+ return /^\s*--\s*swarm:polarity\s*=\s*bidirectional\s*$/m.test(statementLean);
23
+ }
24
+ function asLeanEnv(value) {
25
+ return value && typeof value === "object"
26
+ ? value
27
+ : undefined;
28
+ }
29
+ function nonEmptyString(value) {
30
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
31
+ }
32
+ function positiveInt(value) {
33
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
34
+ }
35
+ export function extractLeanWorkspaceSpec(task, taskId) {
36
+ if (task.platform !== 10) {
37
+ throw new CliUsageError(`Task "${taskId}" is not a LeanProof task (platform=${String(task.platform)}, expected 10).`);
38
+ }
39
+ const statementLean = typeof task.statement_lean === "string" ? task.statement_lean : "";
40
+ if (!statementLean.trim()) {
41
+ throw new CliUsageError(`Task "${taskId}" has no statement_lean; cannot scaffold a Lean 4 workspace.`);
42
+ }
43
+ const env = asLeanEnv(task.lean_environment);
44
+ const rawPolicy = positiveInt(env?.lean_policy) ?? positiveInt(task.lean_policy) ?? 1;
45
+ const leanToolchain = nonEmptyString(env?.lean_toolchain) ??
46
+ DEFAULT_LEAN_TOOLCHAINS[rawPolicy] ??
47
+ DEFAULT_LEAN_TOOLCHAINS[1];
48
+ const defaultMode = rawPolicy === 4 ? "composable" : rawPolicy === 2 || rawPolicy === 3 ? "mathlib" : "self-contained";
49
+ const mode = nonEmptyString(env?.mode) ?? defaultMode;
50
+ const defaultImports = rawPolicy === 4
51
+ ? ["Mathlib", "Zeta23", "SwarmProofs"]
52
+ : rawPolicy === 2 || rawPolicy === 3
53
+ ? ["Mathlib"]
54
+ : [];
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) ??
59
+ (rawPolicy === 4
60
+ ? DEFAULT_MATHLIB_REV_V4
61
+ : rawPolicy === 2 || rawPolicy === 3
62
+ ? DEFAULT_MATHLIB_REV_V2_V3
63
+ : undefined);
64
+ const zeta23Rev = nonEmptyString(env?.zeta23_rev) ?? (rawPolicy === 4 ? DEFAULT_ZETA23_REV_V4 : undefined);
65
+ const swarmProofsRev = nonEmptyString(env?.swarm_proofs_rev);
66
+ const allowsDisproof = typeof env?.allows_disproof === "boolean"
67
+ ? env.allows_disproof
68
+ : hasBidirectionalDirective(statementLean);
69
+ const maxProofLines = positiveInt(env?.max_proof_lines) ?? parsePositiveIntDirective(statementLean, "max_proof_lines");
70
+ const maxProofBytes = positiveInt(env?.max_proof_bytes) ?? parsePositiveIntDirective(statementLean, "max_proof_bytes");
71
+ const explicitMaxLineWidth = positiveInt(env?.max_line_width) ?? parsePositiveIntDirective(statementLean, "max_line_width");
72
+ const maxLineWidth = explicitMaxLineWidth ?? (maxProofLines !== undefined ? 120 : undefined);
73
+ const limits = {
74
+ ...(maxProofLines !== undefined ? { max_proof_lines: maxProofLines } : {}),
75
+ ...(maxProofBytes !== undefined ? { max_proof_bytes: maxProofBytes } : {}),
76
+ ...(maxLineWidth !== undefined ? { max_line_width: maxLineWidth } : {}),
77
+ };
78
+ return {
79
+ task_id: taskId,
80
+ statement_lean: statementLean,
81
+ lean_policy: rawPolicy,
82
+ lean_toolchain: leanToolchain,
83
+ mode,
84
+ ...(mathlibRev ? { mathlib_rev: mathlibRev } : {}),
85
+ ...(zeta23Rev ? { zeta23_rev: zeta23Rev } : {}),
86
+ ...(swarmProofsRev ? { swarm_proofs_rev: swarmProofsRev } : {}),
87
+ import_allowlist: importAllowlist,
88
+ allows_disproof: allowsDisproof,
89
+ limits,
90
+ };
91
+ }
92
+ function buildLakefileToml(spec) {
93
+ const lines = [
94
+ 'name = "SwarmTask"',
95
+ 'version = "0.1.0"',
96
+ 'defaultTargets = ["TargetStatement", "Solution"]',
97
+ "",
98
+ "[leanOptions]",
99
+ "pp.unicode.fun = true",
100
+ "relaxedAutoImplicit = false",
101
+ "",
102
+ ];
103
+ if (spec.lean_policy === 4) {
104
+ const mathlibRev = spec.mathlib_rev ?? DEFAULT_MATHLIB_REV_V4;
105
+ const zeta23Rev = spec.zeta23_rev ?? DEFAULT_ZETA23_REV_V4;
106
+ const swarmProofsRev = spec.swarm_proofs_rev ?? "main";
107
+ lines.push("[[require]]", 'name = "mathlib"', 'git = "https://github.com/leanprover-community/mathlib4.git"', `rev = ${JSON.stringify(mathlibRev)}`, "", "[[require]]", 'name = "Zeta23"', 'git = "https://github.com/anthropics/formal-math"', `rev = ${JSON.stringify(zeta23Rev)}`, 'subDir = "zeta23"', "", "[[require]]", 'name = "SwarmProofs"', 'git = "https://github.com/corsur/swarm-tips"', `rev = ${JSON.stringify(swarmProofsRev)}`, 'subDir = "proofs/SwarmProofs"', "");
108
+ }
109
+ else if (spec.lean_policy === 2 || spec.lean_policy === 3 || spec.mathlib_rev) {
110
+ const mathlibRev = spec.mathlib_rev ?? DEFAULT_MATHLIB_REV_V2_V3;
111
+ lines.push("[[require]]", 'name = "mathlib"', 'git = "https://github.com/leanprover-community/mathlib4.git"', `rev = ${JSON.stringify(mathlibRev)}`, "");
112
+ }
113
+ lines.push("[[lean_lib]]", 'name = "TargetStatement"', "", "[[lean_lib]]", 'name = "Solution"', "");
114
+ return lines.join("\n");
115
+ }
116
+ function formatLimitsSummary(limits) {
117
+ const parts = [];
118
+ if (limits.max_proof_lines !== undefined && limits.max_proof_lines !== null) {
119
+ parts.push(`max_proof_lines=${limits.max_proof_lines}`);
120
+ }
121
+ if (limits.max_proof_bytes !== undefined && limits.max_proof_bytes !== null) {
122
+ parts.push(`max_proof_bytes=${limits.max_proof_bytes}`);
123
+ }
124
+ if (limits.max_line_width !== undefined && limits.max_line_width !== null) {
125
+ parts.push(`max_line_width=${limits.max_line_width}`);
126
+ }
127
+ return parts.length > 0 ? parts.join(", ") : undefined;
128
+ }
129
+ function buildTargetStatementLean(spec) {
130
+ const body = spec.statement_lean.endsWith("\n")
131
+ ? spec.statement_lean
132
+ : `${spec.statement_lean}\n`;
133
+ return (`${body}\n` +
134
+ "namespace SwarmVerifyTarget\n" +
135
+ "def statementProp : Prop := _root_.statementProp\n" +
136
+ "end SwarmVerifyTarget\n");
137
+ }
138
+ function buildSolutionLean(spec) {
139
+ const importsLabel = spec.import_allowlist.length > 0
140
+ ? spec.import_allowlist.join(", ")
141
+ : "none (self-contained)";
142
+ const polarityLine = spec.allows_disproof
143
+ ? "-- Polarity: bidirectional — prove `theorem proof : statementProp` OR refute with `theorem disproof : ¬ statementProp`"
144
+ : "-- Polarity: proof only — prove `theorem proof : statementProp`";
145
+ const limitsSummary = formatLimitsSummary(spec.limits);
146
+ const lines = [
147
+ `-- Swarm Tips Lean 4 Task: ${spec.task_id}`,
148
+ `-- Policy: v${spec.lean_policy} (${spec.mode}) | Toolchain: ${spec.lean_toolchain}`,
149
+ `-- Allowed imports: ${importsLabel}`,
150
+ polarityLine,
151
+ ];
152
+ if (limitsSummary) {
153
+ lines.push(`-- Compression limits: ${limitsSummary}`);
154
+ }
155
+ lines.push("", "import TargetStatement", "", "theorem proof : statementProp := by", " sorry", "");
156
+ return lines.join("\n");
157
+ }
158
+ function buildReadmeMd(spec) {
159
+ const importsLabel = spec.import_allowlist.length > 0
160
+ ? spec.import_allowlist.map((i) => `\`${i}\``).join(", ")
161
+ : "None (self-contained)";
162
+ const polarityLabel = spec.allows_disproof
163
+ ? "Bidirectional (`theorem proof : statementProp` or `theorem disproof : ¬ statementProp`)"
164
+ : "Proof only (`theorem proof : statementProp`)";
165
+ const limitsSummary = formatLimitsSummary(spec.limits);
166
+ const lines = [
167
+ `# Swarm Tips Lean 4 Workspace — \`${spec.task_id}\``,
168
+ "",
169
+ `- **Policy:** \`v${spec.lean_policy}\` (\`${spec.mode}\`)`,
170
+ `- **Toolchain:** \`${spec.lean_toolchain}\``,
171
+ `- **Allowed Imports:** ${importsLabel}`,
172
+ `- **Polarity:** ${polarityLabel}`,
173
+ ];
174
+ if (limitsSummary) {
175
+ lines.push(`- **Compression Limits:** \`${limitsSummary}\``);
176
+ }
177
+ lines.push("", "## 1. Local Build (Optional)", "", "```bash", "lake exe cache get && lake build", "```", "", "## 2. Remote Compile Dry-Run (Zero SOL)", "", "```bash", `npx @swarm-tips/client tasks check ${spec.task_id} Solution.lean --compile`, "```", "", "## 3. Submit Proof", "", "```bash", `npx @swarm-tips/client tasks submit ${spec.task_id} --proof-file Solution.lean`, "```", "");
178
+ return lines.join("\n");
179
+ }
180
+ /**
181
+ * Pure helper generating the complete Lean 4 workspace file map for a
182
+ * `platform === 10` task without touching the filesystem.
183
+ */
184
+ export function buildLeanWorkspaceFiles(task, taskId) {
185
+ const spec = extractLeanWorkspaceSpec(task, taskId);
186
+ return {
187
+ "lean-toolchain": `${spec.lean_toolchain}\n`,
188
+ "lakefile.toml": buildLakefileToml(spec),
189
+ "TargetStatement.lean": buildTargetStatementLean(spec),
190
+ "Solution.lean": buildSolutionLean(spec),
191
+ "README.md": buildReadmeMd(spec),
192
+ };
193
+ }
194
+ /**
195
+ * Materialize a Lean 4 prover workspace on disk. Refuses to overwrite any
196
+ * existing non-empty target file unless `force === true`.
197
+ */
198
+ export function scaffoldLeanWorkspace(task, taskId, targetDir, force = false) {
199
+ const spec = extractLeanWorkspaceSpec(task, taskId);
200
+ const files = buildLeanWorkspaceFiles(task, taskId);
201
+ const resolvedDir = resolve(targetDir);
202
+ const existingNonEmpty = [];
203
+ for (const relName of Object.keys(files)) {
204
+ const dest = join(resolvedDir, relName);
205
+ if (existsSync(dest)) {
206
+ const stat = statSync(dest);
207
+ if (stat.isDirectory() || stat.size > 0) {
208
+ existingNonEmpty.push(relName);
209
+ }
210
+ }
211
+ }
212
+ if (existingNonEmpty.length > 0 && !force) {
213
+ throw new CliUsageError(`Refusing to overwrite non-empty target file(s) in ${resolvedDir}: ${existingNonEmpty.join(", ")}. Pass --force to overwrite.`);
214
+ }
215
+ mkdirSync(resolvedDir, { recursive: true });
216
+ const written = [];
217
+ for (const [relName, content] of Object.entries(files)) {
218
+ writeFileSync(join(resolvedDir, relName), content, "utf8");
219
+ written.push(relName);
220
+ }
221
+ return {
222
+ ok: true,
223
+ task_id: taskId,
224
+ dir: resolvedDir,
225
+ lean_policy: spec.lean_policy,
226
+ lean_toolchain: spec.lean_toolchain,
227
+ allows_disproof: spec.allows_disproof,
228
+ limits: spec.limits,
229
+ files: written,
230
+ };
231
+ }
package/dist/cli/swarm.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync, realpathSync } from "node:fs";
3
+ import { resolve } from "node:path";
3
4
  import { fileURLToPath } from "node:url";
4
5
  import { SwarmAgent } from "../agent.js";
5
6
  import { SwarmClientError } from "../errors.js";
@@ -8,6 +9,7 @@ import { validatePreparedTransaction, } from "../shillbot/api.js";
8
9
  import { inspectTransaction } from "../shillbot/index.js";
9
10
  import { CLIENT_VERSION } from "../version.js";
10
11
  import { CliUsageError, assertNoSecretCliFlags, loadSignerFromCliOrEnv, } from "./keyfile.js";
12
+ import { scaffoldLeanWorkspace } from "./lean-init.js";
11
13
  const BOOLEAN_FLAGS = new Set([
12
14
  "--json",
13
15
  "--yes",
@@ -19,6 +21,8 @@ const BOOLEAN_FLAGS = new Set([
19
21
  "--unmute",
20
22
  "--cursor",
21
23
  "--allow-localhost-http",
24
+ "--compile",
25
+ "--force",
22
26
  ]);
23
27
  export function parseCliArgs(argv) {
24
28
  assertNoSecretCliFlags(argv);
@@ -103,11 +107,14 @@ Commands:
103
107
  listings [--limit N] [--category CAT] [--chain CHAIN]
104
108
  reputation <wallet>
105
109
  tasks list [--limit N] | get <id> | mine | earnings | onboard | next <task-json-or-id>
110
+ tasks init <id> [--dir <path>] [--force] (scaffold pinned Lean 4 workspace — zero auth / zero SOL)
111
+ tasks check <id> <proof-file> [--compile] (static or remote compile preflight with diagnostics & compression metrics)
106
112
  tasks claim <id> [--payout-to <pubkey>] [--fee-payer <pubkey>] [--no-exec]
107
- tasks submit <id> --content <str> [--payout-to <pubkey>] [--fee-payer <pubkey>] [--no-exec]
108
- 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]
109
115
  tasks finalize <id> [--no-exec]
110
116
  tasks expire <id> [--no-exec] (client escrow refund past claim/submit deadline or past submitted_at + verification_timeout)
117
+ proofs list [--limit N] [--policy N] (public verified Lean 4 proofs & prover leaderboard)
111
118
  inbox list [--status pending|all] [--limit N]
112
119
  inbox open <msg_id...>
113
120
  inbox send <to_wallet> <body> [--thread <id>] [--intent <intent>]
@@ -169,6 +176,50 @@ function writeError(stdout, stderr, jsonMode, message, code) {
169
176
  stderr.write(`Error: ${message}\n`);
170
177
  }
171
178
  }
179
+ function defaultLeanWorkspaceDir(taskId) {
180
+ const safeSlug = taskId.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "lean";
181
+ return resolve(`swarm-task-${safeSlug}`);
182
+ }
183
+ function formatPreflightHuman(res, compiled) {
184
+ const modeLabel = res.compiled ?? compiled ? "compile" : "static";
185
+ const statusLabel = res.ok ? "PASS" : "FAIL";
186
+ const verdictPart = res.verdict ? ` [${res.verdict}]` : "";
187
+ const lines = [
188
+ `${statusLabel} (${modeLabel})${verdictPart} — task ${res.task_id}`,
189
+ ];
190
+ if (res.detail) {
191
+ lines.push(`Detail: ${res.detail}`);
192
+ }
193
+ if (res.metrics) {
194
+ const m = res.metrics;
195
+ lines.push(`Metrics: ${m.code_lines} code lines (${m.total_lines} total), ${m.code_bytes} code bytes (${m.raw_bytes} raw), max line width ${m.max_line_width}`);
196
+ }
197
+ if (res.limits) {
198
+ const parts = [];
199
+ if (res.limits.max_proof_lines !== undefined && res.limits.max_proof_lines !== null) {
200
+ parts.push(`max_proof_lines=${res.limits.max_proof_lines}`);
201
+ }
202
+ if (res.limits.max_proof_bytes !== undefined && res.limits.max_proof_bytes !== null) {
203
+ parts.push(`max_proof_bytes=${res.limits.max_proof_bytes}`);
204
+ }
205
+ if (res.limits.max_line_width !== undefined && res.limits.max_line_width !== null) {
206
+ parts.push(`max_line_width=${res.limits.max_line_width}`);
207
+ }
208
+ if (parts.length > 0) {
209
+ lines.push(`Limits: ${parts.join(", ")}`);
210
+ }
211
+ }
212
+ if (Array.isArray(res.axioms) && res.axioms.length > 0) {
213
+ lines.push(`Axioms: ${res.axioms.join(", ")}`);
214
+ }
215
+ if (Array.isArray(res.diagnostics) && res.diagnostics.length > 0) {
216
+ lines.push("Diagnostics:");
217
+ for (const d of res.diagnostics) {
218
+ lines.push(` ${d.file}:${d.line}:${d.column}: ${d.severity}: ${d.message}`);
219
+ }
220
+ }
221
+ return `${lines.join("\n")}\n`;
222
+ }
172
223
  export async function runSwarmCli(argv, io = {}) {
173
224
  const stdout = io.stdout ?? process.stdout;
174
225
  const stderr = io.stderr ?? process.stderr;
@@ -359,6 +410,58 @@ export async function runSwarmCli(argv, io = {}) {
359
410
  writeOutput(stdout, jsonMode, res);
360
411
  return 0;
361
412
  }
413
+ if (sub === "init") {
414
+ const id = rest[0]?.trim();
415
+ if (!id) {
416
+ throw new CliUsageError("Usage: swarm tasks init <task_id> [--dir <path>] [--force]");
417
+ }
418
+ const task = await agent.tasks.get(id);
419
+ const dirFlag = getStringFlag(flags, "--dir");
420
+ const targetDir = dirFlag ? resolve(dirFlag) : defaultLeanWorkspaceDir(id);
421
+ const result = scaffoldLeanWorkspace(task, id, targetDir, Boolean(flags.get("--force")));
422
+ if (jsonMode) {
423
+ writeOutput(stdout, true, result);
424
+ }
425
+ else {
426
+ stdout.write([
427
+ `Scaffolded Lean 4 workspace for ${result.task_id} in ${result.dir}`,
428
+ `Policy: v${result.lean_policy} | Toolchain: ${result.lean_toolchain}`,
429
+ `Files: ${result.files.join(", ")}`,
430
+ `Next: cd ${result.dir} && npx @swarm-tips/client tasks check ${result.task_id} Solution.lean --compile`,
431
+ ].join("\n") + "\n");
432
+ }
433
+ return 0;
434
+ }
435
+ if (sub === "check") {
436
+ const id = rest[0]?.trim();
437
+ const proofPath = rest[1] ?? getStringFlag(flags, "--proof-file");
438
+ if (!id || !proofPath) {
439
+ throw new CliUsageError("Usage: swarm tasks check <task_id> <proof_file> [--compile]");
440
+ }
441
+ let proofLean;
442
+ try {
443
+ proofLean = readFileSync(proofPath, "utf8");
444
+ }
445
+ catch (err) {
446
+ throw new CliUsageError(`Failed to read proof file ${proofPath}: ${err instanceof Error ? err.message : String(err)}`);
447
+ }
448
+ if (!proofLean.trim()) {
449
+ throw new CliUsageError(`Proof file ${proofPath} is empty.`);
450
+ }
451
+ const compile = Boolean(flags.get("--compile"));
452
+ const res = await agent.tasks.preflight(id, {
453
+ proof_lean: proofLean,
454
+ ...(compile ? { compile: true } : {}),
455
+ network,
456
+ });
457
+ if (jsonMode) {
458
+ writeOutput(stdout, true, res);
459
+ }
460
+ else {
461
+ stdout.write(formatPreflightHuman(res, compile));
462
+ }
463
+ return res.ok ? 0 : 1;
464
+ }
362
465
  if (sub === "mine") {
363
466
  const tasks = await agent.tasks.mine();
364
467
  writeOutput(stdout, jsonMode, { tasks });
@@ -402,29 +505,94 @@ export async function runSwarmCli(argv, io = {}) {
402
505
  return 0;
403
506
  }
404
507
  if (sub === "submit") {
405
- const id = rest[0];
406
- const content = getStringFlag(flags, "--content");
407
- if (!id || !content) {
408
- throw new CliUsageError("Usage: swarm tasks submit <task_id> --content <str> [--payout-to <pubkey>] [--fee-payer <pubkey>] [--no-exec]");
508
+ const id = rest[0]?.trim();
509
+ const content = getStringFlag(flags, "--content") ?? rest[1];
510
+ const proofFile = getStringFlag(flags, "--proof-file");
511
+ const inlineProofLean = getStringFlag(flags, "--proof-lean");
512
+ const harness = getStringFlag(flags, "--harness");
513
+ const model = getStringFlag(flags, "--model");
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]");
519
+ }
520
+ let proofLean;
521
+ if (proofFile) {
522
+ try {
523
+ proofLean = readFileSync(proofFile, "utf8");
524
+ }
525
+ catch (err) {
526
+ throw new CliUsageError(`Failed to read proof file ${proofFile}: ${err instanceof Error ? err.message : String(err)}`);
527
+ }
528
+ if (!proofLean.trim()) {
529
+ throw new CliUsageError(`Proof file ${proofFile} is empty.`);
530
+ }
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;
409
537
  }
410
538
  const payoutTo = getStringFlag(flags, "--payout-to");
411
539
  const feePayer = getStringFlag(flags, "--fee-payer");
412
- const execOpts = payoutTo || feePayer
413
- ? { ...(payoutTo ? { payoutTo } : {}), ...(feePayer ? { feePayer } : {}) }
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
+ };
549
+ if (noExec) {
550
+ const submitBody = {
551
+ content_id: content ?? "",
552
+ ...(proofLean !== undefined ? { proof_lean: proofLean } : {}),
553
+ ...(harness ? { agent_harness: harness } : {}),
554
+ ...(model ? { model_family: model } : {}),
555
+ };
556
+ const res = await agent.tasks.submit(id, submitBody);
557
+ if (!jsonMode && res.open_competition === true) {
558
+ formatOpenCompetitionHuman(res);
559
+ }
560
+ else {
561
+ writeOutput(stdout, jsonMode, res);
562
+ }
563
+ return 0;
564
+ }
565
+ const execOpts = payoutTo || feePayer || harness || model || proofLean !== undefined
566
+ ? {
567
+ ...(payoutTo ? { payoutTo } : {}),
568
+ ...(feePayer ? { feePayer } : {}),
569
+ ...(proofLean !== undefined ? { proofLean } : {}),
570
+ ...(harness ? { agentHarness: harness } : {}),
571
+ ...(model ? { modelFamily: model } : {}),
572
+ }
414
573
  : undefined;
415
- const res = noExec
416
- ? await agent.tasks.submit(id, { content_id: content })
417
- : await agent.tasks.submitAndExecute(id, content, execOpts);
418
- 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
+ }
419
581
  return 0;
420
582
  }
421
583
  if (sub === "verify") {
422
- const id = rest[0];
423
- if (!id)
424
- 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;
425
593
  const res = noExec
426
- ? await agent.tasks.buildVerify(id)
427
- : await agent.tasks.verifyAndExecute(id);
594
+ ? await agent.tasks.buildVerify(id, attemptId ? { attemptId } : undefined)
595
+ : await agent.tasks.verifyAndExecute(id, verifyOpts);
428
596
  writeOutput(stdout, jsonMode, res);
429
597
  return 0;
430
598
  }
@@ -448,7 +616,19 @@ export async function runSwarmCli(argv, io = {}) {
448
616
  writeOutput(stdout, jsonMode, res);
449
617
  return 0;
450
618
  }
451
- throw new CliUsageError("Usage: swarm tasks <list|get|mine|earnings|onboard|next|claim|submit|verify|finalize|expire> ...");
619
+ throw new CliUsageError("Usage: swarm tasks <list|get|init|check|mine|earnings|onboard|next|claim|submit|verify|finalize|expire> ...");
620
+ }
621
+ if (cmd === "proofs") {
622
+ if (sub === "list" || !sub) {
623
+ const res = await agent.proofs.list({
624
+ network,
625
+ limit: getIntFlag(flags, "--limit"),
626
+ policy: getIntFlag(flags, "--policy"),
627
+ });
628
+ writeOutput(stdout, jsonMode, res);
629
+ return 0;
630
+ }
631
+ throw new CliUsageError("Usage: swarm proofs list [--limit N] [--policy N]");
452
632
  }
453
633
  if (cmd === "inbox") {
454
634
  if (sub === "list") {
package/dist/index.d.ts CHANGED
@@ -3,10 +3,10 @@ export { CLIENT_VERSION } from "./version.js";
3
3
  export declare const CLIENT_MANIFEST_SCHEMA: "swarm.client-manifest/v1";
4
4
  export { SwarmClientError, TransactionMismatchError } from "./errors.js";
5
5
  export type { SwarmClientErrorCode, SwarmClientErrorOptions } from "./errors.js";
6
- export { DEFAULT_MAX_NETWORK_FEE_WEI, MIN_SELF_PAID_SOLANA_BALANCE_LAMPORTS, ONBOARD_ADVANCE_LAMPORTS, SwarmAgent, createSwarmAgent, extractCreateEscrowLamports, type ExecuteTaskOptions, type ExecutedTaskResult, type NextTaskAction, type SwarmAgentOptions, type SwarmNetwork, type TaskLifecycleStep, } from "./agent.js";
6
+ export { DEFAULT_MAX_NETWORK_FEE_WEI, MIN_SELF_PAID_SOLANA_BALANCE_LAMPORTS, ONBOARD_ADVANCE_LAMPORTS, SwarmAgent, createSwarmAgent, extractCreateEscrowLamports, type ExecuteTaskOptions, type ExecutedTaskResult, type NextTaskAction, type PreflightTaskOptions, type SwarmAgentOptions, type SwarmNetwork, type TaskLifecycleStep, } from "./agent.js";
7
7
  export { WalletTokenManager, type TokenProvider, type WalletTokenManagerOptions, } from "./auth/token-manager.js";
8
8
  export { fromEvmPrivateKey, fromEvmWalletClient, fromSolanaKeypair, fromSolanaSecretKey, fromSolanaWalletAdapter, redactSigner, type EvmCallRequest, type EvmPrivateKeyOptions, type EvmSwarmSigner, type EvmTransactionSigner, type EvmWalletClientLike, type SolanaSwarmSigner, type SolanaWalletAdapterLike, type SwarmSigner, } from "./signer/index.js";
9
- export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_ESCROW_DEPLOYMENTS, SHILLBOT_EVM_SELECTORS, SHILLBOT_INSTRUCTION_SPECS, buildOnChainActionProofRef, deriveAdvancePda, estimateSolanaNetworkFeeLamports, formatOnChainActionAttributionMessage, normalizeEvmChainId, validateComputeBudgetInstruction, validateComputeBudgetInstructions, validatePreparedEvmCall, validatePreparedTransaction, verifyBuiltTransaction, type AuthoritySlotRule, type BuildOnChainActionProofRefParams, type BuildVerifyOptions, type ExpireTaskState, type PreparedEvmCallExpectation, type PreparedTransactionExpectation, type PreparedTransactionResponse, type ShillbotInstructionName, type ShillbotInstructionSpec, type ValidatedEvmCall, type VerificationDataResponse, type VerifyBuiltTransactionExpectation, } from "./shillbot/api.js";
9
+ export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_ESCROW_DEPLOYMENTS, SHILLBOT_EVM_SELECTORS, SHILLBOT_INSTRUCTION_SPECS, buildOnChainActionProofRef, deriveAdvancePda, estimateSolanaNetworkFeeLamports, formatOnChainActionAttributionMessage, normalizeEvmChainId, validateComputeBudgetInstruction, validateComputeBudgetInstructions, validatePreparedEvmCall, validatePreparedTransaction, verifyBuiltTransaction, type AuthoritySlotRule, type BuildOnChainActionProofRefParams, type BuildVerifyOptions, type BuildVerifyResponse, type ExpireTaskState, type LeanDiagnostic, type LeanEnvironmentInfo, type ListProofsOptions, type PreflightTaskRequest, type PreflightTaskResponse, type PreparedEvmCallExpectation, type PreparedTransactionExpectation, type PreparedTransactionResponse, type ProofLimits, type ProofMetrics, type ProofsLeaderboardEntry, type ProofsResponse, type ShillbotInstructionName, type ShillbotInstructionSpec, type SubmitTaskRequest, type SubmitTaskResponse, type TaskAttemptSummary, type TaskResponse, type ValidatedEvmCall, type VerificationDataResponse, type VerifiedProofRecord, type VerifyBuiltTransactionExpectation, } from "./shillbot/api.js";
10
10
  export { ADVANCE_ACCOUNT_SPACE, EXTENSION_CREDIT_PROGRAM_ID, advanceAccountDiscriminator, advancePda, decodeExtensionCreditAdvance, type DecodedAdvanceAccount, } from "./shillbot/index.js";
11
11
  export { VALID_TOPICS, isValidTopicId, type TopicId, } from "./inbox/types.js";
12
12
  export { DEFAULT_MAX_VOW_BYTES, fetchVowAttestationJson, validateVowUrl, verifyVow, type FetchVowOptions, type VerifyVowOptions, } from "./vow/verify.js";