Multiplayer agent harness for work.
Expose native admin actions through existing authenticated handlers (#2208)
Regan Belle652241b7006
diff --git a/skills-seed/admin/SKILL.md b/skills-seed/admin/SKILL.mdindex a6df9538c..85e17546d 100644--- a/skills-seed/admin/SKILL.md+++ b/skills-seed/admin/SKILL.md@@ -5,10 +5,11 @@ description: Act for an org admin — the admin API (scope directory, per-scope# admin — act for an org admin, from chat-A connector skill: no new tool. When the chatting user is an org admin (your system-prompt says so — "Acting for an org admin"), the `/v1/admin/*` endpoints accept your-token. You are acting **as them**: authorization is re-checked against the live grant-store on every call, and every call is audited under their name. Two standing rules:+Use the native `admin` tool for the operations below. Its fixed actions call the same+`/v1/admin/*` handlers and accept the same values; configuration and provider value+objects are validated by those existing handlers. Binary and full captured-prompt downloads, raw-secret setters, connector configuration,+and service-credential configuration still use the self-API, never native tool arguments. You are acting **as them**: authorization is re-checked against the live grant+store on every call; existing admin audit events remain attributed to them. Two standing rules:**confirm before any mutation** (state exactly what you'll change and where), and reportafterwards exactly what changed. Reads are fine to just do.diff --git a/src/api/server.ts b/src/api/server.tsindex 8a33b3047..ccdc096a5 100644--- a/src/api/server.ts+++ b/src/api/server.ts@@ -99,7 +99,7 @@ function unattendedAdminReadAllowed(method: string, pathname: string, claims: Ca}function isAdminContentRead(pathname: string): boolean {- if (pathname === "/v1/admin/memory") return true;+ if (pathname === "/v1/admin/memory" || pathname === "/v1/admin/scopes") return true;if (pathname === "/v1/admin/keychain") return true;if (pathname === "/v1/admin/volumes") return true;if (pathname.startsWith("/v1/admin/scopes/")) return true;diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex a208a6113..1c22f9dff 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -1,3 +1,4 @@+import { createAdminCall } from "../tools/admin.ts";import { scopeTeamsToTurn } from "../teams/teams.ts";import { externalSlackRequestAllowed, currentExternalSlackRun } from "../resolution/external-slack.ts";import { externalTools } from "./orchestrator/external-tools.ts";@@ -2760,6 +2761,15 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {},...(deps.config ? { config: deps.config } : {}),...(deps.control && controlClaims ? { control: deps.control, controlClaims } : {}),+ ...(deps.apiBaseUrl && connectorEnv.AGENT_API_TOKEN+ ? {+ admin: {+ call: createAdminCall(deps.apiBaseUrl, connectorEnv.AGENT_API_TOKEN),+ operationsAvailable:+ actorIsOrgAdmin || Boolean(controlClaims?.grants?.some((grant) => grant.startsWith("admin."))),+ },+ }+ : {}),...(deps.webhookPublicUrl ? { webhookPublicUrl: deps.webhookPublicUrl } : {}),...(humanTurn && !external ? { humanTurn: true } : {}),...(surfaceToolDeps ? { surface: surfaceToolDeps } : {}),diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.tsindex 9c156a382..faf9e3ad4 100644--- a/src/harness/agent-tools.ts+++ b/src/harness/agent-tools.ts@@ -1,3 +1,4 @@+import { adminOperations } from "../tools/admin.ts";import { MaskedExecutionError } from "../security/secret-masking.ts";import type { DocumentInput } from "../core/document-inputs.ts";import { createKeyedQueue } from "../util/async.ts";@@ -3402,6 +3403,53 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):});}+ const admin = resourceTool(+ "admin",+ Object.fromEntries(+ Object.entries(+ ref.current === null || ref.current.admin?.operationsAvailable+ ? adminOperations+ : { whoami: adminOperations.whoami },+ ).map(([action, operation]) => [+ action,+ defineTool({+ name: action,+ label: action,+ description: operation.description,+ parameters: operation.parameters,+ async execute(callId, params) {+ await recordCall(callId, { tool: "admin", action });+ try {+ const result = await ref.current?.admin?.call({ ...params, action }, ref.abortSignal);+ if (!result) throw new Error("Admin API is not available on this turn");+ return recordResult(+ callId,+ { tool: "admin", action, status: result.status },+ {+ ...text(result.status >= 400 ? redactSecrets(JSON.stringify(result)) : JSON.stringify(result)),+ isError: result.status >= 400,+ },+ result.status >= 400,+ );+ } catch (error) {+ return recordResult(+ callId,+ { tool: "admin", action, error: redactSecrets(errMessage(error)) },+ { ...text(redactSecrets(errMessage(error))), isError: true },+ true,+ );+ }+ },+ }),+ ]),+ ),+ );++ if (ref.current === null || ref.current.admin?.operationsAvailable)+ admin.description =+ "Uses existing admin handlers and audit. Authority is rechecked on every call. Private content requires a live admin in a DM or Open conversation; unattended reads require explicit grants. Admin-role changes, impersonation, identity links, and teammate invitations are portal-only. Confirm every mutation, report exactly what changed, and disclose only what this conversation needs. Binary/full captured-prompt downloads and raw-secret setters remain on the self-API; do not put secrets in native arguments.\n\n" ++ admin.description;+const surfaceName = opts?.surfaceName ?? "slack";const surfaceLabel = surfaceName === "slack" ? "Slack" : surfaceName;const surface = defineTool({@@ -4353,6 +4401,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):share: sharingTool("cron"),}),webhook,+ admin,]: []),...(controlTools || surfaceTools ? [guidance] : []),@@ -4449,12 +4498,12 @@ function withToolApprovalGate(async execute(callId: string, params: unknown) {const gate = ref.toolApprovalGate;const resourceAction =- ["sandbox", "files", "apps", "skills", "goal", "cron"].includes(tool.name) &&+ ["sandbox", "files", "apps", "skills", "goal", "cron", "admin"].includes(tool.name) &&isObj(params) &&typeof params.action === "string"? params.action: undefined;- const approvalIdentity = ["sandbox", "files", "apps", "skills", "goal", "cron"].includes(tool.name)+ const approvalIdentity = ["sandbox", "files", "apps", "skills", "goal", "cron", "admin"].includes(tool.name)? `${tool.name}:${resourceAction ?? "invalid"}`: tool.name;const commandLabel = resourceAction ? `${tool.name} ${resourceAction}` : tool.name;diff --git a/src/tools/admin.ts b/src/tools/admin.tsnew file mode 100644index 000000000..bc2113e49--- /dev/null+++ b/src/tools/admin.ts@@ -0,0 +1,316 @@+import { errMessage } from "../util/errors.ts";+import { Type, type TSchema } from "typebox";+import { Check } from "typebox/value";++const string = Type.String();+const optionalString = Type.Optional(string);+const limit = Type.Optional(Type.Integer({ minimum: 1, maximum: 200 }));+const scope = { scope: string };+const scopedId = { ...scope, id: string };+const object = Type.Record(Type.String(), Type.Unknown());++type Operation = {+ description: string;+ parameters: ReturnType<typeof Type.Object>;+ method: "GET" | "POST" | "PUT" | "DELETE";+ path: string;+};++function operation(+ description: string,+ method: Operation["method"],+ path: string,+ properties: Record<string, TSchema> = {},+): Operation {+ return { description, method, path, parameters: Type.Object(properties, { additionalProperties: false }) };+}++export const adminOperations = {+ whoami: operation("Check the requesting person's admin status.", "GET", "/whoami"),+ scopes: operation("Find scopes and their labels; do not guess scope IDs.", "GET", "/scopes"),+ resources: operation("Inspect the existing scope configuration resource manifest.", "GET", "/resources"),+ config: operation("Read a scope's configuration.", "GET", "/scopes/:scope", scope),+ configure: operation(+ "Update one nonsecret configuration resource. Connector and service-credential setters stay on the self-API. Confirm the exact change first. The existing resource validator owns the value shape; read the admin skill for its fields.",+ "PUT",+ "/scopes/:scope/:resource",+ {+ ...scope,+ resource: Type.String({+ description: "Existing resource ID from the resources action; validated by the configuration registry.",+ }),+ value: object,+ },+ ),+ credential_usage: operation(+ "Read a scope's credential usage summary.",+ "GET",+ "/scopes/:scope/credential-usage",+ scope,+ ),+ memory_scopes: operation("List notebook scopes and metadata.", "GET", "/memory/scopes"),+ memory: operation("Read a notebook.", "GET", "/memory", scope),+ replace_memory: operation("Replace a notebook after reading it and confirming the full change.", "PUT", "/memory", {+ ...scope,+ value: Type.Object({ content: string }, { additionalProperties: false }),+ }),+ sessions: operation("List conversations using the returned cursor for the next page.", "GET", "/sessions", {+ ...scope,+ category: Type.Optional(+ Type.Union([Type.Literal("conversation"), Type.Literal("background"), Type.Literal("all")]),+ ),+ origin: optionalString,+ cron: optionalString,+ cursor: optionalString,+ limit,+ }),+ session: operation("Read a bounded conversation transcript.", "GET", "/sessions/:id", { ...scopedId, limit }),+ session_llm: operation(+ "Read captured model call metadata. Full request content stays on the self-API for selective sandbox reading.",+ "GET",+ "/sessions/:id/llm",+ scopedId,+ ),+ runs: operation("Read run history.", "GET", "/runs", scope),+ files: operation("List stored files, optionally matching q.", "GET", "/files", { ...scope, q: optionalString }),+ file: operation("Read a stored text file.", "GET", "/files/read", scopedId),+ upload_file: operation("Register an already staged blob as a scope file. Confirm first.", "POST", "/files/upload", {+ ...scope,+ value: Type.Object({ blobId: string, name: string, mimetype: optionalString }, { additionalProperties: false }),+ }),+ crons: operation("List crons belonging to a scope.", "GET", "/crons", scope),+ deployments: operation("List apps belonging to a scope.", "GET", "/deployments", scope),+ skills: operation("List skills belonging to a scope.", "GET", "/skills", scope),+ skill: operation("Read one skill.", "GET", "/skills/:id", scopedId),+ archive_skill: operation("Archive a skill. Confirm first.", "DELETE", "/skills/:id", scopedId),+ cron_runtime: operation("Set a cron runtime, or null to inherit. Confirm first.", "PUT", "/crons/:id/runtime", {+ ...scopedId,+ value: object,+ }),+ cron_destination: operation("Set or clear a cron destination. Confirm first.", "PUT", "/crons/:id/destination", {+ ...scopedId,+ value: object,+ }),+ audit: operation("Read audit events, optionally filtered by auditAction and resource.", "GET", "/audit", {+ ...scope,+ auditAction: optionalString,+ resource: optionalString,+ limit,+ }),+ errors: operation("Read errors with pagination.", "GET", "/errors", {+ ...scope,+ sessionId: optionalString,+ limit,+ offset: Type.Optional(Type.Integer({ minimum: 0 })),+ }),+ metrics: operation("Read turn metrics.", "GET", "/metrics", scope),+ egress: operation("Read outbound-destination audit.", "GET", "/egress", scope),+ retention: operation("Read usage and retention.", "GET", "/retention"),+ spend: operation("Read spend for a date range.", "GET", "/spend", {+ from: optionalString,+ to: optionalString,+ bucket: Type.Optional(Type.Union([Type.Literal("day"), Type.Literal("week")])),+ breakdown: optionalString,+ }),+ users: operation("List the organization roster and invited external users.", "GET", "/users"),+ user: operation("Read one person's configuration and status.", "GET", "/users/:id", { id: string }),+ directory: operation("Resolve a person in the directory.", "GET", "/directory", { q: string }),+ keychain: operation("Read keychain metadata, never credential secrets.", "GET", "/keychain", {+ principal: optionalString,+ }),+ invite_external: operation(+ "Invite an external member after confirming recipient and expiry; admin-role invitations remain portal-only.",+ "POST",+ "/external-users",+ {+ value: Type.Object(+ { email: string, expiresAt: Type.Union([string, Type.Number()]) },+ { additionalProperties: false },+ ),+ },+ ),+ revoke_external: operation(+ "Revoke an external member's access. Confirm first; admin-role changes remain portal-only.",+ "DELETE",+ "/external-users/:id",+ { id: string },+ ),+ onboarding: operation("Set a user's onboarding state. Confirm first.", "PUT", "/users/:id/onboarding", {+ id: string,+ value: object,+ }),+ reset_user: operation(+ "Reset a user's onboarding data. Confirm the destructive reset first.",+ "POST",+ "/users/:id/reset",+ { id: string },+ ),+ sandboxes: operation("List a scope's sandboxes.", "GET", "/sandboxes/:scope", scope),+ create_sandbox: operation("Create a sandbox in a scope. Confirm first.", "POST", "/sandboxes/:scope", {+ ...scope,+ value: Type.Object(+ { action: Type.Literal("create"), backend: string, name: optionalString },+ { additionalProperties: false },+ ),+ }),+ sandbox_default: operation(+ "Set a scope's default sandbox, or null to clear. Confirm first.",+ "POST",+ "/sandboxes/:scope",+ {+ ...scope,+ value: Type.Object(+ { action: Type.Literal("default"), sandboxId: Type.Union([string, Type.Null()]) },+ { additionalProperties: false },+ ),+ },+ ),+ retire_sandbox: operation("Retire a scope's sandbox. Confirm first.", "POST", "/sandboxes/:scope", {+ ...scope,+ value: Type.Object({ action: Type.Literal("retire"), sandboxId: string }, { additionalProperties: false }),+ }),+ security_flags: operation("Read security screening flags.", "GET", "/security/flags", { limit }),+ release_security: operation("Release a conversation's security taint. Confirm first.", "POST", "/security/release", {+ value: Type.Object({ sessionId: string }, { additionalProperties: false }),+ }),+ slack_installation: operation("Read Slack installation metadata, never tokens.", "GET", "/slack-installation"),+ slack_start: operation("Start Slack setup or installation. Confirm first.", "POST", "/slack-installation/start", {+ value: Type.Object(+ { step: Type.Union([Type.Literal("setup"), Type.Literal("install")]) },+ { additionalProperties: false },+ ),+ }),+ slack_emoji: operation("List Slack emoji.", "GET", "/slack-emoji"),+ model_providers: operation("Read model-provider metadata.", "GET", "/model-providers"),+ custom_providers: operation("Read custom model-provider metadata.", "GET", "/custom-providers"),+ mcp_servers: operation("Read MCP-server metadata.", "GET", "/mcp-servers"),+ model_registry: operation("Read model definitions.", "GET", "/model-registry"),+ model_lookup: operation("Look up a provider's model definition.", "POST", "/model-registry/lookup", {+ value: Type.Object(+ { provider: Type.Union([Type.Literal("openai"), Type.Literal("anthropic")]), id: string },+ { additionalProperties: false },+ ),+ }),+ model_enable: operation(+ "Verify and enable a model, including a small billable request. Confirm first.",+ "POST",+ "/model-registry/:id/enable",+ {+ id: string,+ value: Type.Object(+ { provider: Type.Union([Type.Literal("openai"), Type.Literal("anthropic")]), verify: Type.Literal(true) },+ { additionalProperties: false },+ ),+ },+ ),+ model_delete: operation("Remove an administrator model definition. Confirm first.", "DELETE", "/model-registry/:id", {+ id: string,+ }),++ slack_delete: operation("Remove Slack installation. Confirm first.", "DELETE", "/slack-installation"),++ model_provider_delete: operation("Remove a provider API key. Confirm first.", "DELETE", "/model-providers/:id", {+ id: string,+ }),++ custom_provider_delete: operation("Remove a custom provider. Confirm first.", "DELETE", "/custom-providers/:id", {+ id: string,+ }),++ mcp_delete: operation("Remove an MCP server. Confirm first.", "DELETE", "/mcp-servers/:id", { id: string }),+ model_save: operation(+ "Save a model definition using the existing model spec validator. Requires verify:true and confirmation for the billable verification request.",+ "PUT",+ "/model-registry/:id",+ { id: string, value: object },+ ),+ auto_flagger_test: operation(+ "Test a candidate security screener on recent samples using the existing draft validator. Confirm the billable test first.",+ "POST",+ "/scopes/:scope/auto-flagger/test",+ { ...scope, value: object },+ ),+ shadow_deliveries: operation("Read shadow-delivery diagnostics.", "GET", "/deliveries/shadow", scope),+ slack_mirror: operation("List mirrored Slack containers.", "GET", "/slack-mirror", scope),+ slack_messages: operation("Read a page of mirrored Slack messages.", "GET", "/slack-mirror/messages", {+ ...scope,+ container: string,+ q: optionalString,+ before: optionalString,+ limit,+ }),+ ambient_judgments: operation("Read ambient message judgments.", "GET", "/ambient-judgments", {+ ...scope,+ container: optionalString,+ decision: optionalString,+ before: Type.Optional(Type.Integer()),+ beforeId: Type.Optional(Type.Integer()),+ limit,+ }),+ ack_emoji_picks: operation("Read acknowledgment emoji decisions.", "GET", "/ack-emoji-picks", {+ ...scope,+ container: optionalString,+ outcome: optionalString,+ before: Type.Optional(Type.Integer()),+ beforeId: Type.Optional(Type.Integer()),+ limit,+ }),+} satisfies Record<string, Operation>;++export interface AdminToolAccess {+ call: AdminCall;+ operationsAvailable: boolean;+}++type AdminCall = (+ input: Record<string, unknown>,+ signal?: AbortSignal,+) => Promise<{ status: number; body: unknown; requestId?: string }>;++export function createAdminCall(baseUrl: string, capability: string): AdminCall {+ while (baseUrl.endsWith("/")) baseUrl = baseUrl.slice(0, -1);+ return async (input, signal) => {+ const { action, retrySafe: _retrySafe, ...params } = input;+ const op = Object.hasOwn(adminOperations, String(action))+ ? adminOperations[action as keyof typeof adminOperations]+ : undefined;+ if (!op || !Check(op.parameters, params)) throw new Error("Invalid admin action or arguments");+ if (action === "configure" && (params.resource === "service-credentials" || params.resource === "connectors"))+ throw new Error("Secret-bearing configuration uses the existing admin self-API, not native tool arguments");+ if (action === "session" && params.limit === undefined) params.limit = 50;+ signal?.throwIfAborted();+ let path = op.path;+ const query = new URLSearchParams();+ for (const [key, value] of Object.entries(params)) {+ if (key === "value") continue;+ if (path.includes(`:${key}`)) {+ const segment = String(value);+ if (!segment || segment === "." || segment === "..") throw new Error("Invalid admin resource identifier");+ path = path.replace(`:${key}`, encodeURIComponent(segment));+ } else query.set(key === "auditAction" ? "action" : key, String(value));+ }+ const response = await fetch(`${baseUrl}/v1/admin${path}?${query}`, {+ method: op.method,+ headers: { "x-agent-capability": capability, "content-type": "application/json" },+ ...(params.value !== undefined ? { body: JSON.stringify(params.value) } : {}),+ redirect: "error",+ signal,+ });+ const requestId = response.headers.get("x-request-id") ?? response.headers.get("request-id") ?? undefined;+ const result = { status: response.status, ...(requestId ? { requestId } : {}) };+ let raw: string;+ try {+ raw = await response.text();+ } catch (error) {+ throw new Error(+ `Admin HTTP ${response.status}${requestId ? ` request ${requestId}` : ""}: ${errMessage(error)}`,+ { cause: error },+ );+ }+ try {+ return { ...result, body: JSON.parse(raw) as unknown };+ } catch {+ return { ...result, body: raw };+ }+ };+}diff --git a/src/tools/primitives.ts b/src/tools/primitives.tsindex 7f203f8fd..d28d3e037 100644--- a/src/tools/primitives.ts+++ b/src/tools/primitives.ts@@ -1,3 +1,4 @@+import type { AdminToolAccess } from "./admin.ts";import {prepareExecutionFiles,processCredentialFiles,@@ -196,6 +197,7 @@ export type AttachResult = { ok: true; files: AttachedFileMeta[]; staged: numberexport type AttachFiles = (files: readonly string[]) => Promise<AttachResult>;export interface ToolContext extends SurfaceToolDeps {+ admin?: AdminToolAccess;runtime?(request: RuntimeRequest, signal?: AbortSignal): Promise<RuntimeResult>;attach: AttachFiles;sessionSyscalls?: SessionSyscalls;@@ -440,6 +442,7 @@ export const CONTROL_UNAVAILABLE: ControlUnavailable = {};export interface ToolContextDeps {+ admin?: AdminToolAccess;sandbox: Sandbox;commandCredentials?: readonly CommandCredential[];resolveCommandCredentials?: (handles: readonly string[]) => Promise<readonly CommandCredential[]>;@@ -696,6 +699,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {};return {+ ...(deps.admin ? { admin: deps.admin } : {}),...(deps.commandCredentials?.length? { commandCredentialHandles: deps.commandCredentials.map((credential) => credential.handle) }: {}),diff --git a/test/admin-agent-capability.test.ts b/test/admin-agent-capability.test.tsindex 93a20aeda..c654811f3 100644--- a/test/admin-agent-capability.test.ts+++ b/test/admin-agent-capability.test.ts@@ -1,3 +1,6 @@+import { createAdminCall } from "../src/tools/admin.ts";+import { createAgentTools } from "../src/harness/agent-tools.ts";+import type { ToolContext } from "../src/tools/primitives.ts";import "./support/auto-fake-sprites.ts";import { selectDefaultSandbox } from "./support/default-sandbox.ts";@@ -501,7 +504,6 @@ test("revoking the admin grant cuts off an already-minted token immediately", asconst cap = await capFor("admin-alice");const before = await fetch(`${s.base}/v1/admin/whoami`, { headers: { "x-agent-capability": cap } });assert.equal(((await before.json()) as any).isAdmin, true);-await s.built.admin.revokeGrant({ id: "admin-bob", type: "internal" }, "admin-alice", ORG, "org_admin");const after = await fetch(`${s.base}/v1/admin/whoami`, { headers: { "x-agent-capability": cap } });@@ -802,3 +804,59 @@ test("shared-channel admin runtime mutations do not return a private cron promptawait s.close();}});++test("native admin tools use the authenticated handler, including its live authority, audience and audit checks", async () => {+ const s = start();+ const target = scopeId("personal", "U1");+ try {+ const call = createAdminCall(s.base, await capFor("admin-alice"));+ const tool = createAgentTools(+ { current: { admin: { call, operationsAvailable: true } } as ToolContext },+ { controlTools: true },+ ).find((t) => t.name === "admin")!;+ const written = await tool.execute(+ "native-write",+ {+ action: "replace_memory",+ scope: target,+ value: { content: "- synthetic admin tool fixture" },+ },+ undefined,+ undefined,+ {} as never,+ );+ assert.equal(JSON.parse((written.content[0] as { text: string }).text).status, 200);+ const read = await tool.execute(+ "native-read",+ { action: "memory", scope: target },+ undefined,+ undefined,+ {} as never,+ );+ assert.equal(+ JSON.parse((read.content[0] as { text: string }).text).body.content,+ "- synthetic admin tool fixture\n",+ );+ assert.equal(+ (await s.built.auditLog.events()).filter((e) => e.action === "memory.update" && e.principalId === "admin-alice")+ .length,+ 1,+ );+ for (const claims of [+ await capFor("U1"),+ await capFor("admin-alice", { live: false }),+ await capFor("admin-alice", { scope: "channel:C1" }),+ ]) {+ const denied = await createAdminCall(s.base, claims)({ action: "memory", scope: target });+ assert.equal(denied.status, 403);+ assert.doesNotMatch(JSON.stringify(denied.body), /synthetic admin tool fixture/);+ }+ const shared = createAdminCall(s.base, await capFor("admin-alice", { scope: "channel:C1" }));+ assert.equal((await shared({ action: "scopes" })).status, 403);+ assert.equal((await call({ action: "scopes" })).status, 200);+ await s.built.admin.revokeGrant({ id: "admin-bob", type: "internal" }, "admin-alice", ORG, "org_admin");+ assert.equal((await call({ action: "memory", scope: target })).status, 403);+ } finally {+ await s.close();+ }+});diff --git a/test/admin-tool.test.ts b/test/admin-tool.test.tsnew file mode 100644index 000000000..59df8f4ad--- /dev/null+++ b/test/admin-tool.test.ts@@ -0,0 +1,175 @@+import { openCodeToolDefinitions } from "../src/harness/opencode-harness.ts";+import type { TSchema } from "typebox";+import { test } from "node:test";+import assert from "node:assert/strict";+import { createServer } from "node:http";+import { once } from "node:events";+import type { AddressInfo } from "node:net";+import { Check } from "typebox/value";+import { createAdminCall } from "../src/tools/admin.ts";+import { createAgentTools } from "../src/harness/agent-tools.ts";+import type { ToolContext } from "../src/tools/primitives.ts";++test("admin sends only fixed routes with encoded identifiers and preserves HTTP failures", async () => {+ const requests: { url: string; token: string; method: string; body: string }[] = [];+ const server = createServer(async (req, res) => {+ const chunks = [];+ for await (const chunk of req) chunks.push(chunk);+ requests.push({+ url: req.url!,+ token: String(req.headers["x-agent-capability"]),+ method: req.method!,+ body: Buffer.concat(chunks).toString(),+ });+ res.writeHead(403, { "content-type": "text/plain" });+ res.end("synthetic route denial");+ });+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ try {+ const call = createAdminCall(`http://127.0.0.1:${(server.address() as AddressInfo).port}`, "synthetic-capability");+ const tool = createAgentTools(+ { current: { admin: { call, operationsAvailable: true } } as unknown as ToolContext },+ { controlTools: true },+ ).find((t) => t.name === "admin")!;+ const args = { action: "configure", scope: "channel:test/?evil=1", resource: "soul", value: { content: "hello" } };+ assert.equal(Check(tool.parameters, args), true);+ const result = await tool.execute("configure", args, undefined, undefined, {} as never);+ assert.equal((result as { isError?: boolean }).isError, true);+ assert.deepEqual(JSON.parse((result.content[0] as { text: string }).text), {+ status: 403,+ body: "synthetic route denial",+ });+ assert.deepEqual(requests, [+ {+ url: "/v1/admin/scopes/channel%3Atest%2F%3Fevil%3D1/soul?",+ token: "synthetic-capability",+ method: "PUT",+ body: '{"content":"hello"}',+ },+ ]);+ for (const args of [+ { action: "request", url: "https://example.test" },+ { action: "config", scope: ".." },+ { action: "configure", scope: "org:test", resource: "..", value: {} },+ { action: "whoami", path: "/grants", method: "POST" },+ { action: "invite_external", value: { email: "[email protected]", expiresAt: 1, role: "org_admin" } },+ { action: "session", scope: "org:test", id: "test", limit: 201 },+ { action: "configure", scope: "org:test", resource: "service-credentials", value: {} },+ { action: "session_llm", scope: "org:test", id: "test", turnSeq: "1" },+ ])+ await assert.rejects(() => call(args));+ assert.equal(requests.length, 1);+ } finally {+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+});++test("admin never forwards a capability through redirects", async () => {+ let redirected = false;+ const server = createServer((req, res) => {+ if (req.url === "/escape") redirected = true;+ res.writeHead(302, { location: "/escape" });+ res.end();+ });+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ try {+ const call = createAdminCall(`http://127.0.0.1:${(server.address() as AddressInfo).port}`, "synthetic-capability");+ await assert.rejects(() => call({ action: "whoami" }));+ assert.equal(redirected, false);+ } finally {+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+});++test("ordinary turns only receive the inexpensive admin status action", () => {+ const tool = createAgentTools({ current: {} as unknown as ToolContext }, { controlTools: true }).find(+ (t) => t.name === "admin",+ )!;+ assert.equal(Check(tool.parameters, { action: "whoami" }), true);+ assert.equal(Check(tool.parameters, { action: "memory", scope: "org:test" }), false);+});++test("definition-only harnesses get admin schemas and cancelled calls never reach HTTP", async () => {+ const tool = openCodeToolDefinitions({ controlTools: true }).find((t) => t.name === "admin")!;+ assert.equal(Check(tool.parameters as TSchema, { action: "memory", scope: "org:test" }), true);+ const signal = AbortSignal.abort(new Error("synthetic stop"));+ const call = createAdminCall("http://127.0.0.1:1", "synthetic-capability");+ await assert.rejects(() => call({ action: "whoami" }, signal), /synthetic stop/);+ let received: AbortSignal | undefined;+ const native = createAgentTools(+ {+ current: {+ admin: {+ operationsAvailable: true,+ call: async (_args: Record<string, unknown>, inputSignal?: AbortSignal) => {+ received = inputSignal;+ return { status: 200, body: {} };+ },+ },+ } as unknown as ToolContext,+ abortSignal: signal,+ },+ { controlTools: true },+ ).find((t) => t.name === "admin")!;+ await native.execute("stopped", { action: "whoami" }, undefined, undefined, {} as never);+ assert.equal(received, signal);+});++test("admin error diagnostics retain request evidence and redact secrets", async () => {+ const tool = createAgentTools(+ {+ current: {+ admin: {+ operationsAvailable: true,+ call: async () => ({+ status: 403,+ body: { error: "synthetic denial", apiKey: "synthetic-private-key" },+ requestId: "req-synthetic",+ }),+ },+ } as unknown as ToolContext,+ },+ { controlTools: true },+ ).find((t) => t.name === "admin")!;+ const result = await tool.execute("error", { action: "whoami" }, undefined, undefined, {} as never);+ const text = (result.content[0] as { text: string }).text;+ assert.match(text, /synthetic denial/);+ assert.match(text, /req-synthetic/);+ assert.doesNotMatch(text, /synthetic-private-key/);+});++test("strict approval of an admin read cannot authorize an admin mutation", async () => {+ const calls: string[] = [];+ const approvals: Array<{ approvalKey?: string }> = [];+ const tool = createAgentTools(+ {+ current: {+ admin: {+ operationsAvailable: true,+ call: async (input: Record<string, unknown>) => {+ calls.push(String(input.action));+ return { status: 200, body: {} };+ },+ },+ } as unknown as ToolContext,+ pendingApprovals: approvals as never,+ toolApprovalGate: (identity) => identity === "admin:whoami",+ },+ { controlTools: true },+ ).find((t) => t.name === "admin")!;+ await tool.execute("read", { action: "whoami" }, undefined, undefined, {} as never);+ const blocked = await tool.execute(+ "write",+ { action: "replace_memory", scope: "org:test", value: { content: "synthetic replacement" } },+ undefined,+ undefined,+ {} as never,+ );+ assert.deepEqual(calls, ["whoami"]);+ assert.equal(approvals[0]?.approvalKey, "tool:admin:replace_memory");+ assert.match((blocked.content[0] as { text: string }).text, /needs human approval/);+});