Multiplayer agent harness for work.
self-API: spawn a fresh conversation
Regan Belle23b301df636
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.tsindex 8556ce641..c13acda84 100644--- a/src/api/agent-api-catalog.ts+++ b/src/api/agent-api-catalog.ts@@ -144,7 +144,7 @@ const FAMILIES: AgentApiFamily[] = [{match: (m, p) =>(m === "GET" && (p === "/v1/conversations" || /^\/v1\/conversations\/[^/]+$/.test(p))) ||- (m === "POST" && /^\/v1\/conversations\/[^/]+(?:\/fork)?$/.test(p)),+ (m === "POST" && (p === "/v1/conversations" || /^\/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: [@@ -166,6 +166,12 @@ const FAMILIES: AgentApiFamily[] = [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",+ summary:+ "start a FRESH conversation in this scope (no inherited transcript) — body {text, title?}; text becomes its first message and a run begins there asynchronously. Unlike /fork, the new session starts with only what you put in text. Human-attended turns only — refused (403) from crons and other automations",+ },{method: "POST",path: "/v1/conversations/:id/fork",diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex 9502a5f7e..7639e96b4 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -43,6 +43,7 @@ export function createSessionMethods(| "authorizesCapabilityScope"| "updateSession"| "regenerateTitle"+ | "spawnSession"| "forkSession"| "grant"| "revokeGrant"@@ -469,6 +470,46 @@ export function createSessionMethods(});},+ async spawnSession(principalId, opts) {+ const scope = opts.scopeId;+ const parsed = parseScopeId(scope);+ const create = async (projectMembers?: readonly string[], channelName?: string) => {+ const threadRef = `web:${principalId}:${randomUUID()}`;+ let kind: "group" | "channel" | "dm" = "dm";+ if (parsed.kind === "group") kind = "group";+ else if (parsed.kind === "channel") kind = "channel";+ const session = await deps.sessions.getOrCreateByThread(threadRef, kind, scope, channelName, "web");+ await Promise.all(+ (projectMembers ?? [principalId]).map((memberId) => deps.sessions.addParticipant(session.id, memberId)),+ );+ if (opts.title?.trim()) await deps.sessions.updateTitle(session.id, opts.title.trim());+ deps.auditLog.record({+ at: Date.now(),+ principalId,+ action: "session.spawn",+ resource: session.id,+ scopeLabel: scope,+ });+ return { session: (await deps.sessions.get(session.id)) ?? session };+ };+ if (parsed.kind === "personal") {+ return parsed.ref === principalId ? create() : null;+ }+ const projectId = parsed.kind === "group" ? projectIdFromGroupRef(parsed.ref) : null;+ if (projectId) {+ const projects = deps.projects;+ if (!projects) return null;+ return projects.withRosterLock(projectId, async (project) => {+ if (project.orgId !== orgIdOf()) return null;+ const members = await projects.members(parsed.ref);+ if (!members?.includes(principalId)) return null;+ return create(members, project.name);+ });+ }+ if (!(await principalCanAccessCurrentScope(principalId, scope))) return null;+ return create();+ },+async grant(g) {await deps.acl.grant(g, await artifactAuthor(g.ownerScopeId, g.ref));deps.auditLog.record({diff --git a/src/api/app-types.ts b/src/api/app-types.tsindex cdb801544..ee3537efd 100644--- a/src/api/app-types.ts+++ b/src/api/app-types.ts@@ -279,6 +279,7 @@ export interface App {patch: { title?: string | null; archived?: boolean; pinned?: boolean; color?: string | null },): Promise<Session | null>;regenerateTitle(sessionId: string, principalId: string): Promise<{ title: string | null } | null>;+ spawnSession(principalId: string, opts: { scopeId: ScopeId; title?: string }): Promise<{ session: Session } | null>;forkSession(sessionId: string,principalId: string,diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex 7310e092f..f098eb45c 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -77,6 +77,47 @@ async function forkSession(ctx: ApiCtx): Promise<void> {return sendJson(res, 200, out);}+async function spawnAgentConversation(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" });+ }+ if (!livePersonCapability(capability)) {+ return sendJson(res, 403, {+ error: "human_attended_only",+ message:+ "starting a fresh conversation requires a turn a person is attending — not a cron, trigger, or other automation",+ });+ }+ const b = isObj(body) ? body : {};+ if (typeof b.text !== "string" || !b.text.trim()) {+ return sendJson(res, 400, { error: "bad_request", message: "text required — the new session's first message" });+ }+ if (b.title !== undefined && typeof b.title !== "string") {+ return sendJson(res, 400, { error: "bad_request", message: "title must be a string" });+ }+ const out = await app.spawnSession(capability.actorId, {+ scopeId: capability.scopeId,+ ...(typeof b.title === "string" ? { title: b.title } : {}),+ });+ if (!out) return sendJson(res, 404, { error: "not_found", message: "cannot start a session in this scope" });+ const session = out.session;+ const turn = await app.turn({+ surface: session.surface ?? "web",+ actor: { externalId: capability.actorId },+ conversation: {+ kind: session.type,+ threadRef: session.threadRef,+ ...(session.channelName ? { channelName: session.channelName } : {}),+ },+ text: b.text,+ spawned: true,+ async: true,+ });+ const runId = (turn as { runId?: string }).runId;+ return sendJson(res, 202, { session, turn: { status: turn.status, ...(runId ? { runId } : {}) } });+}+async function forkAgentConversation(ctx: ApiCtx): Promise<void> {const { res, app, body, capability } = ctx;if (!capability) {@@ -1248,6 +1289,7 @@ export const surfaceRoutes: ReadonlyArray<Route<ApiCtx>> = [{ 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", auth: "either", handle: spawnAgentConversation },{ 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 },diff --git a/src/api/server.ts b/src/api/server.tsindex e276baa82..8b82a11fb 100644--- a/src/api/server.ts+++ b/src/api/server.ts@@ -101,6 +101,7 @@ function strictPostAllowed(pathname: string, body: unknown): boolean {if (pathname === "/v1/surface-context" ||pathname === "/v1/projects" ||+ pathname === "/v1/conversations" ||pathname === "/v1/memory/search" ||pathname === "/v1/memory/restore" ||pathname.startsWith("/v1/run-signals/") ||diff --git a/test/agent-conversations-route.test.ts b/test/agent-conversations-route.test.tsindex 3e5f30288..ba06956d3 100644--- a/test/agent-conversations-route.test.ts+++ b/test/agent-conversations-route.test.ts@@ -22,9 +22,9 @@ describe("agent conversations self-API", async () => {let mineId: string;let theirsId: string;- const capFor = (actorId: string, scope = scopeId("personal", actorId)) =>+ const capFor = (actorId: string, scope = scopeId("personal", actorId), live = true) =>mintCapabilityToken(- { actorId, scopeId: scope, aud: CONTROL_PLANE_AUD, exp: Date.now() + CAPABILITY_TTL_MS },+ { actorId, scopeId: scope, aud: CONTROL_PLANE_AUD, exp: Date.now() + CAPABILITY_TTL_MS, liveActor: live },SECRET,);@@ -50,6 +50,58 @@ describe("agent conversations self-API", async () => {await new Promise<void>((resolve) => server.close(() => resolve()));});+ it("spawns a fresh conversation with only the seed text", async () => {+ const token = await capFor("U1");+ const res = await post(+ "/v1/conversations",+ { text: "investigate the flaky test", title: "Flaky test hunt" },+ token,+ );+ assert.equal(res.status, 202);+ const body = (await res.json()) as {+ session: { id: string; scopeId: string; threadRef: string; title?: string | null };+ turn: { status: string; runId?: string };+ };+ assert.notEqual(body.session.id, mineId);+ assert.equal(body.session.scopeId, scopeId("personal", "U1"));+ assert.equal(body.session.title, "Flaky test hunt");+ const list = await get("/v1/conversations", token);+ const { conversations } = (await list.json()) as { conversations: Array<{ id: string }> };+ assert.ok(+ conversations.some((c) => c.id === body.session.id),+ "the spawned session appears in the actor's list",+ );+ assert.equal(body.turn.status, "queued");+ assert.ok(body.turn.runId, "the seed turn is queued as a run");+ const run = await built.runs.get(body.turn.runId!);+ assert.equal(run?.request.text, "investigate the flaky test");+ assert.equal(run?.request.conversation.threadRef, body.session.threadRef, "the seed runs in the new session");+ const read = await get(`/v1/conversations/${body.session.id}`, token);+ assert.equal(read.status, 200);+ const readBody = (await read.json()) as { entries: Array<{ payload: { text?: string } }> };+ assert.ok(+ !readBody.entries.some((e) => (e.payload.text ?? "").includes("plan the launch")),+ "nothing from the spawning conversation leaks in",+ );+ });++ it("spawn requires text and a capability", async () => {+ assert.equal((await post("/v1/conversations", { text: "hi" })).status, 401);+ assert.equal((await post("/v1/conversations", {}, await capFor("U1"))).status, 400);+ assert.equal((await post("/v1/conversations", { text: " " }, await capFor("U1"))).status, 400);+ });++ it("spawn refuses an unattended (automation) turn", async () => {+ const token = await capFor("U1", scopeId("personal", "U1"), false);+ const res = await post("/v1/conversations", { text: "cron trying to spawn" }, token);+ assert.equal(res.status, 403);+ });++ it("spawn refuses a scope the actor doesn't own", async () => {+ const token = await capFor("U1", scopeId("personal", "U2"));+ assert.equal((await post("/v1/conversations", { text: "peek" }, token)).status, 404);+ });+it("requires a capability token", async () => {assert.equal((await get("/v1/conversations")).status, 401);assert.equal((await get(`/v1/conversations/${mineId}`)).status, 401);