Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions packages/cli/src/task.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1042,6 +1042,28 @@ describe("vapi task", () => {
expect(result.value!.proposal).toMatchObject({ id: PROPOSAL_ID });
});

it("signs the caller's --duration when the task has none (#143)", async () => {
const { client, dependencies } = await fixture();
const result = await invoke(
["submit", ID, "--proof", "https://example.com/proof", "--duration", "7d"],
dependencies,
);
expect(result.code).toBe(0);
const [, input] = vi.mocked(client.submit).mock.calls[0]!;
if (!("signedPayload" in input)) throw new Error("Expected signed submission");
expect(input.signedPayload.milestones[0]!.workDurationSeconds).toBe(604800);
});

it("refuses --duration with --withdraw and out-of-range durations", async () => {
const { dependencies } = await fixture();
expect((await invoke(["submit", ID, "--withdraw", "--duration", "7d"], dependencies)).code).not.toBe(0);
const short = await invoke(
["submit", ID, "--proof", "https://example.com/proof", "--duration", "5m"],
dependencies,
);
expect(short.code, short.stdout.join(" ") + short.stderr.join(" ")).not.toBe(0);
});

it.each([401, 403])("explains sign-in for participant HTTP %s", async (status) => {
const { dependencies } = await fixture(
true,
Expand Down
19 changes: 17 additions & 2 deletions packages/cli/src/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ export const TASK_HELP = `Usage:
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 submit <id> [--proof <https-url>...] [--file <path>...] [--duration <dur>] [--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]
Expand Down Expand Up @@ -615,7 +615,7 @@ async function taskCommandInner(
: verb === "propose"
? ["--price", "--duration", "--note"]
: verb === "submit"
? ["--proof", "--file", "--proposal-id"]
? ["--proof", "--file", "--proposal-id", "--duration"]
: verb === "thread"
? ["--after"]
: verb === "deliver"
Expand Down Expand Up @@ -985,6 +985,20 @@ async function taskCommandInner(
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 durationText = parsed.one("--duration");
if (parsed.has("--withdraw") && durationText !== undefined)
throw new UsageError("--duration cannot be combined with --withdraw.");
let durationSeconds: number | undefined;
if (durationText !== undefined) {
const duration = parseTaskDuration(durationText, 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.");
durationSeconds = duration / TASK_LIMITS.proposalDurationUnitMs;
}
const proof: SubmissionProof[] = urls.map((url) => {
httpsUrl(url, "--proof");
return { kind: "url", value: url };
Expand All @@ -995,6 +1009,7 @@ async function taskCommandInner(
target = signedIn(context);
const result = await submitTask(context, {
id: id!,
...(durationSeconds === undefined ? {} : { durationSeconds }),
...(parsed.has("--withdraw")
? { withdraw: true, ...(target.address ? { address: target.address } : {}) }
: {}),
Expand Down
115 changes: 115 additions & 0 deletions packages/core/src/tasks/operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1137,3 +1137,118 @@ describe("post-and-fund amount binding", () => {
);
});
});

describe("submission terms for a task without a duration (#143)", () => {
const deployment = {
configured: true as const,
network: "eip155:84532",
usdc: "0x1111111111111111111111111111111111111111",
escrowContract: "0x2222222222222222222222222222222222222222",
};

function setup(taskDuration: number | null) {
let recorded:
| {
signature: `0x${string}`;
signedPayload: { milestones: { workDurationSeconds: number }[] };
}
| undefined;
const fetch = vi.fn<typeof globalThis.fetch>(async (_input, init) => {
recorded = JSON.parse(String(init?.body));
return Response.json({
proposal: {
id: KEY,
workOrderId: ORDER,
providerAddress: worker.address.toLowerCase(),
state: "pending",
signedPayload: recorded!.signedPayload,
signature: recorded!.signature,
signatureHash: HASH,
proposedMilestones: recorded!.signedPayload.milestones,
acceptedAt: null,
createdAt: NOW.toISOString(),
updatedAt: NOW.toISOString(),
},
});
});
const client = Object.assign(createTasksClient({ baseUrl: "https://tasks.example", fetch }), {
getOrder: vi.fn().mockResolvedValue({
workOrder: { id: ORDER, title: "Build an API", description: "Build the public API." },
}),
publicTask: vi.fn().mockResolvedValue({
id: ORDER,
title: "Build an API",
briefFull: "Build the complete public API.",
durationSeconds: taskDuration,
amount: { gross: "1000000" },
}),
deployment: vi.fn().mockResolvedValue(deployment),
});
return { context: { ...operationFixture(), client }, recorded: () => recorded };
}

const unlock = async () => ({
...worker,
signMessage: (message: string) => worker.signMessage({ message }),
});

it("signs the caller's duration when the task has none", async () => {
const { context, recorded } = setup(null);
await submitTask(context, {
id: ORDER,
proof: [{ kind: "url", value: "https://example.com/proof" }],
files: [],
durationSeconds: 3600,
unlock,
});
expect(recorded()!.signedPayload.milestones[0]!.workDurationSeconds).toBe(3600);
});

it("prefers the caller's duration over the task's own", async () => {
const { context, recorded } = setup(172800);
await submitTask(context, {
id: ORDER,
proof: [{ kind: "url", value: "https://example.com/proof" }],
files: [],
durationSeconds: 604800,
unlock,
});
expect(recorded()!.signedPayload.milestones[0]!.workDurationSeconds).toBe(604800);
});

it("keeps the task's duration when the caller passes none", async () => {
const { context, recorded } = setup(172800);
await submitTask(context, {
id: ORDER,
proof: [{ kind: "url", value: "https://example.com/proof" }],
files: [],
unlock,
});
expect(recorded()!.signedPayload.milestones[0]!.workDurationSeconds).toBe(172800);
});

it.each([599, 7_776_001, 3600.5])("refuses an out-of-contract duration (%s)", async (value) => {
const { context } = setup(null);
await expect(
submitTask(context, {
id: ORDER,
proof: [{ kind: "url", value: "https://example.com/proof" }],
files: [],
durationSeconds: value,
unlock,
}),
).rejects.toBeInstanceOf(TaskInputError);
});

it("still names the missing duration when neither side has one", async () => {
const { context } = setup(null);
await expect(
submitTask(context, {
id: ORDER,
proof: [{ kind: "url", value: "https://example.com/proof" }],
files: [],
unlock,
}),
).rejects.toMatchObject({ code: "not_available" });
});
});
27 changes: 19 additions & 8 deletions packages/core/src/tasks/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,9 @@ export async function submitTask(
withdraw?: boolean;
proposalId?: string;
address?: string;
// Signed instead of the task's own duration when the poster created the
// task without one (submissions-intake tasks, issue #143).
durationSeconds?: number;
},
): Promise<SubmitResponse> {
if (input.withdraw) {
Expand Down Expand Up @@ -340,16 +343,24 @@ export async function submitTask(
if (!task) throw new TaskOperationError("not_found", `Task ${input.id} was not found.`);
if (task.id !== input.id)
throw new TaskOperationError("invalid_response", "The response belongs to a different task.");
const durationSeconds = task.durationSeconds;
if (
durationSeconds === null ||
!Number.isInteger(durationSeconds) ||
durationSeconds < TASK_LIMITS.proposalDurationMinMs / TASK_LIMITS.proposalDurationUnitMs ||
durationSeconds > TASK_LIMITS.proposalDurationMaxMs / TASK_LIMITS.proposalDurationUnitMs
)
const minSeconds = TASK_LIMITS.proposalDurationMinMs / TASK_LIMITS.proposalDurationUnitMs;
const maxSeconds = TASK_LIMITS.proposalDurationMaxMs / TASK_LIMITS.proposalDurationUnitMs;
const usable = (value: number | null | undefined): value is number =>
typeof value === "number" &&
Number.isInteger(value) &&
value >= minSeconds &&
value <= maxSeconds;
if (input.durationSeconds !== undefined && !usable(input.durationSeconds))
throw new TaskInputError(
"durationSeconds must be whole seconds between 10 minutes and 90 days.",
);
// The worker's own duration wins: a task created without one is submittable
// when the caller signs terms with a duration they chose.
const durationSeconds = input.durationSeconds ?? task.durationSeconds;
if (!usable(durationSeconds))
throw new TaskOperationError(
"not_available",
"The task needs a duration between 10 minutes and 90 days for signed submission terms.",
"The task has no duration between 10 minutes and 90 days for signed submission terms; sign your own with durationSeconds.",
);
const deployment = await taskRequest(
"submit",
Expand Down
17 changes: 16 additions & 1 deletion packages/mcp/src/tools/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,10 +296,11 @@ export const tasksProposeTool = descriptor(
},
);
export const tasksSubmitTool = descriptor(
"Does not move money. Sign task submission terms locally with HTTPS proof and optional local files, or withdraw an existing bounty submission without a signature.",
"Does not move money. Sign task submission terms locally with HTTPS proof and optional local files, or withdraw an existing bounty submission without a signature. Pass duration when the task was created without one.",
{
...participant,
proofUrls: z.array(httpsUrl).min(1).optional(),
duration: z.string().min(1).optional(),
withdraw: z.boolean().optional(),
proposalId: id.optional(),
files: z.array(localPath).optional(),
Expand Down Expand Up @@ -1033,11 +1034,25 @@ export function createTasksTools(options: TasksToolsOptions) {
throw new TaskInputError("submit needs proofUrls or withdraw:true.");
if (!input.withdraw && input.proposalId)
throw new TaskInputError("proposalId requires withdraw:true.");
if (input.withdraw && input.duration !== undefined)
throw new TaskInputError("duration cannot be combined with withdraw:true.");
let durationSeconds: number | undefined;
if (input.duration !== undefined) {
const duration = parseTaskDuration(input.duration, now());
if (
duration < TASK_LIMITS.proposalDurationMinMs ||
duration > TASK_LIMITS.proposalDurationMaxMs ||
duration % TASK_LIMITS.proposalDurationUnitMs !== 0
)
throw new TaskInputError("duration must be whole seconds between 10 minutes and 90 days.");
durationSeconds = duration / TASK_LIMITS.proposalDurationUnitMs;
}
const files = await Promise.all((input.files ?? []).map(readTaskFile));
const ctx = await acting(input.wallet);
return taskResult(
await submitTask(ctx, {
id: input.id,
...(durationSeconds === undefined ? {} : { durationSeconds }),
...(input.withdraw
? {
withdraw: true,
Expand Down