Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Extend the agent self-API: conversation read/fork/colors, memory history, skill restore, viewer-scoped files/deployments, projects (#169)

Regan Bell52f6b8bd763b
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index 895bbaca0..8556ce641 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -50,6 +50,38 @@ const FAMILIES: AgentApiFamily[] = [
},
],
},
+ {
+ match: (m, p) =>
+ (p === "/v1/projects" && (m === "GET" || m === "POST")) ||
+ (/^\/v1\/projects\/[^/]+$/.test(p) && m === "PATCH") ||
+ (/^\/v1\/projects\/[^/]+\/members$/.test(p) && m === "POST") ||
+ (/^\/v1\/projects\/[^/]+\/members\/[^/]+$/.test(p) && m === "DELETE"),
+ guidance:
+ "These act as the ASKING PERSON across every project they belong to, matching the web UI. Do not send principalId; the capability token always determines the person, and inaccessible projects return 404.",
+ routes: [
+ { method: "GET", path: "/v1/projects", summary: "list every project the asking person belongs to" },
+ {
+ method: "POST",
+ path: "/v1/projects",
+ summary: "create a project owned by the asking person — body {name}",
+ },
+ {
+ method: "PATCH",
+ path: "/v1/projects/:id",
+ summary: "rename a project the asking person owns — body {name}",
+ },
+ {
+ method: "POST",
+ path: "/v1/projects/:id/members",
+ summary: "add an internal directory member to a project the asking person belongs to — body {memberId}",
+ },
+ {
+ method: "DELETE",
+ path: "/v1/projects/:id/members/:memberId",
+ summary: "remove a member from a project the asking person owns",
+ },
+ ],
+ },
{
match: (m, p) =>
(p === "/v1/crons" && (m === "POST" || m === "GET")) ||
@@ -111,7 +143,8 @@ const FAMILIES: AgentApiFamily[] = [
},
{
match: (m, p) =>
- (m === "GET" && p === "/v1/conversations") || (m === "POST" && /^\/v1\/conversations\/[^/]+$/.test(p)),
+ (m === "GET" && (p === "/v1/conversations" || /^\/v1\/conversations\/[^/]+$/.test(p))) ||
+ (m === "POST" && /^\/v1\/conversations\/[^/]+(?:\/fork)?$/.test(p)),
guidance:
"These act on the ASKING PERSON's own conversation list (the web UI sidebar) — archiving, pinning, or renaming is a per-person view change, never a deletion, and never touches anyone else's list. Confirm before bulk-archiving.",
routes: [
@@ -125,7 +158,37 @@ const FAMILIES: AgentApiFamily[] = [
method: "POST",
path: "/v1/conversations/:id",
summary:
- "update one of the asking person's conversations — body {archived?, pinned?, title?}; archive/unarchive, pin/unpin, rename (null title clears). Per-person and reversible; 404 for a conversation not on their list",
+ "update one of the asking person's conversations — body {archived?, pinned?, title?, color?}; archive/unarchive, pin/unpin, rename (null title clears), or set the sidebar color (#rrggbb; null clears). Per-person and reversible; 404 for a conversation not on their list",
+ },
+ {
+ method: "GET",
+ path: "/v1/conversations/:id?tailTurns=20",
+ summary:
+ "read the bounded transcript of one of the asking person's conversations; defaults to the last 20 turns and supports older paging with tailTurns and beforeSeq; returns 404 for a conversation they cannot see",
+ },
+ {
+ method: "POST",
+ path: "/v1/conversations/:id/fork",
+ summary:
+ "fork one of the asking person's conversations into a new conversation — body optionally {upToSeq}; returns 404 for a conversation they cannot see",
+ },
+ ],
+ },
+ {
+ match: (m, p) => m === "GET" && (p === "/v1/files" || /^\/v1\/files\/[^/]+\/content$/.test(p)),
+ guidance:
+ "These show the ASKING PERSON's file library across every context they can reach. A file outside their visibility returns 404 without revealing whether it exists.",
+ routes: [
+ {
+ method: "GET",
+ path: "/v1/files",
+ summary:
+ "list files the asking person can reach across their contexts, split into owned and shared files; use limit and cursor query parameters to page owned files",
+ },
+ {
+ method: "GET",
+ path: "/v1/files/:id/content",
+ summary: "download the bytes of a file from the asking person's file library",
},
],
},
@@ -144,10 +207,11 @@ const FAMILIES: AgentApiFamily[] = [
match: (m, p) =>
(m === "GET" && p === "/v1/deployments") ||
(m === "GET" && /^\/v1\/deployments\/[^/]+$/.test(p)) ||
+ (m === "GET" && /^\/v1\/deployments\/[^/]+\/fetch$/.test(p)) ||
(m === "GET" && /^\/v1\/deployments\/[^/]+\/git-url$/.test(p)) ||
(m === "POST" && /^\/v1\/deployments\/[^/]+\/(share|archive|restore|name|display-name)$/.test(p)),
guidance:
- 'To see the published apps you can reach across scopes, GET /v1/deployments (each row carries your permission and a clone/push gitUrl). A published app (`publish`) is reachable only by its owner plus whoever the owner shares it with. To widen or narrow that — "share it with everyone" or "share it with <teammate>" — POST /v1/deployments/:id/share with `scope:"org"` or `recipient:"<name>"`; no redeploy. To rename or take down an app, use name / display-name / archive. Anyone who manages the app can change these: its owner from any conversation, a current member of the channel/team it was published from, or someone granted "manage" access.',
+ 'To see the published apps you can reach across scopes, GET /v1/deployments (each row carries your permission and a clone/push gitUrl). Read what an app renders as the asking person with GET /v1/deployments/:id/fetch. A published app (`publish`) is reachable only by its owner plus whoever the owner shares it with. To widen or narrow that — "share it with everyone" or "share it with <teammate>" — POST /v1/deployments/:id/share with `scope:"org"` or `recipient:"<name>"`; no redeploy. To rename or take down an app, use name / display-name / archive. Anyone who manages the app can change these: its owner from any conversation, a current member of the channel/team it was published from, or someone granted "manage" access.',
routes: [
{
method: "GET",
@@ -161,6 +225,12 @@ const FAMILIES: AgentApiFamily[] = [
summary:
"inspect one deployment you can reach — status, owner/home scope, effective permission, current and applied versions, version history with commit ids and timestamps, and gitUrl",
},
+ {
+ method: "GET",
+ path: "/v1/deployments/:id/fetch",
+ summary:
+ "read a deployment's rendered content as the asking person — query path defaults to / and maxBytes defaults to 256KB; returns upstream status, contentType, body, and truncation metadata",
+ },
{
method: "GET",
path: "/v1/deployments/:id/git-url",
@@ -206,6 +276,8 @@ const FAMILIES: AgentApiFamily[] = [
{
match: (m, p) =>
(p === "/v1/memory/self" && (m === "GET" || m === "PUT")) ||
+ (p === "/v1/memory/history" && m === "GET") ||
+ (p === "/v1/memory/restore" && m === "POST") ||
(m === "POST" && (p === "/v1/memory/search" || p === "/v1/memory/facts")),
when: (v) => !!v.claims.memory,
guidance: "Memory bodies and curation rules are documented in the memory skill.",
@@ -215,7 +287,13 @@ const FAMILIES: AgentApiFamily[] = [
{
method: "GET|PUT",
path: "/v1/memory/self",
- summary: "read or rewrite (curate) this conversation's whole notebook",
+ summary: "read or rewrite (curate) this conversation's whole notebook; rewriting is destructive",
+ },
+ { method: "GET", path: "/v1/memory/history", summary: "list notebook versions available to undo a rewrite" },
+ {
+ method: "POST",
+ path: "/v1/memory/restore",
+ summary: "restore a prior notebook version using revision and expectedRevision; use scope: org for org memory",
},
],
},
@@ -335,7 +413,10 @@ const FAMILIES: AgentApiFamily[] = [
},
{
match: (m, p) =>
- (m === "POST" && p === "/v1/skills") || ((m === "PUT" || m === "DELETE") && p.startsWith("/v1/skills/")),
+ (m === "POST" && p === "/v1/skills") ||
+ (m === "GET" && p.startsWith("/v1/skills/")) ||
+ ((m === "PUT" || m === "DELETE") && p.startsWith("/v1/skills/")) ||
+ (m === "POST" && /^\/v1\/skills\/[^/]+\/restore$/.test(p)),
guidance:
"Save a skill when you've worked out a repeatable procedure worth keeping (a checklist, a multi-step flow, a house style) — it auto-loads (skills/<name>/SKILL.md) on every future turn. The skill homes in THIS conversation's scope: in a 1:1 DM it's yours alone; in a private channel or group DM it's owned by that room and every member can edit or delete it (the audit trail records who changed what); a public channel stays owner-only. Write the `body` as a plain-step recipe addressed to your future self; edit or delete it as it goes stale.",
routes: [
@@ -345,6 +426,11 @@ const FAMILIES: AgentApiFamily[] = [
summary:
"save a NEW skill in this conversation's scope — {name, description, body} (the SKILL.md). Auto review+published; a name already taken in this scope is a 409 (edit it instead).",
},
+ {
+ method: "GET",
+ path: "/v1/skills/:id",
+ summary: "read a skill you can see, including an archived skill's body, files, status, and version",
+ },
{
method: "PUT",
path: "/v1/skills/:id",
@@ -354,7 +440,12 @@ const FAMILIES: AgentApiFamily[] = [
{
method: "DELETE",
path: "/v1/skills/:id",
- summary: "delete a skill you manage (hard delete). 404 if missing, 403 if it isn't yours to delete",
+ summary: "archive a skill you manage. 404 if missing, 403 if it isn't yours to archive",
+ },
+ {
+ method: "POST",
+ path: "/v1/skills/:id/restore",
+ summary: "restore an archived skill you manage by re-reviewing and publishing its preserved version",
},
],
},
diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.ts
index 9b59f7d64..ad14714b4 100644
--- a/src/api/routes/deployments.ts
+++ b/src/api/routes/deployments.ts
@@ -127,6 +127,10 @@ const GATEWAY_AUTH_HEADERS = [
];
const PROXY_BUFFER_MAX_BYTES = 10_000_000;
+const AGENT_FETCH_DEFAULT_MAX_BYTES = 256 * 1024;
+const AGENT_FETCH_MAX_BYTES = 1024 * 1024;
+const AGENT_FETCH_TIMEOUT_MS = 10_000;
+const AGENT_FETCH_MAX_REDIRECTS = 5;
const THROTTLE_SHIELD_MS = 5_000;
const throttledUpstreams = new Map<string, number>();
@@ -457,6 +461,173 @@ async function proxyReach(
return;
}
+interface DeploymentFetchResult {
+ status: number;
+ headers: Record<string, string | string[] | number | undefined>;
+ body: Buffer;
+ truncated: boolean;
+}
+
+function boundedResponseBody(
+ stream: NodeJS.ReadableStream & { destroy(error?: Error): void },
+ maxBytes: number,
+ timeoutMs = AGENT_FETCH_TIMEOUT_MS,
+): Promise<{ body: Buffer; truncated: boolean }> {
+ return new Promise((resolve, reject) => {
+ const chunks: Buffer[] = [];
+ let size = 0;
+ let settled = false;
+ const timeout = setTimeout(() => stream.destroy(new Error("timeout")), Math.max(1, timeoutMs));
+ timeout.unref();
+ const finish = (truncated: boolean): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ resolve({ body: Buffer.concat(chunks, Math.min(size, maxBytes)), truncated });
+ if (truncated) stream.destroy();
+ };
+ stream.on("data", (raw: Buffer | string) => {
+ const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
+ const remaining = maxBytes - size;
+ if (remaining > 0) chunks.push(chunk.subarray(0, remaining));
+ size += Math.min(chunk.length, Math.max(remaining, 0));
+ if (chunk.length > remaining) finish(true);
+ });
+ stream.on("end", () => finish(false));
+ const fail = (error?: Error): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ reject(error ?? new Error("upstream aborted"));
+ };
+ stream.on("error", fail);
+ stream.on("aborted", fail);
+ });
+}
+
+function deploymentFetchHttp1(
+ endpoint: Awaited<ReturnType<App["reachDeployment"]>> & { status: "ok" },
+ path: string,
+ maxBytes: number,
+ deadline: number,
+): Promise<DeploymentFetchResult> {
+ return new Promise((resolve, reject) => {
+ const { host, port, tls, proxyHeaders } = endpoint.endpoint;
+ const requestFn = tls ? httpsRequest : httpRequest;
+ const request = requestFn(
+ { hostname: host, port, path, method: "GET", headers: { ...proxyHeaders, "accept-encoding": "identity" } },
+ async (response) => {
+ clearTimeout(timeout);
+ try {
+ const collected = await boundedResponseBody(response, maxBytes, deadline - Date.now());
+ resolve({ status: response.statusCode ?? 502, headers: response.headers, ...collected });
+ } catch (error) {
+ reject(error);
+ }
+ },
+ );
+ const timeout = setTimeout(() => request.destroy(new Error("timeout")), Math.max(1, deadline - Date.now()));
+ timeout.unref();
+ request.on("error", (error) => {
+ clearTimeout(timeout);
+ reject(error);
+ });
+ request.end();
+ });
+}
+
+function deploymentFetchHttp2(
+ endpoint: Awaited<ReturnType<App["reachDeployment"]>> & { status: "ok" },
+ path: string,
+ maxBytes: number,
+ deadline: number,
+): Promise<DeploymentFetchResult> {
+ return new Promise((resolve, reject) => {
+ const { host, port, tls, proxyHeaders } = endpoint.endpoint;
+ const origin = `${tls ? "https" : "http"}://${host}:${port}`;
+ const connection = deploymentHttp2Session(origin);
+ const stream = connection.session.request({
+ ":method": "GET",
+ ":path": path,
+ ":authority": tls ? host : `${host}:${port}`,
+ "accept-encoding": "identity",
+ ...proxyHeaders,
+ });
+ connection.activeStreams++;
+ let headers: Record<string, string | string[] | number | undefined> = {};
+ stream.on("response", (responseHeaders) => {
+ headers = responseHeaders;
+ });
+ boundedResponseBody(stream, maxBytes, deadline - Date.now())
+ .then((collected) => resolve({ status: Number(headers[":status"] ?? 502), headers, ...collected }))
+ .catch(reject);
+ stream.once("close", () => releaseDeploymentHttp2Stream(origin, connection));
+ stream.end();
+ });
+}
+
+function normalizedDeploymentFetchPath(raw: string | null): string | null {
+ const path = raw ?? "/";
+ if (!path.startsWith("/") || path.includes("\\") || path.includes("\0")) return null;
+ try {
+ let decodedPath = path.split("?", 1)[0]!;
+ for (let depth = 0; depth < 8; depth++) {
+ const next = decodeURIComponent(decodedPath);
+ if (
+ next.includes("\\") ||
+ next.includes("\0") ||
+ next.split("/").some((segment) => segment === "." || segment === "..")
+ )
+ return null;
+ if (next === decodedPath) break;
+ if (depth === 7) return null;
+ decodedPath = next;
+ }
+ const normalized = new URL(path, "http://deployment.invalid");
+ if (normalized.origin !== "http://deployment.invalid") return null;
+ return normalized.pathname + normalized.search;
+ } catch {
+ return null;
+ }
+}
+
+function redirectPath(
+ endpoint: Awaited<ReturnType<App["reachDeployment"]>> & { status: "ok" },
+ location: string | string[] | number | undefined,
+ currentPath: string,
+): string | null {
+ if (typeof location !== "string") return null;
+ try {
+ const { host, port, tls } = endpoint.endpoint;
+ const origin = `${tls ? "https" : "http"}://${host}:${port}`;
+ const next = new URL(location, `${origin}${currentPath}`);
+ if (next.origin !== origin) return null;
+ return normalizedDeploymentFetchPath(next.pathname + next.search);
+ } catch {
+ return null;
+ }
+}
+
+async function fetchDeploymentResponse(
+ endpoint: Awaited<ReturnType<App["reachDeployment"]>> & { status: "ok" },
+ initialPath: string,
+ maxBytes: number,
+): Promise<DeploymentFetchResult> {
+ let path = initialPath;
+ const deadline = Date.now() + AGENT_FETCH_TIMEOUT_MS;
+ for (let redirects = 0; ; redirects++) {
+ const response =
+ endpoint.endpoint.httpVersion === "2"
+ ? await deploymentFetchHttp2(endpoint, path, maxBytes, deadline)
+ : await deploymentFetchHttp1(endpoint, path, maxBytes, deadline);
+ if (![301, 302, 303, 307, 308].includes(response.status)) return response;
+ if (redirects >= AGENT_FETCH_MAX_REDIRECTS) throw new Error("too many redirects");
+ const next = redirectPath(endpoint, response.headers.location, path);
+ if (!next) throw new Error("redirect leaves deployment");
+ path = next;
+ }
+}
+
function cookieValue(header: string | undefined, name: string): string {
for (const part of (header ?? "").split(";")) {
const p = part.trim();
@@ -910,6 +1081,54 @@ async function listDeployments(ctx: ApiCtx): Promise<void> {
return sendJson(res, 200, { deployments });
}
+function textContentType(contentType: string): boolean {
+ return (
+ /^text\//i.test(contentType) ||
+ /(?:^|\/)(?:json|xml|javascript)(?:;|$)/i.test(contentType) ||
+ /\+(?:json|xml)(?:;|$)/i.test(contentType)
+ );
+}
+
+async function fetchDeployment(ctx: ApiCtx): Promise<void> {
+ const { res, app, params, capability, actor, url } = ctx;
+ const viewer = capability?.actorId ?? actor?.p;
+ if (!viewer) return sendJson(res, 401, { error: "capability_required" });
+ const path = normalizedDeploymentFetchPath(url.searchParams.get("path"));
+ if (!path) return sendJson(res, 400, { error: "bad_request", message: "path must be a safe absolute path" });
+ const rawMaxBytes = url.searchParams.get("maxBytes");
+ const maxBytes = rawMaxBytes === null ? AGENT_FETCH_DEFAULT_MAX_BYTES : Number(rawMaxBytes);
+ if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > AGENT_FETCH_MAX_BYTES) {
+ return sendJson(res, 400, {
+ error: "bad_request",
+ message: `maxBytes must be an integer from 1 to ${AGENT_FETCH_MAX_BYTES}`,
+ });
+ }
+ const reach = await app.reachDeployment(params.id!, viewer);
+ if (reach.status !== "ok") return sendJson(res, 404, { error: "not_found" });
+ try {
+ const response = await fetchDeploymentResponse(reach, path, maxBytes);
+ const rawContentType = response.headers["content-type"];
+ const contentType = typeof rawContentType === "string" ? rawContentType : "application/octet-stream";
+ if (textContentType(contentType)) {
+ return sendJson(res, 200, {
+ status: response.status,
+ contentType,
+ body: response.body.toString("utf8"),
+ truncated: response.truncated,
+ });
+ }
+ return sendJson(res, 200, {
+ status: response.status,
+ contentType,
+ body: response.body.toString("base64"),
+ encoding: "base64",
+ truncated: response.truncated,
+ });
+ } catch {
+ return sendJson(res, 502, { error: "upstream_unreachable" });
+ }
+}
+
export async function getDeployment(ctx: ApiCtx): Promise<void> {
const { res, app, url, secret, capability, params } = ctx;
const principalId = capability ? capability.actorId : url.searchParams.get("principalId");
@@ -1112,6 +1331,7 @@ export const deploymentRoutes: ReadonlyArray<Route<ApiCtx>> = [
{ method: "POST", path: "/v1/deployments", auth: "source", handle: createDeployment },
{ method: "GET", path: "/v1/deployments", auth: "either", handle: listDeployments },
{ method: "GET", path: "/v1/deployments/:id", auth: "either", handle: getDeployment },
+ { method: "GET", path: "/v1/deployments/:id/fetch", auth: "either", handle: fetchDeployment },
{ method: "GET", path: "/v1/deployments/:id/git-url", auth: "either", handle: deploymentGitUrl },
{ method: "GET", path: "/v1/deployments/:id/owner-url", auth: "source", handle: deploymentOwnerUrl },
{ method: "POST", path: "/v1/deployments/:id/share", auth: "either", handle: shareDeployment },
diff --git a/src/api/routes/projects.ts b/src/api/routes/projects.ts
index 50d20132c..7f5157825 100644
--- a/src/api/routes/projects.ts
+++ b/src/api/routes/projects.ts
@@ -2,15 +2,28 @@ import { sendJson } from "../http.ts";
import { isObj } from "./shared.ts";
import { type ApiCtx, type Route } from "./route.ts";
+function capabilityPrincipal(ctx: ApiCtx, requested: string): string | null {
+ if (!ctx.capability) return requested;
+ if (requested && requested !== ctx.capability.actorId) {
+ sendJson(ctx.res, 404, { error: "not_found" });
+ return null;
+ }
+ return ctx.capability.actorId;
+}
+
async function listProjects(ctx: ApiCtx): Promise<void> {
- const principalId = (ctx.url.searchParams.get("principalId") ?? "").trim();
+ const requested = (ctx.url.searchParams.get("principalId") ?? "").trim();
+ const principalId = capabilityPrincipal(ctx, requested);
+ if (principalId === null) return;
if (!principalId) return sendJson(ctx.res, 400, { error: "bad_request", message: "principalId required" });
return sendJson(ctx.res, 200, { projects: await ctx.app.listProjects(principalId) });
}
async function createProject(ctx: ApiCtx): Promise<void> {
const body = isObj(ctx.body) ? ctx.body : {};
- const principalId = typeof body.principalId === "string" ? body.principalId.trim() : "";
+ const requested = typeof body.principalId === "string" ? body.principalId.trim() : "";
+ const principalId = capabilityPrincipal(ctx, requested);
+ if (principalId === null) return;
const name = typeof body.name === "string" ? body.name.trim() : "";
if (!principalId || !name)
return sendJson(ctx.res, 400, { error: "bad_request", message: "principalId and name required" });
@@ -21,7 +34,8 @@ async function createProject(ctx: ApiCtx): Promise<void> {
function mutationResponse(ctx: ApiCtx, result: Awaited<ReturnType<ApiCtx["app"]["addProjectMember"]>>): void {
if (result.status === "ok") return sendJson(ctx.res, 200, { project: result.project });
if (result.status === "not_found") return sendJson(ctx.res, 404, { error: "not_found" });
- if (result.status === "forbidden") return sendJson(ctx.res, 403, { error: "forbidden" });
+ if (result.status === "forbidden")
+ return sendJson(ctx.res, ctx.capability ? 404 : 403, { error: ctx.capability ? "not_found" : "forbidden" });
if (result.status === "invalid_name")
return sendJson(ctx.res, 400, { error: "invalid_name", message: "project name required" });
return sendJson(ctx.res, 400, {
@@ -32,7 +46,9 @@ function mutationResponse(ctx: ApiCtx, result: Awaited<ReturnType<ApiCtx["app"][
async function addProjectMember(ctx: ApiCtx): Promise<void> {
const body = isObj(ctx.body) ? ctx.body : {};
- const principalId = typeof body.principalId === "string" ? body.principalId.trim() : "";
+ const requested = typeof body.principalId === "string" ? body.principalId.trim() : "";
+ const principalId = capabilityPrincipal(ctx, requested);
+ if (principalId === null) return;
const memberId = typeof body.memberId === "string" ? body.memberId.trim() : "";
if (!principalId || !memberId)
return sendJson(ctx.res, 400, { error: "bad_request", message: "principalId and memberId required" });
@@ -41,7 +57,9 @@ async function addProjectMember(ctx: ApiCtx): Promise<void> {
async function renameProject(ctx: ApiCtx): Promise<void> {
const body = isObj(ctx.body) ? ctx.body : {};
- const principalId = typeof body.principalId === "string" ? body.principalId.trim() : "";
+ const requested = typeof body.principalId === "string" ? body.principalId.trim() : "";
+ const principalId = capabilityPrincipal(ctx, requested);
+ if (principalId === null) return;
const name = typeof body.name === "string" ? body.name.trim() : "";
if (!principalId || !name)
return sendJson(ctx.res, 400, { error: "bad_request", message: "principalId and name required" });
@@ -50,7 +68,9 @@ async function renameProject(ctx: ApiCtx): Promise<void> {
async function removeProjectMember(ctx: ApiCtx): Promise<void> {
const body = isObj(ctx.body) ? ctx.body : {};
- const principalId = typeof body.principalId === "string" ? body.principalId.trim() : "";
+ const requested = typeof body.principalId === "string" ? body.principalId.trim() : "";
+ const principalId = capabilityPrincipal(ctx, requested);
+ if (principalId === null) return;
const memberId = ctx.params.memberId?.trim() ?? "";
if (!principalId || !memberId)
return sendJson(ctx.res, 400, { error: "bad_request", message: "principalId and memberId required" });
@@ -58,9 +78,9 @@ async function removeProjectMember(ctx: ApiCtx): Promise<void> {
}
export const projectRoutes: ReadonlyArray<Route<ApiCtx>> = [
- { method: "GET", path: "/v1/projects", auth: "source", handle: listProjects },
- { method: "POST", path: "/v1/projects", auth: "source", handle: createProject },
- { method: "PATCH", path: "/v1/projects/:id", auth: "source", handle: renameProject },
- { method: "POST", path: "/v1/projects/:id/members", auth: "source", handle: addProjectMember },
- { method: "DELETE", path: "/v1/projects/:id/members/:memberId", auth: "source", handle: removeProjectMember },
+ { method: "GET", path: "/v1/projects", auth: "either", handle: listProjects },
+ { method: "POST", path: "/v1/projects", auth: "either", handle: createProject },
+ { method: "PATCH", path: "/v1/projects/:id", auth: "either", handle: renameProject },
+ { method: "POST", path: "/v1/projects/:id/members", auth: "either", handle: addProjectMember },
+ { method: "DELETE", path: "/v1/projects/:id/members/:memberId", auth: "either", handle: removeProjectMember },
];
diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.ts
index 397a558d8..922608c21 100644
--- a/src/api/routes/surface.ts
+++ b/src/api/routes/surface.ts
@@ -46,6 +46,10 @@ function sharedSkillCreateBlock(capability: ApiCtx["capability"]): string | null
return SHARED_SKILL_TRIGGER_REFUSAL;
}
+function isConversationColor(value: unknown): value is string | null {
+ return value === null || (typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value));
+}
+
async function regenerateSessionTitle(ctx: ApiCtx): Promise<void> {
const { res, app, body } = ctx;
const id = ctx.params.id!;
@@ -73,39 +77,87 @@ async function forkSession(ctx: ApiCtx): Promise<void> {
return sendJson(res, 200, out);
}
-async function getSession(ctx: ApiCtx): Promise<void> {
- const { res, app, url } = ctx;
- const id = ctx.params.id!;
- const viewer = url.searchParams.get("viewer");
- if (!viewer) return sendJson(res, 400, { error: "bad_request", message: "viewer required" });
+async function forkAgentConversation(ctx: ApiCtx): Promise<void> {
+ const { res, app, body, capability } = ctx;
+ if (!capability) {
+ return sendJson(res, 401, { error: "capability_required", message: "this endpoint is for the agent self-API" });
+ }
+ const b = isObj(body) ? body : {};
+ if (b.upToSeq !== undefined && (typeof b.upToSeq !== "number" || !Number.isInteger(b.upToSeq) || b.upToSeq < 0)) {
+ return sendJson(res, 400, { error: "bad_request", message: "upToSeq must be a non-negative integer" });
+ }
+ const out = await app.forkSession(
+ ctx.params.id!,
+ capability.actorId,
+ b.upToSeq !== undefined ? { upToSeq: b.upToSeq } : undefined,
+ );
+ if (!out) return sendJson(res, 404, { error: "not_found", message: "not a conversation you can see" });
+ return sendJson(res, 200, out);
+}
+
+function transcriptWindow(
+ url: URL,
+ defaultTailTurns?: number,
+): { tailTurns?: number; sinceSeq?: number; beforeSeq?: number } | null {
const windowParam = (name: "tailTurns" | "sinceSeq" | "beforeSeq", min: number): number | undefined | null => {
const raw = url.searchParams.get(name);
if (raw === null) return undefined;
const n = Number(raw);
return Number.isInteger(n) && n >= min ? n : null;
};
- const tailTurns = windowParam("tailTurns", 1);
+ const requestedTailTurns = windowParam("tailTurns", 1);
const sinceSeq = windowParam("sinceSeq", 0);
const beforeSeq = windowParam("beforeSeq", 1);
- if (tailTurns === null || sinceSeq === null || beforeSeq === null) {
+ if (requestedTailTurns === null || sinceSeq === null || beforeSeq === null) return null;
+ const tailTurns = requestedTailTurns ?? (sinceSeq === undefined ? defaultTailTurns : undefined);
+ if (tailTurns === undefined && sinceSeq === undefined && beforeSeq === undefined) return {};
+ return {
+ ...(tailTurns !== undefined ? { tailTurns } : {}),
+ ...(sinceSeq !== undefined ? { sinceSeq } : {}),
+ ...(beforeSeq !== undefined ? { beforeSeq } : {}),
+ };
+}
+
+async function getSession(ctx: ApiCtx): Promise<void> {
+ const { res, app, url } = ctx;
+ const id = ctx.params.id!;
+ const viewer = url.searchParams.get("viewer");
+ if (!viewer) return sendJson(res, 400, { error: "bad_request", message: "viewer required" });
+ const window = transcriptWindow(url);
+ if (!window) {
return sendJson(res, 400, {
error: "bad_request",
message: "tailTurns and beforeSeq must be positive integers, sinceSeq a non-negative one",
});
}
- const window =
- tailTurns !== undefined || sinceSeq !== undefined || beforeSeq !== undefined
- ? {
- ...(tailTurns !== undefined ? { tailTurns } : {}),
- ...(sinceSeq !== undefined ? { sinceSeq } : {}),
- ...(beforeSeq !== undefined ? { beforeSeq } : {}),
- }
- : undefined;
- const found = await app.getSessionForViewer(id, viewer, window);
+ const found = await app.getSessionForViewer(id, viewer, Object.keys(window).length ? window : undefined);
if (!found) return sendJson(res, 404, { error: "not_found" });
return sendJson(res, 200, found);
}
+async function getAgentConversation(ctx: ApiCtx): Promise<void> {
+ const { res, app, url, capability } = ctx;
+ if (!capability) {
+ return sendJson(res, 401, { error: "capability_required", message: "this endpoint is for the agent self-API" });
+ }
+ if (url.searchParams.has("sinceSeq")) {
+ return sendJson(res, 400, {
+ error: "bad_request",
+ message: "agent transcript paging supports tailTurns and beforeSeq",
+ });
+ }
+ const window = transcriptWindow(url, 20);
+ if (!window) {
+ return sendJson(res, 400, {
+ error: "bad_request",
+ message: "tailTurns and beforeSeq must be positive integers, sinceSeq a non-negative one",
+ });
+ }
+ const found = await app.getSessionForViewer(ctx.params.id!, capability.actorId, window);
+ if (!found) return sendJson(res, 404, { error: "not_found", message: "not a conversation you can see" });
+ return sendJson(res, 200, found);
+}
+
async function listSessionApprovals(ctx: ApiCtx): Promise<void> {
const { res, app, url } = ctx;
const id = ctx.params.id!;
@@ -137,10 +189,10 @@ async function getSessionBackgroundOutput(ctx: ApiCtx): Promise<void> {
}
async function getFileContent(ctx: ApiCtx): Promise<void> {
- const { res, app, url } = ctx;
+ const { res, app, capability, actor } = ctx;
const id = ctx.params.id!;
- const viewer = url.searchParams.get("viewer");
- if (!viewer) return sendJson(res, 400, { error: "bad_request", message: "viewer required" });
+ const viewer = capability?.actorId ?? actor?.p;
+ if (!viewer) return sendJson(res, 401, { error: "capability_required" });
const opened = await app.openFileForViewer(id, viewer);
if (!opened) return sendJson(res, 404, { error: "not_found" });
res.writeHead(200, {
@@ -153,9 +205,9 @@ async function getFileContent(ctx: ApiCtx): Promise<void> {
}
async function listFiles(ctx: ApiCtx): Promise<void> {
- const { res, app, url } = ctx;
- const viewer = url.searchParams.get("viewer");
- if (!viewer) return sendJson(res, 400, { error: "bad_request", message: "viewer required" });
+ const { res, app, url, capability, actor } = ctx;
+ const viewer = capability?.actorId ?? actor?.p;
+ if (!viewer) return sendJson(res, 401, { error: "capability_required" });
const limitRaw = url.searchParams.get("limit");
const cursor = url.searchParams.get("cursor");
const scope = url.searchParams.get("scope");
@@ -232,7 +284,7 @@ async function patchSession(ctx: ApiCtx): Promise<void> {
patch.pinned = b.pinned;
}
if ("color" in b) {
- if (b.color !== null && !(typeof b.color === "string" && /^#[0-9a-fA-F]{6}$/.test(b.color))) {
+ if (!isConversationColor(b.color)) {
return sendJson(res, 400, { error: "bad_request", message: "color must be '#rrggbb' or null" });
}
patch.color = typeof b.color === "string" ? b.color.toLowerCase() : null;
@@ -276,7 +328,7 @@ async function patchAgentConversation(ctx: ApiCtx): Promise<void> {
return sendJson(res, 401, { error: "capability_required", message: "this endpoint is for the agent self-API" });
}
const b = isObj(body) ? body : {};
- const patch: { title?: string | null; archived?: boolean; pinned?: boolean } = {};
+ const patch: { title?: string | null; archived?: boolean; pinned?: boolean; color?: string | null } = {};
if ("archived" in b) {
if (typeof b.archived !== "boolean") {
return sendJson(res, 400, { error: "bad_request", message: "archived must be a boolean" });
@@ -296,8 +348,19 @@ async function patchAgentConversation(ctx: ApiCtx): Promise<void> {
const trimmed = typeof b.title === "string" ? b.title.trim().slice(0, 200) : null;
patch.title = trimmed ? trimmed : null;
}
- if (patch.archived === undefined && patch.pinned === undefined && patch.title === undefined) {
- return sendJson(res, 400, { error: "bad_request", message: "archived, pinned, or title required" });
+ if ("color" in b) {
+ if (!isConversationColor(b.color)) {
+ return sendJson(res, 400, { error: "bad_request", message: "color must be '#rrggbb' or null" });
+ }
+ patch.color = typeof b.color === "string" ? b.color.toLowerCase() : null;
+ }
+ if (
+ patch.archived === undefined &&
+ patch.pinned === undefined &&
+ patch.title === undefined &&
+ patch.color === undefined
+ ) {
+ return sendJson(res, 400, { error: "bad_request", message: "archived, pinned, title, or color required" });
}
const session = await app.updateSession(ctx.params.id!, capability.actorId, patch);
if (!session) return sendJson(res, 404, { error: "not_found", message: "not a conversation you can see" });
@@ -314,6 +377,7 @@ async function patchAgentConversation(ctx: ApiCtx): Promise<void> {
title: session.title ?? null,
archived: session.archived === true,
pinned: session.pinned === true,
+ color: session.color ?? null,
},
});
}
@@ -382,25 +446,47 @@ async function putSelfMemory(ctx: ApiCtx): Promise<void> {
}
async function getSelfMemoryHistory(ctx: ApiCtx): Promise<void> {
- const { res, deps, url } = ctx;
- const principalId = url.searchParams.get("principalId");
+ const { res, deps, url, capability, actor } = ctx;
+ const viewer = capability?.actorId ?? actor?.p;
+ if (!viewer) return sendJson(res, 401, { error: "capability_required" });
+ const principalId = capability ? viewer : url.searchParams.get("principalId");
if (!principalId) return sendJson(res, 400, { error: "bad_request", message: "principalId required" });
+ if (url.searchParams.has("principalId") && url.searchParams.get("principalId") !== viewer) {
+ return sendJson(res, 404, { error: "not_found" });
+ }
+ const requestedScope = capability ? (url.searchParams.get("scope") ?? undefined) : undefined;
+ if (requestedScope !== undefined && requestedScope !== "org") {
+ return sendJson(res, 400, { error: "bad_request", message: 'scope must be "org" when present' });
+ }
+ let scope: ScopeId | undefined = makeScopeId("personal", principalId);
+ if (capability) scope = requestedScope === "org" ? capability.memory?.orgWrite : capability.memory?.write;
+ if (!scope) return sendJson(res, 404, { error: "not_found" });
if (!deps.memory?.history) return sendJson(res, 200, { revisions: [] });
- return sendJson(res, 200, { revisions: await deps.memory.history(makeScopeId("personal", principalId), 30) });
+ return sendJson(res, 200, { revisions: await deps.memory.history(scope, 30) });
}
async function restoreSelfMemory(ctx: ApiCtx): Promise<void> {
- const { res, deps, body } = ctx;
- const b = body as { principalId?: unknown; revision?: unknown; expectedRevision?: unknown };
- if (typeof b.principalId !== "string" || typeof b.revision !== "string" || typeof b.expectedRevision !== "string") {
- return sendJson(res, 400, { error: "bad_request", message: "principalId, revision, expectedRevision required" });
+ const { res, deps, body, capability, actor } = ctx;
+ const viewer = capability?.actorId ?? actor?.p;
+ if (!viewer) return sendJson(res, 401, { error: "capability_required" });
+ const b = body as { principalId?: unknown; revision?: unknown; expectedRevision?: unknown; scope?: unknown };
+ const principalId = capability ? viewer : b.principalId;
+ if (typeof principalId !== "string" || typeof b.revision !== "string" || typeof b.expectedRevision !== "string") {
+ return sendJson(res, 400, { error: "bad_request", message: "revision and expectedRevision required" });
}
- const scope = makeScopeId("personal", b.principalId);
- const restored = await deps.memory?.restore?.(scope, b.revision, b.expectedRevision, b.principalId);
+ if (b.principalId !== undefined && b.principalId !== viewer) return sendJson(res, 404, { error: "not_found" });
+ const requestedScope = capability ? b.scope : undefined;
+ if (requestedScope !== undefined && requestedScope !== "org") {
+ return sendJson(res, 400, { error: "bad_request", message: 'scope must be "org" when present' });
+ }
+ let scope: ScopeId | undefined = makeScopeId("personal", principalId);
+ if (capability) scope = requestedScope === "org" ? capability.memory?.orgWrite : capability.memory?.write;
+ if (!scope) return sendJson(res, 404, { error: "not_found" });
+ const restored = await deps.memory?.restore?.(scope, b.revision, b.expectedRevision, viewer);
if (!restored)
return sendJson(res, 409, { error: "conflict", message: "Memory changed, or that revision no longer exists." });
audit(deps, {
- principalId: b.principalId,
+ principalId: viewer,
action: "memory.self.restore",
resource: `memory:${b.revision}`,
scopeLabel: scope,
@@ -582,8 +668,11 @@ async function listSkills(ctx: ApiCtx): Promise<void> {
}
async function getSkillDetail(ctx: ApiCtx): Promise<void> {
- const { res, app, url } = ctx;
- const principalId = url.searchParams.get("principalId");
+ const { res, app, url, capability, actor } = ctx;
+ const principalId = capability?.actorId ?? actor?.p ?? url.searchParams.get("principalId");
+ if (!capability && !actor && ctx.secret) {
+ return sendJson(res, 401, { error: "capability_required" });
+ }
if (!principalId) return sendJson(res, 400, { error: "bad_request", message: "principalId required" });
const skill = await app.getSkill(ctx.params.id!);
if (
@@ -617,7 +706,11 @@ async function getSkillDetail(ctx: ApiCtx): Promise<void> {
async function restoreSkill(ctx: ApiCtx): Promise<void> {
const b = (ctx.body ?? {}) as { principalId?: unknown };
- const principalId = typeof b.principalId === "string" ? b.principalId : "";
+ const principalId =
+ ctx.capability?.actorId ?? ctx.actor?.p ?? (typeof b.principalId === "string" ? b.principalId : "");
+ if (!ctx.capability && !ctx.actor && ctx.secret) {
+ return sendJson(ctx.res, 401, { error: "capability_required" });
+ }
if (!principalId) return sendJson(ctx.res, 400, { error: "bad_request", message: "principalId required" });
const restored = await ctx.app.restoreOwnedSkill(ctx.params.id!, principalId);
return restored ? sendJson(ctx.res, 200, { ok: true }) : sendJson(ctx.res, 404, { error: "not_found" });
@@ -1132,19 +1225,21 @@ export const surfaceRoutes: ReadonlyArray<Route<ApiCtx>> = [
handle: getSessionBackgroundOutput,
},
{ method: "GET", path: "/v1/sessions/:id", auth: "source", handle: getSession },
- { method: "GET", path: "/v1/files/:id/content", auth: "source", handle: getFileContent },
+ { method: "GET", path: "/v1/files/:id/content", auth: "either", handle: getFileContent },
{ method: "POST", path: "/v1/files/upload", auth: "source", handle: uploadFile },
- { method: "GET", path: "/v1/files", auth: "source", handle: listFiles },
+ { method: "GET", path: "/v1/files", auth: "either", handle: listFiles },
{ method: "POST", path: "/v1/sessions/:id", auth: "source", handle: patchSession },
{ method: "GET", path: "/v1/sessions", auth: "source", handle: listSessions },
{ method: "GET", path: "/v1/conversations", auth: "either", handle: listAgentConversations },
+ { method: "GET", path: "/v1/conversations/:id", auth: "either", handle: getAgentConversation },
{ method: "POST", path: "/v1/conversations/:id", auth: "either", handle: patchAgentConversation },
+ { method: "POST", path: "/v1/conversations/:id/fork", auth: "either", handle: forkAgentConversation },
{ method: "GET", path: "/v1/contexts", auth: "source", handle: listContexts },
{ method: "GET", path: "/v1/scope-resources", auth: "source", handle: listScopeResources },
{ method: "GET", path: "/v1/memory", auth: "source", handle: getSelfMemory },
{ method: "PUT", path: "/v1/memory", auth: "source", handle: putSelfMemory },
- { method: "GET", path: "/v1/memory/history", auth: "source", handle: getSelfMemoryHistory },
- { method: "POST", path: "/v1/memory/restore", auth: "source", handle: restoreSelfMemory },
+ { method: "GET", path: "/v1/memory/history", auth: "either", handle: getSelfMemoryHistory },
+ { method: "POST", path: "/v1/memory/restore", auth: "either", handle: restoreSelfMemory },
{ method: "GET", path: "/v1/apis", auth: "either", handle: listAgentApis },
{
match: (m, p) =>
@@ -1159,11 +1254,11 @@ export const surfaceRoutes: ReadonlyArray<Route<ApiCtx>> = [
handle: agentMemory,
},
{ method: "GET", path: "/v1/skills", auth: "source", handle: listSkills },
- { method: "GET", path: "/v1/skills/:id", auth: "source", handle: getSkillDetail },
+ { method: "GET", path: "/v1/skills/:id", auth: "either", handle: getSkillDetail },
{ method: "POST", path: "/v1/skills", auth: "either", handle: createSkill },
{ method: "PUT", path: "/v1/skills/:id", auth: "either", handle: updateSkill },
{ method: "DELETE", path: "/v1/skills/:id", auth: "either", handle: deleteSkill },
- { method: "POST", path: "/v1/skills/:id/restore", auth: "source", handle: restoreSkill },
+ { method: "POST", path: "/v1/skills/:id/restore", auth: "either", handle: restoreSkill },
{ method: "POST", path: "/v1/grants", auth: "source", handle: createGrant },
{ method: "POST", path: "/v1/grants/revoke", auth: "source", handle: revokeGrant },
{ method: "POST", path: "/v1/share", auth: "either", handle: shareArtifact },
diff --git a/src/api/server.ts b/src/api/server.ts
index 1458725ac..e276baa82 100644
--- a/src/api/server.ts
+++ b/src/api/server.ts
@@ -98,8 +98,17 @@ function isAdminContentRead(pathname: string): boolean {
}
function strictPostAllowed(pathname: string, body: unknown): boolean {
- if (pathname === "/v1/surface-context" || pathname === "/v1/memory/search" || pathname.startsWith("/v1/run-signals/"))
+ if (
+ pathname === "/v1/surface-context" ||
+ pathname === "/v1/projects" ||
+ pathname === "/v1/memory/search" ||
+ pathname === "/v1/memory/restore" ||
+ pathname.startsWith("/v1/run-signals/") ||
+ /^\/v1\/conversations\/[^/]+\/fork$/.test(pathname)
+ )
return true;
+ if (/^\/v1\/projects\/[^/]+(?:\/members(?:\/[^/]+)?)?$/.test(pathname)) return true;
+ if (/^\/v1\/skills\/[^/]+\/restore$/.test(pathname)) return true;
return (
/^\/v1\/triggers\/[^/]+\/consent$/.test(pathname) && (body as { decision?: unknown } | null)?.decision === "decline"
);
diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.ts
index 032788fe0..c50c93edd 100644
--- a/src/api/user-scoped-routes.ts
+++ b/src/api/user-scoped-routes.ts
@@ -32,9 +32,11 @@ const USER_SCOPED: Rule[] = [
pat("POST", "/v1/memory/restore", { in: "body", name: "principalId" }),
pat("GET", "/v1/contexts/policy", { in: "query", name: "principalId" }),
pat("GET", "/v1/skills", { in: "query", name: "principalId" }),
+ pat("GET", "/v1/skills/:id", { in: "query", name: "principalId" }),
pat("POST", "/v1/skills", { in: "body", name: "principalId" }),
pat("PUT", "/v1/skills/:id", { in: "body", name: "principalId" }),
pat("DELETE", "/v1/skills/:id", { in: "body", name: "principalId" }),
+ pat("POST", "/v1/skills/:id/restore", { in: "body", name: "principalId" }),
pat("POST", "/v1/soul", { in: "body", name: "actorId" }),
pat("GET", "/v1/crons", { in: "query", name: "viewer" }),
pat("POST", "/v1/crons", { in: "body", name: "createdBy" }),
diff --git a/src/memory/memory-service.ts b/src/memory/memory-service.ts
index 0c6af0401..4ff86a01f 100644
--- a/src/memory/memory-service.ts
+++ b/src/memory/memory-service.ts
@@ -11,7 +11,7 @@ function revisionToken(content: string): string {
return createHash("sha256").update(content).digest("hex");
}
-interface MemoryRevision {
+export interface MemoryRevision {
revision: string;
content: string;
operation: string;
diff --git a/test/agent-api-discovery.test.ts b/test/agent-api-discovery.test.ts
index 4591b43cb..2f3196557 100644
--- a/test/agent-api-discovery.test.ts
+++ b/test/agent-api-discovery.test.ts
@@ -170,6 +170,8 @@ test("the catalog IS the gate: discovery rows with real paths are admitted, unli
assert.equal(agentApiMatches("POST", "/v1/skills"), true);
assert.equal(agentApiMatches("PUT", "/v1/skills/abc"), true);
assert.equal(agentApiMatches("DELETE", "/v1/skills/abc"), true);
+ assert.equal(agentApiMatches("GET", "/v1/skills/abc"), true);
+ assert.equal(agentApiMatches("POST", "/v1/skills/abc/restore"), true);
assert.equal(agentApiMatches("GET", "/v1/crons/abc"), true);
assert.equal(agentApiMatches("PUT", "/v1/memory/self"), true);
assert.equal(agentApiMatches("PUT", "/v1/admin/memory"), true);
diff --git a/test/agent-conversations-route.test.ts b/test/agent-conversations-route.test.ts
index fc7b87d4f..3e5f30288 100644
--- a/test/agent-conversations-route.test.ts
+++ b/test/agent-conversations-route.test.ts
@@ -52,7 +52,9 @@ describe("agent conversations self-API", async () => {
it("requires a capability token", async () => {
assert.equal((await get("/v1/conversations")).status, 401);
+ assert.equal((await get(`/v1/conversations/${mineId}`)).status, 401);
assert.equal((await post(`/v1/conversations/${mineId}`, { archived: true })).status, 401);
+ assert.equal((await post(`/v1/conversations/${mineId}/fork`, {})).status, 401);
});
it("lists only the actor's own conversations", async () => {
@@ -84,7 +86,61 @@ describe("agent conversations self-API", async () => {
});
it("refuses a conversation the actor can't see (404, no existence leak)", async () => {
- const res = await post(`/v1/conversations/${theirsId}`, { archived: true }, await capFor("U1"));
+ const token = await capFor("U1");
+ assert.equal((await get(`/v1/conversations/${theirsId}`, token)).status, 404);
+ assert.equal((await post(`/v1/conversations/${theirsId}`, { archived: true }, token)).status, 404);
+ assert.equal((await post(`/v1/conversations/${theirsId}/fork`, {}, token)).status, 404);
+ });
+
+ it("reads and tail-pages one of the actor's own conversations", async () => {
+ for (let turn = 2; turn <= 21; turn++) {
+ await built.app.turn(dm("U1", `launch question ${turn}`, "web:U1:c1"));
+ }
+ const token = await capFor("U1");
+ const bounded = await get(`/v1/conversations/${mineId}`, token);
+ assert.equal(bounded.status, 200);
+ const boundedBody = (await bounded.json()) as {
+ entries: Array<{ type: string; payload: { text?: string } }>;
+ earlierEntries?: number;
+ };
+ assert.ok(!boundedBody.entries.some((entry) => entry.payload.text === "plan the launch"));
+ assert.ok(boundedBody.entries.some((entry) => entry.payload.text === "launch question 21"));
+ assert.ok((boundedBody.earlierEntries ?? 0) > 0);
+
+ const tail = await get(`/v1/conversations/${mineId}?tailTurns=1`, token);
+ assert.equal(tail.status, 200);
+ const tailBody = (await tail.json()) as {
+ entries: Array<{ type: string; payload: { text?: string } }>;
+ earlierEntries?: number;
+ };
+ assert.ok(tailBody.entries.some((entry) => entry.payload.text === "launch question 21"));
+ assert.ok(!tailBody.entries.some((entry) => entry.payload.text === "launch question 20"));
+ assert.ok((tailBody.earlierEntries ?? 0) > 0);
+ assert.equal((await get(`/v1/conversations/${mineId}?sinceSeq=0`, token)).status, 400);
+ });
+
+ it("forks one of the actor's own conversations", async () => {
+ const res = await post(`/v1/conversations/${mineId}/fork`, {}, await capFor("U1"));
+ assert.equal(res.status, 200);
+ const body = (await res.json()) as { session: { id: string }; entries: Array<{ payload: { text?: string } }> };
+ assert.notEqual(body.session.id, mineId);
+ assert.ok(body.entries.some((entry) => entry.payload.text === "plan the launch"));
+ const mine = await built.app.listSessions("U1");
+ assert.ok(mine.some((session) => session.id === body.session.id));
+ });
+
+ it("allows forking under strict posture", async () => {
+ const scope = scopeId("personal", "U1");
+ await built.config.setSecurityPosture(scope, "strict");
+ try {
+ assert.equal((await post(`/v1/conversations/${mineId}/fork`, {}, await capFor("U1"))).status, 200);
+ } finally {
+ await built.config.setSecurityPosture(scope, "auto");
+ }
+ });
+
+ it("refuses to color a conversation the actor can't see", async () => {
+ const res = await post(`/v1/conversations/${theirsId}`, { color: "#123456" }, await capFor("U1"));
assert.equal(res.status, 404);
});
@@ -93,6 +149,18 @@ describe("agent conversations self-API", async () => {
assert.equal((await post(`/v1/conversations/${mineId}`, {}, token)).status, 400);
assert.equal((await post(`/v1/conversations/${mineId}`, { archived: "yes" }, token)).status, 400);
assert.equal((await post(`/v1/conversations/${mineId}`, { title: 5 }, token)).status, 400);
+ assert.equal((await post(`/v1/conversations/${mineId}`, { color: "red" }, token)).status, 400);
+ });
+
+ it("sets and clears the sidebar color", async () => {
+ const token = await capFor("U1");
+ const set = await post(`/v1/conversations/${mineId}`, { color: "#A1B2C3" }, token);
+ assert.equal(set.status, 200);
+ assert.equal(((await set.json()) as { conversation: { color: string | null } }).conversation.color, "#a1b2c3");
+
+ const clear = await post(`/v1/conversations/${mineId}`, { color: null }, token);
+ assert.equal(clear.status, 200);
+ assert.equal(((await clear.json()) as { conversation: { color: string | null } }).conversation.color, null);
});
it("renames and pins through the same patch", async () => {
diff --git a/test/agent-deployment-fetch.test.ts b/test/agent-deployment-fetch.test.ts
new file mode 100644
index 000000000..a9cb7ea3b
--- /dev/null
+++ b/test/agent-deployment-fetch.test.ts
@@ -0,0 +1,128 @@
+import { after, before, describe, it } from "node:test";
+import assert from "node:assert/strict";
+import { createServer as createHttpServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { createServer } from "../src/api/server.ts";
+import type { App } from "../src/api/app.ts";
+import { CAPABILITY_TTL_MS, CONTROL_PLANE_AUD, mintCapabilityToken } from "../src/auth/capability-token.ts";
+import { scopeId } from "../src/types.ts";
+
+const SECRET = "agent-deployment-fetch-secret".repeat(2);
+
+describe("agent deployment fetch", () => {
+ let upstream: Server;
+ let server: Server;
+ let base: string;
+ let upstreamPort: number;
+ let downPort: number;
+
+ const capFor = (actorId: string) =>
+ mintCapabilityToken(
+ {
+ actorId,
+ scopeId: scopeId("personal", actorId),
+ aud: CONTROL_PLANE_AUD,
+ exp: Date.now() + CAPABILITY_TTL_MS,
+ },
+ SECRET,
+ );
+
+ const get = async (path: string, actorId?: string) =>
+ fetch(`${base}${path}`, {
+ headers: actorId ? { "x-agent-capability": await capFor(actorId) } : {},
+ });
+
+ before(async () => {
+ upstream = createHttpServer((req, res) => {
+ if (req.url === "/binary") {
+ res.writeHead(200, { "content-type": "application/octet-stream" });
+ res.end(Buffer.from([0, 255, 1, 254]));
+ return;
+ }
+ if (req.url === "/large") {
+ res.writeHead(200, { "content-type": "text/plain" });
+ res.end("abcdefghij");
+ return;
+ }
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
+ res.end("<h1>owner dashboard</h1>");
+ });
+ await new Promise<void>((resolve) => upstream.listen(0, resolve));
+ upstreamPort = (upstream.address() as AddressInfo).port;
+
+ const closed = createHttpServer();
+ await new Promise<void>((resolve) => closed.listen(0, resolve));
+ downPort = (closed.address() as AddressInfo).port;
+ await new Promise<void>((resolve) => closed.close(() => resolve()));
+
+ const app = {
+ authorizesCapabilityScope: async () => true,
+ reachDeployment: async (id: string, viewer: string) => {
+ if (id !== "mine" && id !== "down") return { status: "not_found" as const };
+ if (viewer !== "U1") return { status: "denied" as const };
+ return {
+ status: "ok" as const,
+ endpoint: { host: "127.0.0.1", port: id === "down" ? downPort : upstreamPort },
+ };
+ },
+ } as unknown as App;
+ server = createServer(app, { signingSecret: SECRET });
+ await new Promise<void>((resolve) => server.listen(0, resolve));
+ base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ });
+
+ after(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ await new Promise<void>((resolve) => upstream.close(() => resolve()));
+ });
+
+ it("requires an identified viewer", async () => {
+ assert.equal((await get("/v1/deployments/mine/fetch")).status, 401);
+ });
+
+ it("fetches rendered text for the owner", async () => {
+ const response = await get("/v1/deployments/mine/fetch", "U1");
+ assert.equal(response.status, 200);
+ assert.deepEqual(await response.json(), {
+ status: 200,
+ contentType: "text/html; charset=utf-8",
+ body: "<h1>owner dashboard</h1>",
+ truncated: false,
+ });
+ });
+
+ it("hides an out-of-reach deployment", async () => {
+ assert.equal((await get("/v1/deployments/mine/fetch", "U2")).status, 404);
+ });
+
+ it("truncates at the requested byte cap", async () => {
+ const response = await get("/v1/deployments/mine/fetch?path=%2Flarge&maxBytes=4", "U1");
+ assert.deepEqual(await response.json(), {
+ status: 200,
+ contentType: "text/plain",
+ body: "abcd",
+ truncated: true,
+ });
+ });
+
+ it("maps an unavailable upstream to 502", async () => {
+ const response = await get("/v1/deployments/down/fetch", "U1");
+ assert.equal(response.status, 502);
+ assert.deepEqual(await response.json(), { error: "upstream_unreachable" });
+ });
+
+ it("encodes binary content as base64", async () => {
+ const response = await get("/v1/deployments/mine/fetch?path=%2Fbinary", "U1");
+ assert.deepEqual(await response.json(), {
+ status: 200,
+ contentType: "application/octet-stream",
+ body: Buffer.from([0, 255, 1, 254]).toString("base64"),
+ encoding: "base64",
+ truncated: false,
+ });
+ });
+
+ it("rejects encoded traversal variants", async () => {
+ assert.equal((await get("/v1/deployments/mine/fetch?path=%2F%2525252e%2525252e%2525255csecret", "U1")).status, 400);
+ });
+});
diff --git a/test/agent-files-route.test.ts b/test/agent-files-route.test.ts
new file mode 100644
index 000000000..a60fc371a
--- /dev/null
+++ b/test/agent-files-route.test.ts
@@ -0,0 +1,89 @@
+import "./support/auto-fake-sprites.ts";
+
+import { after, before, describe, it } from "node:test";
+import assert from "node:assert/strict";
+import type { AddressInfo } from "node:net";
+import type { Server } from "node:http";
+import { buildApp, type BuiltApp } from "../src/wiring.ts";
+import { createServer } from "../src/api/server.ts";
+import { fileArtifactId } from "../src/files/file-artifact-store.ts";
+import { mintCapabilityToken, CAPABILITY_TTL_MS, CONTROL_PLANE_AUD } from "../src/auth/capability-token.ts";
+import { scopeId } from "../src/types.ts";
+import { testConfig } from "./support/test-config.ts";
+
+const SECRET = "agent-files-secret".repeat(3);
+
+describe("agent files self-API", async () => {
+ let server: Server;
+ let base: string;
+ let built: BuiltApp;
+ let mineId: string;
+ let theirsId: string;
+
+ const capFor = (actorId: string) =>
+ mintCapabilityToken(
+ {
+ actorId,
+ scopeId: scopeId("personal", actorId),
+ aud: CONTROL_PLANE_AUD,
+ exp: Date.now() + CAPABILITY_TTL_MS,
+ },
+ SECRET,
+ );
+
+ const get = async (path: string, token?: string) =>
+ fetch(`${base}${path}`, { headers: token ? { "x-agent-capability": token } : {} });
+
+ before(async () => {
+ built = buildApp(testConfig({ signingSecret: SECRET }));
+ server = createServer(built.app, { signingSecret: SECRET });
+ await new Promise<void>((resolve) => server.listen(0, resolve));
+ base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ mineId = fileArtifactId("mine", "out", 0);
+ theirsId = fileArtifactId("theirs", "out", 0);
+ await built.files.put({
+ id: mineId,
+ ownerScopeId: scopeId("personal", "U1"),
+ createdBy: "U1",
+ name: "mine.txt",
+ path: `artifacts/${mineId}/mine.txt`,
+ mimetype: "text/plain",
+ data: Buffer.from("mine"),
+ direction: "out",
+ });
+ await built.files.put({
+ id: theirsId,
+ ownerScopeId: scopeId("personal", "U2"),
+ createdBy: "U2",
+ name: "theirs.txt",
+ path: `artifacts/${theirsId}/theirs.txt`,
+ mimetype: "text/plain",
+ data: Buffer.from("theirs"),
+ direction: "out",
+ });
+ });
+
+ after(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ it("requires a capability token", async () => {
+ assert.equal((await get("/v1/files")).status, 401);
+ });
+
+ it("lists only files visible to the capability actor", async () => {
+ const res = await get("/v1/files", await capFor("U1"));
+ assert.equal(res.status, 200);
+ const page = (await res.json()) as { owned: Array<{ id: string }>; shared: Array<{ id: string }> };
+ assert.deepEqual(
+ page.owned.map((file) => file.id),
+ [mineId],
+ );
+ assert.deepEqual(page.shared, []);
+ });
+
+ it("returns 404 for another principal's file content", async () => {
+ const res = await get(`/v1/files/${theirsId}/content`, await capFor("U1"));
+ assert.equal(res.status, 404);
+ });
+});
diff --git a/test/agent-projects-route.test.ts b/test/agent-projects-route.test.ts
new file mode 100644
index 000000000..afc6ae413
--- /dev/null
+++ b/test/agent-projects-route.test.ts
@@ -0,0 +1,135 @@
+import { describe, it, before, after } from "node:test";
+import assert from "node:assert/strict";
+import type { AddressInfo } from "node:net";
+import type { Server } from "node:http";
+import { buildApp, type BuiltApp } from "../src/wiring.ts";
+import { createServer } from "../src/api/server.ts";
+import { mintCapabilityToken, CAPABILITY_TTL_MS, CONTROL_PLANE_AUD } from "../src/auth/capability-token.ts";
+import { scopeId } from "../src/types.ts";
+import { testConfig } from "./support/test-config.ts";
+
+const SECRET = "agent-projects-secret".repeat(2);
+
+describe("agent projects self-API", async () => {
+ let server: Server;
+ let base: string;
+ let built: BuiltApp;
+ let mineId: string;
+ let theirsId: string;
+
+ const capFor = (actorId: string) =>
+ mintCapabilityToken(
+ {
+ actorId,
+ scopeId: scopeId("personal", actorId),
+ aud: CONTROL_PLANE_AUD,
+ exp: Date.now() + CAPABILITY_TTL_MS,
+ },
+ SECRET,
+ );
+
+ const request = async (method: string, path: string, body?: unknown, token?: string) =>
+ fetch(`${base}${path}`, {
+ method,
+ headers: {
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
+ ...(token ? { "x-agent-capability": token } : {}),
+ },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+
+ before(async () => {
+ built = buildApp(testConfig({ signingSecret: SECRET }));
+ await built.app.upsertDirectory([
+ { principalId: "U1", displayName: "One", type: "internal" },
+ { principalId: "U2", displayName: "Two", type: "internal" },
+ { principalId: "U3", displayName: "Three", type: "internal" },
+ ]);
+ mineId = (await built.app.createProject("U1", "Mine"))!.id;
+ theirsId = (await built.app.createProject("U2", "Theirs"))!.id;
+ server = createServer(built.app, { signingSecret: SECRET });
+ await new Promise<void>((resolve) => server.listen(0, resolve));
+ base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ });
+
+ after(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ it("requires a capability token on every route", async () => {
+ assert.equal((await request("GET", "/v1/projects")).status, 401);
+ assert.equal((await request("POST", "/v1/projects", { name: "New" })).status, 401);
+ assert.equal((await request("PATCH", `/v1/projects/${mineId}`, { name: "Renamed" })).status, 401);
+ assert.equal((await request("POST", `/v1/projects/${mineId}/members`, { memberId: "U3" })).status, 401);
+ assert.equal((await request("DELETE", `/v1/projects/${mineId}/members/U3`, {})).status, 401);
+ });
+
+ it("lists only projects visible to the token actor", async () => {
+ const response = await request("GET", "/v1/projects", undefined, await capFor("U1"));
+ assert.equal(response.status, 200);
+ const { projects } = (await response.json()) as { projects: Array<{ id: string }> };
+ assert.ok(projects.some((project) => project.id === mineId));
+ assert.ok(!projects.some((project) => project.id === theirsId));
+ });
+
+ it("creates, renames, adds a member, and removes a member as the token actor", async () => {
+ const token = await capFor("U1");
+ const created = await request("POST", "/v1/projects", { name: "Agent Project" }, token);
+ assert.equal(created.status, 201);
+ const project = ((await created.json()) as { project: { id: string } }).project;
+
+ const renamed = await request("PATCH", `/v1/projects/${project.id}`, { name: "Agent Renamed" }, token);
+ assert.equal(renamed.status, 200);
+ assert.equal(((await renamed.json()) as { project: { name: string } }).project.name, "Agent Renamed");
+
+ const added = await request("POST", `/v1/projects/${project.id}/members`, { memberId: "U3" }, token);
+ assert.equal(added.status, 200);
+ assert.ok(
+ ((await added.json()) as { project: { members: Array<{ principalId: string }> } }).project.members.some(
+ (member) => member.principalId === "U3",
+ ),
+ );
+
+ const removed = await request("DELETE", `/v1/projects/${project.id}/members/U3`, {}, token);
+ assert.equal(removed.status, 200);
+ assert.ok(
+ !((await removed.json()) as { project: { members: Array<{ principalId: string }> } }).project.members.some(
+ (member) => member.principalId === "U3",
+ ),
+ );
+ });
+
+ it("returns 404 for another principal's project", async () => {
+ const token = await capFor("U1");
+ assert.equal((await request("PATCH", `/v1/projects/${theirsId}`, { name: "Hidden" }, token)).status, 404);
+ assert.equal((await request("POST", `/v1/projects/${theirsId}/members`, { memberId: "U3" }, token)).status, 404);
+ assert.equal((await request("DELETE", `/v1/projects/${theirsId}/members/U3`, {}, token)).status, 404);
+ });
+
+ it("uses the token actor when principalId is omitted or matching and hides mismatches", async () => {
+ const token = await capFor("U1");
+ assert.equal((await request("GET", "/v1/projects?principalId=U1", undefined, token)).status, 200);
+ assert.equal((await request("GET", "/v1/projects?principalId=U2", undefined, token)).status, 404);
+ assert.equal((await request("POST", "/v1/projects", { principalId: "U1", name: "Matching" }, token)).status, 201);
+ assert.equal((await request("POST", "/v1/projects", { principalId: "U2", name: "Hidden" }, token)).status, 404);
+ });
+
+ it("allows every mutation under strict posture", async () => {
+ const token = await capFor("U1");
+ const scope = scopeId("personal", "U1");
+ await built.config.setSecurityPosture(scope, "strict");
+ try {
+ const created = await request("POST", "/v1/projects", { name: "Strict" }, token);
+ assert.equal(created.status, 201);
+ const projectId = ((await created.json()) as { project: { id: string } }).project.id;
+ assert.equal(
+ (await request("PATCH", `/v1/projects/${projectId}`, { name: "Strict Renamed" }, token)).status,
+ 200,
+ );
+ assert.equal((await request("POST", `/v1/projects/${projectId}/members`, { memberId: "U3" }, token)).status, 200);
+ assert.equal((await request("DELETE", `/v1/projects/${projectId}/members/U3`, {}, token)).status, 200);
+ } finally {
+ await built.config.setSecurityPosture(scope, "auto");
+ }
+ });
+});
diff --git a/test/memory-history-agent-routes.test.ts b/test/memory-history-agent-routes.test.ts
new file mode 100644
index 000000000..84dd7c0bd
--- /dev/null
+++ b/test/memory-history-agent-routes.test.ts
@@ -0,0 +1,152 @@
+import { after, before, describe, it } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import type { Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createServer } from "../src/api/server.ts";
+import { CAPABILITY_TTL_MS, CONTROL_PLANE_AUD, mintCapabilityToken } from "../src/auth/capability-token.ts";
+import type { MemoryRevision, MemoryService } from "../src/memory/memory-service.ts";
+import { scopeId, type ScopeId } from "../src/types.ts";
+import { buildApp, type BuiltApp } from "../src/wiring.ts";
+import { testConfig } from "./support/test-config.ts";
+
+const SECRET = "memory-history-route-secret".repeat(3);
+
+describe("agent memory history and restore", () => {
+ let server: Server;
+ let base: string;
+ let built: BuiltApp;
+ let memory: MemoryService;
+
+ const capFor = (actorId: string, write: ScopeId, orgWrite?: ScopeId) =>
+ mintCapabilityToken(
+ {
+ actorId,
+ scopeId: scopeId("personal", actorId),
+ aud: CONTROL_PLANE_AUD,
+ exp: Date.now() + CAPABILITY_TTL_MS,
+ memory: { write, read: [write], ...(orgWrite ? { orgWrite } : {}) },
+ },
+ SECRET,
+ );
+ const get = (path: string, token?: string) =>
+ fetch(`${base}${path}`, { headers: token ? { "x-agent-capability": token } : {} });
+ const post = (path: string, body: unknown, token?: string) =>
+ fetch(`${base}${path}`, {
+ method: "POST",
+ headers: { "content-type": "application/json", ...(token ? { "x-agent-capability": token } : {}) },
+ body: JSON.stringify(body),
+ });
+ const put = (path: string, body: unknown, token: string) =>
+ fetch(`${base}${path}`, {
+ method: "PUT",
+ headers: { "content-type": "application/json", "x-agent-capability": token },
+ body: JSON.stringify(body),
+ });
+
+ before(async () => {
+ built = buildApp(
+ testConfig({ dataDir: mkdtempSync(join(tmpdir(), "memory-history-routes-")), signingSecret: SECRET }),
+ );
+ const revisions = new Map<ScopeId, MemoryRevision[]>();
+ memory = {
+ ...built.memory,
+ async replace(scope, content, author) {
+ await built.memory.replace(scope, content, author);
+ const history = revisions.get(scope) ?? [];
+ history.push({
+ revision: String(history.length + 1),
+ content: await built.memory.read(scope),
+ operation: "replace",
+ ...(author ? { author } : {}),
+ at: Date.now(),
+ });
+ revisions.set(scope, history);
+ },
+ async history(scope, limit = 30) {
+ return (revisions.get(scope) ?? []).toReversed().slice(0, limit);
+ },
+ async restore(scope, revision, expectedRevision, author) {
+ const history = revisions.get(scope) ?? [];
+ if (String(history.length) !== expectedRevision) return false;
+ const target = history.find((entry) => entry.revision === revision);
+ if (!target) return false;
+ await this.replace(scope, target.content, author);
+ return true;
+ },
+ };
+ server = createServer(built.app, { signingSecret: SECRET, memory });
+ await new Promise<void>((resolve) => server.listen(0, resolve));
+ base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ });
+
+ after(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ it("lists versions after writes and restores a prior version", async () => {
+ const mine = scopeId("personal", "U1");
+ const token = await capFor("U1", mine);
+ assert.equal((await put("/v1/memory/self", { content: "first version" }, token)).status, 200);
+ assert.equal((await put("/v1/memory/self", { content: "second version" }, token)).status, 200);
+
+ const history = await get("/v1/memory/history", token);
+ assert.equal(history.status, 200);
+ const { revisions } = (await history.json()) as {
+ revisions: Array<{ revision: string; content: string }>;
+ };
+ assert.equal(revisions.length, 2);
+ assert.equal(revisions[0]?.content, "second version\n");
+ assert.equal(revisions[1]?.content, "first version\n");
+
+ const restored = await post(
+ "/v1/memory/restore",
+ { revision: revisions[1]?.revision, expectedRevision: revisions[0]?.revision },
+ token,
+ );
+ assert.equal(restored.status, 200);
+ assert.equal(await memory.read(mine), "first version\n");
+ });
+
+ it("does not expose or restore another principal's notebook", async () => {
+ const token = await capFor("U2", scopeId("personal", "U2"));
+ assert.equal((await get("/v1/memory/history?principalId=U1", token)).status, 404);
+ assert.equal(
+ (await post("/v1/memory/restore", { principalId: "U1", revision: "1", expectedRevision: "2" }, token)).status,
+ 404,
+ );
+ });
+
+ it("binds org history and restore to the token's org write scope", async () => {
+ const mine = scopeId("personal", "A1");
+ const org = scopeId("org", "default-org");
+ const token = await capFor("A1", mine, org);
+ assert.equal((await put("/v1/memory/self", { content: "first org version", scope: "org" }, token)).status, 200);
+ assert.equal((await put("/v1/memory/self", { content: "second org version", scope: "org" }, token)).status, 200);
+
+ const history = await get("/v1/memory/history?scope=org", token);
+ assert.equal(history.status, 200);
+ const { revisions } = (await history.json()) as { revisions: Array<{ revision: string }> };
+ const restored = await post(
+ "/v1/memory/restore",
+ { scope: "org", revision: revisions[1]?.revision, expectedRevision: revisions[0]?.revision },
+ token,
+ );
+ assert.equal(restored.status, 200);
+ assert.equal(await memory.read(org), "first org version\n");
+
+ const personalOnly = await capFor("U3", scopeId("personal", "U3"));
+ assert.equal((await get("/v1/memory/history?scope=org", personalOnly)).status, 404);
+ assert.equal(
+ (await post("/v1/memory/restore", { scope: "org", revision: "1", expectedRevision: "2" }, personalOnly)).status,
+ 404,
+ );
+ });
+
+ it("requires authentication", async () => {
+ assert.equal((await get("/v1/memory/history")).status, 401);
+ assert.equal((await post("/v1/memory/restore", { revision: "1", expectedRevision: "2" })).status, 401);
+ });
+});
diff --git a/test/projects.test.ts b/test/projects.test.ts
index 60f4b5ab5..1a876a061 100644
--- a/test/projects.test.ts
+++ b/test/projects.test.ts
@@ -117,7 +117,7 @@ async function listen(server: Server): Promise<string> {
}
test("Project routes use ordinary group sessions with the durable roster as authority", async (t) => {
- assert.ok(projectRoutes.every((route) => route.auth === "source"));
+ assert.ok(projectRoutes.every((route) => route.auth === "either"));
const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "projects-lean-")) }));
const server = createInsecureTestServer(built.app, {});
const base = await listen(server);
diff --git a/test/skills-http.test.ts b/test/skills-http.test.ts
index 3d13014b5..568dc7d6f 100644
--- a/test/skills-http.test.ts
+++ b/test/skills-http.test.ts
@@ -1012,3 +1012,88 @@ test("DELETE /v1/skills/:id via a capability token archives the token-actor's ow
await srv.close();
}
});
+
+test("a capability token reads and restores its archived skill without losing identity, files, or version", async () => {
+ const srv = await startSecure();
+ try {
+ const created = await srv.skills.create({
+ scopeId: scopeId("personal", "U1"),
+ manifest: {
+ name: "recover-me",
+ description: "recoverable",
+ requiredCapabilities: [],
+ body: "# recover-me",
+ files: [{ path: "scripts/run.sh", content: "exit 0", executable: true }],
+ },
+ createdBy: "U1",
+ });
+ await srv.skills.review(created.id, "reviewer-1", []);
+ await srv.skills.publish(created.id);
+ const before = (await srv.skills.get(created.id))!;
+ const token = await srv.cap("U1");
+
+ const archived = await fetch(`${srv.base}/v1/skills/${created.id}`, {
+ method: "DELETE",
+ headers: { "x-agent-capability": token },
+ });
+ assert.equal(archived.status, 200);
+
+ const detail = await fetch(`${srv.base}/v1/skills/${created.id}`, {
+ headers: { "x-agent-capability": token },
+ });
+ assert.equal(detail.status, 200);
+ const detailBody = (await detail.json()) as {
+ skill: { id: string; body: string; status: string; version: number; files: Array<{ path: string }> };
+ };
+ assert.equal(detailBody.skill.id, before.id);
+ assert.equal(detailBody.skill.body, before.manifest.body);
+ assert.equal(detailBody.skill.status, "archived");
+ assert.equal(detailBody.skill.version, before.version);
+ assert.deepEqual(detailBody.skill.files, [{ path: "scripts/run.sh", executable: true }]);
+
+ const restored = await fetch(`${srv.base}/v1/skills/${created.id}/restore`, {
+ method: "POST",
+ headers: { "x-agent-capability": token },
+ });
+ assert.equal(restored.status, 200);
+ const after = (await srv.skills.get(created.id))!;
+ assert.equal(after.id, before.id);
+ assert.equal(after.version, before.version);
+ assert.deepEqual(after.manifest.files, before.manifest.files);
+ assert.equal(after.status, "published");
+ } finally {
+ await srv.close();
+ }
+});
+
+test("skill detail and restore capability calls hide other principals' skills and require identity", async () => {
+ const srv = await startSecure();
+ try {
+ const skill = await srv.skills.create({
+ scopeId: scopeId("personal", "U2"),
+ manifest: { name: "private", description: "theirs", requiredCapabilities: [], body: "# private" },
+ createdBy: "U2",
+ });
+ await srv.skills.review(skill.id, "reviewer-1", []);
+ await srv.skills.publish(skill.id);
+ await srv.skills.archive(skill.id);
+
+ const headers = { "x-agent-capability": await srv.cap("U1") };
+ assert.equal((await fetch(`${srv.base}/v1/skills/${skill.id}`, { headers })).status, 404);
+ assert.equal((await fetch(`${srv.base}/v1/skills/${skill.id}/restore`, { method: "POST", headers })).status, 404);
+ assert.equal((await fetch(`${srv.base}/v1/skills/${skill.id}?principalId=U2`)).status, 401);
+ assert.equal(
+ (
+ await fetch(`${srv.base}/v1/skills/${skill.id}/restore`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ principalId: "U2" }),
+ })
+ ).status,
+ 401,
+ );
+ assert.equal((await srv.skills.get(skill.id))?.status, "archived");
+ } finally {
+ await srv.close();
+ }
+});