diff --git a/AGENTS.md b/AGENTS.md index 7cf710b0f..02b0d2593 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -259,8 +259,11 @@ durable. (`AgentLink.catalog`): from the moment the person's accounts change it is no longer what the client offers, and only a report through a launch prepared since counts again, named in `catalogLaunch` by a client offering `catalog-launches`, never one through an earlier launch. - An end, a replacement or a session's close is in force in the - process the moment it is asked, before storage deletes the rows (`#ending`), an end + An end or a session's close is in force in the + process the moment it is asked, before storage deletes the rows (`#ending`), while a + session launch replaced by renewal stays live for a two-minute grace period + (`REPLACED_LAUNCH_GRACE_MS` in `apps/server/src/harness/remote/link.ts`) and ends at + once if the session does; an end storage refuses is retried, and the writer lease's holder ends launches nothing owns as it starts serving and with each sweep (`AiCredentials.retire`). A key refused as invalid, or a Copilot seat GitHub confirms lost or back, tells the person's lasting @@ -326,7 +329,11 @@ durable. message, except one sent once the turn is being stopped or finishing, which starts its next turn. Chopin keeps no workflow runs of a client's and draws no run cards: a session outlives its turn only while it waits on a question it asked or on an answer its client has not - received. Signing out the owner's login, its expiry, or a Planner reset closes the link. A lost + received (whether the turn finished or failed, so a failing reply never withdraws open + Decisions). A routine renewal of the owner's GitHub credential rebinds a running or retained + remote session (`ownerSignal` and `rebindRetained` in `chat/service.ts`) without aborting the + turn or withdrawing its questions; only signing out, an unrenewable credential, or a Planner + reset closes the link. A lost connection never ends work by itself: a link that offered `resumable-sessions` and then dropped unexpectedly keeps its sessions that hold an open question or an answer its client has not acknowledged, however long it stays away. @@ -654,26 +661,45 @@ means a former target can no longer be identified safely. ## Planner-created documents -The Planner's `create_document` host tool (every harness) makes new top-level -documents, one per piece of work that splits naturally, each with its own Chat, -Decisions and Planner. Only a turn a person's message (in Chat or a thread) -drives may call it: that person is the creator, and their own live browser login -is rechecked for write access as for `chat:send`; a turn nobody typed and -background jobs are refused. It reuses MCP `create_document`'s draft validation, -visual assessment and creation (`createDocument` in `apps/server/src/mcp/hosted.ts`), -keeps the creating document's repository and base branch, with an idempotency -key scoped to the creating document and no per-turn or hourly cap. The creating -document's model choice is stored in the transaction that creates the new one -(`CreateChannel.modelChoice`), so a retry never overwrites a choice made since. -A retry is found in storage, is compared against the base the first call -recorded, and posts the linked line only if the first call could not save it. -The document is stored before the sidebar, the asking Chat's -one linked line (`Entry.document`) or its optional first instruction (posted as -the creator's message, as `invoke_planner` does) hear of it. Each records the -document it was created from (`ChannelRecord.createdFrom`), and the Planner's -`fan_out` tool opens several at once, lists their state, instructs their Planners -and keeps a table of them in the creating document, reaching only documents whose -`createdFrom` is its own. See +The Planner's `create_document` host tool (every harness) opens one top-level +document per piece of work, each with its own Chat, Decisions, and Planner. +Only a turn driven by a person's message (in Chat or a thread) may call it: +that person is the creator, and their live browser login is rechecked for write +access as for `chat:send`. Turns nobody typed and background jobs are refused. + +`create_document` reuses MCP's draft validation, visual assessment, and +creation transaction (`createDocument` in `apps/server/src/mcp/hosted.ts`), +keeping the creating document's repository and base branch with a +source-scoped idempotency key and no per-turn or hourly cap. The creating +document's model choice is saved in the same transaction +(`CreateChannel.modelChoice`), so retries never overwrite a choice made since. +Retries compare against the recorded base and post the linked Chat line only if +the first call could not save it. The document is stored before the sidebar, +the asking Chat's linked line (`Entry.document`), or its optional first +instruction (posted as the creator's message, as `invoke_planner` does) hear of +it. + +Each created document records its parent in `ChannelRecord.createdFrom` +(migration 054; cleared when the parent is deleted, keeping the child). The +Planner's `orchestrate` host tool (`apps/server/src/agent/orchestrate.ts`, +`orchestrate-index.ts`) is offered under the same permissions and reaches only +unarchived top-level documents in the same repository whose `createdFrom` is +this document: + +- `open`: creates up to 20 documents at once, each with `create_document` + semantics. +- `list`: returns each created document's link, Planner state (`working`, + `idle`, `stopped`), open Decisions count, and build state. +- `instruct`: posts one instruction as the person's message to all or named + (`targets`) created documents, starting stopped Planners. +- `index`: writes or updates a table under `## Documents created from this one` + (`open` and `list` refresh an existing table; unchanged tables are not + rewritten). + +Limits: documents created before migration 054 have no `createdFrom` link and +are invisible to `orchestrate`; the index refreshes only when `open`, `list`, +or `index` runs; `list`, `instruct`, and `index` cover up to 200 created +documents. See [Creating documents](docs/hosted-agent.md#creating-documents). ## Research requests and child documents @@ -993,7 +1019,7 @@ run `bun run ci` and validate relative links with exact casing. When a disposable Planner session is created, diagnostics report available tool names and the external GitHub MCP contribution. Counts vary with SDK and remote MCP versions. A healthy boundary includes Chopin's document tools (currently -plan-named), `create_document`, child document tools, repository tools, and allowed pull-request +plan-named), `create_document`, `orchestrate`, child document tools, repository tools, and allowed pull-request tools, and excludes ambient capabilities such as `bash`, filesystem access, URL fetch, host Git, issues, and unrestricted search. The exception is an `atomic` Planner session, which deliberately adds Atomic's builtins and coding tools but diff --git a/apps/server/src/agent/job-scope.ts b/apps/server/src/agent/job-scope.ts index 6d9c56ee5..551fbbbb5 100644 --- a/apps/server/src/agent/job-scope.ts +++ b/apps/server/src/agent/job-scope.ts @@ -24,7 +24,7 @@ export const WRITE_TOOLS: ReadonlySet = new Set([ "edit_implementation_graph", "create_research_workspace", "create_document", - "fan_out", + "orchestrate", "propose_investigation", "set_investigation_build_blocker", "revise_open_decision", diff --git a/apps/server/src/agent/fan-out-index.ts b/apps/server/src/agent/orchestrate-index.ts similarity index 98% rename from apps/server/src/agent/fan-out-index.ts rename to apps/server/src/agent/orchestrate-index.ts index 9ad7bd23f..d48245f16 100644 --- a/apps/server/src/agent/fan-out-index.ts +++ b/apps/server/src/agent/orchestrate-index.ts @@ -7,7 +7,7 @@ import * as edit from "../plan/edit"; import { admitBlockEdit, applyBlockEdit } from "./document-ops"; import { implementationActive } from "../plan/service"; -import type { CreatedDocumentState, IndexOutcome } from "./fan-out"; +import type { CreatedDocumentState, IndexOutcome } from "./orchestrate"; import type { DocumentRoom } from "./tools"; export const INDEX_HEADING = "Documents created from this one"; diff --git a/apps/server/src/agent/fan-out.test.ts b/apps/server/src/agent/orchestrate.test.ts similarity index 91% rename from apps/server/src/agent/fan-out.test.ts rename to apps/server/src/agent/orchestrate.test.ts index 9abea6e67..f2e2b6c85 100644 --- a/apps/server/src/agent/fan-out.test.ts +++ b/apps/server/src/agent/orchestrate.test.ts @@ -4,8 +4,8 @@ import { MemoryStorage } from "../storage/memory/adapter"; import { createDocument } from "../mcp/hosted"; import { openPlan } from "../testing/plan"; import * as edit from "../plan/edit"; -import { buildState, fanOut, fanOutArguments, MAX_OPEN } from "./fan-out"; -import { INDEX_HEADING, writeIndex } from "./fan-out-index"; +import { buildState, MAX_OPEN, orchestrate, orchestrateArguments } from "./orchestrate"; +import { INDEX_HEADING, writeIndex } from "./orchestrate-index"; import { documentRoom } from "./heading-harness.test-fixtures"; import type { AuthenticatedSession } from "../auth/session"; @@ -16,11 +16,11 @@ import type { NewDocumentArguments } from "./new-documents"; import type { BuildState, CreatedDocumentState, - FanOutArguments, - FanOutDeps, IndexWriter, + OrchestrateArguments, + OrchestrateDeps, PlannerState, -} from "./fan-out"; +} from "./orchestrate"; import type { BuildRequest } from "@chopin/protocol/implementation"; const NOW = new Date("2026-11-16T12:00:00.000Z"); @@ -85,7 +85,7 @@ async function fixture( let planners = new Map(); let builds = new Map(); let push = options.push ?? true; - let deps: FanOutDeps = { + let deps: OrchestrateDeps = { channel: id => storage.channels.get(id), deleting: () => false, login: async () => login(), @@ -110,8 +110,8 @@ async function fixture( indexed.push({ documents, create }); return create ? { state: "written" } : { state: "absent" }; }; - let call = (args: FanOutArguments) => - fanOut(deps, { + let call = (args: OrchestrateArguments) => + orchestrate(deps, { sourceId: source.id, creator: { userId: "U_mona", handle: "mona" }, arguments: args, @@ -134,42 +134,44 @@ function byTitle(documents: T[]): T[] { return documents.toSorted((left, right) => left.title.localeCompare(right.title)); } -describe("fan_out arguments", () => { +describe("orchestrate arguments", () => { test("take each operation's own fields only", () => { - expect(fanOutArguments({ operation: "list" })).toEqual({ operation: "list" }); - expect(fanOutArguments({ operation: "instruct", instruction: "Resume." })).toEqual({ + expect(orchestrateArguments({ operation: "list" })).toEqual({ operation: "list" }); + expect(orchestrateArguments({ operation: "instruct", instruction: "Resume." })).toEqual({ operation: "instruct", instruction: "Resume.", }); - expect(() => fanOutArguments({ operation: "list", instruction: "Resume." })).toThrow( - "fan_out list does not take `instruction`", + expect(() => orchestrateArguments({ operation: "list", instruction: "Resume." })).toThrow( + "orchestrate list does not take `instruction`", ); - expect(() => fanOutArguments({ operation: "close" })).toThrow("operation must be one of"); - expect(() => fanOutArguments({ operation: "instruct" })).toThrow("instruction"); - expect(() => fanOutArguments({ operation: "instruct", instruction: "Go.", targets: [] })) + expect(() => orchestrateArguments({ operation: "close" })).toThrow("operation must be one of"); + expect(() => orchestrateArguments({ operation: "instruct" })).toThrow("instruction"); + expect(() => orchestrateArguments({ operation: "instruct", instruction: "Go.", targets: [] })) .toThrow("targets"); }); test("open checks every document as create_document does, and needs distinct keys", () => { - expect(() => fanOutArguments({ operation: "open", documents: [] })).toThrow("at least one"); + expect(() => orchestrateArguments({ operation: "open", documents: [] })).toThrow( + "at least one", + ); expect(() => - fanOutArguments({ + orchestrateArguments({ operation: "open", documents: [piece("login-page", "Login"), { title: "x" }], }) ).toThrow("documents[1]: idempotencyKey"); expect(() => - fanOutArguments({ + orchestrateArguments({ operation: "open", documents: [piece("login-page", "Login"), piece("login-page", "Login again")], }) ).toThrow("its own idempotencyKey"); let many = Array.from({ length: MAX_OPEN + 1 }, (_, n) => piece(`document-${n}`, `D${n}`)); - expect(() => fanOutArguments({ operation: "open", documents: many })).toThrow("at most"); + expect(() => orchestrateArguments({ operation: "open", documents: many })).toThrow("at most"); }); }); -describe("fanOut", () => { +describe("orchestrate", () => { test("open creates each document linked to this one, and a retry makes none twice", async () => { let context = await fixture(); let opened = await context.open( diff --git a/apps/server/src/agent/fan-out.ts b/apps/server/src/agent/orchestrate.ts similarity index 87% rename from apps/server/src/agent/fan-out.ts rename to apps/server/src/agent/orchestrate.ts index c9b02b9b9..95640b764 100644 --- a/apps/server/src/agent/fan-out.ts +++ b/apps/server/src/agent/orchestrate.ts @@ -1,5 +1,5 @@ /** - * The Planner's `fan_out`: one document's Planner working with the documents it created. + * The Planner's `orchestrate`: one document's Planner working with the documents it created. * * `open` creates several documents at once, each exactly as `create_document` would; `list` reads * each created document's state as Chopin holds it; `instruct` hands their Planners one instruction @@ -35,20 +35,20 @@ export const MAX_CREATED = 200; /** How many documents are created, or Planners instructed, at once. */ const CONCURRENCY = 4; -export const FAN_OUT_OPERATIONS = ["open", "list", "instruct", "index"] as const; +export const ORCHESTRATE_OPERATIONS = ["open", "list", "instruct", "index"] as const; -export type FanOutArguments = +export type OrchestrateArguments = | { operation: "open"; documents: NewDocumentArguments[] } | { operation: "list" } | { operation: "instruct"; instruction: string; targets?: string[] } | { operation: "index" }; -export const FAN_OUT_SCHEMA = { +export const ORCHESTRATE_SCHEMA = { type: "object", properties: { operation: { type: "string", - enum: [...FAN_OUT_OPERATIONS], + enum: [...ORCHESTRATE_OPERATIONS], description: "`open` creates documents from `documents`; `list` reports every document " + "this one created, with its Planner, open Decisions and build; `instruct` sends " + "`instruction` to their Planners; `index` writes or refreshes their table in this " @@ -81,7 +81,7 @@ export const FAN_OUT_SCHEMA = { additionalProperties: false, }; -const FIELDS: Record = { +const FIELDS: Record = { open: ["documents"], list: [], instruct: ["instruction", "targets"], @@ -89,18 +89,18 @@ const FIELDS: Record = { }; /** The tool's arguments, checked; throws with a sentence the model can act on. */ -export function fanOutArguments(raw: unknown): FanOutArguments { +export function orchestrateArguments(raw: unknown): OrchestrateArguments { if (!raw || typeof raw !== "object" || Array.isArray(raw)) { - throw new Error("fan_out arguments must be an object"); + throw new Error("orchestrate arguments must be an object"); } let args = raw as Record; let operation = args.operation; - if (!FAN_OUT_OPERATIONS.includes(operation as FanOutArguments["operation"])) { - throw new Error(`operation must be one of ${FAN_OUT_OPERATIONS.join(", ")}`); + if (!ORCHESTRATE_OPERATIONS.includes(operation as OrchestrateArguments["operation"])) { + throw new Error(`operation must be one of ${ORCHESTRATE_OPERATIONS.join(", ")}`); } - let op = operation as FanOutArguments["operation"]; + let op = operation as OrchestrateArguments["operation"]; let unknown = Object.keys(args).find(key => key !== "operation" && !FIELDS[op].includes(key)); - if (unknown) throw new Error(`fan_out ${op} does not take \`${unknown}\``); + if (unknown) throw new Error(`orchestrate ${op} does not take \`${unknown}\``); if (op === "open") { if (!Array.isArray(args.documents) || args.documents.length === 0) { throw new Error("open needs documents, at least one"); @@ -176,15 +176,15 @@ export type IndexWriter = ( create: boolean, ) => Promise; -export type FanOutDeps = NewDocumentDeps & { +export type OrchestrateDeps = NewDocumentDeps & { /** Unarchived documents created from a document, oldest first. */ createdFrom: (sourceId: string, limit: number) => Promise; planner: (channelId: string) => PlannerState; build: (channelId: string) => Promise; }; -export type FanOutRequest = Omit & { - arguments: FanOutArguments; +export type OrchestrateRequest = Omit & { + arguments: OrchestrateArguments; index: IndexWriter; }; @@ -192,7 +192,7 @@ type Instructed = & Pick & ({ started: true } | { started: false; reason: string; message?: string }); -export type FanOutResult = +export type OrchestrateResult = | { ok: true; operation: "open"; @@ -220,7 +220,7 @@ const REFUSALS: Record = { "nothing-created": "No document was created from this one, so there is nothing to instruct.", }; -function refused(reason: string): FanOutResult { +function refused(reason: string): OrchestrateResult { return { ok: false, reason, message: REFUSALS[reason]! }; } @@ -238,7 +238,7 @@ async function bounded(items: T[], work: (item: T) => Promise): Promise return results; } -function url(deps: FanOutDeps, channel: ChannelRecord): string { +function url(deps: OrchestrateDeps, channel: ChannelRecord): string { return new URL( documentPath(channel.repositoryOwner, channel.repositoryName, channel.slug), deps.appOrigin, @@ -246,14 +246,17 @@ function url(deps: FanOutDeps, channel: ChannelRecord): string { } /** The documents `source` created that are still its repository's, top-level and unarchived. */ -async function created(deps: FanOutDeps, source: ChannelRecord): Promise { +async function created(deps: OrchestrateDeps, source: ChannelRecord): Promise { return (await deps.createdFrom(source.id, MAX_CREATED)).filter(channel => channel.createdFrom === source.id && channel.repositoryId === source.repositoryId && !channel.parentChannelId && !channel.archivedAt && !deps.deleting(channel.id) ); } -async function states(deps: FanOutDeps, source: ChannelRecord): Promise { +async function states( + deps: OrchestrateDeps, + source: ChannelRecord, +): Promise { return Promise.all((await created(deps, source)).map(async channel => ({ id: channel.id, title: channel.title, @@ -265,18 +268,18 @@ async function states(deps: FanOutDeps, source: ChannelRecord): Promise, -): Promise { + args: Extract, +): Promise { let all = await created(deps, source); if (all.length === 0) return refused("nothing-created"); let unknown = args.targets?.filter(wanted => !all.some(channel => names(deps, channel, wanted))); @@ -327,7 +330,10 @@ async function instruct( }; } -export async function fanOut(deps: FanOutDeps, request: FanOutRequest): Promise { +export async function orchestrate( + deps: OrchestrateDeps, + request: OrchestrateRequest, +): Promise { let source = await deps.channel(request.sourceId); if (!source || source.archivedAt || deps.deleting(source.id) || source.parentChannelId) { return refused("document-unavailable"); diff --git a/apps/server/src/agent/planner.ts b/apps/server/src/agent/planner.ts index cbcd56260..b47d3b4a5 100644 --- a/apps/server/src/agent/planner.ts +++ b/apps/server/src/agent/planner.ts @@ -214,7 +214,7 @@ and an \`instruction\` when its own Planner should start on it now. One document holding every piece is too large to review; write one only when the member asks for it. Each new document has its own Chat and Planner and shares nothing with this one, so its draft and instruction must carry everything it needs. Tell the -member what you created, with each link from the result. \`fan_out\` works with +member what you created, with each link from the result. \`orchestrate\` works with the documents this one created: \`open\` creates several at once, \`list\` shows each one's Planner, open Decisions and build, \`instruct\` hands their Planners one instruction (to resume or change their work), and \`index\` keeps a table of them diff --git a/apps/server/src/agent/tools.test.ts b/apps/server/src/agent/tools.test.ts index 464a278ed..43658683a 100644 --- a/apps/server/src/agent/tools.test.ts +++ b/apps/server/src/agent/tools.test.ts @@ -87,7 +87,7 @@ test("document tool names and schemas remain available to the Planner", async () "read_background_job", "create_research_workspace", "create_document", - "fan_out", + "orchestrate", "upload_plan_image", "assess_visual", "edit_plan", @@ -275,14 +275,14 @@ test("read_plan and edit_plan give a child document its nested canonical URL", a expect(edited).toMatchObject({ ok: true, document: identity }); }); -async function callFanOut(tools: ReturnType, raw: unknown) { - let fanOut = tools.find(tool => tool.name === "fan_out"); - if (!fanOut?.handler) throw new Error("fan_out is missing"); - let text = String(await fanOut.handler(raw as never, { toolCallId: "call" })); +async function callOrchestrate(tools: ReturnType, raw: unknown) { + let orchestrate = tools.find(tool => tool.name === "orchestrate"); + if (!orchestrate?.handler) throw new Error("orchestrate is missing"); + let text = String(await orchestrate.handler(raw as never, { toolCallId: "call" })); return text.startsWith("Error: ") ? text : JSON.parse(text); } -test("fan_out hands checked arguments and this room's index to the member turn, and refuses without one", async () => { +test("orchestrate hands checked arguments and this room's index to the member turn, and refuses without one", async () => { let { plan, server } = await opened("# Whole app\n\nWhat the app does.\n"); let room = { plan, @@ -294,7 +294,7 @@ test("fan_out hands checked arguments and this room's index to the member turn, anchors() {}, changes() {}, }; - expect(await callFanOut(fixtureTools(room), { operation: "list" })).toEqual({ + expect(await callOrchestrate(fixtureTools(room), { operation: "list" })).toEqual({ ok: false, reason: "member-request-required", message: "Only a turn a person asked for in Chat can work with created documents.", @@ -302,7 +302,7 @@ test("fan_out hands checked arguments and this room's index to the member turn, let received: unknown[] = []; let tools = fixtureTools({ ...room, - fanOut: async (args, index) => { + orchestrate: async (args, index) => { received.push(args); let written = await index([{ id: "doc", @@ -315,7 +315,7 @@ test("fan_out hands checked arguments and this room's index to the member turn, return { ok: true, operation: "index", documents: [], index: written }; }, }); - expect(await callFanOut(tools, { operation: "index" })).toMatchObject({ + expect(await callOrchestrate(tools, { operation: "index" })).toMatchObject({ ok: true, index: { state: "written" }, }); diff --git a/apps/server/src/agent/tools.ts b/apps/server/src/agent/tools.ts index 343ab2a7d..fb3594744 100644 --- a/apps/server/src/agent/tools.ts +++ b/apps/server/src/agent/tools.ts @@ -35,9 +35,9 @@ import { experimentTools } from "./experiment-tools"; import { planImage } from "./plan-images"; import { NEW_DOCUMENT_SCHEMA, newDocumentArguments } from "./new-documents"; import type { NewDocumentArguments, NewDocumentResult } from "./new-documents"; -import { FAN_OUT_SCHEMA, fanOutArguments } from "./fan-out"; -import { writeIndex } from "./fan-out-index"; -import type { FanOutArguments, FanOutResult, IndexWriter } from "./fan-out"; +import { ORCHESTRATE_SCHEMA, orchestrateArguments } from "./orchestrate"; +import { writeIndex } from "./orchestrate-index"; +import type { IndexWriter, OrchestrateArguments, OrchestrateResult } from "./orchestrate"; import type { InvestigationTools } from "./experiment-tools"; import type { ActiveOwnerBinding } from "./active-owner"; @@ -201,11 +201,11 @@ export type DocumentRoom = { * Works with the documents this one created, for the person whose message drives the current * turn; absent, or refusing, where `createDocument` is. */ - fanOut?: ( - args: FanOutArguments, + orchestrate?: ( + args: OrchestrateArguments, index: IndexWriter, signal?: AbortSignal, - ) => Promise; + ) => Promise; /** Starts the exact research request represented by the current member turn. */ createResearch?: (question: string) => Promise; /** Reads one reference retained by this room's active Planner session. */ @@ -376,7 +376,7 @@ export const documentTools = { }), }), - fan_out: tool({ + orchestrate: tool({ contextSchema: roomContext, description: "Work with the documents this document created, each with its own Chat, " + "Decisions and Planner. `open` creates several at once, each exactly as " @@ -388,18 +388,18 @@ export const documentTools = { + "`index` writes a table of them, kept current by later calls, under its own heading in " + "this document. Only a turn a person asked for can use it, and it reaches only the " + "documents this one created.", - inputSchema: jsonSchema(FAN_OUT_SCHEMA), + inputSchema: jsonSchema(ORCHESTRATE_SCHEMA), execute: (raw, { context: { room: context }, abortSignal }) => - answer("fan_out", async () => { - let args = fanOutArguments(raw); - if (!context.fanOut) { + answer("orchestrate", async () => { + let args = orchestrateArguments(raw); + if (!context.orchestrate) { return { ok: false, reason: "member-request-required", message: "Only a turn a person asked for in Chat can work with created documents.", }; } - return context.fanOut( + return context.orchestrate( args, (documents, create) => writeIndex(context, documents, create, abortSignal), abortSignal, diff --git a/apps/server/src/chat/service.ts b/apps/server/src/chat/service.ts index 52cfacb8b..f17902bf9 100644 --- a/apps/server/src/chat/service.ts +++ b/apps/server/src/chat/service.ts @@ -39,7 +39,7 @@ import type { AiAccountRefusal } from "../ai/account-check"; import type { ActiveOwnerBinding } from "../agent/active-owner"; import type { DocumentRoom, ResearchWorkspaceRequest } from "../agent/tools"; import type { NewDocumentRequest, NewDocumentResult } from "../agent/new-documents"; -import type { FanOutRequest, FanOutResult } from "../agent/fan-out"; +import type { OrchestrateRequest, OrchestrateResult } from "../agent/orchestrate"; import type { VisualAdmission } from "../agent/visual-admission"; import type { ChildDocuments } from "./children"; import type { TellChat } from "./thread-notes"; @@ -926,7 +926,7 @@ export type Room = { /** Creates a top-level document for the person whose message drives the turn. */ createDocument?: (request: Omit) => Promise; /** Works with the documents this one created, for the person whose message drives the turn. */ - fanOut?: (request: Omit) => Promise; + orchestrate?: (request: Omit) => Promise; /** Keeps the room loaded while a retained Planner still waits on a question; returns the release. */ hold?: () => () => void; /** The task draft the turn being started carries. */ @@ -2587,8 +2587,8 @@ export function documentRoom(context: Room): DocumentRoom { return context.createDocument!({ ...request, arguments: args }); }, }), - ...(!chat.job && context.fanOut && !context.rootChannelId && { - fanOut: async (args, index, signal) => { + ...(!chat.job && context.orchestrate && !context.rootChannelId && { + orchestrate: async (args, index, signal) => { let request = creatorRequest(context, signal); if (!request) { return { @@ -2597,7 +2597,7 @@ export function documentRoom(context: Room): DocumentRoom { message: "Only a turn a person asked for in Chat can work with created documents.", }; } - return context.fanOut!({ ...request, arguments: args, index }); + return context.orchestrate!({ ...request, arguments: args, index }); }, }), createResearch: async _question => { diff --git a/apps/server/src/chat/threads.ts b/apps/server/src/chat/threads.ts index 1316e9fe9..410e351f2 100644 --- a/apps/server/src/chat/threads.ts +++ b/apps/server/src/chat/threads.ts @@ -666,7 +666,7 @@ function buildThreadRoom( hold: topContext.hold, children: topContext.children, createDocument: topContext.createDocument, - fanOut: topContext.fanOut, + orchestrate: topContext.orchestrate, // A reaction saves the transcript it is about to make, before it changes the live one. persist: async next => { await saveThreadRecord(topContext, managed, override, next?.().entries); diff --git a/apps/server/src/harness/tool-names.ts b/apps/server/src/harness/tool-names.ts index 3563e79f0..8a579cead 100644 --- a/apps/server/src/harness/tool-names.ts +++ b/apps/server/src/harness/tool-names.ts @@ -12,7 +12,7 @@ export const PLANNER_TOOL_NAMES = [ "read_background_job", "create_research_workspace", "create_document", - "fan_out", + "orchestrate", "upload_plan_image", "edit_plan", "open_decision", diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 3b0e0f9ff..f4f4c0a66 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -122,9 +122,9 @@ import { JobService } from "./jobs/service"; import { DocumentSummaryCoordinator } from "./jobs/summary-coordinator"; import { invokeRouted, SystemTurns } from "./mcp/invoke"; import { createNewDocument } from "./agent/new-documents"; -import { buildState, fanOut } from "./agent/fan-out"; +import { buildState, orchestrate } from "./agent/orchestrate"; import type { NewDocumentDeps } from "./agent/new-documents"; -import type { FanOutDeps } from "./agent/fan-out"; +import type { OrchestrateDeps } from "./agent/orchestrate"; import type { BuildRequest } from "@chopin/protocol/implementation"; import { liveClassifier } from "./tasks/live-gate"; import { LiveSyncCoordinator } from "./tasks/live-sync"; @@ -1113,8 +1113,8 @@ function conversation( createDocument: config.agent ? request => createNewDocument(plannerDocuments(), { ...request, sourceId: room.id }) : undefined, - fanOut: config.agent - ? request => fanOut(createdDocuments(), { ...request, sourceId: room.id }) + orchestrate: config.agent + ? request => orchestrate(createdDocuments(), { ...request, sourceId: room.id }) : undefined, createResearch: config.agent ? async request => { @@ -2757,8 +2757,8 @@ function plannerDocuments(): NewDocumentDeps { }; } -/** The Planner's `fan_out`: `create_document`'s rules, and the state of what a document created. */ -function createdDocuments(): FanOutDeps { +/** The Planner's `orchestrate`: `create_document`'s rules, and the state of what a document created. */ +function createdDocuments(): OrchestrateDeps { return { ...plannerDocuments(), createdFrom: (sourceId, limit) => storage.channels.createdFrom(sourceId, limit), diff --git a/docs/agent-connection.md b/docs/agent-connection.md index 86bc7d3ca..0cc5a29c2 100644 --- a/docs/agent-connection.md +++ b/docs/agent-connection.md @@ -850,10 +850,11 @@ session is one launch, prepared before its `start` or `fork` and carried in `ai` back), half an hour before the launch's deadline, and after a [resume](#resuming-after-a-dropped-link), because the launch a session held may have ended with its link or with the server's process. A change while the session starts - is sent once the client answers `started`, as the accounts are then. The earlier - launch ends once the new one is sent, so use the new grants from then on: a request - still waiting at Chopin on the earlier one is refused. An empty `providers` says the - session has no grant now. + is sent once the client answers `started`, as the accounts are then. Switch to the + new grants right away. The replaced launch stays live for a two-minute grace period + (`REPLACED_LAUNCH_GRACE_MS`) before ending, so requests the client already sent on + it or is still streaming are not refused as ended; if the session ends first, both + launches end at once. An empty `providers` says the session has no grant now. - A launch ends with its session (`destroy`, or a link that closes for good), and when its machine is revoked or its document archived; Chopin's proxy then answers `launch-ended`, or `unknown-placeholder` once its placeholders are gone (401, `{ @@ -1401,14 +1402,15 @@ not apply to it. first and handle `resumed`, then the redelivered `input-result`s; retry the same `resume` on a `refused` with `retry`, and treat any other `refused` or `error` as final. - **What still ends it for good.** Its own `detach`; any definitive `refused` (every - one without `retry`) or protocol error; the owner's sign-out or its expiry; a Planner reset; revoking or unpairing - the machine that attached it; the document's owner choosing another machine for it; - archiving or deleting the document; a Stop that withdraws its last question; and the - same account attaching with a client that does not resume, which includes a browser - sign-in attaching over a paired machine's parked work, since that client cannot - resume it. All of these withdraw the questions, and a later `resume` finds nothing. A - server restart does not end it: see below. A person - with write access can always end a disconnected Planner by resetting it. + one without `retry`) or protocol error; the owner's sign-out or a credential that + cannot be renewed (routine credential renewal does not end it); a Planner reset; + revoking or unpairing the machine that attached it; the document's owner choosing + another machine for it; archiving or deleting the document; a Stop that withdraws + its last question; and the same account attaching with a client that does not + resume, which includes a browser sign-in attaching over a paired machine's parked + work, since that client cannot resume it. All of these withdraw the questions, and + a later `resume` finds nothing. A server restart does not end it: see below. A + person with write access can always end a disconnected Planner by resetting it. #### When the server is restarting diff --git a/docs/channels.md b/docs/channels.md index 540738c65..5cacced10 100644 --- a/docs/channels.md +++ b/docs/channels.md @@ -316,11 +316,12 @@ differs. `update_document` later replaces that canonical source against the plan revision last read, with the same dialect validation and an idempotency key that returns the original applied result on replay. -The Planner's `create_document` tool goes through the same creation transaction -from a member's turn: its draft is validated and assessed for visuals as MCP's, -its repository and base branch are the creating document's (the base it recorded, -else the default branch's current commit), and its idempotency key is scoped to -the creating document. See +The Planner's `create_document` and `orchestrate` (`open`) tools go through the +same creation transaction from a member's turn: each draft is validated and +assessed for visuals as MCP's, its repository and base branch are the creating +document's (the base it recorded, else the default branch's current commit), +its idempotency key is scoped to the creating document, and it records the +creating document in `createdFrom` (migration 054). See [Creating documents](hosted-agent.md#creating-documents). ## Generated descriptions diff --git a/docs/hosted-agent.md b/docs/hosted-agent.md index 101c45ca1..8111d51f3 100644 --- a/docs/hosted-agent.md +++ b/docs/hosted-agent.md @@ -371,7 +371,7 @@ Chopin's tools available to the Planner under every harness are: never offered to background jobs, and unexpected storage errors reach the model only as a generic message; - `create_document`, which makes new top-level documents for the person whose - message drives the turn, and `fan_out`, which opens, lists, instructs and + message drives the turn, and `orchestrate`, which opens, lists, instructs and indexes the documents this one created (see [Creating documents](#creating-documents)); neither is offered to background jobs; @@ -610,20 +610,21 @@ remote client's workflow-stage input, become ordinary shared Decisions: cancellation by `@chopin`. Member cancellations retain any answers already given in that batch. Late submissions cannot approve withdrawn input. - A request has no time limit. It waits until members answer it or it is - withdrawn: the Planner stops, the document is archived - or deleted, or the asker's link closes for good, which includes its owner's - sign-in ending. A lost connection is never such an end. A link that dropped - unexpectedly and offered `resumable-sessions` keeps its open questions for its - account to [resume](agent-connection.md#resuming-after-a-dropped-link) - however long it stays away: no timer, including `PLANNER_ATTACH_GRACE_MS`, ends - them. While it is away Chat adds no line about the connection (the machine - button carries it); the Decisions stay open and answerable, their answers kept - for the client. Stop on - a Planner that only waits on a question withdraws it, and Chat says that. A - document on **Default machine** - keeps its Planner running while that Planner is replying or waits on a question, - a disconnected Planner's kept work included, so - nobody viewing the document does not withdraw it or cut its work short. + withdrawn: the Planner stops, the document is archived or deleted, or the + asker's link closes for good (such as the owner signing out or a credential + that cannot be renewed). A failed turn, a routine renewal of the owner's + GitHub credential, and a lost connection never withdraw open questions. A + link that dropped unexpectedly and offered `resumable-sessions` keeps its + open questions for its account to + [resume](agent-connection.md#resuming-after-a-dropped-link) however long it + stays away: no timer, including `PLANNER_ATTACH_GRACE_MS`, ends them. While + it is away, Chat adds no line about the connection (the machine button + carries it), and Decisions stay open and answerable with answers held for the + client. Stopping a Planner that only waits on a question withdraws it, and + Chat says so. A document on **Default machine** keeps its Planner running + while it is replying or waiting on a question (including a disconnected + Planner's kept work), so an idle document never withdraws questions or cuts + work short. - Cards an earlier Chopin closed unanswered after a fixed time stay in the document and in Decisions, among the resolved cards, marked `status="expired"`; each reads "Nobody answered this question, so the Planner @@ -1386,17 +1387,20 @@ for (`owner`: `run:`, `session:` or `link:`), which ends it (see bel An `ai` message hands the session a new launch when what a launch for the person may be given changes (they connect, replace or remove a provider, their provider refuses a key of theirs as invalid, or GitHub confirms their Copilot seat lost or regained), - half an hour before the deadline, and when a resumed session comes back; the earlier - launch ends once the new one is sent. A change while the session is starting reaches - it once the client acknowledges `start` or `fork`, prepared again from what the person - has then, once however often it changed. A renewal that finds nothing left to give - hands the session an empty `providers` and ends its launch. The session's end - (`destroy`, or its link closing for good) ends its launch. A session a restart's hold - keeps keeps its launch, named in the hold (`aiLaunchId`, an id and no credential): - from the moment the cut takes the hold no launch of its changes, and one a renewal - prepared meanwhile is ended unsent, so the hold names the launch its client holds. The - next process ends it when the session ends or the hold does, and replaces it when the - client resumes. A client that does not offer the feature is launched nothing. See + half an hour before the deadline, and when a resumed session comes back. The replaced + launch stays held and live for a two-minute grace period (`REPLACED_LAUNCH_GRACE_MS` in + `apps/server/src/harness/remote/link.ts`) before ending, so requests the client already + sent on it or is still streaming are not refused as ended. Ending the session ends both + the current launch and any replaced launch still in grace at once. A change while the + session is starting reaches it once the client acknowledges `start` or `fork`, prepared + again from what the person has then, once however often it changed. A renewal that finds + nothing left to give hands the session an empty `providers` and retires its launch. The + session's end (`destroy`, or its link closing for good) ends its launches at once. A + session a restart's hold keeps keeps its launch, named in the hold (`aiLaunchId`, an id + and no credential): from the moment the cut takes the hold no launch of its changes, and + one a renewal prepared meanwhile is ended unsent, so the hold names the launch its client + holds. The next process ends it when the session ends or the hold does, and replaces it + when the client resumes. A client that does not offer the feature is launched nothing. See [Models through Chopin](agent-connection.md#models-through-chopin). - **A link's catalog launch**, for a client that offers `ai-credentials` and `ai-catalog` and asks for it once attached, is launched for the same account its sessions are, for the @@ -1918,31 +1922,43 @@ Chat is restored, so it shows no mark. See [Storage](storage.md#a-live-database- ## Session lifecycle -A harness session is disposable. A process restart, credential rotation, -logout, or ownership reset discards it. A later turn bootstraps from the -bounded transcript and reads the current document. - -The one exception is a Planner session that waits on a question it asked, such as an -`ask_user_question`, or on an answer its client has not received, when its turn ends. Chopin -keeps the session and its owner binding, and keeps the document loaded, until a member answers -the question or it is withdrawn, and the next turn reuses it. The session is let go once no -question is open and every answer has reached its client, when its owner binding ends, or when -the document closes. A turn whose Chat reply could not be verified, or moved into inline -decisions, fails without letting go a session that waits on a question, so that failure -withdraws no question. **Stop Planner** stops the running turn; with no turn running, it lets go -a session that only waits on a question, which withdraws the question, and Chat says so. Chopin -keeps no workflow runs and shows no run cards: a remote client's own work that outlives its turn -is the client's to report in its replies. The Atomic adapter stops any turn Atomic starts on its -own, such as for its lifecycle notices or, since Atomic 0.9.41, for a message queued while the -session is idle, because Chopin would neither show nor record it. The Planner's next turn still -starts normally. An Atomic Planner session keeps its history in -memory, and Chopin saves its every entry with the document for forks and threads, -so Atomic's shared top-level `storage` setting and its `ATOMIC_STORAGE` and -`ATOMIC_SESSIONS_STORAGE` selections do not move it. Atomic still checks every set -`ATOMIC_STORAGE` and `ATOMIC_SESSIONS_STORAGE` when it creates a session, so an -invalid value fails every Atomic turn with a `StorageConfigError` naming the variable. A Build's tasks, their -state and pull requests show under **Build**, whichever machine runs it. The -Planner's instructions say so, so it does not point people to Chat for a Build. +A harness session is disposable unless it holds an open question or an +unacknowledged answer. Logout, an unrenewable credential, a process restart +(without a remote Planner handover hold), or an ownership reset discards it; a +later turn bootstraps from the bounded transcript and reads the current +document. + +- **Credential renewal.** A routine renewal of the owner's GitHub credential + does not abort a running turn or discard a retained session on harnesses that + support rebinding (`remote`). The session takes the renewed credential and + keeps going, even if the renewal lands just as the turn closes. A turn + running on a retained session shares that session's rebind so the session + holds one binding at a time. Only signing out, a credential that cannot be + renewed, or a harness that cannot rebind ends the session. +- **Kept sessions and failed turns.** When a turn finishes or fails while its + session still holds an open question (such as `ask_user_question`) or an + answer its client has not received, Chopin keeps the session, its owner + binding, and the loaded document. A failing reply never withdraws open + Decisions. The next turn reuses the session, and Chopin lets it go once no + question is open and every answer has reached its client, when its owner + binding ends for good, or when the document closes. +- **Stop Planner.** Clicking **Stop Planner** stops a running turn. With no + turn running, it releases a kept session that only waits on a question, + withdrawing that question and posting a note in Chat. +- **No workflow run cards.** Chopin keeps no workflow runs and shows no run + cards: a remote client's own work that outlives its turn is the client's to + report in its replies. +- **Atomic sessions.** The Atomic adapter stops any turn Atomic starts on its + own (such as lifecycle notices or messages queued while idle) because Chopin + would neither show nor record it; the Planner's next turn still starts + normally. An Atomic Planner session keeps its history in memory and Chopin + saves every entry with the document for forks and threads, so Atomic's + top-level `storage` setting and `ATOMIC_STORAGE` / `ATOMIC_SESSIONS_STORAGE` + do not move it. Atomic still validates those variables on session creation, + so an invalid value fails every Atomic turn with `StorageConfigError`. +- **Builds.** A Build's tasks, state, and pull requests appear under **Build**, + whichever machine runs it; the Planner's instructions tell it not to point + people to Chat for a Build. An interrupted turn is visible and is never replayed automatically because it may already have made durable document or question changes. `HarnessAgent.stream()` @@ -2014,30 +2030,43 @@ kept, when the creating document is deleted. ### Working with created documents -`fan_out` (`apps/server/src/agent/fan-out.ts`) is the Planner's tool for the -documents its document created. It is offered with `create_document`, under the -same rules: only a turn a person's message drives may call it, that person's live -browser login is rechecked for write access, and it reaches only unarchived -top-level documents of the same repository whose `createdFrom` is this document. -It takes one `operation`: - -- `open` creates up to 20 documents at once from `documents`, each exactly as - `create_document` takes and creates it, with its own idempotency key. Results - come back in the order given. -- `list` gives each created document's `id`, `title`, `url`, its Planner - (`working` while a turn runs, `idle` while a session or attached machine holds - it, otherwise `stopped`), its open Decisions, and its build (`building`, - `built`, `failed`, `stopped` or `not built`). -- `instruct` posts one `instruction` in every created document's Chat, or only in - the `targets` named by id or url, as the person's message, exactly as - `invoke_planner` does, starting a Planner that isn't running. Each document's - outcome is reported; a busy Planner is refused and can be instructed again - later. A target that is not a document this one created is named in `unknown`. -- `index` writes a table of the created documents under the heading "Documents - created from this one" in the creating document. The heading and the one block - after it are Chopin's; the rest of the document is left alone. `open` and - `list` refresh a table already there, and nothing is written when it would not - change. +`orchestrate` (`apps/server/src/agent/orchestrate.ts`) lets a document's Planner +open, inspect, instruct, and index the documents this document created. It is +offered alongside `create_document` under the same rules: only a turn driven by +a person's message may call it, that person's live browser login is rechecked +for write access, and it is never offered to background jobs or child rooms. It +reaches only unarchived top-level documents in the same repository whose stored +`createdFrom` link (migration 054) points to this document. + +Each call takes one `operation`: + +- **`open`** creates up to 20 documents at once (`documents`), each with the + same schema, idempotency key, and creation rules as `create_document`. + Results come back in the order given. +- **`list`** returns each created document's `id`, `title`, `url`, Planner + state (`working` while a turn runs, `idle` while a session or attached + machine holds it, otherwise `stopped`), open Decisions count, and build state + (`building`, `built`, `failed`, `stopped`, or `not built`). +- **`instruct`** posts one `instruction` (up to 64 KiB) to every created + document's Chat—or only to `targets` matched by `id` or `url`—as the person's + message, exactly as `invoke_planner` does, starting stopped Planners. It + reports each document's outcome; a busy Planner returns `planner-busy` and + can be retried later. Any target not created from this document is returned + in `unknown`. +- **`index`** writes or updates a table of the created documents under the + heading `## Documents created from this one` (`orchestrate-index.ts`). Chopin + owns only that heading and the one block after it; the rest of the document + is left alone. `open` and `list` refresh an existing table, and nothing is + written when the table would not change. + +**Limits:** + +- Documents created before `createdFrom` (migration 054) have no parent link, + so `orchestrate` cannot list, instruct, or index them. +- The index table refreshes only when `open`, `list`, or `index` runs; Chopin + does not push status changes into the parent document automatically. +- `open` accepts at most 20 documents per call; `list`, `instruct`, and `index` + cover up to 200 created documents. ## Background jobs