Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Let admin-reading crons work unattended, or say why at creation (#2578)

Joshua Francef503f61f4e77
diff --git a/skills-seed/admin/SKILL.md b/skills-seed/admin/SKILL.md
index 6e38357e9..ee16537af 100644
--- a/skills-seed/admin/SKILL.md
+++ b/skills-seed/admin/SKILL.md
@@ -42,10 +42,11 @@ Limits the API enforces (don't offer what it will refuse):
Open reads can expose private data to everyone in the conversation: retrieve and
report only what the request needs. Two other exceptions: org-targeted
memory/config reads work anywhere (org content is ambient to every conversation), and
- a cron can carry **unattended read grants** (`unattendedGrants` on the cron:
- `admin.sessions.read`, `admin.audit.read`, `admin.egress.read`, `admin.files.read`)
- — set only on a live turn by the cron's owner, who must be a current org admin, on a
- personal-scope cron running as its owner. Each grant opens exactly its own GET
+ a cron can carry **unattended read grants** (`unattendedGrants` on the cron tool;
+ see [Scheduling admin-reading work](#scheduling-admin-reading-work)) — set only on a
+ live turn by the cron's owner, who must be a current org admin, on a cron that lives
+ in and delivers only to their own DM (never a channel, group or another person).
+ Each grant opens exactly its own GET
routes to that cron's autonomous fires, audited as the owner
(re-checked live — revoking their admin grant closes it). Other mutations work
anywhere; the room sees what changed, by design.
@@ -233,12 +234,35 @@ Not available through you: who governs the org changes only in the admin dashboa
where the admin acts directly. If asked, point them there — don't try the API
(`POST/DELETE /v1/admin/grants` refuses agent tokens).
+## Scheduling admin-reading work
+
+Cron fires are autonomous, so the admin plane refuses them unless the cron carries
+the grant each route needs (webhooks can't carry grants). When an admin asks for scheduled work that
+reads admin data, settle the grants at creation, not after the first fire fails:
+
+1. Work out which admin tool actions or admin API routes the task will call.
+2. Fetch the live mapping with the admin tool's `unattended_grants` action
+ (`GET /v1/admin/unattended-grants`, org admins on a live turn only). It is built
+ from the routes themselves: each entry gives the grant, method, path, summary and,
+ where one exists, the admin tool action. Reads it doesn't list have no grant.
+3. Create the cron from a live turn in the admin's own DM, delivering to that DM, with
+ exactly the grants those reads need in `unattendedGrants`.
+4. If a needed action or route has no grant, or the cron can't carry grants (not the
+ owner's own DM, not a live turn by a current org admin, or delivery to a channel,
+ group or another person), tell the admin plainly before or at creation which part
+ won't work unattended. Don't create a cron that will fail on its first fire without
+ saying so.
+5. After creating it, confirm the grants appear in the cron's details (the create
+ result or `get`).
+
## Failure modes
- `403 admin grant required for this scope` — the user isn't an org admin (or was just
revoked). Say so; don't retry or work around it.
- `403 … require a turn the admin started themselves` — this is an autonomous run
- (cron/webhook); admin actions only ride turns the admin personally initiated. Say so.
+ (cron/webhook) without the unattended grant the route needs. Report it where the run
+ delivers — never finish silently — naming the grant the message cites so the owner can
+ add it from their DM.
- `403 … returns private content — ask the agent in a DM` — the shared room does not have effective Open access for this live admin turn;
tell the admin to ask again in a DM with you (or, for reads they want recurring
on a schedule, to put an unattended read grant on a personal-scope cron — from
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index 1ec734578..614bf5fb1 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -1,6 +1,7 @@
import type { CapabilityClaims } from "../auth/capability-token.ts";
import { livePersonCapability } from "./artifact-share.ts";
import { adminRoutes } from "./routes/admin.ts";
+import { unattendedGrantListing } from "./routes/admin/unattended-grants.ts";
import { UNATTENDED_ADMIN_GRANTS } from "./control-service.ts";
interface AgentApiRoute {
@@ -690,10 +691,8 @@ const unattendedFamilies = (): AgentApiFamily[] =>
when: (v) => !livePersonCapability(v.claims) && v.claims.grants?.includes(grant) === true,
guidance:
"This cron has a specific read-only admin grant. Use only these listed routes; flag any other admin action to a human.",
- routes: adminRoutes.flatMap((route) =>
- "path" in route && route.admin?.unattended?.grant === grant
- ? [{ method: route.method, path: route.path, summary: route.admin.unattended.summary }]
- : [],
+ routes: unattendedGrantListing(adminRoutes).flatMap((entry) =>
+ entry.grant === grant ? [{ method: entry.method, path: entry.path, summary: entry.summary }] : [],
),
}));
diff --git a/src/api/control-service.ts b/src/api/control-service.ts
index a93bd9823..f4eeed168 100644
--- a/src/api/control-service.ts
+++ b/src/api/control-service.ts
@@ -323,6 +323,8 @@ export const UNATTENDED_ADMIN_GRANTS = [
"admin.audit.read",
"admin.egress.read",
"admin.files.read",
+ "admin.spend.read",
+ "admin.crons.read",
] as const;
function validateUnattendedGrants(grants: string[]): string | null {
@@ -452,11 +454,11 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
destination = resolved.destination;
}
- if (req.unattendedGrants !== undefined) {
+ if (req.unattendedGrants?.length) {
const refusal = await unattendedGrantRefusal(
app,
admin,
- { owner: capability.actorId, ownerScopeId },
+ { owner: capability.actorId, ownerScopeId, ...(destination ? { destination } : {}) },
capability,
);
if (refusal) return { ok: false, ...refusal };
@@ -544,7 +546,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
if (req.unattendedGrants !== undefined) patch.unattendedGrants = req.unattendedGrants;
else if ((before.unattendedGrants?.length ?? 0) > 0) patch.unattendedGrants = before.unattendedGrants;
if (!cronPatchChanges(before, patch)) return { ok: true, cron: before };
- if ((before.unattendedGrants?.length ?? 0) > 0 || req.unattendedGrants !== undefined) {
+ if ((patch.unattendedGrants?.length ?? 0) > 0) {
const refusal = await unattendedGrantRefusal(app, admin, before, capability);
if (refusal) return { ok: false, ...refusal };
}
@@ -683,10 +685,6 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
if (!(await canAdministerCron(app, cron, capability.actorId)))
return { ok: false, code: "forbidden", message: "not your cron" };
- if ((cron.unattendedGrants?.length ?? 0) > 0) {
- const refusal = await unattendedGrantRefusal(app, admin, cron, capability);
- if (refusal) return { ok: false, code: "forbidden", message: refusal.message };
- }
const resolved = resolveCapabilityDestination(capability, destinationKey);
if (!resolved.ok) {
return {
@@ -695,6 +693,15 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
message: "destinationKey is not one of the destinations available for this conversation",
};
}
+ if ((cron.unattendedGrants?.length ?? 0) > 0) {
+ const refusal = await unattendedGrantRefusal(
+ app,
+ admin,
+ { ...cron, destination: resolved.destination },
+ capability,
+ );
+ if (refusal) return { ok: false, code: "forbidden", message: refusal.message };
+ }
if (isDeepStrictEqual(cron.destination, resolved.destination)) return { ok: true, cron };
const updated = await app.setCronDestination(id, resolved.destination);
const destLabel = capability.destinations?.find((d) => d.key === destinationKey)?.label;
diff --git a/src/api/routes/admin.ts b/src/api/routes/admin.ts
index 96465c256..b6708ee57 100644
--- a/src/api/routes/admin.ts
+++ b/src/api/routes/admin.ts
@@ -56,6 +56,7 @@ import { deleteCustomProvider, getCustomProviders, putCustomProvider } from "./a
import { deleteMcpServer, getMcpServers, putMcpServer } from "./admin/mcp-servers.ts";
import { listSecurityFlags } from "./admin/security.ts";
import { spend } from "./admin/spend.ts";
+import { listUnattendedGrants } from "./admin/unattended-grants.ts";
import { createPrincipalLink, deletePrincipalLink, listPrincipalLinks } from "./admin/principal-links.ts";
const timed =
@@ -144,8 +145,20 @@ const routes: Route<ApiCtx>[] = [
handle: getCredentialUsageSummary,
},
{ method: "GET", path: "/v1/admin/resources", auth: "either", handle: getAdminResources },
+ {
+ method: "GET",
+ path: "/v1/admin/unattended-grants",
+ auth: "either",
+ handle: (ctx) => listUnattendedGrants(ctx, routes),
+ },
{ method: "GET", path: "/v1/admin/retention", auth: "either", handle: retention },
- { method: "GET", path: "/v1/admin/spend", auth: "either", handle: spend },
+ {
+ method: "GET",
+ path: "/v1/admin/spend",
+ auth: "either",
+ admin: { unattended: { grant: "admin.spend.read", summary: "read the org spend report" } },
+ handle: spend,
+ },
{
method: "GET",
path: "/v1/admin/egress",
@@ -287,7 +300,7 @@ const routes: Route<ApiCtx>[] = [
method: "GET",
path: "/v1/admin/crons",
auth: "either",
- admin: { privateRead: "always" },
+ admin: { privateRead: "always", unattended: { grant: "admin.crons.read", summary: "list a scope's crons" } },
handle: listAdminArtifacts,
},
{
diff --git a/src/api/routes/admin/artifacts.ts b/src/api/routes/admin/artifacts.ts
index 7b27bc342..e5b0c0c76 100644
--- a/src/api/routes/admin/artifacts.ts
+++ b/src/api/routes/admin/artifacts.ts
@@ -137,6 +137,11 @@ export async function putAdminCronDestination(ctx: ApiCtx): Promise<void> {
if (typeof body !== "object" || body === null || !("destination" in body)) {
return sendJson(res, 400, { error: "bad_request", message: "destination is required; use null to clear" });
}
+ if ((cron.unattendedGrants?.length ?? 0) > 0)
+ return sendJson(res, 409, {
+ error: "conflict",
+ message: "this cron carries unattended admin read grants, so only its owner can change where it delivers",
+ });
const destination = (body as { destination: unknown }).destination;
if (destination !== null && !isAdminCronDestination(destination)) {
return sendJson(res, 400, {
diff --git a/src/api/routes/admin/unattended-grants.ts b/src/api/routes/admin/unattended-grants.ts
new file mode 100644
index 000000000..3f5396123
--- /dev/null
+++ b/src/api/routes/admin/unattended-grants.ts
@@ -0,0 +1,28 @@
+import { adminOperations } from "../../../tools/admin.ts";
+import { sendJson } from "../../http.ts";
+import { audit, authorizeAdmin, orgScope } from "../shared.ts";
+import type { ApiCtx, Route } from "../route.ts";
+
+export function unattendedGrantListing(routes: ReadonlyArray<Route<ApiCtx>>) {
+ return routes.flatMap((route) => {
+ if (!("path" in route) || !route.admin?.unattended) return [];
+ const action = Object.entries(adminOperations).find(
+ ([, op]) => op.method === route.method && `/v1/admin${op.path}` === route.path,
+ )?.[0];
+ const { grant, summary } = route.admin.unattended;
+ return [{ grant, method: route.method, path: route.path, summary, ...(action ? { action } : {}) }];
+ });
+}
+
+export async function listUnattendedGrants(ctx: ApiCtx, routes: ReadonlyArray<Route<ApiCtx>>): Promise<void> {
+ const scope = orgScope(ctx.deps);
+ const actor = await authorizeAdmin(ctx, scope);
+ if (!actor) return;
+ audit(ctx.deps, {
+ principalId: actor.id,
+ action: "unattended-grants.read",
+ resource: "unattended-grants",
+ scopeLabel: scope,
+ });
+ sendJson(ctx.res, 200, { grants: unattendedGrantListing(routes) });
+}
diff --git a/src/api/server.ts b/src/api/server.ts
index 862ce2a0c..837a5ce90 100644
--- a/src/api/server.ts
+++ b/src/api/server.ts
@@ -43,7 +43,9 @@ async function capabilityAdminDenied(
if (access.agent === "anyone") return null;
if (claims.aud !== CONTROL_PLANE_AUD) return "admin routes require the per-turn agent token";
if (!livePersonCapability(claims) && !(access.unattended && claims.grants?.includes(access.unattended.grant))) {
- return "admin actions through the agent require a turn the admin started themselves — autonomous turns (crons, webhooks) cannot act as an admin";
+ return access.unattended
+ ? `admin actions through the agent require a turn the admin started themselves — this autonomous run lacks the unattended grant ${access.unattended.grant}, which only a cron's org-admin owner can add, from a live turn in their own DM. Report this failure where the run delivers instead of finishing silently.`
+ : "admin actions through the agent require a turn the admin started themselves — autonomous turns (crons, webhooks) cannot use this route. Report this failure where the run delivers instead of finishing silently.";
}
if (typeof access.agent === "object") return access.agent.portalOnly;
if (access.privateRead && parseScopeId(claims.scopeId).kind !== "personal") {
diff --git a/src/cron/authority.ts b/src/cron/authority.ts
index 84644b7dc..853dee18f 100644
--- a/src/cron/authority.ts
+++ b/src/cron/authority.ts
@@ -4,6 +4,8 @@ import type { CapabilityClaims } from "../auth/capability-token.ts";
import type { App } from "../api/app.ts";
import type { AdminService } from "../admin/admin-service.ts";
import { errMessage } from "../util/errors.ts";
+import { parseScopeId } from "../types.ts";
+import { samePerson } from "../directory/person.ts";
type TriggerAuthority = Pick<TriggerSpec, "owner" | "ownerScopeId" | "unattendedGrants">;
@@ -15,6 +17,14 @@ export function cronTriggerAuthority(cron: TriggerAuthority): TriggerAuthority {
};
}
+export function grantsStayWithOwner(cron: Pick<Cron, "owner" | "ownerScopeId" | "destination">): boolean {
+ const ownersOwn = (scope: string | undefined): boolean => {
+ const parsed = parseScopeId(scope ?? "");
+ return parsed.kind === "personal" && samePerson(parsed.ref, cron.owner);
+ };
+ return ownersOwn(cron.ownerScopeId) && (!cron.destination || ownersOwn(cron.destination.audienceScopeId));
+}
+
export interface UnattendedGrantRefusal {
code: "bad_request" | "forbidden";
message: string;
@@ -23,7 +33,7 @@ export interface UnattendedGrantRefusal {
export async function unattendedGrantRefusal(
app: App,
admin: AdminService | undefined,
- cron: Pick<Cron, "owner" | "ownerScopeId">,
+ cron: Pick<Cron, "owner" | "ownerScopeId" | "destination">,
capability: Pick<CapabilityClaims, "actorId" | "liveActor">,
): Promise<UnattendedGrantRefusal | null> {
const forbidden = (message: string): UnattendedGrantRefusal => ({ code: "forbidden", message });
@@ -31,8 +41,12 @@ export async function unattendedGrantRefusal(
return forbidden("unattended grants require a live turn started by the cron owner");
if (!(await app.samePerson(cron.owner, capability.actorId)))
return forbidden("only the cron owner may set unattended grants");
- if (!cron.ownerScopeId.startsWith("personal:"))
- return { code: "bad_request", message: "unattended grants require a personal-scope cron" };
+ if (!grantsStayWithOwner(cron))
+ return {
+ code: "bad_request",
+ message:
+ "unattended grants require a cron that lives in its owner's own DM and delivers only to them — admin reads must not reach a shared room or another person; create it from the owner's DM without a channel, recipient or group",
+ };
let status: Awaited<ReturnType<AdminService["adminStatusOf"]>> | undefined;
try {
status = await admin?.adminStatusOf({ id: capability.actorId, type: "internal" });
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index 5a596b525..9db2dc082 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -61,7 +61,7 @@ import {
type ToolResultScreenInput,
} from "../security/security-posture.ts";
import { SANDBOX_CAPABILITY_TTL_MS } from "../auth/capability-token.ts";
-import { CRON_FIRE_NOTE_MAX_CHARS } from "../api/control-service.ts";
+import { CRON_FIRE_NOTE_MAX_CHARS, UNATTENDED_ADMIN_GRANTS } from "../api/control-service.ts";
import { utcMinute } from "../util/time.ts";
function describePublishAudience(a: PublishAudienceDescriptor | undefined): string {
@@ -219,6 +219,7 @@ interface CronLike {
nextFireAt?: number;
destination?: { type: string; target: string };
lastFireNote?: { text: string; at: number; by?: string };
+ unattendedGrants?: string[];
}
const LIST_PAGE_SIZE = 25;
@@ -285,7 +286,8 @@ function fmtCronLine(c: CronLike, preview = false): string {
const runtime = c.runtime
? `\n runtime: ${c.runtime.harnessId}/${c.runtime.modelId}${c.runtime.effortLevel ? ` (${c.runtime.effortLevel})` : ""}`
: "";
- return `${c.id}${c.title ? ` "${c.title}"` : ""} — ${fmtCronSchedule(c)}${dest}${state}${next}${what ? `\n ${what}` : ""}${runtime}${note}`;
+ const grants = c.unattendedGrants?.length ? `\n unattended grants: ${c.unattendedGrants.join(", ")}` : "";
+ return `${c.id}${c.title ? ` "${c.title}"` : ""} — ${fmtCronSchedule(c)}${dest}${state}${next}${what ? `\n ${what}` : ""}${runtime}${grants}${note}`;
}
function fmtCronCreated(r: {
@@ -2386,6 +2388,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
"plus, where they share Open with it, their own keychain. Everyone in the conversation " +
"can see it; only its owner can change it unless they share write access (action=share, permission=write). " +
"If the owner leaves the conversation, the cron is deleted.\n" +
+ 'A cron whose fires read admin data (admin tool or API) needs `unattendedGrants`, and many admin reads have none: before creating it, follow the admin skill\'s "Scheduling admin-reading work", which fetches the live grant list.\n' +
"action=list pages through your crons (and ones visible through shared scopes), 25 per page — enabled first, " +
"newest first, long task text trimmed; when there's more, a footer line names the offset for the next page. " +
"action=get inspects one in full; " +
@@ -2522,6 +2525,12 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
},
),
),
+ unattendedGrants: Type.Optional(
+ Type.Array(Type.Union(UNATTENDED_ADMIN_GRANTS.map((grant) => Type.Literal(grant))), {
+ description:
+ "create/patch: read-only admin grants for this cron's fires (org admins only; the cron must live in and deliver to their own DM); the admin tool's unattended_grants action lists which read needs which. patch replaces; [] removes.",
+ }),
+ ),
enabled: Type.Optional(Type.Boolean({ description: "patch only: false pauses the cron, true resumes it." })),
archived: Type.Optional(Type.Boolean({ description: "patch only: true archives the cron." })),
limit: Type.Optional(
@@ -2573,6 +2582,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
...(params.destinationKey !== undefined ? { destinationKey: params.destinationKey } : {}),
...(params.unfurlLinks !== undefined ? { unfurlLinks: params.unfurlLinks } : {}),
...(params.session !== undefined ? { session: params.session } : {}),
+ ...(params.unattendedGrants !== undefined ? { unattendedGrants: params.unattendedGrants } : {}),
});
if (isUnavailable(r)) return unavailable(callId, "cron");
if (!r.ok) {
@@ -2703,6 +2713,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
...(params.archived !== undefined ? { archived: params.archived } : {}),
...(params.unfurlLinks !== undefined ? { unfurlLinks: params.unfurlLinks } : {}),
...(params.session !== undefined ? { session: params.session } : {}),
+ ...(params.unattendedGrants !== undefined ? { unattendedGrants: params.unattendedGrants } : {}),
});
if (isUnavailable(r)) return unavailable(callId, "cron");
if (!r.ok) return recordResult(callId, { tool: "cron", error: r.code }, text(`[error] ${r.message}`), true);
diff --git a/src/tools/admin.ts b/src/tools/admin.ts
index a1ba4c7ed..1911a0d88 100644
--- a/src/tools/admin.ts
+++ b/src/tools/admin.ts
@@ -29,6 +29,11 @@ export const adminOperations = {
whoami: operation("Check the requesting person's admin status.", "GET", "/whoami"),
scopes: operation("Find scopes and their labels; do not guess scope IDs.", "GET", "/scopes"),
resources: operation("Inspect the existing scope configuration resource manifest.", "GET", "/resources"),
+ unattended_grants: operation(
+ "List the admin reads a cron can be granted for unattended fires: each grant, route and admin action. Reads not listed have no grant.",
+ "GET",
+ "/unattended-grants",
+ ),
config: operation("Read a scope's configuration.", "GET", "/scopes/:scope", scope),
configure: operation(
"Update one nonsecret configuration resource. Connector and service-credential setters stay on the self-API. Confirm the exact change first. The existing resource validator owns the value shape; read the admin skill for its fields.",
diff --git a/src/triggers/run-trigger.ts b/src/triggers/run-trigger.ts
index 882c61d2d..3945cd3b8 100644
--- a/src/triggers/run-trigger.ts
+++ b/src/triggers/run-trigger.ts
@@ -9,6 +9,7 @@ import { reachEnqueue } from "../reach/reach.ts";
import { isVisible, type VisibilityDirectory } from "../directory/visibility.ts";
import type { DirectoryMember, DirectoryStore, RecipientResolution } from "../directory/directory-store.ts";
import { samePerson } from "../directory/person.ts";
+import { grantsStayWithOwner } from "../cron/authority.ts";
import type { CurrentScopeMembers } from "../resolution/scope-membership.ts";
import { isProjectGroupRef } from "../projects/project-store.ts";
import { reportFailureAs, swallowAs } from "../util/errors.ts";
@@ -284,7 +285,7 @@ export async function runTrigger(deps: TriggerDeps, spec: TriggerSpec): Promise<
text: typeof spec.input === "string" ? spec.input : spec.input(roster),
...(spec.securityScreenData !== undefined ? { securityScreenData: spec.securityScreenData } : {}),
triggered: true,
- ...(ownerKind === "personal" && spec.unattendedGrants ? { unattendedGrants: spec.unattendedGrants } : {}),
+ ...(spec.unattendedGrants && grantsStayWithOwner(spec) ? { unattendedGrants: spec.unattendedGrants } : {}),
...(spec.runtime ? { model: spec.runtime.modelId, harness: spec.runtime.harnessId } : {}),
...turnModelOptions({
triggered: true,
diff --git a/test/admin-agent-capability.test.ts b/test/admin-agent-capability.test.ts
index 363dd0aa3..a8d5d10bc 100644
--- a/test/admin-agent-capability.test.ts
+++ b/test/admin-agent-capability.test.ts
@@ -1,4 +1,6 @@
import { createAdminCall } from "../src/tools/admin.ts";
+import { adminRoutes } from "../src/api/routes/admin.ts";
+import { UNATTENDED_ADMIN_GRANTS } from "../src/api/control-service.ts";
import { createAgentTools } from "../src/harness/agent-tools.ts";
import type { ToolContext } from "../src/tools/primitives.ts";
import "./support/auto-fake-sprites.ts";
@@ -293,10 +295,17 @@ test("an unattended admin-read grant opens only the five read-only routes and ke
}
const ungranted = await capFor("admin-alice", { live: false });
- assert.equal(
- (await fetch(`${s.base}/v1/admin/sessions`, { headers: { "x-agent-capability": ungranted } })).status,
- 403,
+ const ungrantedRead = await fetch(`${s.base}/v1/admin/spend`, { headers: { "x-agent-capability": ungranted } });
+ assert.equal(ungrantedRead.status, 403);
+ assert.match(
+ ((await ungrantedRead.json()) as { message: string }).message,
+ /lacks the unattended grant admin\.spend\.read/,
);
+ const noGrantRoute = await fetch(`${s.base}/v1/admin/memory?${scopeQ}`, {
+ headers: { "x-agent-capability": ungranted },
+ });
+ assert.equal(noGrantRoute.status, 403);
+ assert.match(((await noGrantRoute.json()) as { message: string }).message, /cannot use this route/);
const channelGrant = await capFor("admin-alice", {
live: false,
grants: ["admin.sessions.read"],
@@ -320,12 +329,16 @@ test("each new unattended read grant opens exactly its own routes", async () =>
["admin.audit.read", [`/v1/admin/audit?${scopeQ}`]],
["admin.egress.read", [`/v1/admin/egress?${scopeQ}`]],
["admin.files.read", [`/v1/admin/files?${scopeQ}`]],
+ ["admin.spend.read", ["/v1/admin/spend"]],
+ ["admin.crons.read", [`/v1/admin/crons?${scopeQ}`]],
];
const crossDenied = [
`/v1/admin/sessions?${scopeQ}`,
`/v1/admin/audit?${scopeQ}`,
`/v1/admin/egress?${scopeQ}`,
`/v1/admin/files?${scopeQ}`,
+ "/v1/admin/spend",
+ `/v1/admin/crons?${scopeQ}`,
];
for (const [grant, allowed] of cases) {
const token = await capFor("admin-alice", { live: false, grants: [grant] });
@@ -360,6 +373,45 @@ test("each new unattended read grant opens exactly its own routes", async () =>
}
});
+test("the unattended-grant listing mirrors the route annotations and only answers a live org admin", async () => {
+ const s = start();
+ try {
+ const expected = adminRoutes.flatMap((route) =>
+ "path" in route && route.admin?.unattended
+ ? [{ grant: route.admin.unattended.grant, method: route.method, path: route.path }]
+ : [],
+ );
+ const listing = await createAdminCall(s.base, await capFor("admin-alice"))({ action: "unattended_grants" });
+ assert.equal(listing.status, 200);
+ const grants = (listing.body as { grants: Array<Record<string, string>> }).grants;
+ assert.deepEqual(
+ grants.map(({ grant, method, path }) => ({ grant, method, path })),
+ expected,
+ );
+ assert.deepEqual(new Set(grants.map((entry) => entry.grant)), new Set(UNATTENDED_ADMIN_GRANTS));
+ assert.ok(grants.every((entry) => entry.summary));
+ assert.deepEqual(
+ grants.filter((entry) => entry.action === "spend" || entry.action === "crons").map((entry) => entry.grant),
+ ["admin.spend.read", "admin.crons.read"],
+ );
+ assert.ok(!grants.some((entry) => entry.path === "/v1/admin/users"));
+ assert.ok((await s.built.auditLog.events()).some((e) => e.action === "unattended-grants.read"));
+
+ const nonAdmin = await fetch(`${s.base}/v1/admin/unattended-grants`, {
+ headers: { "x-agent-capability": await capFor("U1") },
+ });
+ assert.equal(nonAdmin.status, 403);
+ const unattended = await fetch(`${s.base}/v1/admin/unattended-grants`, {
+ headers: {
+ "x-agent-capability": await capFor("admin-alice", { live: false, grants: [...UNATTENDED_ADMIN_GRANTS] }),
+ },
+ });
+ assert.equal(unattended.status, 403);
+ } finally {
+ await s.close();
+ }
+});
+
test("an aud-less token never opens the admin door", async () => {
const s = start();
try {
diff --git a/test/admin-artifact-pages.test.ts b/test/admin-artifact-pages.test.ts
index 725723596..87388045f 100644
--- a/test/admin-artifact-pages.test.ts
+++ b/test/admin-artifact-pages.test.ts
@@ -100,6 +100,35 @@ test("per-kind artifact reads are scope-filtered, authz-gated, and audited", asy
}
});
+test("an admin cannot repoint a grant-carrying cron; only its owner can", async () => {
+ const s = start();
+ try {
+ const cron = await s.built.app.createCron({
+ ownerScopeId: "personal:U1",
+ owner: "U1",
+ createdBy: "U1",
+ schedule: { everyMs: 60_000 },
+ action: "review spend",
+ unattendedGrants: ["admin.spend.read"],
+ });
+ const put = (destination: unknown) =>
+ fetch(`${s.base}/v1/admin/crons/${encodeURIComponent(cron.id)}/destination?scope=personal:U1`, {
+ method: "PUT",
+ headers: { ...ALICE_ADMIN, "content-type": "application/json" },
+ body: JSON.stringify({ destination }),
+ });
+ assert.equal((await put({ type: "slack", target: "C9", audienceScopeId: "channel:C9" })).status, 409);
+ assert.equal(
+ (await put({ type: "slack", target: "C9", audienceScopeId: "personal:U1" })).status,
+ 409,
+ "a caller-supplied audience cannot launder a room destination",
+ );
+ assert.equal((await s.built.app.getCron(cron.id))?.destination, undefined);
+ } finally {
+ await s.close();
+ }
+});
+
test("an admin can edit and clear a cron destination inside the administered scope", async () => {
const s = start();
try {
diff --git a/test/control-service.test.ts b/test/control-service.test.ts
index e9ed6fd41..8ae93dd73 100644
--- a/test/control-service.test.ts
+++ b/test/control-service.test.ts
@@ -35,11 +35,12 @@ function claims(
scope: ScopeId = scopeId("personal", actorId),
extra: Partial<CapabilityClaims> = {},
): CapabilityClaims {
+ const dm = { ...D1, audienceScopeId: scopeId("personal", actorId) };
return {
actorId,
scopeId: scope,
- destination: { type: D1.type, target: D1.target, audienceScopeId: D1.audienceScopeId },
- destinations: [D1, ROOM],
+ destination: { type: dm.type, target: dm.target, audienceScopeId: dm.audienceScopeId },
+ destinations: [dm, ROOM],
defaultDestinationKey: D1.key,
exp: Date.now() + CAPABILITY_TTL_MS,
...extra,
@@ -121,23 +122,60 @@ test("unattended cron grants require a live org-admin owner and protect later pa
assert.deepEqual(cleared.ok ? cleared.cron.unattendedGrants : undefined, []);
});
-test("all five unattended read grant types are accepted on create", async () => {
+test("every unattended read grant type is accepted on create", async () => {
const { control } = setup();
- const created = await control.createCron(
- {
- schedule: { everyMs: 3_600_000 },
- action: "nightly usage analysis",
- unattendedGrants: ["admin.sessions.read", "admin.audit.read", "admin.egress.read", "admin.files.read"],
- },
- claims("admin-alice", scopeId("personal", "admin-alice"), { liveActor: true }),
- );
- assert.ok(created.ok, JSON.stringify(created));
- assert.deepEqual(created.ok ? created.cron.unattendedGrants : undefined, [
+ const grants = [
"admin.sessions.read",
"admin.audit.read",
"admin.egress.read",
"admin.files.read",
+ "admin.spend.read",
+ "admin.crons.read",
+ ];
+ const created = await control.createCron(
+ { schedule: { everyMs: 3_600_000 }, action: "nightly usage analysis", unattendedGrants: grants },
+ claims("admin-alice", scopeId("personal", "admin-alice"), { liveActor: true }),
+ );
+ assert.ok(created.ok, JSON.stringify(created));
+ assert.deepEqual(created.ok ? created.cron.unattendedGrants : undefined, grants);
+});
+
+test("a grant-carrying cron delivers only to its owner: shared or third-party destinations are refused at create and retarget", async () => {
+ const { built, control } = setup();
+ await built.app.upsertDirectory([
+ { principalId: "admin-alice", displayName: "Alice", type: "internal" },
+ { principalId: "U2", displayName: "User Two", type: "internal" },
]);
+ await built.app.upsertChannels(
+ [{ channelId: "C-spend", name: "spend", isPrivate: false }],
+ [{ channelId: "C-spend", principalId: "admin-alice" }],
+ );
+ const live = claims("admin-alice", scopeId("personal", "admin-alice"), { liveActor: true });
+ const request = {
+ schedule: { cron: "0 8 * * 1-5", timezone: "America/Los_Angeles" },
+ action: "daily spend review",
+ unattendedGrants: ["admin.spend.read"],
+ };
+
+ for (const elsewhere of [{ channel: "spend" }, { recipient: "User Two" }, { destinationKey: ROOM.key }]) {
+ const refused = await control.createCron({ ...request, ...elsewhere }, live);
+ assert.equal(refused.ok, false, JSON.stringify(elsewhere));
+ assert.match(refused.ok ? "" : refused.message, /delivers only to them/);
+ }
+
+ const own = await control.createCron(request, live);
+ assert.ok(own.ok, JSON.stringify(own));
+ assert.equal(own.cron.ownerScopeId, scopeId("personal", "admin-alice"));
+
+ const retarget = await control.retargetCron(own.cron.id, ROOM.key, live);
+ assert.equal(retarget.ok, false);
+ assert.match(retarget.ok ? "" : retarget.message, /delivers only to them/);
+
+ const cleared = await control.patchCron(own.cron.id, { unattendedGrants: [] }, claims("admin-alice"));
+ assert.ok(cleared.ok, "removing grants only narrows access, so it needs no live admin turn");
+ assert.deepEqual(cleared.ok ? cleared.cron.unattendedGrants : undefined, []);
+ const moved = await control.retargetCron(own.cron.id, ROOM.key, live);
+ assert.ok(moved.ok, "once grants are gone the cron can deliver anywhere");
});
test("a raw unreaffirmed cron patch strips unattended grants; a live-owner patch reaffirms them", async () => {
diff --git a/test/control-tool-context.test.ts b/test/control-tool-context.test.ts
index f8044d19b..2c73b747c 100644
--- a/test/control-tool-context.test.ts
+++ b/test/control-tool-context.test.ts
@@ -82,6 +82,54 @@ test("createToolContext.cronCreate creates a real cron through the shared servic
assert.equal(stored.title, "digest");
});
+test("the cron tool lets a live org-admin owner attach unattended admin-read grants and shows them back", async () => {
+ const { built } = build();
+ const control = createControlService(built.app, built.scheduler, built.admin);
+ const ctx = ctxFor({ control, controlClaims: { ...claims("admin-alice"), liveActor: true } });
+ const cron = createAgentTools({ current: ctx }, { controlTools: true }).find((t) => t.name === "cron")!;
+ const run = async (params: Record<string, unknown>) =>
+ (
+ (await cron.execute("call", params as never, undefined, undefined, {} as never)) as {
+ content: Array<{ text: string }>;
+ }
+ ).content[0]!.text;
+
+ const created = await run({
+ action: "create",
+ title: "Spend review",
+ schedule: { everyMs: 3_600_000 },
+ task: "review spend",
+ unattendedGrants: ["admin.spend.read", "admin.crons.read"],
+ });
+ const id = /Created cron (\S+)/.exec(created)?.[1];
+ assert.ok(id, created);
+ assert.deepEqual((await built.app.getCron(id))?.unattendedGrants, ["admin.spend.read", "admin.crons.read"]);
+ assert.match(await run({ action: "get", id }), /unattended grants: admin\.spend\.read, admin\.crons\.read/);
+
+ await run({ action: "patch", id, unattendedGrants: ["admin.spend.read"] });
+ assert.deepEqual((await built.app.getCron(id))?.unattendedGrants, ["admin.spend.read"]);
+
+ const nonAdmin = createAgentTools(
+ { current: ctxFor({ control, controlClaims: { ...claims("U1"), liveActor: true } }) },
+ { controlTools: true },
+ ).find((t) => t.name === "cron")!;
+ const refused = (
+ (await nonAdmin.execute(
+ "call",
+ {
+ action: "create",
+ schedule: { everyMs: 3_600_000 },
+ task: "review spend",
+ unattendedGrants: ["admin.spend.read"],
+ } as never,
+ undefined,
+ undefined,
+ {} as never,
+ )) as { content: Array<{ text: string }> }
+ ).content[0]!.text;
+ assert.match(refused, /\[error\].*current org admin/);
+});
+
test("webhook registration through the tool requires a live person and leaves refused calls without effects", async () => {
const { built, control } = build();
const request = { action: "handle the event", verification: { scheme: "hmac-sha256" as const, secret: "secret" } };
diff --git a/test/cron-credential-resumption.test.ts b/test/cron-credential-resumption.test.ts
index b2c5c23d8..d22025347 100644
--- a/test/cron-credential-resumption.test.ts
+++ b/test/cron-credential-resumption.test.ts
@@ -75,7 +75,7 @@ test("cron credential approval resumes the original fire once and delivers to th
assert.equal(request.actor.externalId, "U_ALICE");
assert.equal(request.conversation.threadRef, f.ask.requesterThreadRef);
assert.deepEqual(request.triggerDestination, destination);
- assert.deepEqual(request.unattendedGrants, ["allowed-job-grant"]);
+ assert.equal(request.unattendedGrants, undefined, "grants never ride a fire that delivers to another person");
assert.match(request.text, /approved access until revoked/);
assert.ok(!request.text.includes(f.ask.id) && !request.text.includes(f.ask.purpose));
const pending = await f.deliveries.pending("principal");
diff --git a/test/run-trigger.test.ts b/test/run-trigger.test.ts
index 0daa54f0d..4e5064963 100644
--- a/test/run-trigger.test.ts
+++ b/test/run-trigger.test.ts
@@ -204,7 +204,7 @@ describe("runTrigger: a monitor fire runs first-class live and delivers its own
});
describe("runTrigger: an autonomous cron does NOT go live (it may be conditionally silent by design)", () => {
- it("threads grants only for personal crons", async () => {
+ it("threads grants only for crons homed in and delivering to their owner's own DM", async () => {
const requests: TurnRequest[] = [];
const d = deps(async (request) => {
requests.push(request);
@@ -225,9 +225,13 @@ describe("runTrigger: an autonomous cron does NOT go live (it may be conditional
ownerScopeId: scopeId("channel", "C1"),
fireKey: "cron:conversation",
});
+ await runTrigger(d, { ...base, destination: toChannel, fireKey: "cron:owner-to-room" });
+ await runTrigger(d, { ...base, ownerScopeId: scopeId("personal", "U2"), fireKey: "cron:foreign-dm" });
assert.deepEqual(requests[0]?.unattendedGrants, ["admin.sessions.read"]);
assert.equal(requests[1]?.unattendedGrants, undefined);
assert.equal(requests[2]?.unattendedGrants, undefined);
+ assert.equal(requests[3]?.unattendedGrants, undefined, "a personal cron delivering to a room carries no grants");
+ assert.equal(requests[4]?.unattendedGrants, undefined, "a cron homed in someone else's DM carries no grants");
});
it("a failed fire's error notice carries friendly copy while the fire history keeps the raw reason", async () => {