Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 2 additions & 0 deletions docs/architecture/native-request-processing.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ The control plane refuses to exchange an expired grant, so the client renews bef

A run that carries a grant gets seven read tools built on the client: `user_projects_search`, `user_project_get`, `user_runs_list`, `user_conversations_list`, `user_inbox_read`, `user_billing_read` and `user_account_members_list`. Each tool builds a fixed API path from validated input and returns the JSON body. A run without a grant has none of these tools.

The run also gets a tool for each phase 2 capability that the grant names in its `authorization_details`: `user_schedules_list` (`schedules.list`), `user_project_create` (`projects.create`), `user_schedule_set_status` (`schedules.activate` or `schedules.pause`, offering only the statuses the grant carries) and `user_input_request_answer` (`input_requests.answer`). The client decodes the capabilities without verifying the signature, because they only decide which tools exist; the API checks the capability of every call. Each write sends exactly the body that the API admits for its capability, through a client helper that serializes the JSON once before the grant enters the request, so a 401 retry replays the same method and bytes. Its result states what changed and how the person can undo it. An answer carries one `Idempotency-Key`, which the retry keeps. The tool set is built once per run: a renewed grant that drops a capability stops its tool before any call, and a capability that only a renewed grant names waits for the next run. A refusal tells the model that nothing changed and why, without echoing the API body.

The same run resolves the project that a `studio_open_project` or `studio_navigate` call names, as the person, before it forwards the call. Studio receives the project's slug, or its id when it has no slug. A confirmed switch to another project ends the turn and does not re-scope the run. A run without a grant forwards the reference unchanged and continues in the new project. Only a run with a grant sends `x-veryfront-project-references: resolved` on its Studio MCP requests, so Studio skips its own lookup with the run token; the grant itself never goes to Studio.

A runtime that handles the header this way registers with `capabilities: { "delegated_user_token": true }`.
Expand Down
137 changes: 137 additions & 0 deletions src/agent/hosted/delegated-user-credential.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -971,3 +971,140 @@ describe("agent/hosted/delegated-user-credential API client", () => {
},
);
});

describe("agent/hosted/delegated-user-credential JSON writes and capabilities", () => {
it("serializes a JSON write once, before the grant, and replays the same bytes on the 401 retry", async () => {
const api = recordingFetch((call) => {
if (call.url.endsWith("/renew")) return Response.json({ token: RENEWED_TOKEN });
return call.headers.get("authorization") === `Bearer ${RENEWED_TOKEN}`
? Response.json({ ok: true })
: Response.json({}, { status: 401 });
});
const client = createHostedDelegatedUserApiClient(boundRequest(), {
apiBaseUrl: API_URL,
fetch: api.fetch,
})!;
let serialized = 0;
const body = {
toJSON() {
serialized++;
// Runs before any request exists.
assertEquals(api.calls.length, 0);
return { status: "paused" };
},
};
const write = { method: "PATCH" as const, body };
const pending = client.sendJson("/projects/p/schedules/s", write);
(write as { method: string }).method = "POST";
(write as { body: unknown }).body = { status: "active" };
assertEquals((await pending).status, 200);
assertEquals(serialized, 1);
const sent = api.calls.filter((call) => !call.url.endsWith("/renew"));
assertEquals(
sent.map((call) => [
call.method,
call.headers.get("content-type"),
call.headers.get("accept"),
call.body,
]),
[
["PATCH", "application/json", "application/json", '{"status":"paused"}'],
["PATCH", "application/json", "application/json", '{"status":"paused"}'],
],
);
});

it("sends only POST or PATCH, and only a body that serializes to JSON", async () => {
const api = recordingFetch(() => Response.json({}));
const client = createHostedDelegatedUserApiClient(boundRequest(), {
apiBaseUrl: API_URL,
fetch: api.fetch,
})!;
for (const method of ["DELETE", "PUT", "GET", "post", undefined]) {
await assertRejects(
() => client.sendJson("/projects", { method: method as "POST", body: {} }),
TypeError,
"POST or PATCH",
);
}
const cyclic: Record<string, unknown> = {};
cyclic.self = cyclic;
for (const body of [undefined, () => 1, cyclic]) {
await assertRejects(
() => client.sendJson("/projects", { method: "POST", body }),
TypeError,
"not JSON",
);
}
assertEquals(api.calls.length, 0);
});

it("sends an idempotency key on every attempt and refuses an unusable one", async () => {
const api = recordingFetch((call) => {
if (call.url.endsWith("/renew")) return Response.json({ token: RENEWED_TOKEN });
return call.headers.get("authorization") === `Bearer ${RENEWED_TOKEN}`
? Response.json({ ok: true })
: Response.json({}, { status: 401 });
});
const client = createHostedDelegatedUserApiClient(boundRequest(), {
apiBaseUrl: API_URL,
fetch: api.fetch,
})!;
await client.sendJson("/input-requests/r/responses", {
method: "POST",
body: { values: {} },
idempotencyKey: "answer-1",
});
assertEquals(
api.calls.filter((call) => !call.url.endsWith("/renew")).map((call) =>
call.headers.get("idempotency-key")
),
["answer-1", "answer-1"],
);
for (const key of ["", "has space", "x".repeat(256), 7]) {
await assertRejects(
() =>
client.sendJson("/input-requests/r/responses", {
method: "POST",
body: {},
idempotencyKey: key as string,
}),
TypeError,
"idempotency key",
);
}
});

it("reads the capabilities from the grant's authorization details, unverified", async () => {
const grant = (actions: unknown, type = "veryfront_delegated_actions") =>
jwtGrant({
exp: Math.floor(Date.now() / 1000) + 900,
authorization_details: [{ type, actions }],
});
const capabilitiesOf = (token: string) =>
createHostedDelegatedUserApiClient(boundRequest(token), { apiBaseUrl: API_URL })!
.capabilities();

assertEquals(capabilitiesOf(grant(["projects.search", "schedules.pause"])), [
"projects.search",
"schedules.pause",
]);
assertEquals(capabilitiesOf(grant(["projects.create", 7, "", null])), ["projects.create"]);
assertEquals(capabilitiesOf(grant(["projects.create"], "other")), []);
assertEquals(capabilitiesOf(grant("projects.create")), []);
assertEquals(capabilitiesOf(jwtGrant({ exp: 1 })), []);
assertEquals(capabilitiesOf(TOKEN), []);
assert(Object.isFrozen(capabilitiesOf(grant(["projects.create"]))));

// A renewed grant's capabilities replace the old ones.
const renewed = grant(["projects.search"]);
const api = recordingFetch(() => Response.json({ token: renewed }));
const client = createHostedDelegatedUserApiClient(
boundRequest(grant(["projects.search", "projects.create"])),
{ apiBaseUrl: API_URL, fetch: api.fetch },
)!;
assertEquals(client.capabilities(), ["projects.search", "projects.create"]);
assertEquals(await client.renew(), "renewed");
assertEquals(client.capabilities(), ["projects.search"]);
});
});
Loading
Loading