Repository navigation
Expand file tree
/
Copy pathtask.ts
More file actions
1917 lines (1879 loc) · 74.5 KB
/
Copy pathtask.ts
File metadata and controls
1917 lines (1879 loc) · 74.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import { getVapiPaths, KeystoreError, loadConfig, spendCapsForWallet } from "@vapi-network/core";
import {
executeTaskV2,
taskUsesV2,
taskV2PreparedSchema,
autoReleaseDecision,
awardTask,
cachedMoneyClient,
createScopeBindings,
createPendingTransactions,
createTasksChain,
createTasksRpcFor,
readTaskV2Limits,
type TaskV2LimitsReader,
deliverTaskOperation,
disputeTaskOperation,
counterEvidenceTaskOperation,
resolveUnmatchedTaskOperation,
fundTaskOperation,
fundTaskWithX402,
requireTaskMethod,
formatBaseUnitsUsd,
isTaskUsdcAsset,
messageTask,
questionsTask,
askTask,
answerTask,
replyTask,
askTaskInputSchema,
answerTaskInputSchema,
replyTaskInputSchema,
missingTasksChain,
nextTaskEvents,
parseTaskDuration as parseCoreTaskDuration,
parseUsdToBaseUnits,
postTask,
POOL_OPEN_CHECKS,
type PoolClaimsResponse,
prepareTaskPost,
parseTaskMilestone,
parseTaskProof,
checkinInputSchema,
taskEventLine,
proposeTask,
publicNotFoundFetch,
readTaskFile as readCoreTaskFile,
refundTaskOperation,
releaseTask,
releaseTaskOperation,
safeTasksChainError,
resolveTaskBearer,
searchTasks,
showTask,
signTaskScope,
submitTask,
taskEventState,
taskMoney,
taskFeeReservationKey,
taskMoneySnapshot,
taskPolicyForWallet,
taskRequest as coreTaskRequest,
taskStateMatches,
taskStatus,
threadTask,
waitForMilestone,
TASK_LIMITS,
TASK_WATCH_STATES,
TASKS_CLIENT_VERBS,
TaskInputError,
TaskOperationError,
TasksScopeCreationError,
TasksChainError,
type TasksChain,
type TasksClient,
type TasksClientOptions,
type PendingTransactions,
type SubmissionProof,
type UploadFileInput,
type CreateOrderInput,
type TaskMoney,
type TaskQuestion,
type SignedScopeTerms,
validTaskBrief,
} from "@vapi-network/core/tasks";
import {
TASK_V2_JURY_RULES,
TASK_V2_REVIEWER_GUIDANCE,
taskV2OutcomeLines,
normalizeTaskV2Outcomes,
} from "@vapi-network/core/tasks";
import { createHostedTasksClient, registeredAgentProfileSchema } from "@vapi-network/mcp";
import {
getEnvironment,
getLinePrompt,
getSecretStore,
parseArguments,
registryBaseUrl,
targetWallet,
unlockTarget,
UsageError,
type CliDependencies,
type CliIo,
type WalletTarget,
} from "./cli.js";
import { commandFetch } from "./cli-context.js";
import { taskV2Command } from "./task-v2.js";
import { TASK_JURY_VERBS, taskJuryCommand } from "./task-jury.js";
import {
TASK_PROVIDER_OPTIONS,
TASK_PROVIDER_VERBS,
taskProviderCommand,
} from "./task-provider.js";
export type TasksCommandDependencies = {
client?: TasksClient | ((options: TasksClientOptions) => TasksClient);
chain?: TasksChain;
sleep?: (milliseconds: number) => Promise<void>;
randomUUID?: () => string;
/** Read-only RPC for reviewer-status; defaults to the configured Tasks RPC. */
rpcFor?: (chainId: number) => import("viem").PublicClient;
};
export const TASK_HELP = `Usage:
vapi task search [--open] [--min <usd>] [--tab trending|new|closing|paid] [--limit <n>] [--json]
vapi task show <id> [--account <name>] [--json]
vapi task pending [--account <name>] [--json]
vapi task checkin <id> --status on-track|blocked|need-input [--note <text>] [--link <url>] [--account <name>] [--json]
vapi task post --title <text> --brief <file|-> --deadline <duration|ISO> [--shape task|bounty|pool] [--amount <usd>] [--milestone "amount|acceptance|deadline"...] [--proof <preset>[:mustContain]...] [--checkin none|6h|24h|72h|7d] [--winners <n> --reward-per-winner <usd> --choice-window <sec>] [--reward-per-claim <usd> --budget <usd> --gate open|proven --verifier poster|vapi --open-check allowlist|invite|vapi-id] [--fund] [--yes] [--no-wait] [--timeout 120s] [--intake proposals|submissions] [--max-awards <k>] [--webhook <https-url>] [--account <name>] [--json]
vapi task profile [--name <text> --bio <file|-> --skill <text>...] [--language <name>...] [--location <text>] [--photo <path>|--remove-photo] [--account <name>] [--json]
vapi task offer [<offerId>] [--title <text>] [--description <file|->] [--package <tier>:<usd>:<time>:<summary>...] [--category general-digital|software-api|research-data|design-content] [--skill <tag>...] [--pause|--resume] [--account <name>] [--json]
vapi task propose <id> --price <usd> --duration <duration> --note <text> [--account <name>] [--json]
vapi task submit <id> [--proof <https-url>...] [--file <path>...] [--withdraw] [--proposal-id <id>] [--account <name>] [--json]
vapi task milestone <id> --index N submit|approve|reject|finalize|close-rejected [--proof <https-url>...] [--file <path>...] [--proof-json <file>] [--note <text>] [--reason <text>] [--json]
vapi task cancel <id> offer|remainder|expire|pool [--json]
vapi task claim <id> --claimant <addr> [--json]
vapi task pool-claims <id> [--account <name>] [--json]
vapi task award <id> [<proposalId>|--worker <addr>|--winners a,b,c] [--account <name>] [--json]
vapi task sign <id> [--action award-consent|split-consent|bump-consent-nonce --index N --to-worker <base-units> --new-nonce N] [--yes] [--no-wait] [--timeout 120s] [--counterparty <0x…>] [--account <name>] [--json]
vapi task fund <id> [--yes] [--no-wait] [--timeout 120s] [--counterparty <0x…>] [--account <name>] [--json]
vapi task deliver <id> --files <path...> --note <text> [--no-wait] [--timeout 120s] [--counterparty <0x…>] [--account <name>] [--json]
vapi task release <id> [--no-wait] [--timeout 120s] [--counterparty <0x…>] [--account <name>] [--json]
vapi task refund <id> [--counterparty <0x…>] [--account <name>] [--json]
vapi task dispute <id> [--evidence-hash <0x + 64 hex>|--index N --evidence <text>] [--action raise|resolve-unmatched|split --to-worker <base-units>] [--yes] [--counterparty <0x…>] [--account <name>] [--json]
vapi task counter-evidence <id> [--evidence-hash <0x + 64 hex>|--index N --evidence <text>] [--yes] [--counterparty <0x…>] [--account <name>] [--json]
vapi task resolve-unmatched <id> [--index N] [--counterparty <0x…>] [--account <name>] [--json]
vapi task close-rejected <id> --index N [--account <name>] [--json]
vapi task bump-consent-nonce <id> --new-nonce N [--account <name>] [--json]
vapi task prune-reviewer <id> --reviewer <address> [--account <name>] [--json]
vapi task prune-reviewers <id> --reviewers a,b,c [--account <name>] [--json]
vapi task jury <id> --index N --step open|draw|rearm|resolve [--account <name>] [--json]
vapi task vote <id> --index N (--commit worker|poster|split [--to-worker <base-units>] | --reveal) [--account <name>] [--json]
vapi task approve-bond <id> [--yes] [--account <name>] [--json]
vapi task claim-owed <id> [--to <0x…>] [--account <name>] [--json]
vapi task reviewer-status [--address <0x…>] [--account <name>] [--json]
vapi task message <id> <text> [--account <name>] [--json]
vapi task thread <id> [--after <cursor>] [--account <name>] [--json]
vapi task questions <id> [--account <name>] [--json]
vapi task ask <id> <text> [--question-id <uuid>] [--account <name>] [--json]
vapi task answer <id> <questionId> <text> [--account <name>] [--json]
vapi task reply <id> <questionId> <text> [--parent <replyId>] [--account <name>] [--json]
vapi task watch <id> [--until <state>] [--auto-release] [--timeout 7d] [--interval 5s] [--counterparty <0x…>] [--account <name>] [--json]
vapi task status <id> [--operation <uuid> --step <v2-step> --recover|--abandon] [--account <name>] [--json]
Durations: 5s, 10m, 48h, 7d, or an ISO-8601 timestamp. A task deadline and every task milestone deadline must be at least 3 hours ahead when vAPI receives the post (one hour of work time, one to award, one to fund); use 181m or more. Bounty and pool posting and proposal terms require at least 10 minutes.
V1 dispute accepts a precomputed evidence hash. V2 dispute accepts --index with --evidence text. Milestone action indices are zero-based; declared milestone indices remain one-based.
Jury: ${TASK_V2_JURY_RULES} ${TASK_V2_REVIEWER_GUIDANCE} Jury open repeats while the case is Snapshotting.
Vote --commit seals the salt in a local ballot under VAPI_HOME before vAPI sees the commitment; --reveal reads that ballot back by the onchain commitment, so reveal from the machine that committed. --to-worker is USDC base units and only for split.
Watch requires an interval of at least 1s and a positive timeout. Auto-release uses the acting wallet's agent profile, or defaults, and releases only amounts strictly below the threshold.
Posting without --fund moves no money. --fund applies task and daily caps before signing. Fund, post --fund, approve-bond, sign --action award-consent and award --worker need vAPI to report Tasks as available and stop before signing when it does not; a rerun of an operation that already signed something is resumed instead. Show or raise task limits with vapi accounts caps <name> [--max-per-task <usd>] [--approve-above <usd>].
Base mainnet runs V2 only: the worker runs sign --action award-consent, then the poster runs award --worker <addr>. propose sends an offer the poster can read. award <proposalId> and sign without --action are V1 only. Task reads require tasks:read and writes require tasks:write; write access includes reads.
Provider: profile without options shows your provider profile, its services, and its verification status with the three checks vAPI runs. The first run needs --name, --bio and at least one --skill. Later runs change --bio, --language (up to 5), --location or the photo (--photo takes a PNG, JPEG or WebP image of at most 5 MB). The name and skills of a live profile cannot be changed from here yet. A new profile is live at once and vAPI reviews every unverified provider for the Verified badge on its own, so there is nothing to request.
offer without options lists your services. With --title, --description and one to three --package values it publishes a service on the network vAPI reports; offer <offerId> changes the given fields, and --pause or --resume hides or shows it. A package is tier:usd:delivery time:summary with tier starter, standard or advanced, delivery time from 1h to 90d (90m, 48h, 7d), and a summary of 10 to 160 characters, for example starter:150:3d:One landing page with copy. --category defaults to general-digital. Profile and offer move no money; a buyer funds escrow only when they hire.
The thread cursor is the previous page's nextBeforeSeq; --after reads older messages using beforeSeq.
Every command accepts --json. Watch and a partially completed sign may write more than one JSON value. Human diagnostics go to stderr.
Exit codes:
0 ok
1 error, including invalid usage, unavailable routes and chain failures
2 policy refusal only (JSON ok:false with reason policy.perTask or policy.perDay)
3 approval needed in non-interactive mode
Fund, deliver, release, refund, dispute, counter-evidence, resolve-unmatched and watch auto-release sign with the local vault wallet. The CLI waits for two confirmations and records pending transactions for recovery. It never retries a chain mutation automatically. Sign, fund, deliver and release wait up to 120s for vAPI to index a confirmed transaction unless --no-wait is set; an indexing timeout keeps exit code 0.`;
const IMPLEMENTED_VERBS = TASKS_CLIENT_VERBS;
const USAGE = `Usage: vapi task <${IMPLEMENTED_VERBS.join("|")}>. Run vapi task --help.`;
type Parsed = ReturnType<typeof parseArguments>;
type TaskRoute = keyof TasksClient;
export class TaskCommandError extends Error {
constructor(
readonly code: string,
message: string,
readonly manifestHash?: `0x${string}`,
readonly prefixCode = false,
readonly details?: Record<string, unknown>,
) {
super(message);
this.name = "TaskCommandError";
}
}
function mapTaskError(error: unknown): unknown {
if (error instanceof TaskInputError) return new UsageError(error.message);
if (error instanceof TaskOperationError) {
const retryAfter = error.details?.retryAfter;
const hint =
typeof retryAfter !== "string" || !retryAfter
? ""
: /^\d+$/u.test(retryAfter)
? ` Retry after ${retryAfter} seconds.`
: ` Retry-After: ${terminalText(retryAfter)}.`;
return new TaskCommandError(
error.code,
error.message + hint,
error.manifestHash,
true,
error.details,
);
}
return error;
}
async function mapped<T>(operation: () => Promise<T>): Promise<T> {
try {
return await operation();
} catch (error) {
throw mapTaskError(error);
}
}
/** Relative milliseconds; timestamps are measured from the supplied clock. */
export function parseTaskDuration(text: string, now: Date): number {
try {
return parseCoreTaskDuration(text, now);
} catch (error) {
throw mapTaskError(error);
}
}
export type TaskContext = {
client: TasksClient;
limitsV2?: TaskV2LimitsReader;
chain: TasksChain;
pending?: PendingTransactions;
baseUrl: string;
target?: WalletTarget;
token?: string;
randomUUID: () => string;
sleep: (milliseconds: number) => Promise<void>;
signInHint: string;
};
function lazyTasksChain(
factory: () => Promise<TasksChain>,
pending: PendingTransactions,
signingAddress?: SignedScopeTerms["self"],
): TasksChain {
let chain: Promise<TasksChain> | undefined;
const get = () =>
(chain ??= factory().catch((error: unknown) => {
if (error instanceof TasksChainError) throw error;
throw safeTasksChainError(error, false, false);
}));
async function feeChain(
action: "dispute" | "counter-evidence",
input: Parameters<TasksChain["dispute"]>[0],
) {
let initialized: TasksChain;
try {
initialized = await get();
} catch (error) {
let exposed = true;
try {
exposed = await pending.exposure(taskFeeReservationKey(input.escrowId, action));
} catch {
/* A failed read cannot prove rollback is safe. */
}
throw safeTasksChainError(
error,
error instanceof TasksChainError && error.broadcast,
exposed,
);
}
return action === "dispute" ? initialized.dispute(input) : initialized.counterEvidence(input);
}
async function juryV2() {
const initialized = await get();
if (!initialized.juryV2)
throw new TaskOperationError("chain_unavailable", "Local jury signing is unavailable.");
return initialized.juryV2;
}
return {
available: true,
executeV2: async (input) => {
const initialized = await get();
if (!initialized.executeV2)
throw new TaskOperationError("chain_unavailable", "V2 signing is unavailable.");
return initialized.executeV2(input);
},
juryV2: {
caseState: async (input) => (await juryV2()).caseState(input),
assertJuryOpenable: async (input) => (await juryV2()).assertJuryOpenable(input),
sealBallot: async (input) => (await juryV2()).sealBallot(input),
openBallot: async (input) => (await juryV2()).openBallot(input),
assertSealedCase: async (input) => (await juryV2()).assertSealedCase(input),
},
...(signingAddress === undefined ? {} : { signingAddress }),
getSigningAddress: async () => {
const initialized = await get();
const address = initialized.signingAddress ?? (await initialized.getSigningAddress?.());
if (!address)
throw new TasksChainError(
"A local signing wallet is required for accepted scope recovery.",
false,
{ authorizationExposed: false },
);
return address;
},
createEscrow: async (input) => (await get()).createEscrow(input),
validateFunding: async (input) => {
const initialized = await get();
if (!initialized.validateFunding)
throw new TasksChainError("Local funding verification is unavailable.", false, {
authorizationExposed: false,
});
return initialized.validateFunding(input);
},
fundingAuthorizationState: async (input) => {
const initialized = await get();
if (!initialized.fundingAuthorizationState)
throw new TasksChainError("Authorization state verification is unavailable.", false, {
authorizationExposed: false,
});
return initialized.fundingAuthorizationState(input);
},
fund: async (input) => {
let initialized: TasksChain;
try {
initialized = await get();
} catch (error) {
let exposed = true;
try {
exposed = await pending.exposure(input.escrowId);
} catch {
// A failed exposure read cannot prove rollback is safe.
}
throw safeTasksChainError(
error,
error instanceof TasksChainError && error.broadcast,
exposed,
);
}
return initialized.fund(input);
},
deliver: async (input) => (await get()).deliver(input),
release: async (input) => (await get()).release(input),
refund: async (input) => (await get()).refund(input),
dispute: async (input) => feeChain("dispute", input),
disputeFee: async (input) => (await get()).disputeFee(input),
counterEvidence: async (input) => feeChain("counter-evidence", input),
resolveUnmatched: async (input) => (await get()).resolveUnmatched(input),
bindScope: async (binding) => (await get()).bindScope?.(binding),
signScopeMessage: async (message) => (await get()).signScopeMessage(message),
};
}
/** Reuses wallet selection, registry configuration and device-link credentials. */
export async function taskContext(
parsed: Parsed,
io: CliIo,
dependencies: CliDependencies,
publicOnly = false,
): Promise<TaskContext> {
const env = getEnvironment(dependencies);
const config = await loadConfig(getVapiPaths().config, env, { notice: io.stderr });
const baseUrl = registryBaseUrl(config);
const fetchImpl = commandFetch(dependencies, config);
let target: WalletTarget | undefined;
try {
target = await targetWallet(parsed, dependencies);
} catch (error) {
if (!(
error instanceof KeystoreError &&
error.message === "No wallet yet. Run vapi init." &&
parsed.one("--wallet") === undefined &&
!env.VAPI_WALLET?.trim()
))
throw error;
}
const token =
publicOnly || target === undefined
? undefined
: await mapped(() =>
resolveTaskBearer({
secrets: getSecretStore(dependencies),
wallets: target.store as unknown as Parameters<typeof resolveTaskBearer>[0]["wallets"],
wallet: target.name,
baseUrl,
signInHint: "Run vapi login for this server.",
fetchImpl,
...(dependencies.now === undefined ? {} : { now: () => dependencies.now!().getTime() }),
}),
);
const options: TasksClientOptions = {
baseUrl,
...(token === undefined ? {} : { token }),
fetch: publicNotFoundFetch(fetchImpl, baseUrl),
};
const injected = dependencies.tasks?.client;
const client =
typeof injected === "function"
? injected(options)
: (injected ?? createHostedTasksClient(options));
const pending = createPendingTransactions(getVapiPaths().directory);
const readRpcFor =
dependencies.tasks?.rpcFor ??
createTasksRpcFor(config, {
env,
...(dependencies.fetchImpl === undefined ? {} : { fetch: dependencies.fetchImpl }),
});
const chain =
dependencies.tasks?.chain ??
(publicOnly || target === undefined
? missingTasksChain
: lazyTasksChain(
async () => {
const { account } = await unlockTarget(target, dependencies);
return createTasksChain({
client,
account,
trustedFactories: config.tasksEscrowFactoryOverrides,
env,
onV2UntrustedOverride: io.stderr,
trustedDurations: config.tasksEscrowDurationOverrides,
bindings: createScopeBindings(getVapiPaths().directory),
ballotsHome: getVapiPaths().directory,
rpcFor: createTasksRpcFor(config, {
env,
...(dependencies.fetchImpl === undefined ? {} : { fetch: dependencies.fetchImpl }),
}),
pending,
...(dependencies.now === undefined ? {} : { now: dependencies.now }),
...(dependencies.tasks?.sleep === undefined
? {}
: { sleep: dependencies.tasks.sleep }),
});
},
pending,
target.address as SignedScopeTerms["self"],
));
return {
client,
limitsV2: (chainId, shape) => readTaskV2Limits({ chainId, shape, rpcFor: readRpcFor, env }),
baseUrl,
...(target === undefined ? {} : { target }),
...(token === undefined ? {} : { token }),
chain,
pending,
randomUUID: dependencies.tasks?.randomUUID ?? randomUUID,
signInHint: "Run vapi login for the acting wallet.",
sleep:
dependencies.tasks?.sleep ??
((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds))),
};
}
export async function taskRequest<T>(
verb: string,
route: TaskRoute,
operation: () => Promise<T>,
): Promise<T> {
return await mapped(() =>
coreTaskRequest(verb, route, operation, {
signInHint: "Run vapi login for the acting wallet.",
}),
);
}
export function taskOutput(
io: CliIo,
json: boolean,
context: TaskContext,
verb: string,
value: object,
lines: string[],
): void {
value = normalizeTaskV2Outcomes(value);
lines = [...lines, ...taskV2OutcomeLines(value)];
if (json) {
io.stdout(
JSON.stringify({
command: `task ${verb}`,
...(context.target === undefined ? {} : { wallet: context.target.name }),
...value,
}),
);
return;
}
if (context.target)
io.stdout(
`Wallet: ${context.target.name}${context.target.address ? ` (${context.target.address})` : ""}`,
);
for (const line of lines) io.stdout(line);
}
export function signedIn(context: TaskContext): WalletTarget {
if (!context.token || !context.target)
throw new TaskCommandError(
"not_signed_in",
"Sign-in is needed for the acting wallet. Run vapi login.",
);
return context.target;
}
export async function taskCommand(
argv: string[],
json: boolean,
io: CliIo,
dependencies: CliDependencies,
): Promise<number | undefined> {
return await mapped(() => taskCommandInner(argv, json, io, dependencies));
}
async function taskCommandInner(
argv: string[],
json: boolean,
io: CliIo,
dependencies: CliDependencies,
): Promise<number | undefined> {
const verb = argv[0];
if (verb === "--help" || verb === "help") {
if (argv.length !== 1) throw new UsageError("Usage: vapi task --help.");
io.stdout(json ? JSON.stringify({ command: "task help", help: TASK_HELP }) : TASK_HELP);
return;
}
if (!IMPLEMENTED_VERBS.includes(verb as (typeof IMPLEMENTED_VERBS)[number]))
throw new UsageError(USAGE);
const now = dependencies.now?.() ?? new Date();
const commandArguments = verb === "deliver" ? expandDeliveryFiles(argv.slice(1)) : argv.slice(1);
const parsed = parseArguments(commandArguments, {
valueOptions: new Set([
"--wallet",
...(verb === "ask" ? ["--question-id"] : []),
...(verb === "reply" ? ["--parent"] : []),
...([
"milestone",
"dispute",
"counter-evidence",
"resolve-unmatched",
"close-rejected",
"sign",
].includes(verb!)
? ["--index"]
: []),
...(verb === "jury" ? ["--index", "--step"] : []),
...(verb === "vote" ? ["--index", "--commit", "--to-worker"] : []),
...(verb === "claim-owed" ? ["--to"] : []),
...(["bump-consent-nonce", "sign"].includes(verb!) ? ["--new-nonce"] : []),
...(verb === "prune-reviewer" ? ["--reviewer"] : []),
...(verb === "prune-reviewers" ? ["--reviewers"] : []),
...(verb === "reviewer-status" ? ["--address"] : []),
...(verb === "profile" || verb === "offer" ? TASK_PROVIDER_OPTIONS[verb].value : []),
...(verb === "milestone"
? ["--reason", "--proof", "--file", "--files", "--note", "--proof-json"]
: []),
...(verb === "award" ? ["--worker", "--winners"] : []),
...(["sign", "dispute"].includes(verb!) ? ["--action", "--to-worker"] : []),
...(["dispute", "counter-evidence"].includes(verb!) ? ["--evidence"] : []),
...(verb === "claim" ? ["--claimant"] : []),
...(verb === "status" ? ["--operation", "--step"] : []),
...([
"sign",
"fund",
"deliver",
"release",
"refund",
"dispute",
"counter-evidence",
"resolve-unmatched",
"watch",
].includes(verb!)
? ["--counterparty"]
: []),
...(verb === "search"
? ["--min", "--tab", "--limit"]
: verb === "post"
? [
"--title",
"--brief",
"--amount",
"--deadline",
"--intake",
"--max-awards",
"--webhook",
"--shape",
"--milestone",
"--proof",
"--checkin",
"--winners",
"--reward-per-winner",
"--choice-window",
"--reward-per-claim",
"--budget",
"--gate",
"--verifier",
"--open-check",
"--timeout",
]
: verb === "checkin"
? ["--status", "--note", "--link"]
: verb === "propose"
? ["--price", "--duration", "--note"]
: verb === "submit"
? ["--proof", "--file", "--proposal-id"]
: verb === "thread"
? ["--after"]
: verb === "deliver"
? ["--files", "--note"]
: ["dispute", "counter-evidence"].includes(verb!)
? ["--evidence-hash"]
: verb === "watch"
? ["--until", "--timeout", "--interval"]
: []),
...(["sign", "fund", "deliver", "release"].includes(verb!) ? ["--timeout"] : []),
]),
booleanOptions: new Set([
...(verb === "search" ? ["--open"] : []),
...(verb === "status" ? ["--abandon", "--recover"] : []),
...(verb === "release" ? ["--finalize"] : []),
...(["milestone", "cancel", "award", "claim"].includes(verb!) ? ["--yes"] : []),
...(verb === "post" ? ["--fund", "--yes", "--no-wait"] : []),
...(verb === "submit" ? ["--withdraw"] : []),
...(["sign", "fund", "dispute", "counter-evidence"].includes(verb!) ? ["--yes"] : []),
...(["sign", "fund", "deliver", "release"].includes(verb!) ? ["--no-wait"] : []),
...(verb === "watch" ? ["--auto-release"] : []),
...(verb === "vote" ? ["--reveal"] : []),
...(verb === "approve-bond" ? ["--yes"] : []),
...(verb === "profile" || verb === "offer" ? TASK_PROVIDER_OPTIONS[verb].boolean : []),
]),
repeatableOptions: new Set([
...(["submit", "milestone"].includes(verb!) ? ["--proof", "--file"] : []),
...(verb === "milestone" ? ["--files"] : []),
...(verb === "deliver" ? ["--files"] : []),
...(verb === "post" ? ["--milestone", "--proof"] : []),
...(verb === "profile" || verb === "offer" ? TASK_PROVIDER_OPTIONS[verb].repeatable : []),
]),
maximumPositionals: ["search", "post", "pending", "reviewer-status", "profile"].includes(verb!)
? 0
: ["answer", "reply"].includes(verb!)
? 3
: ["award", "ask", "message", "milestone", "cancel"].includes(verb!)
? 2
: 1,
});
if ((TASK_PROVIDER_VERBS as readonly string[]).includes(verb!))
return await taskProviderCommand(
verb as (typeof TASK_PROVIDER_VERBS)[number],
parsed,
json,
io,
dependencies,
readProcessStdin,
);
const id = ["search", "post", "pending", "reviewer-status"].includes(verb!)
? undefined
: taskId(parsed.positionals[0]);
if ((TASK_JURY_VERBS as readonly string[]).includes(verb!))
return await taskJuryCommand(
verb as (typeof TASK_JURY_VERBS)[number],
id,
parsed,
json,
io,
dependencies,
);
if (id !== undefined) {
const v2 = await taskV2Command(verb!, id, parsed, json, io, dependencies);
if (v2 !== null) return v2;
}
if (
[
"sign",
"fund",
"deliver",
"release",
"refund",
"dispute",
"counter-evidence",
"resolve-unmatched",
"watch",
].includes(verb!)
) {
return await escrowTaskCommand(verb!, id!, parsed, json, io, dependencies, now);
}
if (verb === "search") {
const tab = parsed.one("--tab");
if (tab !== undefined && !(TASK_LIMITS.searchTabs as readonly string[]).includes(tab))
throw new UsageError("--tab must be trending, new, closing or paid.");
const limit = optionalInteger(parsed.one("--limit"), "--limit");
const min =
parsed.one("--min") === undefined ? undefined : usd(parsed.one("--min")!, "--min", true);
const context = await taskContext(parsed, io, dependencies, true);
const board = await searchTasks(context, {
...(tab === undefined ? {} : { tab: tab as (typeof TASK_LIMITS.searchTabs)[number] }),
...(limit === undefined ? {} : { limit }),
...(parsed.has("--open") ? { open: true } : {}),
...(min === undefined ? {} : { min }),
});
const { cards, pinned } = board;
taskOutput(io, json, context, verb, { ...board, cards, pinned }, [
...(pinned ? [`Pinned task: ${pinned.id} · ${pinned.title}`] : []),
...cards.map(
(task) =>
`${task.id} · ${task.title} · ${task.amount === null ? "amount unavailable" : taskMoney(task.amount.gross, task.amount.feeBp).line} · ${task.state}`,
),
...(cards.length || pinned ? [] : ["No tasks found."]),
]);
return;
}
if (verb === "post") {
if (parsed.has("--fund") && parseTaskDuration(parsed.one("--timeout") ?? "120s", now) <= 0)
throw new UsageError("--timeout must be positive.");
const title = required(parsed, "--title"),
briefPath = required(parsed, "--brief");
const prepared = prepareTaskPost(
{
shape: enumOption(parsed.one("--shape"), ["task", "bounty", "pool"], "--shape"),
amountUsd: parsed.one("--amount"),
deadline: required(parsed, "--deadline"),
...(parsed.many("--milestone").length
? {
milestones: parsed
.many("--milestone")
.map((value, index) => parseTaskMilestone(value, index + 1, now)),
}
: {}),
...(parsed.many("--proof").length
? { proofSpec: parsed.many("--proof").map(parseTaskProof) }
: {}),
checkin: enumOption(
parsed.one("--checkin"),
["none", "6h", "24h", "72h", "7d"],
"--checkin",
),
winners: optionalInteger(parsed.one("--winners"), "--winners"),
rewardPerWinner: parsed.one("--reward-per-winner"),
choiceWindowSeconds: optionalInteger(parsed.one("--choice-window"), "--choice-window"),
rewardPerClaim: parsed.one("--reward-per-claim"),
budget: parsed.one("--budget"),
gate: enumOption(parsed.one("--gate"), ["open", "proven"], "--gate"),
verifier: enumOption(parsed.one("--verifier"), ["poster", "vapi"], "--verifier"),
openCheck: enumOption(parsed.one("--open-check"), POOL_OPEN_CHECKS, "--open-check"),
intake: enumOption(parsed.one("--intake"), ["proposals", "submissions"], "--intake"),
},
now,
);
const { amount, deadlineAt } = prepared;
const intake = parsed.one("--intake");
if (intake !== undefined && !["proposals", "submissions"].includes(intake))
throw new UsageError("--intake must be proposals or submissions.");
const maxAwards = optionalInteger(parsed.one("--max-awards"), "--max-awards");
if (maxAwards !== undefined && maxAwards > TASK_LIMITS.maxAwardsMax)
throw new UsageError("--max-awards must be between 1 and 50.");
if (parsed.one("--webhook") !== undefined) httpsUrl(parsed.one("--webhook")!, "--webhook");
const brief =
briefPath === "-"
? await (dependencies.readStdin ?? readProcessStdin)()
: await readFile(briefPath, "utf8");
const input: CreateOrderInput = {
title: title.trim(),
description: brief.trim(),
policyFamily: "general-digital",
...(parsed.one("--shape") !== undefined ||
parsed.many("--milestone").length ||
parsed.many("--proof").length ||
parsed.one("--checkin") !== undefined
? prepared.terms
: {}),
};
if (!validTaskBrief(input.title, input.description))
throw new UsageError(
"--title must be 3 to 120 characters and the brief must be 10 to 8000 characters.",
);
const context = await taskContext(parsed, io, dependencies);
signedIn(context);
const outcome = await postTask(context, {
order: input,
amount,
deadlineAt,
...(parsed.has("--fund") ? { fund: true } : {}),
...(intake === undefined ? {} : { intake: intake as "proposals" | "submissions" }),
...(maxAwards === undefined ? {} : { maxAwards }),
...(parsed.one("--webhook") === undefined ? {} : { webhook: parsed.one("--webhook")! }),
onFeeUnavailable: () =>
io.stderr(
"The fee could not be read from the Tasks contract or from vAPI. Funding shows it before anything is signed.",
),
});
if (parsed.has("--fund")) {
if (outcome.funding?.error) {
taskOutput(
io,
json,
context,
verb,
{ ...outcome.result, ok: false, funding: outcome.funding, postingMovesMoney: false },
[
`Posted task ${outcome.result.workOrder.id}.`,
`Funding unavailable: ${outcome.funding.error}.`,
],
);
return 1;
}
try {
const target = signedIn(context);
const policy = await taskPolicyForWallet({
directory: getVapiPaths().directory,
wallet: target.name,
schema: registeredAgentProfileSchema,
warn: io.stderr,
});
const v2Prepared = taskV2PreparedSchema.safeParse(outcome.funding);
if (v2Prepared.success && (await taskUsesV2(context, outcome.result.workOrder.id))) {
const funding = await executeTaskV2(context, {
id: outcome.result.workOrder.id,
write: { action: "fund" },
prepared: v2Prepared.data,
preparationKey: outcome.fundingIdempotencyKey,
expectedGrossBaseUnits: prepared.escrowAmount,
policy,
caps: await spendCapsForWallet(target.store, target.name),
wallet: target.name,
ledgerPath: getVapiPaths().ledger,
approval: { granted: parsed.has("--yes") },
onMoney: (money) => {
io.stderr(money.line);
},
});
taskOutput(
io,
json,
context,
verb,
{
...outcome.result,
...funding,
funding,
postingMovesMoney: funding.ok,
},
[
`Posted task ${outcome.result.workOrder.id}.`,
funding.ok
? "Hosted funding confirmed."
: "Funding requires policy approval or was refused.",
],
);
return funding.ok ? undefined : "approval" in funding ? 3 : 2;
}
const funding = await fundTaskOperation(context, {
fundingIntent: outcome.funding,
expectedGrossBaseUnits: prepared.escrowAmount,
id: outcome.result.workOrder.id,
policy,
caps: await spendCapsForWallet(target.store, target.name),
wallet: target.name,
ledgerPath: getVapiPaths().ledger,
now: dependencies.now ?? (() => new Date()),
approval: { granted: parsed.has("--yes") },
});
const wait = funding.ok
? await waitForTaskIndex(
context,
dependencies,
parsed,
json,
io,
outcome.result.workOrder.id,
funding.result,
"locked",
"funding",
parsed.one("--timeout") ?? "120s",
parseTaskDuration(parsed.one("--timeout") ?? "120s", now),
)
: null;
taskOutput(
io,
json,
context,
verb,
{ ...outcome.result, ...funding, funding, wait, postingMovesMoney: funding.ok },
[
`Posted task ${outcome.result.workOrder.id}.`,
funding.ok
? wait?.reached
? "escrow funded"
: "Funding submitted; waiting for hosted confirmation."
: `Policy: ${funding.policyDecision}.`,
],
);
return funding.ok ? undefined : "reason" in funding ? 2 : "approval" in funding ? 3 : 1;
} catch (error) {
const mapped = mapTaskError(error);
const detail = {
code:
mapped instanceof TaskCommandError
? mapped.code
: mapped instanceof UsageError
? "usage_error"
: "task_error",
message: mapped instanceof Error ? mapped.message : "Task funding failed.",
};
taskOutput(
io,
json,
context,
verb,
{ ...outcome.result, ok: false, error: detail, funding: { state: "unknown" } },
[
`Posted task ${outcome.result.workOrder.id}.`,
`Funding did not complete: ${detail.message}`,
`Check vapi task show ${outcome.result.workOrder.id} before another payment.`,
],
);
return 1;
}
}
taskOutput(
io,
json,
context,
verb,
{
...outcome.result,
money: outcome.money,
postingMovesMoney: false,
unsupportedFields: outcome.unsupportedFields,
},
[
`Posted task ${outcome.result.workOrder.id}.`,
outcome.money.line,
"Posting a task moves no money.",
],
);
return;
}
if (verb === "propose") {
const price = usd(required(parsed, "--price"), "--price");
const duration = parseTaskDuration(required(parsed, "--duration"), now);
if (
duration < TASK_LIMITS.proposalDurationMinMs ||
duration > TASK_LIMITS.proposalDurationMaxMs ||
duration % TASK_LIMITS.proposalDurationUnitMs !== 0
)
throw new UsageError("--duration must be whole seconds between 10 minutes and 90 days.");
const note = required(parsed, "--note").trim();
if (!note || note.length > TASK_LIMITS.proposalNoteMax)
throw new UsageError("--note must be between 1 and 8000 characters.");
const context = await taskContext(parsed, io, dependencies),
target = signedIn(context);
const result = await proposeTask(context, {
id: id!,
price,
durationSeconds: duration / TASK_LIMITS.proposalDurationUnitMs,
note,
unlock: async () => {
const { account } = await unlockTarget(target, dependencies);
return {
address: account.address,
signMessage: (message) => account.signMessage({ message }),
};
},
});
taskOutput(io, json, context, verb, result, [`Proposed terms for task ${id}.`]);
return;
}
if (verb === "submit") {
const urls = parsed.many("--proof");
if (parsed.one("--proposal-id") && !parsed.has("--withdraw"))
throw new UsageError("--proposal-id requires --withdraw.");
if (parsed.has("--withdraw") && (urls.length || parsed.many("--file").length))
throw new UsageError("--withdraw cannot be combined with proof or files.");
if (!parsed.has("--withdraw") && !urls.length)
throw new UsageError("submit needs at least one --proof <https-url>.");
const proof: SubmissionProof[] = urls.map((url) => {
httpsUrl(url, "--proof");
return { kind: "url", value: url };
});
// Check every local file before starting any uploads.
const files = await Promise.all(parsed.many("--file").map(readTaskFile));
const context = await taskContext(parsed, io, dependencies),
target = signedIn(context);
const result = await submitTask(context, {
id: id!,
...(parsed.has("--withdraw")
? { withdraw: true, ...(target.address ? { address: target.address } : {}) }
: {}),