Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Let an admin grant a specific cron narrow admin-read access for unattended fires (#471)

Regan Bell95ce87d4050b
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index a1f1f8505..f2abe4277 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -585,6 +585,19 @@ const FAMILIES: AgentApiFamily[] = [
},
],
},
+ {
+ match: () => false,
+ when: (v) => v.claims.liveActor !== true && v.claims.grants?.includes("admin.sessions.read") === 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: [
+ { method: "GET", path: "/v1/admin/sessions", summary: "list conversation metadata" },
+ { method: "GET", path: "/v1/admin/sessions/:id", summary: "read a conversation transcript" },
+ { method: "GET", path: "/v1/admin/scopes", summary: "list the scope directory" },
+ { method: "GET", path: "/v1/admin/errors", summary: "read error telemetry" },
+ { method: "GET", path: "/v1/admin/runs", summary: "read queued, in-flight, and recent runs" },
+ ],
+ },
];
const WHOAMI_FOR_ALL: AgentApiFamily = {
diff --git a/src/api/app-messaging.ts b/src/api/app-messaging.ts
index 9ffc01f53..f0e3c9b5e 100644
--- a/src/api/app-messaging.ts
+++ b/src/api/app-messaging.ts
@@ -152,7 +152,10 @@ export function createMessagingMethods(
const members = patch.members ?? before.members;
if (!members?.length) throw new Error("scopeShared requires a member snapshot");
}
- const updated = await deps.crons.update(id, patch);
+ const grantsReaffirmed = patch.unattendedGrants !== undefined;
+ const guardedPatch =
+ (before.unattendedGrants?.length ?? 0) > 0 && !grantsReaffirmed ? { ...patch, unattendedGrants: [] } : patch;
+ const updated = await deps.crons.update(id, guardedPatch);
deps.auditLog.record({
at: Date.now(),
principalId: before.owner,
diff --git a/src/api/app-turn.ts b/src/api/app-turn.ts
index d4ece64fd..ecaaf052e 100644
--- a/src/api/app-turn.ts
+++ b/src/api/app-turn.ts
@@ -242,6 +242,7 @@ export function createTurnMethods(
...turnModelOptions(req),
...(req.readOnly ? { readOnly: true } : {}),
...(req.skipMemory ? { skipMemory: true } : {}),
+ ...(req.unattendedGrants?.length ? { unattendedGrants: req.unattendedGrants } : {}),
...(req.surfaceTools ? { surfaceTools: true } : {}),
...(req.envelopeWrapped ? { envelopeWrapped: true } : {}),
...(typeof req.displayText === "string" && req.displayText ? { displayText: req.displayText } : {}),
diff --git a/src/api/control-service.ts b/src/api/control-service.ts
index f236ef44f..03f4bf71a 100644
--- a/src/api/control-service.ts
+++ b/src/api/control-service.ts
@@ -1,3 +1,4 @@
+import { isDeepStrictEqual } from "node:util";
import type { Cron, CronFireLogEntry, CronSchedule, Destination, Principal } from "../types.ts";
import type { CreateCronInput, CronPatch } from "../cron/cron-store.ts";
import type { CapabilityClaims } from "../auth/capability-token.ts";
@@ -10,6 +11,7 @@ import { sendConsentNotice } from "../triggers/consent-notice.ts";
import { notifyOwnerOfCronEdit, type CronEditDetail } from "../triggers/edit-notice.ts";
import { errMessage, swallow } from "../util/errors.ts";
import { AdminError } from "../admin/admin-service.ts";
+import type { AdminService } from "../admin/admin-service.ts";
import {
livePersonCapability,
resolveShareTarget,
@@ -32,6 +34,7 @@ export interface CronCreateRequest {
destinationKey?: string;
runAs?: "owner" | "scopeFloor" | "scopeShared";
unfurlLinks?: boolean;
+ unattendedGrants?: string[];
}
export type CronCreateResult =
@@ -55,6 +58,7 @@ export type CronCreateResult =
| "identity_unverified"
| "unknown_destination"
| "members_unavailable"
+ | "forbidden"
| "cron_create_failed";
message: string;
candidates?: Array<{ id: string; label: string }>;
@@ -69,6 +73,7 @@ export interface CronPatchRequest {
archived?: boolean;
unfurlLinks?: boolean;
runAs?: "owner" | "scopeFloor" | "scopeShared";
+ unattendedGrants?: string[];
}
export interface CronRunsRequest {
@@ -81,6 +86,9 @@ export interface CronRunsResult {
total: number;
}
+export const CRON_PATCH_NOTHING_TO_CHANGE =
+ "nothing to change — pass title, task, schedule, enabled, archived, unfurlLinks, runAs, or unattendedGrants";
+
export type ControlOk<T> = { ok: true } & T;
export type ControlErr<C extends string> = { ok: false; code: C; message: string };
@@ -151,6 +159,26 @@ function scopeIsMembershipControlled(scope: string, cap: { scopeId: string; priv
return cap.privateScope === true && cap.scopeId === scope;
}
+function hasCronPatchField(req: CronPatchRequest): boolean {
+ return (
+ req.title !== undefined ||
+ req.action !== undefined ||
+ req.text !== undefined ||
+ req.schedule !== undefined ||
+ req.enabled !== undefined ||
+ req.archived !== undefined ||
+ req.unfurlLinks !== undefined ||
+ req.runAs !== undefined ||
+ req.unattendedGrants !== undefined
+ );
+}
+
+function cronPatchChanges(before: Cron, patch: CronPatch): boolean {
+ return (Object.entries(patch) as Array<[keyof CronPatch, unknown]>).some(
+ ([key, value]) => !isDeepStrictEqual(before[key as keyof Cron], value),
+ );
+}
+
export async function resolveRunAsChange(
app: Pick<App, "samePerson">,
before: Cron,
@@ -197,25 +225,16 @@ async function patchFromCronPatchRequest(
req: CronPatchRequest,
capability: CapabilityClaims,
): Promise<CronPatch | ControlErr<"bad_request" | "forbidden">> {
- const mode = await resolveRunAsChange(app, before, req.runAs, capability);
- if (!mode.ok) return mode;
- const changesMode = mode.patch.runAs !== undefined;
- if (
- req.title === undefined &&
- req.action === undefined &&
- req.text === undefined &&
- req.schedule === undefined &&
- req.enabled === undefined &&
- req.archived === undefined &&
- req.unfurlLinks === undefined &&
- !changesMode
- ) {
+ if (!hasCronPatchField(req)) {
return {
ok: false,
code: "bad_request",
- message: "nothing to change — pass title, task, schedule, enabled, archived, unfurlLinks, or runAs",
+ message: CRON_PATCH_NOTHING_TO_CHANGE,
};
}
+ const mode = await resolveRunAsChange(app, before, req.runAs, capability);
+ if (!mode.ok) return mode;
+ const changesMode = mode.patch.runAs !== undefined;
if (req.unfurlLinks !== undefined && !before.destination) {
return {
ok: false,
@@ -243,7 +262,29 @@ async function patchFromCronPatchRequest(
};
}
-export function createControlService(app: App, scheduler?: Scheduler): ControlService {
+const UNATTENDED_GRANTS = new Set(["admin.sessions.read"]);
+
+function validateUnattendedGrants(grants: string[]): string | null {
+ if (!grants.every((grant) => UNATTENDED_GRANTS.has(grant))) return "unknown unattended grant";
+ return null;
+}
+
+async function unattendedGrantRefusal(
+ app: App,
+ admin: AdminService | undefined,
+ cron: Pick<Cron, "owner" | "ownerScopeId" | "runAs">,
+ capability: CapabilityClaims,
+): Promise<string | null> {
+ if (capability.liveActor !== true) return "unattended grants require a live turn started by the cron owner";
+ if (!(await app.samePerson(cron.owner, capability.actorId))) return "only the cron owner may set unattended grants";
+ if (!cron.ownerScopeId.startsWith("personal:") || (cron.runAs !== undefined && cron.runAs !== "owner"))
+ return "unattended grants require a personal-scope cron that runs as its owner";
+ const status = await admin?.adminStatusOf({ id: capability.actorId, type: "internal" }).catch(() => undefined);
+ if (!status?.isAdmin) return "unattended grants require the cron owner to be a current org admin";
+ return null;
+}
+
+export function createControlService(app: App, scheduler?: Scheduler, admin?: AdminService): ControlService {
const notifyEdit = (
cron: Cron,
cap: CapabilityClaims,
@@ -260,6 +301,10 @@ export function createControlService(app: App, scheduler?: Scheduler): ControlSe
});
return {
async createCron(req, capability): Promise<CronCreateResult> {
+ if (req.unattendedGrants !== undefined) {
+ const invalid = validateUnattendedGrants(req.unattendedGrants);
+ if (invalid) return { ok: false, code: "bad_request", message: invalid };
+ }
if (req.action === undefined && req.text === undefined) {
return { ok: false, code: "bad_request", message: "task (what to do) or text (exact text to send) required" };
}
@@ -391,6 +436,18 @@ export function createControlService(app: App, scheduler?: Scheduler): ControlSe
"scopeShared needs a private channel or group DM you're in — not a public channel, a DM, or a different named channel",
};
}
+ if (req.unattendedGrants !== undefined) {
+ const refusal = await unattendedGrantRefusal(
+ app,
+ admin,
+ { owner: capability.actorId, ownerScopeId, runAs },
+ capability,
+ );
+ if (refusal) {
+ const code = refusal.includes("personal-scope") ? "bad_request" : "forbidden";
+ return { ok: false, code, message: refusal };
+ }
+ }
if (req.unfurlLinks !== undefined && !destination) {
return {
@@ -417,6 +474,7 @@ export function createControlService(app: App, scheduler?: Scheduler): ControlSe
? { recipientConsent: { recipientId: consentRecipient, status: "pending" as const } }
: {}),
...(runAs === "scopeFloor" || runAs === "scopeShared" ? { runAs, members: capability.members } : {}),
+ ...(req.unattendedGrants !== undefined ? { unattendedGrants: req.unattendedGrants } : {}),
};
try {
const cron = await app.createCron(input);
@@ -482,8 +540,31 @@ export function createControlService(app: App, scheduler?: Scheduler): ControlSe
if (!before) return { ok: false, code: "not_found", message: `no cron ${id}` };
if (!(await canAdministerCron(app, before, capability.actorId, capability.scopeId)))
return { ok: false, code: "forbidden", message: "not your cron" };
+ if (req.unattendedGrants !== undefined) {
+ const invalid = validateUnattendedGrants(req.unattendedGrants);
+ if (invalid) return { ok: false, code: "bad_request", message: invalid };
+ }
const patch = await patchFromCronPatchRequest(app, before, req, capability);
if ("ok" in patch) return patch;
+ 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) {
+ const refusal = await unattendedGrantRefusal(
+ app,
+ admin,
+ {
+ owner: before.owner,
+ ownerScopeId: before.ownerScopeId,
+ runAs: req.runAs ?? before.runAs,
+ },
+ capability,
+ );
+ if (refusal) {
+ const code = refusal.includes("personal-scope") ? "bad_request" : "forbidden";
+ return { ok: false, code, message: refusal };
+ }
+ }
try {
const cron = await app.updateCron(id, patch);
if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
@@ -519,6 +600,10 @@ export function createControlService(app: App, scheduler?: Scheduler): ControlSe
if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
if (!(await canAdministerCron(app, cron, capability.actorId, capability.scopeId)))
return { ok: false, code: "forbidden", message: "not your cron" };
+ if (enabled && (cron.unattendedGrants?.length ?? 0) > 0) {
+ const refusal = await unattendedGrantRefusal(app, admin, cron, capability);
+ if (refusal) return { ok: false, code: "forbidden", message: refusal };
+ }
await app.setCronEnabled(id, enabled);
await notifyEdit(cron, capability, [`enabled=${enabled}`], `enabled=${enabled}`);
const after = await app.getCron(id);
@@ -530,6 +615,10 @@ export function createControlService(app: App, scheduler?: Scheduler): ControlSe
if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
if (!(await canAdministerCron(app, cron, capability.actorId, capability.scopeId)))
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 };
+ }
if (!scheduler)
return {
ok: false,
@@ -551,6 +640,10 @@ export function createControlService(app: App, scheduler?: Scheduler): ControlSe
if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
if (!(await canAdministerCron(app, cron, capability.actorId, capability.scopeId)))
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 };
+ }
const resolved = resolveCapabilityDestination(capability, destinationKey);
if (!resolved.ok) {
return {
diff --git a/src/api/routes/crons.ts b/src/api/routes/crons.ts
index ba66508ef..9eafd89f4 100644
--- a/src/api/routes/crons.ts
+++ b/src/api/routes/crons.ts
@@ -7,6 +7,7 @@ import { sendJson } from "../http.ts";
import { isObj } from "./shared.ts";
import { decideRecipientConsent } from "../../triggers/trigger-store.ts";
import { canAdministerCron } from "../control-service.ts";
+import { CRON_PATCH_NOTHING_TO_CHANGE } from "../control-service.ts";
import { type ApiCtx, type Route } from "./route.ts";
function defaultTimezoneFor(capability: CapabilityClaims | null): string {
@@ -47,6 +48,7 @@ function isCreateCron(b: unknown): b is CreateCronInput {
isObj(b) &&
scheduleFromBody(b.schedule) !== null &&
(typeof b.action === "string" || typeof (b as { message?: unknown }).message === "string") &&
+ (b as { unattendedGrants?: unknown }).unattendedGrants === undefined &&
typeof b.ownerScopeId === "string" &&
typeof b.owner === "string" &&
typeof b.createdBy === "string" &&
@@ -69,6 +71,7 @@ type CapabilityCronBody = {
participants?: unknown;
scope?: unknown;
unfurlLinks?: unknown;
+ unattendedGrants?: unknown;
};
function taskText(b: CapabilityCronBody): string | undefined {
@@ -126,8 +129,10 @@ function isCronPatch(b: unknown): b is {
archived?: boolean;
unfurlLinks?: boolean;
runAs?: "owner" | "scopeFloor" | "scopeShared";
+ unattendedGrants?: string[];
} {
if (!isObj(b)) return false;
+ if (!hasCronPatchFields(b)) return true;
const hasTitle = b.title !== undefined;
const hasAction = b.action !== undefined;
const hasTask = b.task !== undefined;
@@ -136,17 +141,7 @@ function isCronPatch(b: unknown): b is {
const hasArchived = b.archived !== undefined;
const hasUnfurlLinks = b.unfurlLinks !== undefined;
const hasRunAs = b.runAs !== undefined;
- if (
- !hasTitle &&
- !hasAction &&
- !hasTask &&
- !hasSchedule &&
- !hasEnabled &&
- !hasArchived &&
- !hasUnfurlLinks &&
- !hasRunAs
- )
- return false;
+ const hasUnattendedGrants = b.unattendedGrants !== undefined;
if (hasTitle && typeof b.title !== "string") return false;
if (hasAction && typeof b.action !== "string") return false;
if (hasTask && typeof b.task !== "string") return false;
@@ -154,10 +149,29 @@ function isCronPatch(b: unknown): b is {
if (hasArchived && typeof b.archived !== "boolean") return false;
if (hasUnfurlLinks && typeof b.unfurlLinks !== "boolean") return false;
if (hasRunAs && b.runAs !== "owner" && b.runAs !== "scopeFloor" && b.runAs !== "scopeShared") return false;
+ if (
+ hasUnattendedGrants &&
+ (!Array.isArray(b.unattendedGrants) || !b.unattendedGrants.every((grant) => typeof grant === "string"))
+ )
+ return false;
if (hasSchedule && scheduleFromBody(b.schedule) === null) return false;
return true;
}
+function hasCronPatchFields(b: Record<string, unknown>): boolean {
+ return (
+ b.title !== undefined ||
+ b.action !== undefined ||
+ b.task !== undefined ||
+ b.schedule !== undefined ||
+ b.enabled !== undefined ||
+ b.archived !== undefined ||
+ b.unfurlLinks !== undefined ||
+ b.runAs !== undefined ||
+ b.unattendedGrants !== undefined
+ );
+}
+
const CRON_ERROR_STATUS: Record<string, number> = {
bad_request: 400,
recipient_not_found: 404,
@@ -180,6 +194,15 @@ async function createCron(ctx: ApiCtx): Promise<void> {
const { res, app, body, capability } = ctx;
if (capability) {
const b = body as CapabilityCronBody;
+ if (
+ b.unattendedGrants !== undefined &&
+ (!Array.isArray(b.unattendedGrants) || !b.unattendedGrants.every((grant) => typeof grant === "string"))
+ ) {
+ return sendJson(res, 400, {
+ error: "bad_request",
+ message: "unattendedGrants must be an array of recognized grant strings",
+ });
+ }
const schedule = scheduleFromBody(b.schedule, defaultTimezoneFor(capability));
const task = taskText(b);
const text = exactText(b);
@@ -205,6 +228,7 @@ async function createCron(ctx: ApiCtx): Promise<void> {
...(typeof b.destinationKey === "string" ? { destinationKey: b.destinationKey } : {}),
...(b.runAs === "owner" || b.runAs === "scopeFloor" || b.runAs === "scopeShared" ? { runAs: b.runAs } : {}),
...(typeof b.unfurlLinks === "boolean" ? { unfurlLinks: b.unfurlLinks } : {}),
+ ...(Array.isArray(b.unattendedGrants) ? { unattendedGrants: b.unattendedGrants } : {}),
},
capability,
);
@@ -328,7 +352,7 @@ async function cronRuns(ctx: ApiCtx): Promise<void> {
}
const CRON_PATCH_BAD_REQUEST =
- "expected a cron patch: title (string), task (string), schedule, enabled (boolean), archived (boolean), unfurlLinks (boolean), and/or runAs (owner/scopeFloor/scopeShared)";
+ "expected a cron patch: title (string), task (string), schedule, enabled (boolean), archived (boolean), unfurlLinks (boolean), runAs (owner/scopeFloor/scopeShared), and/or unattendedGrants (string[])";
async function cronById(ctx: ApiCtx): Promise<void> {
const { res, app, pathname, method, body, capability } = ctx;
@@ -347,6 +371,9 @@ async function cronById(ctx: ApiCtx): Promise<void> {
: sendJson(res, CRON_ERROR_STATUS[r.code] ?? 400, { error: r.code, message: r.message });
}
if (!isCronPatch(body)) return sendJson(res, 400, { error: "bad_request", message: CRON_PATCH_BAD_REQUEST });
+ if (!hasCronPatchFields(body)) {
+ return sendJson(res, 400, { error: "bad_request", message: CRON_PATCH_NOTHING_TO_CHANGE });
+ }
const schedule =
body.schedule !== undefined ? scheduleFromBody(body.schedule, defaultTimezoneFor(capability))! : undefined;
const task = body.action ?? body.task;
@@ -360,6 +387,7 @@ async function cronById(ctx: ApiCtx): Promise<void> {
...(body.archived !== undefined ? { archived: body.archived } : {}),
...(body.unfurlLinks !== undefined ? { unfurlLinks: body.unfurlLinks } : {}),
...(body.runAs !== undefined ? { runAs: body.runAs } : {}),
+ ...(body.unattendedGrants !== undefined ? { unattendedGrants: body.unattendedGrants } : {}),
},
capability,
);
@@ -378,7 +406,16 @@ async function cronById(ctx: ApiCtx): Promise<void> {
await app.deleteCron(id);
return sendJson(res, 200, { ok: true });
}
+ if ((cron.unattendedGrants?.length ?? 0) > 0) {
+ return sendJson(res, 403, {
+ error: "forbidden",
+ message: "a privileged cron may only be patched by its owner from a live turn",
+ });
+ }
if (!isCronPatch(body)) return sendJson(res, 400, { error: "bad_request", message: CRON_PATCH_BAD_REQUEST });
+ if (!hasCronPatchFields(body)) {
+ return sendJson(res, 400, { error: "bad_request", message: CRON_PATCH_NOTHING_TO_CHANGE });
+ }
if (body.runAs !== undefined)
return sendJson(res, 403, {
error: "forbidden",
diff --git a/src/api/routes/turns.ts b/src/api/routes/turns.ts
index 14d841334..97cdf1a53 100644
--- a/src/api/routes/turns.ts
+++ b/src/api/routes/turns.ts
@@ -34,7 +34,12 @@ async function postTurn(ctx: ApiCtx): Promise<void> {
return sendJson(res, 400, { error: "bad_request", message: "expected a TurnRequest" });
}
const wantAsync = url.searchParams.get("async") === "1" || body.async === true;
- const { ownerKeychainUnion: _ownerKeychainUnion, spawned: _spawned, ...safeBody } = body;
+ const {
+ ownerKeychainUnion: _ownerKeychainUnion,
+ spawned: _spawned,
+ unattendedGrants: _unattendedGrants,
+ ...safeBody
+ } = body;
const resolvedOrigin = publicTurnOrigin(safeBody);
if (resolvedOrigin.error) return sendJson(res, 400, { error: "bad_request", message: resolvedOrigin.error });
const origin = resolvedOrigin.origin;
diff --git a/src/api/server.ts b/src/api/server.ts
index 7cd533842..016d0a9c8 100644
--- a/src/api/server.ts
+++ b/src/api/server.ts
@@ -38,7 +38,7 @@ const safeDecode = (s: string): string => {
function capabilityAdminDenied(method: string, pathname: string, url: URL, claims: CapabilityClaims): string | null {
if (method === "GET" && pathname === "/v1/admin/whoami") return null;
if (claims.aud !== CONTROL_PLANE_AUD) return "admin routes require the per-turn agent token";
- if (claims.liveActor !== true) {
+ if (claims.liveActor !== true && !unattendedAdminReadAllowed(method, pathname, claims)) {
return "admin actions through the agent require a turn the admin started themselves — autonomous turns (crons) cannot act as an admin";
}
if (pathname.startsWith("/v1/admin/grants")) {
@@ -72,6 +72,17 @@ function capabilityAdminDenied(method: string, pathname: string, url: URL, claim
return null;
}
+function unattendedAdminReadAllowed(method: string, pathname: string, claims: CapabilityClaims): boolean {
+ if (method !== "GET" || !claims.grants?.includes("admin.sessions.read")) return false;
+ return (
+ pathname === "/v1/admin/sessions" ||
+ /^\/v1\/admin\/sessions\/[^/]+$/.test(pathname) ||
+ pathname === "/v1/admin/scopes" ||
+ pathname === "/v1/admin/errors" ||
+ pathname === "/v1/admin/runs"
+ );
+}
+
function isAdminContentRead(pathname: string): boolean {
if (pathname === "/v1/admin/memory") return true;
if (pathname === "/v1/admin/keychain") return true;
@@ -438,7 +449,7 @@ function buildServer(app: App, deps: ServerOptions, allowUnsignedSourceAuth: boo
: null;
const wiring: Wiring = {
app,
- deps: { ...deps, control: createControlService(app, deps.scheduler) },
+ deps: { ...deps, control: createControlService(app, deps.scheduler, deps.admin) },
secret: deps.signingSecret,
auth,
requirePortalIdentity,
diff --git a/src/auth/capability-token.ts b/src/auth/capability-token.ts
index 24cbbcf3e..0fa545085 100644
--- a/src/auth/capability-token.ts
+++ b/src/auth/capability-token.ts
@@ -38,6 +38,7 @@ export interface CapabilityClaims {
liveActor?: boolean;
liveAuthor?: boolean;
triggered?: boolean;
+ grants?: string[];
threadRef?: string;
exp: number;
}
@@ -75,6 +76,11 @@ export async function verifyCapabilityToken(
if (claims.scopeVersion !== undefined && typeof claims.scopeVersion !== "string") return null;
if (claims.destinations !== undefined && !Array.isArray(claims.destinations)) return null;
if (claims.credentials !== undefined && !Array.isArray(claims.credentials)) return null;
+ if (
+ claims.grants !== undefined &&
+ (!Array.isArray(claims.grants) || !claims.grants.every((g) => typeof g === "string"))
+ )
+ return null;
if (claims.keychainMembers !== undefined && !Array.isArray(claims.keychainMembers)) return null;
if (claims.memory !== undefined && !Array.isArray(claims.memory?.read)) return null;
if (claims.liveActor !== undefined && typeof claims.liveActor !== "boolean") return null;
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index a4a4cf428..94336e511 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -1105,6 +1105,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
...(liveTurn ? { liveActor: true } : {}),
...(liveAuthorTurn ? { liveAuthor: true } : {}),
...(automatedTurn ? { triggered: true } : {}),
+ ...(!liveTurn && input.unattendedGrants ? { grants: input.unattendedGrants } : {}),
threadRef: conversation.threadRef,
};
connectorEnv.AGENT_API_TOKEN = await mintCapabilityToken(
diff --git a/src/cron/cron-store.ts b/src/cron/cron-store.ts
index 8a75502df..b80b1d26b 100644
--- a/src/cron/cron-store.ts
+++ b/src/cron/cron-store.ts
@@ -18,6 +18,7 @@ export interface CreateCronInput extends CreateTriggerInput {
message?: string;
runAs?: Cron["runAs"];
members?: Principal[];
+ unattendedGrants?: string[];
}
export interface CronPatch {
@@ -30,6 +31,7 @@ export interface CronPatch {
destination?: Destination;
members?: Principal[];
runAs?: Cron["runAs"];
+ unattendedGrants?: string[];
}
export interface CronStore {
@@ -71,6 +73,7 @@ export function createCronStore(backing: DurableMap<Cron> = createMemoryMap<Cron
contentPart(input.destination),
contentPart(input.runAs),
contentPart(input.members),
+ contentPart(input.unattendedGrants),
contentPart(title),
]);
return createDeduped(backing, contentId, (id) => ({
@@ -82,6 +85,7 @@ export function createCronStore(backing: DurableMap<Cron> = createMemoryMap<Cron
...(input.message !== undefined ? { message: input.message } : {}),
...(input.runAs ? { runAs: input.runAs } : {}),
...(input.members ? { members: input.members } : {}),
+ ...(input.unattendedGrants ? { unattendedGrants: input.unattendedGrants } : {}),
}));
},
get: (id) => backing.get(id),
@@ -102,6 +106,7 @@ export function createCronStore(backing: DurableMap<Cron> = createMemoryMap<Cron
if (patch.archived === true) fields.enabled = false;
if (patch.members !== undefined) fields.members = patch.members;
if (patch.runAs !== undefined) fields.runAs = patch.runAs;
+ if (patch.unattendedGrants !== undefined) fields.unattendedGrants = patch.unattendedGrants;
return backing.merge(id, fields);
},
delete: (id) => backing.delete(id),
diff --git a/src/cron/scheduler.ts b/src/cron/scheduler.ts
index cfb935069..d74c3b243 100644
--- a/src/cron/scheduler.ts
+++ b/src/cron/scheduler.ts
@@ -138,6 +138,7 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {
...(cron.message !== undefined ? { message: cron.message } : {}),
...(cron.destination ? { destination: cron.destination } : {}),
...(cron.runAs ? { runAs: cron.runAs } : {}),
+ ...(cron.unattendedGrants ? { unattendedGrants: cron.unattendedGrants } : {}),
...(cron.members ? { members: cron.members } : {}),
...(cron.recipientConsent ? { recipientConsent: cron.recipientConsent } : {}),
recipientConsentRequired: cron.schedule.everyMs !== undefined || cron.schedule.cron !== undefined,
diff --git a/src/triggers/run-trigger.ts b/src/triggers/run-trigger.ts
index b6a14ac12..4c8ee98f7 100644
--- a/src/triggers/run-trigger.ts
+++ b/src/triggers/run-trigger.ts
@@ -47,6 +47,7 @@ export interface TriggerSpec {
message?: string;
threadRef?: string;
runAs?: "owner" | "scopeFloor" | "scopeShared";
+ unattendedGrants?: string[];
members?: Principal[];
recipientConsent?: RecipientConsent;
recipientConsentRequired?: boolean;
@@ -282,6 +283,7 @@ export async function runTrigger(deps: TriggerDeps, spec: TriggerSpec): Promise<
text: spec.input,
...(spec.securityScreenData !== undefined ? { securityScreenData: spec.securityScreenData } : {}),
triggered: true,
+ ...(!isScopeFloor && !isScopeShared && spec.unattendedGrants ? { unattendedGrants: spec.unattendedGrants } : {}),
...turnModelOptions({ triggered: true, ...(spec.thinkingLevel ? { thinkingLevel: spec.thinkingLevel } : {}) }),
...(spec.readOnly ? { readOnly: true } : {}),
...(typeof spec.turnWallClockMs === "number" ? { turnWallClockMs: spec.turnWallClockMs } : {}),
diff --git a/src/types.ts b/src/types.ts
index 292aea843..664b3d55e 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -226,6 +226,7 @@ export interface Cron extends TriggerBase {
createdAt: number;
runAs?: "owner" | "scopeFloor" | "scopeShared";
members?: Principal[];
+ unattendedGrants?: string[];
fireLog?: CronFireLogEntry[];
}
@@ -388,6 +389,7 @@ export interface TurnRequest {
entryTs?: string;
gatewayContext?: GatewayContext;
triggered?: boolean;
+ unattendedGrants?: string[];
securityScreenData?: string;
triggerDestination?: Destination;
ownerKeychainUnion?: boolean;
diff --git a/src/wiring.ts b/src/wiring.ts
index 62c3d0116..c665b6573 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1289,7 +1289,7 @@ export function buildApp(
: {}),
});
cronChanged.notify = (id) => scheduler.notifyChanged(id);
- orchestratorDeps.control = createControlService(app, scheduler);
+ orchestratorDeps.control = createControlService(app, scheduler, admin);
const monitorPoller: MonitorPoller | null =
processes && supportsProcessSessions(sandbox)
? createMonitorPoller({
diff --git a/test/admin-agent-capability.test.ts b/test/admin-agent-capability.test.ts
index e791ca876..cac0ef924 100644
--- a/test/admin-agent-capability.test.ts
+++ b/test/admin-agent-capability.test.ts
@@ -41,6 +41,9 @@ function start() {
memory: built.memory,
config: built.config,
auditLog: built.auditLog,
+ sessions: built.sessions,
+ runs: built.runs,
+ errors: built.errors,
keychain,
signingSecret: SECRET,
});
@@ -49,7 +52,10 @@ function start() {
return { base, built, keychain, close: () => new Promise<void>((r) => server.close(() => r())) };
}
-const capFor = async (actorId: string, opts: { aud?: string | null; live?: boolean; scope?: string } = {}) => {
+const capFor = async (
+ actorId: string,
+ opts: { aud?: string | null; live?: boolean; scope?: string; grants?: string[] } = {},
+) => {
const aud = opts.aud === undefined ? CONTROL_PLANE_AUD : opts.aud;
return await mintCapabilityToken(
{
@@ -57,6 +63,7 @@ const capFor = async (actorId: string, opts: { aud?: string | null; live?: boole
scopeId: opts.scope ?? scopeId("personal", actorId),
...(aud === null ? {} : { aud }),
...(opts.live === false ? {} : { liveActor: true }),
+ ...(opts.grants ? { grants: opts.grants } : {}),
exp: Date.now() + CAPABILITY_TTL_MS,
},
SECRET,
@@ -178,6 +185,60 @@ test("an autonomous turn's token cannot act as an admin, even when its actor hol
}
});
+test("an unattended admin-read grant opens only the five read-only routes and keeps the DM gate", async () => {
+ const s = start();
+ try {
+ const granted = await capFor("admin-alice", { live: false, grants: ["admin.sessions.read"] });
+ const scopeQ = `scope=${encodeURIComponent(ORG)}`;
+ const allowed: Array<[string, number]> = [
+ [`/v1/admin/sessions?${scopeQ}`, 200],
+ [`/v1/admin/sessions/missing-session?${scopeQ}`, 404],
+ ["/v1/admin/scopes", 200],
+ [`/v1/admin/errors?${scopeQ}`, 200],
+ [`/v1/admin/runs?${scopeQ}`, 200],
+ ];
+ for (const [path, expected] of allowed) {
+ const response = await fetch(`${s.base}${path}`, { headers: { "x-agent-capability": granted } });
+ assert.equal(response.status, expected, `${path} is usable under the grant (got ${response.status})`);
+ }
+
+ const denied = [
+ ["GET", "/v1/admin/sessions/missing-session/llm"],
+ ["GET", "/v1/admin/memory"],
+ ["GET", `/v1/admin/scopes/${encodeURIComponent(ORG)}`],
+ ["POST", "/v1/admin/sessions"],
+ ["PUT", "/v1/admin/scopes"],
+ ["DELETE", "/v1/admin/errors"],
+ ] as const;
+ for (const [method, path] of denied) {
+ const response = await fetch(`${s.base}${path}`, {
+ method,
+ headers: { "x-agent-capability": granted, "content-type": "application/json" },
+ body: method === "GET" ? undefined : "{}",
+ });
+ assert.equal(response.status, 403, `${method} ${path} stays attended-only`);
+ }
+
+ 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 channelGrant = await capFor("admin-alice", {
+ live: false,
+ grants: ["admin.sessions.read"],
+ scope: scopeId("channel", "C1"),
+ });
+ const channelRead = await fetch(`${s.base}/v1/admin/sessions`, {
+ headers: { "x-agent-capability": channelGrant },
+ });
+ assert.equal(channelRead.status, 403);
+ assert.match(((await channelRead.json()) as { message: string }).message, /ask the agent in a DM/);
+ } finally {
+ await s.close();
+ }
+});
+
test("an aud-less token never opens the admin door", async () => {
const s = start();
try {
diff --git a/test/agent-api-discovery.test.ts b/test/agent-api-discovery.test.ts
index 2f3196557..734e3e02a 100644
--- a/test/agent-api-discovery.test.ts
+++ b/test/agent-api-discovery.test.ts
@@ -36,7 +36,11 @@ async function start() {
const capFor = (
actorId: string,
- opts: { memory?: { write?: ScopeId; orgWrite?: ScopeId; read: ScopeId[] }; liveActor?: boolean } = {},
+ opts: {
+ memory?: { write?: ScopeId; orgWrite?: ScopeId; read: ScopeId[] };
+ liveActor?: boolean;
+ grants?: string[];
+ } = {},
) =>
mintCapabilityToken(
{
@@ -45,6 +49,7 @@ const capFor = (
exp: Date.now() + CAPABILITY_TTL_MS,
...(opts.memory ? { memory: opts.memory } : {}),
...(opts.liveActor ? { liveActor: true } : {}),
+ ...(opts.grants ? { grants: opts.grants } : {}),
},
SECRET,
);
@@ -131,6 +136,25 @@ test("an admin's AUTONOMOUS turn (no liveActor) is shown no admin plane — matc
}
});
+test("a granted autonomous turn discovers only the unattended read family", async () => {
+ const s = await start();
+ try {
+ const { body } = await listApis(s.base, await capFor("admin-alice", { grants: ["admin.sessions.read"] }));
+ const adminPaths = paths(body).filter((path) => path.startsWith("/v1/admin/"));
+ assert.deepEqual(adminPaths, [
+ "/v1/admin/sessions",
+ "/v1/admin/sessions/:id",
+ "/v1/admin/scopes",
+ "/v1/admin/errors",
+ "/v1/admin/runs",
+ "/v1/admin/whoami",
+ ]);
+ assert.ok(body.guidance.some((guidance: string) => guidance.includes("flag any other admin action")));
+ } finally {
+ await s.close();
+ }
+});
+
test("discovery requires a capability token", async () => {
const s = await start();
try {
diff --git a/test/capability-routes.test.ts b/test/capability-routes.test.ts
index 006436d19..f81a1df94 100644
--- a/test/capability-routes.test.ts
+++ b/test/capability-routes.test.ts
@@ -64,9 +64,14 @@ describe("capability-token control plane (crons + SOUL)", () => {
signingSecret: SECRET,
}),
);
- server = createServer(built.app, { signingSecret: SECRET, scheduler: built.scheduler, config: built.config });
- await new Promise<void>((resolve) => server.listen(0, resolve));
- base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ server = createServer(built.app, {
+ signingSecret: SECRET,
+ scheduler: built.scheduler,
+ config: built.config,
+ admin: built.admin,
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
after(async () => {
@@ -107,6 +112,111 @@ describe("capability-token control plane (crons + SOUL)", () => {
SECRET,
);
+ it("enforces unattended grant creation and privileged-cron tamper rules at the HTTP boundary", async () => {
+ const body = {
+ schedule: { everyMs: 60_000 },
+ action: "scan transcripts",
+ unattendedGrants: ["admin.sessions.read"],
+ };
+ assert.equal((await post("/v1/crons", body, { "x-agent-capability": await capFor("admin-alice") })).status, 403);
+ assert.equal(
+ (
+ await post("/v1/crons", body, {
+ "x-agent-capability": await capFor("U1", scopeId("personal", "U1"), { liveActor: true }),
+ })
+ ).status,
+ 403,
+ );
+ assert.equal(
+ (
+ await post(
+ "/v1/crons",
+ { ...body, unattendedGrants: ["admin.everything"] },
+ {
+ "x-agent-capability": await capFor("admin-alice", scopeId("personal", "admin-alice"), {
+ liveActor: true,
+ }),
+ },
+ )
+ ).status,
+ 400,
+ );
+ assert.equal(
+ (
+ await post(
+ "/v1/crons",
+ { ...body, runAs: "scopeFloor" },
+ {
+ "x-agent-capability": await capFor("admin-alice", scopeId("channel", "C"), {
+ liveActor: true,
+ members: [{ id: "admin-alice", type: "internal" }],
+ }),
+ },
+ )
+ ).status,
+ 400,
+ );
+ assert.equal(
+ (
+ await post(
+ "/v1/crons",
+ { ...body, runAs: "scopeShared" },
+ {
+ "x-agent-capability": await capFor("admin-alice", scopeId("channel", "C"), {
+ liveActor: true,
+ members: [{ id: "admin-alice", type: "internal" }],
+ }),
+ },
+ )
+ ).status,
+ 400,
+ );
+ const create = await post("/v1/crons", body, {
+ "x-agent-capability": await capFor("admin-alice", scopeId("personal", "admin-alice"), { liveActor: true }),
+ });
+ assert.equal(create.status, 200);
+ const { cron } = (await create.json()) as { cron: { id: string; unattendedGrants?: string[] } };
+ assert.deepEqual(cron.unattendedGrants, ["admin.sessions.read"]);
+ const got = (await (
+ await get(`/v1/crons/${cron.id}`, {
+ "x-agent-capability": await capFor("admin-alice", scopeId("personal", "admin-alice"), { liveActor: true }),
+ })
+ ).json()) as { cron: { unattendedGrants?: string[] } };
+ assert.deepEqual(got.cron.unattendedGrants, ["admin.sessions.read"]);
+ const listed = (await (
+ await get("/v1/crons", {
+ "x-agent-capability": await capFor("admin-alice", scopeId("personal", "admin-alice"), { liveActor: true }),
+ })
+ ).json()) as { crons: Array<{ id: string; unattendedGrants?: string[] }> };
+ assert.deepEqual(listed.crons.find((candidate) => candidate.id === cron.id)?.unattendedGrants, [
+ "admin.sessions.read",
+ ]);
+ assert.equal(
+ (
+ await patch(
+ `/v1/crons/${cron.id}`,
+ { action: "tamper" },
+ {
+ "x-agent-capability": await capFor("admin-alice"),
+ },
+ )
+ ).status,
+ 403,
+ );
+ assert.equal(
+ (
+ await patch(
+ `/v1/crons/${cron.id}`,
+ { unattendedGrants: [] },
+ {
+ "x-agent-capability": await capFor("admin-bob", scopeId("personal", "admin-bob"), { liveActor: true }),
+ },
+ )
+ ).status,
+ 403,
+ );
+ });
+
it("creates a cron as the TOKEN's actor, ignoring a forged owner in the body", async () => {
const res = await post(
"/v1/crons",
@@ -497,6 +607,15 @@ describe("capability-token control plane (crons + SOUL)", () => {
assert.equal(patched.cron.id, id);
assert.equal(patched.cron.action, "edited");
assert.equal(patched.cron.schedule.cron, "0 9 * * *");
+ const same = (await (
+ await patch(
+ `/v1/crons/${id}`,
+ { action: "edited", schedule: { cron: "0 9 * * *", timezone: "America/Los_Angeles" } },
+ { "x-agent-capability": await capFor("U1") },
+ )
+ ).json()) as any;
+ assert.equal(same.cron.id, id);
+ assert.equal(same.cron.action, "edited");
const list = (await (await get("/v1/crons", { "x-agent-capability": await capFor("U1") })).json()) as any;
assert.equal(list.crons.filter((c: any) => c.id === id).length, 1);
@@ -533,11 +652,16 @@ describe("capability-token control plane (crons + SOUL)", () => {
{ "x-agent-capability": await capFor("U1") },
)
).json()) as any;
- assert.equal(
- (await patch(`/v1/crons/${created.cron.id}`, { nonsense: true }, { "x-agent-capability": await capFor("U1") }))
- .status,
- 400,
+ const nonsense = await patch(
+ `/v1/crons/${created.cron.id}`,
+ { nonsense: true },
+ { "x-agent-capability": await capFor("U1") },
);
+ assert.equal(nonsense.status, 400);
+ assert.match(((await nonsense.json()) as any).message, /nothing to change/);
+ const empty = await patch(`/v1/crons/${created.cron.id}`, {}, { "x-agent-capability": await capFor("U1") });
+ assert.equal(empty.status, 400);
+ assert.match(((await empty.json()) as any).message, /nothing to change/);
});
it("creates a scopeFloor cron when the token carries a member snapshot", async () => {
diff --git a/test/capability-token.test.ts b/test/capability-token.test.ts
index 4e2f34b15..18dff3c9c 100644
--- a/test/capability-token.test.ts
+++ b/test/capability-token.test.ts
@@ -24,6 +24,23 @@ test("mint → verify round-trips the claims", async () => {
assert.deepEqual(got, { orgId: "default-org", ...c });
});
+test("grants round-trip and reject malformed claims", async () => {
+ const granted = claims({ grants: ["admin.sessions.read"] });
+ assert.deepEqual(await verifyCapabilityToken(await mintCapabilityToken(granted, SECRET), SECRET), {
+ orgId: "default-org",
+ ...granted,
+ });
+ for (const grants of ["admin.sessions.read", ["admin.sessions.read", 1]]) {
+ assert.equal(
+ await verifyCapabilityToken(
+ await mintCapabilityToken(claims({ grants } as unknown as Partial<CapabilityClaims>), SECRET),
+ SECRET,
+ ),
+ null,
+ );
+ }
+});
+
test("timezone claims must be valid IANA timezone strings", async () => {
const c = claims({ timezone: "America/Los_Angeles" });
assert.deepEqual(await verifyCapabilityToken(await mintCapabilityToken(c, SECRET), SECRET), {
diff --git a/test/control-service.test.ts b/test/control-service.test.ts
index b27525332..8e33b8c2a 100644
--- a/test/control-service.test.ts
+++ b/test/control-service.test.ts
@@ -46,10 +46,105 @@ function claims(
function setup(): { built: BuiltApp; control: ControlService } {
const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "control-svc-")), signingSecret: SECRET }));
- const control = createControlService(built.app, built.scheduler);
+ const control = createControlService(built.app, built.scheduler, built.admin);
return { built, control };
}
+test("unattended cron grants require a live org-admin owner and protect later patches", async () => {
+ const { control } = setup();
+ const grant = ["admin.sessions.read"];
+ const request = { schedule: { everyMs: 3_600_000 }, action: "scan failures", unattendedGrants: grant };
+
+ const unattended = await control.createCron(request, claims("admin-alice"));
+ assert.deepEqual(unattended, {
+ ok: false,
+ code: "forbidden",
+ message: "unattended grants require a live turn started by the cron owner",
+ });
+
+ const nonAdmin = await control.createCron(request, claims("U1", scopeId("personal", "U1"), { liveActor: true }));
+ assert.equal(nonAdmin.ok, false);
+ assert.match(nonAdmin.ok ? "" : nonAdmin.message, /current org admin/);
+
+ const unknown = await control.createCron(
+ { ...request, unattendedGrants: ["admin.everything"] },
+ claims("admin-alice", scopeId("personal", "admin-alice"), { liveActor: true }),
+ );
+ assert.equal(unknown.ok, false);
+ assert.equal(unknown.ok ? "" : unknown.code, "bad_request");
+
+ const shared = await control.createCron(
+ { ...request, runAs: "scopeFloor" },
+ claims("admin-alice", scopeId("channel", "C9"), {
+ liveActor: true,
+ members: [{ id: "admin-alice", type: "internal" }],
+ }),
+ );
+ assert.equal(shared.ok, false);
+ assert.equal(shared.ok ? "" : shared.code, "bad_request");
+
+ const created = await control.createCron(
+ request,
+ claims("admin-alice", scopeId("personal", "admin-alice"), { liveActor: true }),
+ );
+ assert.ok(created.ok, JSON.stringify(created));
+ assert.deepEqual(created.cron.unattendedGrants, grant);
+
+ const nonOwner = await control.patchCron(
+ created.cron.id,
+ { unattendedGrants: [] },
+ claims("admin-bob", scopeId("personal", "admin-bob"), { liveActor: true }),
+ );
+ assert.equal(nonOwner.ok, false);
+ assert.equal(nonOwner.ok ? "" : nonOwner.code, "forbidden");
+
+ const tamper = await control.patchCron(created.cron.id, { action: "rewrite instructions" }, claims("admin-alice"));
+ assert.equal(tamper.ok, false);
+ assert.match(tamper.ok ? "" : tamper.message, /live turn/);
+
+ const privilegedNoop = await control.patchCron(created.cron.id, { enabled: true }, claims("admin-alice"));
+ assert.ok(privilegedNoop.ok, "a privileged cron no-op does not need a live grant reaffirmation");
+ assert.deepEqual(privilegedNoop.ok ? privilegedNoop.cron.unattendedGrants : undefined, grant);
+
+ const unattendedRun = await control.runCron(created.cron.id, claims("admin-alice"));
+ assert.equal(unattendedRun.ok, false);
+ assert.match(unattendedRun.ok ? "" : unattendedRun.message, /live turn/);
+
+ const cleared = await control.patchCron(
+ created.cron.id,
+ { unattendedGrants: [] },
+ claims("admin-alice", scopeId("personal", "admin-alice"), { liveActor: true }),
+ );
+ assert.ok(cleared.ok, "a grants-only patch from the live owner is a real patch");
+ assert.deepEqual(cleared.ok ? cleared.cron.unattendedGrants : undefined, []);
+});
+
+test("a raw unreaffirmed cron patch strips unattended grants; a live-owner patch reaffirms them", async () => {
+ const { built, control } = setup();
+ const created = await control.createCron(
+ { schedule: { everyMs: 3_600_000 }, action: "scan failures", unattendedGrants: ["admin.sessions.read"] },
+ claims("admin-alice", scopeId("personal", "admin-alice"), { liveActor: true }),
+ );
+ assert.ok(created.ok, JSON.stringify(created));
+ const id = created.ok ? created.cron.id : "";
+
+ const ownerPatch = await control.patchCron(
+ id,
+ { title: "renamed by owner" },
+ claims("admin-alice", scopeId("personal", "admin-alice"), { liveActor: true }),
+ );
+ assert.ok(ownerPatch.ok, JSON.stringify(ownerPatch));
+ assert.deepEqual(
+ ownerPatch.ok ? ownerPatch.cron.unattendedGrants : undefined,
+ ["admin.sessions.read"],
+ "a legitimate live-owner patch keeps the grant",
+ );
+
+ const tampered = await built.app.updateCron(id, { action: "attacker task" });
+ assert.equal(tampered?.action, "attacker task");
+ assert.deepEqual(tampered?.unattendedGrants, [], "a raw patch that does not reaffirm grants drops the cron to floor");
+});
+
test("cron create with a destinationKey resolves to that menu destination, and returns the created cron", async () => {
const { control } = setup();
const r = await control.createCron(
@@ -481,8 +576,16 @@ test("scopeShared is explicit: shared-scope crons default to owner, while collab
assert.equal(afterMemberEdit.length, 1, "non-owner edit via control service notifies the owner");
assert.equal(afterMemberEdit[0]!.destination.target, "U1");
+ const memberNoop = await control.patchCron(ok.cron.id, { title: "expo digest v2" }, chanClaims("U2"));
+ assert.ok(memberNoop.ok, JSON.stringify(memberNoop));
+ assert.equal((await editNotices()).length, 1, "same-value member edit produces no notice");
+
+ const memberChange = await control.patchCron(ok.cron.id, { title: "expo digest v3" }, chanClaims("U2"));
+ assert.ok(memberChange.ok, JSON.stringify(memberChange));
+ assert.equal((await editNotices()).length, 2, "a later real member edit still notifies the owner");
+
await control.patchCron(ok.cron.id, { title: "owner tweak" }, chanClaims("U1"));
- assert.equal((await editNotices()).length, 1, "owner self-edit produces no notice");
+ assert.equal((await editNotices()).length, 2, "owner self-edit produces no notice");
const byOutsider = await control.patchCron(
ok.cron.id,
@@ -627,7 +730,13 @@ test("app.turn forwards ownerKeychainUnion onto the persisted run request (else
});
test("cron list / get / patch / delete / run round-trip with owner authz", async () => {
- const { control } = setup();
+ const { built, control } = setup();
+ const updateCron = built.app.updateCron.bind(built.app);
+ let updateCalls = 0;
+ built.app.updateCron = async (id, patch) => {
+ updateCalls += 1;
+ return updateCron(id, patch);
+ };
const created = await control.createCron(
{ title: "orig", schedule: { everyMs: 3_600_000 }, action: "do x" },
claims("U1"),
@@ -652,6 +761,20 @@ test("cron list / get / patch / delete / run round-trip with owner authz", async
assert.equal(patched.cron.title, "renamed");
assert.equal(patched.cron.schedule.cron, "0 9 * * 1-5");
assert.equal(patched.cron.destination?.unfurlLinks, false);
+ assert.equal(updateCalls, 1);
+
+ const same = await control.patchCron(
+ id,
+ { title: "renamed", schedule: { cron: "0 9 * * 1-5", timezone: "America/Los_Angeles" }, unfurlLinks: false },
+ claims("U1"),
+ );
+ assert.ok(same.ok, JSON.stringify(same));
+ assert.equal(same.cron.id, id);
+ assert.equal(updateCalls, 1, "same-value patches return the cron without writing");
+
+ const sameMode = await control.patchCron(id, { runAs: "owner" }, claims("U1"));
+ assert.ok(sameMode.ok, JSON.stringify(sameMode));
+ assert.equal(updateCalls, 1, "the current effective mode is a recognized no-op");
const tooFrequent = await control.patchCron(id, { schedule: { everyMs: 1 } }, claims("U1"));
assert.equal(tooFrequent.ok, false);
@@ -663,6 +786,7 @@ test("cron list / get / patch / delete / run round-trip with owner authz", async
const empty = await control.patchCron(id, {}, claims("U1"));
assert.equal(empty.ok, false);
assert.equal(empty.ok ? "" : empty.code, "bad_request");
+ assert.match(empty.ok ? "" : empty.message, /nothing to change/);
const disabled = await control.setCronEnabled(id, false, claims("U1"));
assert.ok(disabled.ok);
diff --git a/test/cron-scheduler.test.ts b/test/cron-scheduler.test.ts
index cdd5cba1c..cd253a8bd 100644
--- a/test/cron-scheduler.test.ts
+++ b/test/cron-scheduler.test.ts
@@ -52,6 +52,20 @@ function harness(
const member = (id: string) => ({ id, type: "internal" as const });
+test("scheduler threads stored unattended grants into owner-mode turns", async () => {
+ const { crons, calls, scheduler } = harness();
+ const cron = await crons.create({
+ schedule: { everyMs: 1000 },
+ action: "scan transcripts",
+ owner: "U1",
+ createdBy: "U1",
+ ownerScopeId: scopeId("personal", "U1"),
+ unattendedGrants: ["admin.sessions.read"],
+ });
+ await scheduler.runNow(cron.id);
+ assert.deepEqual(calls[0]?.unattendedGrants, ["admin.sessions.read"]);
+});
+
test("a channel cron runs in the channel scope and delivers its real output to the channel", async () => {
const { crons, deliveries, calls, scheduler } = harness();
const cron = await crons.create({
diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.ts
index f9825bdf1..a4520c019 100644
--- a/test/orchestrator.test.ts
+++ b/test/orchestrator.test.ts
@@ -749,6 +749,35 @@ test("turn timezone rides the prompt and control-plane capability token", async
assert.equal(invalidClaims!.timezone, undefined, "invalid surface timezones are omitted from the token");
});
+test("unattended grants enter capability claims only on non-live turns", async () => {
+ const config = testConfig({
+ dataDir: mkdtempSync(join(tmpdir(), "ap-")),
+ signingSecret: "test-secret",
+ apiBaseUrl: "https://core.example.com",
+ });
+ const { app, sandbox } = buildApp(config);
+ let captured: ProvisionOptions | undefined;
+ const realProvision = sandbox.provision.bind(sandbox);
+ sandbox.provision = (layers, opts) => {
+ captured = opts;
+ return realProvision(layers, opts);
+ };
+
+ await app.turn(dm("!run echo cron", { triggered: true, unattendedGrants: ["admin.sessions.read"] }));
+ let claims = await verifyCapabilityToken(captured!.env!.AGENT_API_TOKEN!, TEST_CAPABILITY_SECRET);
+ assert.deepEqual(claims?.grants, ["admin.sessions.read"]);
+
+ await app.turn(
+ dm("!run echo live", {
+ liveActor: true,
+ conversation: { kind: "dm", threadRef: "dm:U1:live-grant" },
+ unattendedGrants: ["admin.sessions.read"],
+ }),
+ );
+ claims = await verifyCapabilityToken(captured!.env!.AGENT_API_TOKEN!, TEST_CAPABILITY_SECRET);
+ assert.equal(claims?.grants, undefined);
+});
+
test("the egress claim keeps the control-plane host reachable under an allowlist or a matching denylist", () => {
const core = "https://core.example.com";
diff --git a/test/run-trigger.test.ts b/test/run-trigger.test.ts
index 6f8bd5485..f2c0317eb 100644
--- a/test/run-trigger.test.ts
+++ b/test/run-trigger.test.ts
@@ -203,6 +203,37 @@ 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 for owner mode but omits them for scopeFloor and scopeShared", async () => {
+ const requests: TurnRequest[] = [];
+ const d = deps(async (request) => {
+ requests.push(request);
+ return { status: "ok" };
+ });
+ const base = {
+ owner: "U1",
+ ownerScopeId: scopeId("personal", "U1"),
+ input: "scan",
+ surface: "cron",
+ unattendedGrants: ["admin.sessions.read"],
+ };
+ await runTrigger(d, { ...base, fireKey: "cron:owner" });
+ await runTrigger(d, {
+ ...base,
+ fireKey: "cron:floor",
+ runAs: "scopeFloor",
+ members: [{ id: "U1", type: "internal" }],
+ });
+ await runTrigger(d, {
+ ...base,
+ fireKey: "cron:shared",
+ runAs: "scopeShared",
+ members: [{ id: "U1", type: "internal" }],
+ });
+ assert.deepEqual(requests[0]?.unattendedGrants, ["admin.sessions.read"]);
+ assert.equal(requests[1]?.unattendedGrants, undefined);
+ assert.equal(requests[2]?.unattendedGrants, undefined);
+ });
+
it("a destination-bearing cron keeps the compose-then-enqueue path: no surface tools, one delivery", async () => {
let req: TurnRequest | undefined;
const d = deps(async (r) => {
diff --git a/test/turns-union-guard.test.ts b/test/turns-union-guard.test.ts
index 4c858c952..164715a3f 100644
--- a/test/turns-union-guard.test.ts
+++ b/test/turns-union-guard.test.ts
@@ -56,6 +56,36 @@ test("POST /v1/turns strips ownerKeychainUnion from the external body but keeps
assert.equal(run?.request.skipMemory, true, "the source-authenticated memory opt-out is forwarded");
});
+test("POST /v1/turns strips unattendedGrants from the external body", async () => {
+ const body = JSON.stringify({
+ surface: "cron",
+ actor: { externalId: "internal:owner" },
+ conversation: {
+ kind: "channel",
+ channelRef: "C9",
+ threadRef: "t-grants-guard",
+ audience: [{ externalId: "internal:owner" }],
+ },
+ text: "x",
+ triggered: true,
+ unattendedGrants: ["admin.sessions.read"],
+ async: true,
+ });
+ const r = await fetch(`${base}/v1/turns`, {
+ method: "POST",
+ headers: { ...signedHeaders(SECRET, "POST", "/v1/turns", body), "content-type": "application/json" },
+ body,
+ });
+ assert.equal(r.status, 202);
+ const { runId } = (await r.json()) as { runId: string };
+ const run = await built.runs.get(runId);
+ assert.equal(
+ run?.request.unattendedGrants,
+ undefined,
+ "an external caller cannot smuggle an unattended admin grant into a turn",
+ );
+});
+
test("POST /v1/turns strips nested owner-keychain union from typed automation origin", async () => {
const body = JSON.stringify({
surface: "cron",