Multiplayer agent harness for work.
Branch on typed error codes instead of error text in core API paths (#2441)
Regan Bellbc737b6fb706
diff --git a/plugins/web-ui/src/inbox.ts b/plugins/web-ui/src/inbox.tsindex 54dd50206..e35535275 100644--- a/plugins/web-ui/src/inbox.ts+++ b/plugins/web-ui/src/inbox.ts@@ -911,7 +911,7 @@ function editDraft(item: InboxItem, patch: Partial<InboxDraft>): void {}function isDraftConflict(e: unknown): boolean {- return e instanceof ApiError && e.status === 409 && /draft changed/i.test(e.message);+ return e instanceof ApiError && (e.body as { error?: unknown } | null)?.error === "draft_changed";}async function explainDraftConflict(item: InboxItem, edited: boolean): Promise<void> {diff --git a/plugins/web-ui/test/inbox-conversation.test.ts b/plugins/web-ui/test/inbox-conversation.test.tsindex b1f4c066d..21b7dace2 100644--- a/plugins/web-ui/test/inbox-conversation.test.ts+++ b/plugins/web-ui/test/inbox-conversation.test.ts@@ -121,7 +121,8 @@ test("draft stays outside AI chat and Send it submits the combined instruction",globalThis.fetch = async (url) => {if (String(url).includes("runtime-config")) return Response.json(inboxRuntime);staleCalls.push(String(url));- if (String(url).endsWith("/action")) return Response.json({ message: "draft changed" }, { status: 409 });+ if (String(url).endsWith("/action"))+ return Response.json({ error: "draft_changed", message: "draft changed" }, { status: 409 });staleLedger.proposal = { data: { body: "New agent draft" }, by: "agent", at: 200 };return Response.json({ item: staleLedger });};@@ -258,9 +259,12 @@ test("draft stays outside AI chat and Send it submits the combined instruction",if (String(url).endsWith("/action"))return new Response(JSON.stringify({ message: "Save unavailable" }), { status: 502 });if (String(url).endsWith("/followup"))- return new Response(JSON.stringify({ message: "the draft changed; review it before continuing" }), {- status: 409,- });+ return new Response(+ JSON.stringify({ error: "draft_changed", message: "the draft changed; review it before continuing" }),+ {+ status: 409,+ },+ );return Response.json({item: { ...ledger, proposal: { ...ledger.proposal, data: { body: "New server draft" }, at: 101 } },});diff --git a/plugins/web-ui/test/inbox-upload-draft.test.ts b/plugins/web-ui/test/inbox-upload-draft.test.tsindex 266e9190d..9c66f48ac 100644--- a/plugins/web-ui/test/inbox-upload-draft.test.ts+++ b/plugins/web-ui/test/inbox-upload-draft.test.ts@@ -65,7 +65,7 @@ test("a submission freezes the edited draft before upload and never retries a coat: 101,};return conflict- ? Response.json({ message: "the draft changed" }, { status: 409 })+ ? Response.json({ error: "draft_changed", message: "the draft changed" }, { status: 409 }): Response.json({ item: ledger });}if (path.endsWith("/followup")) {diff --git a/scripts/dev/commands/doctor.ts b/scripts/dev/commands/doctor.tsindex ed6016170..f9dafdcab 100644--- a/scripts/dev/commands/doctor.ts+++ b/scripts/dev/commands/doctor.ts@@ -8,7 +8,7 @@ import { portHolders } from "../lib/proc.ts";import { resolveSocketPath, supervisorReachable, supervisorRequest } from "../lib/client.ts";import { EXIT, CHILD_ORDER } from "../lib/types.ts";import { errMessage } from "../lib/util.ts";-import type { StatusReport } from "../lib/types.ts";+import type { CanaryReply, StatusReport } from "../lib/types.ts";interface Check {id: string;@@ -19,6 +19,23 @@ interface Check {autoFixable?: boolean;}+export function eventDeliveryCheck(canary: CanaryReply): Check {+ const unconfigured = !canary.ok && canary.code === "unconfigured";+ let remedy: string | undefined;+ if (!canary.ok) {+ remedy = unconfigured+ ? "set CANARY_CHANNEL in the slot env (a channel the bot is in), then dev down && dev up"+ : "events are not arriving: dev up --rotate (stolen/stale app), or check the slack log";+ }+ return {+ id: "event-delivery",+ ok: canary.ok,+ severity: unconfigured ? "warn" : "critical",+ detail: canary.ok ? `canary round trip ${canary.rttMs}ms` : `canary failed: ${canary.reason}`,+ remedy,+ };+}+export async function runDoctor(opts: { json: boolean; fix: boolean; store: string; slack: boolean }): Promise<number> {const checks: Check[] = [];const worktree = (() => {@@ -119,25 +136,8 @@ export async function runDoctor(opts: { json: boolean; fix: boolean; store: stri? "check for other instances; reconnect and verify with dev up --rotate": undefined,});- const canary = (await supervisorRequest(sock, "POST", "/canary", {}, 40_000)).body as {- ok: boolean;- rttMs?: number;- reason?: string;- };- const unconfigured = !canary.ok && /no canary channel configured/.test(canary.reason ?? "");- let eventDeliveryRemedy: string | undefined;- if (!canary.ok) {- eventDeliveryRemedy = unconfigured- ? "set CANARY_CHANNEL in the slot env (a channel the bot is in), then dev down && dev up"- : "events are not arriving: dev up --rotate (stolen/stale app), or check the slack log";- }- checks.push({- id: "event-delivery",- ok: canary.ok,- severity: unconfigured ? "warn" : "critical",- detail: canary.ok ? `canary round trip ${canary.rttMs}ms` : `canary failed: ${canary.reason}`,- remedy: eventDeliveryRemedy,- });+ const canary = (await supervisorRequest(sock, "POST", "/canary", {}, 40_000)).body as CanaryReply;+ checks.push(eventDeliveryCheck(canary));}const gitNow = gitHead(worktree);checks.push({diff --git a/scripts/dev/lib/types.ts b/scripts/dev/lib/types.tsindex f96294a41..d4f851482 100644--- a/scripts/dev/lib/types.ts+++ b/scripts/dev/lib/types.ts@@ -128,3 +128,10 @@ export interface LeaseInfo {heartbeat: { pid: number; at: number; phase: string } | null;state: Record<string, unknown> | null;}++export interface CanaryReply {+ ok: boolean;+ code?: "unconfigured";+ rttMs?: number;+ reason?: string;+}diff --git a/scripts/dev/supervisor/main.ts b/scripts/dev/supervisor/main.tsindex b174a9b47..626b8c6c9 100644--- a/scripts/dev/supervisor/main.ts+++ b/scripts/dev/supervisor/main.ts@@ -24,7 +24,15 @@ import { envSha as computeEnvSha, errMessage, nowEpoch, sleep } from "../lib/utiimport { discoverCanaryChannel } from "../lib/canary.ts";import { buildChildSpecs, type SpecInputs } from "./specs.ts";import { Child } from "./children.ts";-import type { BootPhaseEvent, BootResult, BootSpec, ChildName, SlackHealth, StatusReport } from "../lib/types.ts";+import type {+ BootPhaseEvent,+ BootResult,+ BootSpec,+ CanaryReply,+ ChildName,+ SlackHealth,+ StatusReport,+} from "../lib/types.ts";import { CHILD_ORDER, EXIT } from "../lib/types.ts";const HEALTH_INTERVAL_MS = 10_000;@@ -157,17 +165,14 @@ async function fetchSlackHealth(): Promise<SlackHealth | null> {}}-async function runCanary(- channel: string,- timeoutMs = 15_000,-): Promise<{ ok: boolean; rttMs?: number; reason?: string }> {+async function runCanary(channel: string, timeoutMs = 15_000): Promise<CanaryReply> {try {const res = await fetch(`http://127.0.0.1:${ports.slackHealth}/canary`, {method: "POST",body: JSON.stringify({ channel, timeoutMs }),signal: AbortSignal.timeout(timeoutMs + 5000),});- return (await res.json()) as { ok: boolean; rttMs?: number; reason?: string };+ return (await res.json()) as CanaryReply;} catch (err) {return { ok: false, reason: `canary endpoint unreachable: ${errMessage(err)}` };}@@ -662,7 +667,12 @@ function serveApi(): Server {if (req.method === "POST" && req.url === "/canary") {if (!canaryChannel) await resolveCanaryChannel(readBootSpec());const channel = String(body.channel || canaryChannel || "");- respond(200, channel ? await runCanary(channel) : { ok: false, reason: "no canary channel configured" });+ respond(+ 200,+ channel+ ? await runCanary(channel)+ : ({ ok: false, code: "unconfigured", reason: "no canary channel configured" } satisfies CanaryReply),+ );return;}if (req.method === "POST" && req.url === "/shutdown") {diff --git a/src/admin/postgres-audit-log.ts b/src/admin/postgres-audit-log.tsindex 7b70d4a6f..38fe745ff 100644--- a/src/admin/postgres-audit-log.ts+++ b/src/admin/postgres-audit-log.ts@@ -117,13 +117,5 @@ export function createPostgresAuditLog(connectionString: string): AuditLog {);return rows.map(rowToEvent);},- async tallyByResource(action) {- await Promise.allSettled(pendingWrites);- const rows = await q(- `SELECT resource, count(*)::bigint AS n FROM audit_log WHERE action = $1 GROUP BY resource`,- [action],- );- return new Map(rows.map((r) => [String(r.resource), Number(r.n)]));- },};}diff --git a/src/api/app-deployments.ts b/src/api/app-deployments.tsindex 9d2cb2507..75acb759e 100644--- a/src/api/app-deployments.ts+++ b/src/api/app-deployments.ts@@ -3,7 +3,7 @@ import { createMemoryAdvisoryLock } from "../persistence/advisory-lock.ts";import { INVITE_EMAIL_NOT_CONFIGURED, renderInviteEmail } from "../admin/invite-email.ts";import { deploymentShareScope } from "../deploy/email-access.ts";import { errMessage } from "../util/errors.ts";-import type { Reach } from "../deploy/deploy-service.ts";+import { DeployAccessError, type Reach } from "../deploy/deploy-service.ts";import { mintDeployGitAccess } from "../deploy/access-token.ts";import type { App, AppDeps, ViewerDeployment } from "./app-types.ts";@@ -70,9 +70,12 @@ export function createDeploymentMethods(if (!validEmail(email)) throw new Error("a valid email address is required");const grantee = await deploymentShareScope(`personal:${email}`, "read");const deployment = await deps.deploy.getDeployment(idOrName);- if (!deployment) throw new Error(`no such app: ${idOrName}`);+ if (!deployment) throw new DeployAccessError("not_found", `no such app: ${idOrName}`);if (deployment.ownerScopeId !== `personal:${actorId}`)- throw new Error(`only the owner can change who can reach "${deployment.name ?? deployment.id}"`);+ throw new DeployAccessError(+ "forbidden",+ `only the owner can change who can reach "${deployment.name ?? deployment.id}"`,+ );return invitationLock.withLock(`deployment-invite:${deployment.id}:${email}`, async () => {const previous = await deps.deploy.deploymentGrantees(deployment.id);const alreadyShared = previous.some((g) => g.scope === grantee);diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex c209ecf31..717e3188e 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -26,7 +26,14 @@ import { MAX_ATTACHMENT_BYTES, mimeFromName, safeAttachmentName } from "../core/import { projectIdFromGroupRef, projectScopeId } from "../projects/project-store.ts";import type { App, AppDeps } from "./app-types.ts";-import { toFileItem, type ScopeDeployment, type SessionPinView, type SessionSearchHit } from "./app-types.ts";+import {+ SoulUpdateDeniedError,+ SoulVersionConflictError,+ toFileItem,+ type ScopeDeployment,+ type SessionPinView,+ type SessionSearchHit,+} from "./app-types.ts";import type { AppHelpers } from "./app-helpers.ts";const MAX_SESSION_PINS = 50;@@ -1213,7 +1220,7 @@ export function createSessionMethods(const allowedPersonal = kind === "personal" && samePerson(ref, actorId);const allowedShared = opts?.allowSharedScope && (kind === "channel" || kind === "group");if (!allowedPersonal && !allowedShared) {- throw new Error("not authorized to update SOUL for this scope");+ throw new SoulUpdateDeniedError();}const write = async (): Promise<number> => {let snapshot: Awaited<ReturnType<typeof deps.config.captureSoulSnapshot>> | undefined;@@ -1224,7 +1231,7 @@ export function createSessionMethods(opts?.expectedVersion === undefined? await deps.config.setSoul(scopeIdValue, content, actorId): await deps.config.setSoulIfVersion(scopeIdValue, opts.expectedVersion, content, actorId);- if (version === null) throw new Error("Guidance changed; read it and retry the edit.");+ if (version === null) throw new SoulVersionConflictError();deps.auditLog.record({at: Date.now(),principalId: actorId,diff --git a/src/api/app-types.ts b/src/api/app-types.tsindex 3f59c4ab2..2cab2140d 100644--- a/src/api/app-types.ts+++ b/src/api/app-types.ts@@ -776,6 +776,20 @@ export function toFileItem(a: FileArtifact): FileListItem {};}+export class SoulUpdateDeniedError extends Error {+ constructor() {+ super("not authorized to update SOUL for this scope");+ this.name = "SoulUpdateDeniedError";+ }+}++export class SoulVersionConflictError extends Error {+ constructor() {+ super("Guidance changed; read it and retry the edit.");+ this.name = "SoulVersionConflictError";+ }+}+export const CONTEXT_REQUEST_EXPIRY_MS = 2 * 60_000;export const STALE_LEASE_GRACE_MS = 30_000;diff --git a/src/api/control-service.ts b/src/api/control-service.tsindex a11e1abe9..463902acb 100644--- a/src/api/control-service.ts+++ b/src/api/control-service.ts@@ -16,6 +16,7 @@ import { resolveCapabilityDestination } from "./capability-destination.ts";import { withSlackUnfurlOption, principalDestination } from "../reach/reach.ts";import { notifyOwnerOfCronEdit, type CronEditDetail } from "../triggers/edit-notice.ts";import { errMessage } from "../util/errors.ts";+import { SoulUpdateDeniedError, SoulVersionConflictError } from "./app-types.ts";import { AdminError } from "../admin/admin-service.ts";import type { AdminService } from "../admin/admin-service.ts";import {@@ -176,10 +177,18 @@ export interface ControlService {content: string,claims: CapabilityClaims,expectedVersion?: number,- ): Promise<ControlOk<{ version: number }> | ControlErr<"soul_update_denied">>;+ ): Promise<ControlOk<{ version: number }> | ControlErr<SoulWriteFailureCode>>;shareArtifact(req: ShareArtifactRequest, claims: CapabilityClaims): Promise<ShareArtifactResult>;}+type SoulWriteFailureCode = "soul_update_denied" | "soul_version_conflict" | "soul_update_failed";++function soulWriteFailureCode(e: unknown): SoulWriteFailureCode {+ if (e instanceof SoulUpdateDeniedError) return "soul_update_denied";+ if (e instanceof SoulVersionConflictError) return "soul_version_conflict";+ return "soul_update_failed";+}+async function ownsCron(app: Pick<App, "samePerson" | "isCurrentSharedScopeMember" | "membershipControlsScope" | "managesScope">,cron: Cron,@@ -449,10 +458,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad{ owner: capability.actorId, ownerScopeId },capability,);- if (refusal) {- const code = refusal.includes("personal-scope") ? "bad_request" : "forbidden";- return { ok: false, code, message: refusal };- }+ if (refusal) return { ok: false, ...refusal };}if (req.unfurlLinks !== undefined && !destination) {@@ -539,10 +545,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Adif (!cronPatchChanges(before, patch)) return { ok: true, cron: before };if ((before.unattendedGrants?.length ?? 0) > 0 || req.unattendedGrants !== undefined) {const refusal = await unattendedGrantRefusal(app, admin, before, capability);- if (refusal) {- const code = refusal.includes("personal-scope") ? "bad_request" : "forbidden";- return { ok: false, code, message: refusal };- }+ if (refusal) return { ok: false, ...refusal };}try {const cron = await app.updateCron(id, patch);@@ -606,7 +609,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Adconst ownFire = capability.threadRef?.startsWith(`cron:${id}:fire:`) === true;if (!ownFire && (cron.unattendedGrants?.length ?? 0) > 0) {const refusal = await unattendedGrantRefusal(app, admin, cron, capability);- if (refusal) return { ok: false, code: "forbidden", message: refusal };+ if (refusal) return { ok: false, code: "forbidden", message: refusal.message };}const fireEntry = ownFire ? await app.latestCronFireForThread(id, capability.threadRef!) : undefined;const outcome = await app.setCronFireNote(id, {@@ -636,7 +639,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Adreturn { 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 };+ if (refusal) return { ok: false, code: "forbidden", message: refusal.message };}if (cron.enabled === enabled) return { ok: true, cron };await app.setCronEnabled(id, enabled);@@ -652,7 +655,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Adreturn { 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 (refusal) return { ok: false, code: "forbidden", message: refusal.message };}if (!scheduler)return {@@ -681,7 +684,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Adreturn { 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 (refusal) return { ok: false, code: "forbidden", message: refusal.message };}const resolved = resolveCapabilityDestination(capability, destinationKey);if (!resolved.ok) {@@ -775,7 +778,11 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad});return { ok: true, version };} catch (e) {- return { ok: false, code: "soul_update_denied", message: errMessage(e) };+ return {+ ok: false,+ code: soulWriteFailureCode(e),+ message: errMessage(e),+ };}},diff --git a/src/api/routes/admin/users.ts b/src/api/routes/admin/users.tsindex ac623f7d9..71097a911 100644--- a/src/api/routes/admin/users.ts+++ b/src/api/routes/admin/users.ts@@ -359,15 +359,7 @@ export async function listKeychainStatus(ctx: ApiCtx): Promise<void> {pendingAskCount: asks.filter((a) => samePerson(a.ownerId, principalId) && a.status === "pending").length,}));- const tally = (await deps.auditLog?.tallyByResource?.("keychain.materialize")) ?? new Map<string, number>();- const useCountByGrant = new Map<string, number>();- for (const [resource, n] of tally) {- const m = /\(grant ([0-9a-f]+)\)$/.exec(resource);- if (m) useCountByGrant.set(m[1]!, (useCountByGrant.get(m[1]!) ?? 0) + n);- }- const grantsWithUse = grants.map((g) => ({ ...g, useCount: useCountByGrant.get(g.id) ?? 0 }));-- return sendJson(res, 200, { scopeId: scope, people, credentials, grants: grantsWithUse, asks, enabled: true });+ return sendJson(res, 200, { scopeId: scope, people, credentials, grants, asks, enabled: true });}async function resolveAdminUser(deps: ApiCtx["deps"], requestedPrincipal: string) {diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.tsindex 7ddbf3ec1..767e10e75 100644--- a/src/api/routes/deployments.ts+++ b/src/api/routes/deployments.ts@@ -1,5 +1,5 @@-import { EXTERNAL_APP_SHARING_OFF, externalAppSharingAllowed } from "../../feature-flags.ts";-import { PublicLinksUnavailableError } from "../../deploy/deploy-service.ts";+import { externalAppSharingAllowed } from "../../feature-flags.ts";+import { DeployAccessError, type DeployAccessErrorCode } from "../../deploy/deploy-service.ts";import { SocksProxyAgent } from "socks-proxy-agent";import { request as httpRequest } from "node:http";import { request as httpsRequest } from "node:https";@@ -1619,23 +1619,7 @@ export async function shareDeployment(ctx: ApiCtx): Promise<void> {grantees: await app.deploymentGrantees(deployment.id),});} catch (e) {- const msg = errMessage(e);- let status = 400;- let error = "share_failed";- if (/no such app/.test(msg)) {- status = 404;- error = "not_found";- } else if (/only the owner/.test(msg)) {- status = 403;- error = "forbidden";- } else if (msg === EXTERNAL_APP_SHARING_OFF) {- status = 403;- error = "external_sharing_disabled";- } else if (e instanceof PublicLinksUnavailableError) {- status = 409;- error = "public_links_unavailable";- }- return sendJson(res, status, { error, message: msg });+ return sendShareFailure(res, e);}}if (b.email !== undefined && typeof b.email !== "string")@@ -1691,18 +1675,23 @@ export async function shareDeployment(ctx: ApiCtx): Promise<void> {grantees,});} catch (e) {- const msg = errMessage(e);- let status = 400;- if (/no such app/.test(msg)) status = 404;- else if (/only the owner/.test(msg) || msg === EXTERNAL_APP_SHARING_OFF) status = 403;- let error = "share_failed";- if (status === 404) error = "not_found";- else if (msg === EXTERNAL_APP_SHARING_OFF) error = "external_sharing_disabled";- else if (status === 403) error = "forbidden";- return sendJson(res, status, { error, message: msg });+ return sendShareFailure(res, e);}}+const DEPLOY_ACCESS_STATUS: Record<DeployAccessErrorCode, number> = {+ not_found: 404,+ forbidden: 403,+ external_sharing_disabled: 403,+ public_links_unavailable: 409,+};++function sendShareFailure(res: ApiCtx["res"], e: unknown): void {+ if (e instanceof DeployAccessError)+ return sendJson(res, DEPLOY_ACCESS_STATUS[e.code], { error: e.code, message: e.message });+ return sendJson(res, 400, { error: "share_failed", message: errMessage(e) });+}+export const deploymentRawRoutes: ReadonlyArray<Route<BaseCtx>> = [{ match: isDeploymentGitRoute, auth: "public", handle: serveDeploymentGit },{diff --git a/src/api/routes/file-uploads.ts b/src/api/routes/file-uploads.tsindex f06ad3644..4ace362c0 100644--- a/src/api/routes/file-uploads.ts+++ b/src/api/routes/file-uploads.ts@@ -1,7 +1,7 @@import { readFile } from "node:fs/promises";import { sendJson } from "../http.ts";import { scopeId, type ScopeId } from "../../types.ts";-import { FileUploadError } from "../../files/direct-file-upload.ts";+import { FileUploadError } from "../../files/file-upload-store.ts";import { isObj, audit } from "./shared.ts";import { withActor, type ApiCtx, type Route } from "./route.ts";@@ -70,9 +70,7 @@ async function handleUpload(ctx: ApiCtx): Promise<void> {return sendJson(res, 200, { ok: true });} catch (error) {if (error instanceof FileUploadError)- return sendJson(res, error.status, { error: "upload_error", message: error.message });- if (error instanceof Error && error.message === "active upload quota exceeded")- return sendJson(res, 429, { error: "upload_quota", message: error.message });+ return sendJson(res, error.status, { error: error.code, message: error.message });throw error;}}diff --git a/src/api/routes/loop-items.ts b/src/api/routes/loop-items.tsindex 3a45f8bb7..bd270d648 100644--- a/src/api/routes/loop-items.ts+++ b/src/api/routes/loop-items.ts@@ -299,7 +299,7 @@ async function actOnItem(ctx: ApiCtx): Promise<void> {const expectedAt = typeof args.expectedProposalAt === "number" ? args.expectedProposalAt : undefined;const draftChanged = (): void =>sendJson(ctx.res, 409, {- error: "conflict",+ error: "draft_changed",message: "the draft changed since you last saw it; review the new draft before sending",});@@ -478,7 +478,10 @@ async function followUpOnItem(ctx: ApiCtx): Promise<void> {});}if (typeof body.expectedProposalAt === "number" && item.proposal?.at !== body.expectedProposalAt) {- return sendJson(ctx.res, 409, { error: "conflict", message: "the draft changed; review it before continuing" });+ return sendJson(ctx.res, 409, {+ error: "draft_changed",+ message: "the draft changed; review it before continuing",+ });}if (!deps.fire) return sendJson(ctx.res, 404, { error: "not_found", message: "loop firing is not wired" });try {diff --git a/src/api/routes/loops.ts b/src/api/routes/loops.tsindex ac3cd734f..c25ae7af4 100644--- a/src/api/routes/loops.ts+++ b/src/api/routes/loops.ts@@ -109,9 +109,9 @@ export async function requireLoopAuthority(ctx: ApiCtx, deps: LoopServiceDeps, lconst principal = ctx.capability ?? (ctx.actor?.p ? { actorId: ctx.actor.p, liveActor: true } : undefined);const refusal = principal? await unattendedGrantRefusal(ctx.app, ctx.deps.admin, cron, principal)- : "a privileged loop requires a live turn started by its owner";+ : { message: "a privileged loop requires a live turn started by its owner" };if (!refusal) return true;- sendJson(ctx.res, 403, { error: "forbidden", message: refusal });+ sendJson(ctx.res, 403, { error: "forbidden", message: refusal.message });return false;}diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex 5ca820592..bd4764cf3 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -18,6 +18,7 @@ import {} from "../../model/pi-models.ts";import { builtInModelCatalog, selectableCatalogForHarness, selectableModelCatalog } from "../../model/model-catalog.ts";import { errMessage } from "../../util/errors.ts";+import { SoulUpdateDeniedError } from "../app-types.ts";import { parsePinnedSkills } from "../../skills/materialize.ts";import { renderAgentApis } from "../agent-api-catalog.ts";import { mintCapabilityToken, CAPABILITY_TTL_MS } from "../../auth/capability-token.ts";@@ -1313,9 +1314,9 @@ export async function postSoul(ctx: ApiCtx): Promise<void> {);return sendJson(res, 200, { ok: true, version });} catch (e) {- const message = errMessage(e);- const denied = message === "not authorized to update SOUL for this scope";- return sendJson(res, denied ? 403 : 500, { error: denied ? "soul_update_denied" : "soul_update_failed", message });+ if (e instanceof SoulUpdateDeniedError)+ return sendJson(res, 403, { error: "soul_update_denied", message: e.message });+ return sendJson(res, 500, { error: "soul_update_failed", message: errMessage(e) });}}diff --git a/src/audit/audit-log.ts b/src/audit/audit-log.tsindex 5e2dbce6a..b48aa6e45 100644--- a/src/audit/audit-log.ts+++ b/src/audit/audit-log.ts@@ -22,8 +22,6 @@ export interface AuditLog {since?: number;resourceContains?: string;}): Promise<readonly AuditEvent[]>;-- tallyByResource?(action: string): Promise<ReadonlyMap<string, number>>;}const MAX = 50000;@@ -53,10 +51,5 @@ export function createAuditLog(): AuditLog {(resourceContains === undefined || e.resource.includes(resourceContains)),).slice(0, limit),- async tallyByResource(action) {- const out = new Map<string, number>();- for (const e of sink.all()) if (e.action === action) out.set(e.resource, (out.get(e.resource) ?? 0) + 1);- return out;- },};}diff --git a/src/cron/authority.ts b/src/cron/authority.tsindex f8f56f0ea..84644b7dc 100644--- a/src/cron/authority.ts+++ b/src/cron/authority.ts@@ -15,21 +15,30 @@ export function cronTriggerAuthority(cron: TriggerAuthority): TriggerAuthority {};}+export interface UnattendedGrantRefusal {+ code: "bad_request" | "forbidden";+ message: string;+}+export async function unattendedGrantRefusal(app: App,admin: AdminService | undefined,cron: Pick<Cron, "owner" | "ownerScopeId">,capability: Pick<CapabilityClaims, "actorId" | "liveActor">,-): 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:")) return "unattended grants require a personal-scope cron";+): Promise<UnattendedGrantRefusal | null> {+ const forbidden = (message: string): UnattendedGrantRefusal => ({ code: "forbidden", message });+ if (capability.liveActor !== true)+ 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" };let status: Awaited<ReturnType<AdminService["adminStatusOf"]>> | undefined;try {status = await admin?.adminStatusOf({ id: capability.actorId, type: "internal" });} catch (e) {- return `unattended grants could not confirm the cron owner is a current org admin: ${errMessage(e)}`;+ return forbidden(`unattended grants could not confirm the cron owner is a current org admin: ${errMessage(e)}`);}- if (!status?.isAdmin) return "unattended grants require the cron owner to be a current org admin";+ if (!status?.isAdmin) return forbidden("unattended grants require the cron owner to be a current org admin");return null;}diff --git a/src/deploy/deploy-service.ts b/src/deploy/deploy-service.tsindex 86108374c..3efa8843f 100644--- a/src/deploy/deploy-service.ts+++ b/src/deploy/deploy-service.ts@@ -118,10 +118,15 @@ export interface DeploymentGrantee {const PUBLIC_LINKS_UNAVAILABLE ="This instance serves apps at /d/<app>/ on its own domain, which always requires sign-in, so a public link would still ask visitors to sign in. Public links need an apps domain: set DEPLOY_APPS_DOMAIN to a domain with a wildcard DNS record routed to the portal, and AWS_DEPLOY_GATE_SECRET.";-export class PublicLinksUnavailableError extends Error {- constructor() {- super(PUBLIC_LINKS_UNAVAILABLE);- this.name = "PublicLinksUnavailableError";+export type DeployAccessErrorCode =+ "not_found" | "forbidden" | "external_sharing_disabled" | "public_links_unavailable";++export class DeployAccessError extends Error {+ readonly code: DeployAccessErrorCode;+ constructor(code: DeployAccessErrorCode, message: string) {+ super(message);+ this.name = "DeployAccessError";+ this.code = code;}}@@ -197,7 +202,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {const { kind, ref } = parseScopeId(grantee);if (permission === null || kind !== "personal" || !ref?.includes("@")) return;if ((await deps.canManageEmail?.(ref)) || (await externalSharingAllowed(ownerScopeId))) return;- throw new Error(EXTERNAL_APP_SHARING_OFF);+ throw new DeployAccessError("external_sharing_disabled", EXTERNAL_APP_SHARING_OFF);}function withDeployLock<T>(id: string, fn: () => Promise<T>): Promise<T> {return deployQueue(id, () => advisoryLock.withLock(`deploy:${id}`, fn));@@ -554,12 +559,14 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {async setDeploymentPublic(idOrName, isPublic, actor) {const d = (await deps.deployStore.get(idOrName)) ?? (await deps.deployStore.getByName(idOrName));- if (!d) throw new Error(`no such app: ${idOrName}`);+ if (!d) throw new DeployAccessError("not_found", `no such app: ${idOrName}`);if (d.ownerScopeId !== scopeId("personal", actor.createdBy)) {- throw new Error(`only the owner can change who can reach "${d.name ?? d.id}"`);+ throw new DeployAccessError("forbidden", `only the owner can change who can reach "${d.name ?? d.id}"`);}- if (isPublic && !(await externalSharingAllowed(d.ownerScopeId))) throw new Error(EXTERNAL_APP_SHARING_OFF);- if (isPublic && deps.publicLinksAvailable === false) throw new PublicLinksUnavailableError();+ if (isPublic && !(await externalSharingAllowed(d.ownerScopeId)))+ throw new DeployAccessError("external_sharing_disabled", EXTERNAL_APP_SHARING_OFF);+ if (isPublic && deps.publicLinksAvailable === false)+ throw new DeployAccessError("public_links_unavailable", PUBLIC_LINKS_UNAVAILABLE);await deps.deployStore.setPublic(d.id, isPublic);deps.auditLog.record({at: Date.now(),@@ -788,9 +795,9 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {async shareDeployment(idOrName, grantee, permission, actor) {const d = (await deps.deployStore.get(idOrName)) ?? (await deps.deployStore.getByName(idOrName));- if (!d) throw new Error(`no such app: ${idOrName}`);+ if (!d) throw new DeployAccessError("not_found", `no such app: ${idOrName}`);if (d.ownerScopeId !== scopeId("personal", actor.createdBy)) {- throw new Error(`only the owner can change who can reach "${d.name ?? d.id}"`);+ throw new DeployAccessError("forbidden", `only the owner can change who can reach "${d.name ?? d.id}"`);}grantee = await deploymentShareScope(grantee, permission, deps.canManageEmail);await assertShareAllowed(d.ownerScopeId, grantee, permission);@@ -826,9 +833,9 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {async transferDeploymentOwner(idOrName, toScope, actor) {const d = (await deps.deployStore.get(idOrName)) ?? (await deps.deployStore.getByName(idOrName));- if (!d) throw new Error(`no such app: ${idOrName}`);+ if (!d) throw new DeployAccessError("not_found", `no such app: ${idOrName}`);if (!(await managesHome(d, actor.callerId, actor.actingScopeId))) {- throw new Error(`only the owner can transfer "${d.name ?? d.id}"`);+ throw new DeployAccessError("forbidden", `only the owner can transfer "${d.name ?? d.id}"`);}if (d.ownerScopeId === toScope) return d;const ref = deploymentRef(d.id);diff --git a/src/files/direct-file-upload.ts b/src/files/direct-file-upload.tsindex aac8ca91a..638bf8b67 100644--- a/src/files/direct-file-upload.ts+++ b/src/files/direct-file-upload.ts@@ -18,7 +18,7 @@ import {type FileArtifact,type FileArtifactStore,} from "./file-artifact-store.ts";-import type { FileUpload, FileUploadStore } from "./file-upload-store.ts";+import { FileUploadError, type FileUpload, type FileUploadStore } from "./file-upload-store.ts";import { safeAttachmentName, mimeFromName } from "../core/attachments.ts";import { createSweeper } from "../util/sweeper.ts";@@ -28,14 +28,6 @@ const UPLOAD_TTL_MS = 24 * 60 * 60 * 1000;const URL_TTL_SECONDS = 15 * 60;const SHA256_BASE64 = /^[A-Za-z0-9+/]{43}=$/;-export class FileUploadError extends Error {- status: number;- constructor(message: string, status = 400) {- super(message);- this.status = status;- }-}-export function multipartChecksum(checksums: string[]): string {return `${createHash("sha256").update(Buffer.concat(checksums.map((v) => Buffer.from(v, "base64"))))diff --git a/src/files/file-upload-store.ts b/src/files/file-upload-store.tsindex dcb01a048..18530b0e9 100644--- a/src/files/file-upload-store.ts+++ b/src/files/file-upload-store.ts@@ -25,6 +25,17 @@ export interface FileUploadStore {expired(now: number): Promise<FileUpload[]>;}+export class FileUploadError extends Error {+ readonly status: number;+ readonly code: "upload_error" | "upload_quota";+ constructor(message: string, status = 400, code: "upload_error" | "upload_quota" = "upload_error") {+ super(message);+ this.name = "FileUploadError";+ this.status = status;+ this.code = code;+ }+}+export const MAX_ACTIVE_UPLOADS = 4;const MAX_ACTIVE_UPLOAD_BYTES = 500 * 1024 ** 3;@@ -69,7 +80,7 @@ export function createPostgresFileUploadStore(connectionString: string): FileUplNumber(result.rows[0].count) >= MAX_ACTIVE_UPLOADS ||Number(result.rows[0].bytes) + upload.sizeBytes > MAX_ACTIVE_UPLOAD_BYTES)- throw new Error("active upload quota exceeded");+ throw new FileUploadError("active upload quota exceeded", 429, "upload_quota");await client.query("INSERT INTO file_uploads(id,actor_id,state,size_bytes,expires_at,data) VALUES($1,$2,$3,$4,$5,$6)",[upload.id, upload.actorId, upload.state, upload.sizeBytes, upload.expiresAt, JSON.stringify(upload)],diff --git a/src/slack/dev-introspection.ts b/src/slack/dev-introspection.tsindex 453f3231c..228952519 100644--- a/src/slack/dev-introspection.ts+++ b/src/slack/dev-introspection.ts@@ -59,9 +59,9 @@ export function installDevIntrospection(app: any, opts: DevIntrospectionOptionsconst canary = async (channel: string,timeoutMs = 15_000,- ): Promise<{ ok: boolean; rttMs?: number; reason?: string; nonce: string }> => {+ ): Promise<{ ok: boolean; code?: "unconfigured"; rttMs?: number; reason?: string; nonce: string }> => {const nonce = randomUUID();- if (!channel) return { ok: false, reason: "no canary channel configured", nonce };+ if (!channel) return { ok: false, code: "unconfigured", reason: "no canary channel configured", nonce };const arrival = new Promise<number>((resolve) => canaryWaiters.set(nonce, { postedAt: now(), resolve }));let postedTs: string | undefined;try {diff --git a/src/tools/primitives.ts b/src/tools/primitives.tsindex 270060054..461a6ac01 100644--- a/src/tools/primitives.ts+++ b/src/tools/primitives.ts@@ -323,7 +323,11 @@ export interface ToolContext extends SurfaceToolDeps {soulWrite(content: string,expectedVersion?: number,- ): Promise<ControlOk<{ version: number }> | ControlErr<"soul_update_denied"> | ControlUnavailable>;+ ): Promise<+ | ControlOk<{ version: number }>+ | ControlErr<"soul_update_denied" | "soul_version_conflict" | "soul_update_failed">+ | ControlUnavailable+ >;shareArtifact(req: ShareArtifactRequest): Promise<ShareArtifactResult | ControlUnavailable>;}diff --git a/test/admin-keychain.test.ts b/test/admin-keychain.test.tsindex fe2145940..9fe90e355 100644--- a/test/admin-keychain.test.ts+++ b/test/admin-keychain.test.ts@@ -157,8 +157,6 @@ test("user keychain reads only the selected owner's metadata and grants", asynct.mock.method(s.keychain, "listAsks", fail);t.mock.method(s.built.sessions, "distinctParticipants", fail);t.mock.method(s.built.app, "directoryMembers", fail);- if (s.built.auditLog.tallyByResource)- t.mock.method(s.built.auditLog as Required<typeof s.built.auditLog>, "tallyByResource", fail);const response = await fetch(s.base + "/v1/admin/keychain?principal=Alice%40example.com", {headers: { "x-admin-actor": "admin-alice@default-org" },});diff --git a/test/control-service.test.ts b/test/control-service.test.tsindex 9388a1ee7..4325c5827 100644--- a/test/control-service.test.ts+++ b/test/control-service.test.ts@@ -778,6 +778,15 @@ test("soul write in a shared (channel) scope is allowed (allowSharedScope, likeassert.equal(after.soul, "Channel standing note.");});+test("soul write separates a refused scope from a failed write", async () => {+ const { control } = setup();+ const denied = await control.writeSoul("Not my scope.", claims("U1", scopeId("personal", "U2")));+ assert.equal(denied.ok ? "" : denied.code, "soul_update_denied");++ const stale = await control.writeSoul("Stale edit.", claims("U1"), 41);+ assert.equal(stale.ok ? "" : stale.code, "soul_version_conflict");+});+test("noteCron stores a flattened shift-change note, overwriting the previous one, with owner authz", async () => {const { control } = setup();const created = await control.createCron(diff --git a/test/dev-doctor-event-delivery.test.ts b/test/dev-doctor-event-delivery.test.tsnew file mode 100644index 000000000..a9079cdac--- /dev/null+++ b/test/dev-doctor-event-delivery.test.ts@@ -0,0 +1,8 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { eventDeliveryCheck } from "../scripts/dev/commands/doctor.ts";++test("doctor warns on a missing canary channel by code and treats every other canary failure as critical", () => {+ assert.equal(eventDeliveryCheck({ ok: false, code: "unconfigured", reason: "any wording" }).severity, "warn");+ assert.equal(eventDeliveryCheck({ ok: false, reason: "no canary channel configured" }).severity, "critical");+});diff --git a/test/direct-file-upload.test.ts b/test/direct-file-upload.test.tsindex 762390ca1..80453876f 100644--- a/test/direct-file-upload.test.ts+++ b/test/direct-file-upload.test.ts@@ -1,13 +1,8 @@import { test } from "node:test";import assert from "node:assert/strict";import { createHash } from "node:crypto";-import {- FileUploadError,- createDirectFileUploads,- multipartChecksum,- FILE_UPLOAD_PART_SIZE,-} from "../src/files/direct-file-upload.ts";-import type { FileUpload, FileUploadStore } from "../src/files/file-upload-store.ts";+import { createDirectFileUploads, multipartChecksum, FILE_UPLOAD_PART_SIZE } from "../src/files/direct-file-upload.ts";+import { FileUploadError, type FileUpload, type FileUploadStore } from "../src/files/file-upload-store.ts";import { createMemoryFileArtifactStore } from "../src/files/file-artifact-store.ts";import { createMemoryDurableByteStore } from "../src/files/durable-byte-store.ts";import { scopeId } from "../src/types.ts";diff --git a/test/loop-item-routes.test.ts b/test/loop-item-routes.test.tsindex c6b4a5b19..e8de0ee38 100644--- a/test/loop-item-routes.test.ts+++ b/test/loop-item-routes.test.ts@@ -717,7 +717,7 @@ test("a send carrying the draft it saw is refused when the agent redrafted in bebody: { kind: "send", args: { proposal: { body: "what I saw" }, expectedProposalAt: seenAt } },});assert.equal(stale.status, 409);- assert.match((stale.body as { message: string }).message, /draft changed/);+ assert.equal((stale.body as { error: string }).error, "draft_changed");assert.equal(w.sent.length, 0, "nothing reached Slack");const fresh = (await w.loops.items.get(item.id))!.proposal!;assert.equal(fresh.by, "agent", "the stale edit did not overwrite the newer draft");@@ -754,7 +754,7 @@ test("an edit carrying the draft it was based on is refused when the agent redrabody: { kind: "edit", args: { proposal: { body: "typed over the old one" }, expectedProposalAt: basedOn } },});assert.equal(stale.status, 409);- assert.match((stale.body as { message: string }).message, /draft changed/);+ assert.equal((stale.body as { error: string }).error, "draft_changed");assert.deepEqual((await w.loops.items.get(item.id))!.proposal!.data, { body: "newer agent draft" });});@@ -842,6 +842,7 @@ test("a conversational send refuses a stale draft before starting an agent turn"body: { message: "Send it", expectedProposalAt: item.proposal!.at - 1 },});assert.equal(out.status, 409);+ assert.equal((out.body as { error: string }).error, "draft_changed");assert.deepEqual(w.followUps, []);assert.deepEqual(w.sent, []);const accepted = await call(w, {diff --git a/test/member-edit-authz.test.ts b/test/member-edit-authz.test.tsindex 2cbfbec9c..f87f75872 100644--- a/test/member-edit-authz.test.ts+++ b/test/member-edit-authz.test.ts@@ -294,6 +294,27 @@ test("SOUL: the HTTP route reports durable storage failures as 500", async () =>assert.equal(out.body?.error, "soul_update_failed");});+test("SOUL: the HTTP route reports a write to someone else's personal SOUL as a 403 denial", async () => {+ const app = createApp(makeDeps() as unknown as AppDeps);+ const out: { status?: number; body?: { error?: string } } = {};+ const res = {+ getHeader() {},+ writeHead(status: number) {+ out.status = status;+ },+ end(data?: string) {+ out.body = data ? JSON.parse(data) : undefined;+ },+ };+ await postSoul({+ res,+ app,+ body: { scopeId: scopeId("personal", OWNER), content: "not yours", actorId: OUTSIDER },+ } as unknown as ApiCtx);+ assert.equal(out.status, 403);+ assert.equal(out.body?.error, "soul_update_denied");+});+test("SOUL: failed persistence restores the pre-write cache even when compensating reads fail", async () => {const backing = createMemoryMap<PersistedSoul>();const prior: PersistedSoul = {diff --git a/test/postgres-file-upload-store.test.ts b/test/postgres-file-upload-store.test.tsindex 4685697d4..86a3bac66 100644--- a/test/postgres-file-upload-store.test.ts+++ b/test/postgres-file-upload-store.test.ts@@ -1,8 +1,12 @@import { test } from "node:test";import assert from "node:assert/strict";import { randomUUID } from "node:crypto";-import { createPostgresFileUploadStore, MAX_ACTIVE_UPLOADS } from "../src/files/file-upload-store.ts";-import type { FileUpload } from "../src/files/file-upload-store.ts";+import {+ createPostgresFileUploadStore,+ FileUploadError,+ MAX_ACTIVE_UPLOADS,+ type FileUpload,+} from "../src/files/file-upload-store.ts";import { scopeId } from "../src/types.ts";const url = process.env.DATABASE_URL;@@ -30,6 +34,12 @@ test(const uploads = Array.from({ length: MAX_ACTIVE_UPLOADS + 3 }, row);const results = await Promise.allSettled(uploads.map((r, i) => (i % 2 ? first : second).insert(r)));assert.equal(results.filter((r) => r.status === "fulfilled").length, MAX_ACTIVE_UPLOADS);+ for (const r of results) {+ if (r.status === "fulfilled") continue;+ assert.ok(r.reason instanceof FileUploadError);+ assert.equal(r.reason.status, 429);+ assert.equal(r.reason.code, "upload_quota");+ }const accepted = uploads[results.findIndex((r) => r.status === "fulfilled")]!;assert.deepEqual(await second.get(accepted.id), accepted);const claims = await Promise.all([diff --git a/test/share-deployment.test.ts b/test/share-deployment.test.tsindex dacc29809..5dd542fb7 100644--- a/test/share-deployment.test.ts+++ b/test/share-deployment.test.ts@@ -307,12 +307,18 @@ test("share endpoint: only the owner can share (non-owner capability → 403)",});const r = await callShare(app, cap("U2"), "owned", { scope: "org" });assert.equal(r.status, 403);+ assert.equal(r.body.error, "forbidden");assert.match(r.body.message, /only the owner/);});test("share endpoint: unknown app → 404; no capability → 403; bad/ambiguous/missing args → 400", async () => {const { app } = apiHarness();- assert.equal((await callShare(app, cap("U1"), "ghost", { scope: "org" })).status, 404);+ const ghost = await callShare(app, cap("U1"), "ghost", { scope: "org" });+ assert.equal(ghost.status, 404);+ assert.equal(ghost.body.error, "not_found");+ const ghostPublic = await callShare(app, cap("U1"), "ghost", { public: true });+ assert.equal(ghostPublic.status, 404);+ assert.equal(ghostPublic.body.error, "not_found");assert.equal((await callShare(app, null, "ghost", { scope: "org" })).status, 403);await app.deploy({ ownerScopeId: scopeId("personal", "U1"), createdBy: "U1", entrypoint: "x", files: [], name: "a" });assert.equal(@@ -554,6 +560,7 @@ test("deployment public access is explicit, owner-only, and reversible", async (const denied = await callShare(app, cap("U2"), "public-toggle", { public: true });assert.equal(denied.status, 403, "only the owner may make an app public");+ assert.equal(denied.body.error, "forbidden");const enabled = await callShare(app, cap("U1"), "public-toggle", { public: true });assert.equal(enabled.status, 200);