From bb651f1d51b8b7364fa5b94ad42ef4cfe2535c46 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Thu, 29 Oct 2026 23:23:07 +0530 Subject: [PATCH 1/6] feat(harness): report per-thread usage and rebase relinks in one place ThreadInfo carries the thread's own billed usage. The session store's new `rebase` is the only place that works out where a session's or a thread's directory lands under another root; the embedder relink and the store relink both use it. Co-Authored-By: Claude Opus 5.5 --- packages/harness/src/effect/session.ts | 39 ++++++++++------ packages/harness/src/session/session.ts | 62 +++++++++++++++++++------ 2 files changed, 73 insertions(+), 28 deletions(-) diff --git a/packages/harness/src/effect/session.ts b/packages/harness/src/effect/session.ts index b6b3fcdd..971de97a 100644 --- a/packages/harness/src/effect/session.ts +++ b/packages/harness/src/effect/session.ts @@ -129,9 +129,19 @@ export interface ThreadInfo { * resumes it; the next prompt runs it again. */ readonly parked: boolean; + /** Billed usage of its own entries; what it inherits through a fork point counts for its source. */ + readonly usage: Usage; readonly session: Info; } +export interface Usage { + readonly cost: number; + readonly input: number; + readonly output: number; + readonly cacheRead: number; + readonly cacheWrite: number; +} + export interface ForkInput { readonly entryId: string; readonly mode?: "at" | "before"; @@ -282,6 +292,13 @@ export const threadInfo = Effect.fn("Session.threadInfo")(function* (id: ThreadS ...(agent.thinkingLevel === undefined ? {} : { thinkingLevel: agent.thinkingLevel }), ...(agent.placement === undefined ? {} : { placement: agent.placement }), parked, + usage: { + cost: row.cost, + input: row.tokensInput, + output: row.tokensOutput, + cacheRead: row.tokensCacheRead, + cacheWrite: row.tokensCacheWrite, + }, session: yield* info(SessionSchema.ID.make(row.sessionId)), } satisfies ThreadInfo; }); @@ -448,23 +465,15 @@ export const relink = Effect.fn("Session.relink")(function* (input: RelinkInput) sandboxId, Effect.gen(function* () { const location = yield* Location.Service.use(Effect.succeed).pipe(Effect.provide(Location.layerMounted())); - const session = yield* sessions.get(input.sessionId); - const own = yield* sessions.space(input.sessionId); - const current = - input.threadId === undefined - ? Option.flatMap(session, (row) => Option.map(own, (space) => ({ space, directory: row.directory }))) - : yield* sessions.placement(input.threadId); - const rebased = Option.isSome(current) - ? SessionStore.rebaseDirectory( - current.value.space.location, - location.space.location, - current.value.directory, - ) - : undefined; + const rebased = yield* sessions.rebase({ + sessionId: input.sessionId, + ...(input.threadId === undefined ? {} : { threadId: input.threadId }), + to: location.space.location, + }); const fs = yield* SandboxIO.FileSystem; const directory = - rebased !== undefined && (yield* fs.exists(rebased).pipe(Effect.orElseSucceed(() => false))) - ? rebased + Option.isSome(rebased) && (yield* fs.exists(rebased.value).pipe(Effect.orElseSucceed(() => false))) + ? rebased.value : location.directory; yield* sessions.relink({ sessionId: input.sessionId, diff --git a/packages/harness/src/session/session.ts b/packages/harness/src/session/session.ts index e7b07d70..aa8cdca9 100644 --- a/packages/harness/src/session/session.ts +++ b/packages/harness/src/session/session.ts @@ -79,7 +79,7 @@ const directoryWithin = (location: AbsolutePath, directory: AbsolutePath) => * root is kept, so `dir = /old/app/pkg/x` under `from = /old/app` lands on `/new/app/pkg/x` under * `to = /new/app`. A directory not under the old root — a broken invariant — lands on the new root. */ -export const rebaseDirectory = (from: AbsolutePath, to: AbsolutePath, directory: AbsolutePath): AbsolutePath => { +const rebaseDirectory = (from: AbsolutePath, to: AbsolutePath, directory: AbsolutePath): AbsolutePath => { if (!directoryWithin(from, directory)) return to; const relative = posix.relative(from, directory); return AbsolutePath.make(relative === "" ? to : posix.join(to, relative)); @@ -140,7 +140,7 @@ export interface RelinkInput { readonly spaceId: SpaceSchema.ID; /** * Landing directory; must equal or sit under the target space's location. - * Default: `rebaseDirectory` of the current directory onto the new root. + * Default: {@link Interface.rebase} onto the target space's location. */ readonly directory?: AbsolutePath; } @@ -171,6 +171,16 @@ export interface Interface { readonly space: (sessionId: string) => Effect.Effect>; /** Where a thread runs. None when the thread is unknown or its space is gone. */ readonly placement: (threadId: ThreadSchema.ID) => Effect.Effect>; + /** + * Where the session's directory (or the thread's placement) lands under another root, keeping + * its position relative to its current space's location. None when the session or thread is + * unknown, or its space is gone. + */ + readonly rebase: (input: { + readonly sessionId: SessionSchema.ID; + readonly threadId?: ThreadSchema.ID; + readonly to: AbsolutePath; + }) => Effect.Effect>; /** The project a session belongs to, through its space. None when the session is unknown. */ readonly project: (sessionId: string) => Effect.Effect>; /** Sessions newest first, across the whole database when no scope is given. */ @@ -334,6 +344,22 @@ export const layer = Layer.effect( return Option.some({ space: own.value, directory: session.value.directory }); }); + const rebase = Effect.fn("Session.rebase")(function* (input: { + readonly sessionId: SessionSchema.ID; + readonly threadId?: ThreadSchema.ID; + readonly to: AbsolutePath; + }) { + const current: Option.Option = + input.threadId === undefined + ? Option.zipWith( + yield* findSession(input.sessionId).pipe(Effect.orDie), + yield* space(input.sessionId), + (row, own) => ({ space: own, directory: row.directory }), + ) + : yield* placement(input.threadId); + return Option.map(current, (one) => rebaseDirectory(one.space.location, input.to, one.directory)); + }); + // A bare lookup has no checkout to ask, so the info carries no `vcs` (as with `Project.get`). const project = Effect.fn("Session.project")(function* (sessionId: string) { return Option.map( @@ -387,18 +413,16 @@ export const layer = Layer.effect( if (Option.isSome(own) && own.value.projectId !== target.value.projectId) { return yield* reject("project_scope_mismatch"); } - const current = - input.threadId === undefined - ? Option.map(own, (row) => ({ location: row.location, directory: session.value.directory })) - : Option.map(yield* placement(input.threadId), (one) => ({ - location: one.space.location, - directory: one.directory, - })); const directory = input.directory ?? - (Option.isSome(current) - ? rebaseDirectory(current.value.location, target.value.location, current.value.directory) - : target.value.location); + Option.getOrElse( + yield* rebase({ + sessionId: input.sessionId, + ...(input.threadId === undefined ? {} : { threadId: input.threadId }), + to: target.value.location, + }), + () => target.value.location, + ); if (!directoryWithin(target.value.location, directory)) return yield* reject("directory_outside_space"); if (input.threadId === undefined) { const now = yield* epochNow; @@ -432,7 +456,19 @@ export const layer = Layer.effect( .pipe(Effect.orDie); }); - return Service.of({ create, projectCreated, link, get, space, placement, project, list, relink, delete: remove }); + return Service.of({ + create, + projectCreated, + link, + get, + space, + placement, + rebase, + project, + list, + relink, + delete: remove, + }); }), ); From bbabb30a7ca2c17165974b63c3390732a4b07b60 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Thu, 29 Oct 2026 23:23:07 +0530 Subject: [PATCH 2/6] feat(codework): move RPC, ACP and CLI onto threads - RPC: ThreadInfo gains `usage`; `session.relink` answers with the addressed thread (main when absent); `event.subscribe` and `session.log` take an optional `threadId` filter. - ACP: every thread is an ACP session (main keeps the session id, others use their thread id) for list, load, prompt and cancel; `session/fork` forks at the last committed entry. - CLI: `thread list`, `thread fork --at|--before`, and `session relink [--thread]`. Co-Authored-By: Claude Opus 5.5 --- packages/codework/src/acp/agent.ts | 2 + packages/codework/src/acp/handlers.ts | 128 ++++++++--- packages/codework/src/cli/cmd/cmd.ts | 90 +++++++- packages/codework/src/cli/cmd/handlers/run.ts | 14 +- .../src/cli/cmd/handlers/session/relink.ts | 34 +++ .../src/cli/cmd/handlers/thread/fork.ts | 39 ++++ .../src/cli/cmd/handlers/thread/list.ts | 49 ++++ packages/codework/src/cli/output.ts | 8 +- packages/codework/src/cli/thread.ts | 14 ++ packages/codework/src/index.ts | 5 + packages/codework/src/server/client.ts | 11 +- packages/codework/src/server/contract.ts | 30 ++- packages/codework/src/server/envelope.ts | 8 +- packages/codework/src/server/handlers.ts | 20 +- .../codework/test/__artifacts__/acp.fork.json | 27 +++ packages/codework/test/__artifacts__/acp.json | 3 +- .../__artifacts__/server.cli-threads.json | 73 ++++++ .../test/__artifacts__/server.threads.json | 115 ++++++++++ packages/codework/test/acp.test.ts | 97 ++++++++ packages/codework/test/server.test.ts | 210 +++++++++++++++++- sites/www/content/docs/agent/sessions.mdx | 2 +- sites/www/content/docs/cli/reference.mdx | 4 + sites/www/content/docs/integrations/acp.mdx | 3 +- sites/www/content/docs/integrations/rpc.mdx | 23 +- 24 files changed, 920 insertions(+), 89 deletions(-) create mode 100644 packages/codework/src/cli/cmd/handlers/session/relink.ts create mode 100644 packages/codework/src/cli/cmd/handlers/thread/fork.ts create mode 100644 packages/codework/src/cli/cmd/handlers/thread/list.ts create mode 100644 packages/codework/src/cli/thread.ts create mode 100644 packages/codework/test/__artifacts__/acp.fork.json create mode 100644 packages/codework/test/__artifacts__/server.cli-threads.json create mode 100644 packages/codework/test/__artifacts__/server.threads.json diff --git a/packages/codework/src/acp/agent.ts b/packages/codework/src/acp/agent.ts index ebc20b9b..7593306b 100644 --- a/packages/codework/src/acp/agent.ts +++ b/packages/codework/src/acp/agent.ts @@ -25,6 +25,7 @@ export interface Handlers { /** Must replay the session's history through `Client.sessionUpdate` before it returns. */ readonly loadSession: Handler; readonly listSessions: Handler; + readonly forkSession: Handler; readonly setConfigOption: Handler; readonly prompt: Handler; readonly cancel: (notification: Acp.CancelNotification) => Effect.Effect; @@ -81,6 +82,7 @@ export const serve = Effect.fn("ACP.serve")(function* ( .onRequest("session/new", handle(handlers.newSession)) .onRequest("session/load", handle(handlers.loadSession)) .onRequest("session/list", handle(handlers.listSessions)) + .onRequest("session/fork", handle(handlers.forkSession)) .onRequest("session/set_config_option", handle(handlers.setConfigOption)) .onRequest("session/prompt", handle(handlers.prompt)) .onNotification("session/cancel", handle(handlers.cancel)) diff --git a/packages/codework/src/acp/handlers.ts b/packages/codework/src/acp/handlers.ts index a7f74ec4..1c0b43bc 100644 --- a/packages/codework/src/acp/handlers.ts +++ b/packages/codework/src/acp/handlers.ts @@ -76,7 +76,7 @@ const promptParts = Effect.fnUntraced(function* (blocks: ReadonlyArray Session.SessionSchema.ID.make(id); +const threadId = (id: string) => Session.ThreadSchema.ID.make(id); type Services = Layer.Success>; @@ -89,10 +89,30 @@ export const make = Effect.gen(function* () { const running = new Set(); - const found = Effect.fn("ACP.found")(function* (id: string) { - const row = yield* sessions.get(sessionId(id)); - if (Option.isNone(row)) return yield* new SessionStore.SessionNotFoundError({ sessionId: sessionId(id) }); - return row.value; + // Every thread is an ACP session of its own. The main thread keeps the CodeWork session's id, + // so a session an editor knew before it had forks still loads; any other thread goes by its id. + const acpId = (thread: { readonly originKind: string; readonly sessionId: string; readonly id: string }) => + thread.originKind === "main" ? thread.sessionId : thread.id; + + /** The CodeWork session and thread an ACP session id names. */ + const resolve = Effect.fn("ACP.resolve")(function* (id: string) { + const session = yield* sessions.get(id); + if (Option.isSome(session)) { + const main = yield* threads.main(session.value.id); + if (Option.isSome(main)) return { session: session.value, threadId: threadId(main.value.id) }; + } + const thread = yield* threads.get(id); + if (Option.isSome(thread)) { + const owner = yield* sessions.get(thread.value.sessionId); + if (Option.isSome(owner)) return { session: owner.value, threadId: threadId(thread.value.id) }; + } + return yield* new SessionStore.SessionNotFoundError({ sessionId: id }); + }); + + const attach = Effect.fn("ACP.attach")(function* (id: string) { + const { session, threadId } = yield* resolve(id); + const thread = yield* Session.attach({ sessionId: session.id, threadId }); + return { thread, hostDir: Option.getOrUndefined(session.hostDir) }; }); return (client: Agent.Client): Agent.Handlers => { @@ -107,7 +127,7 @@ export const make = Effect.gen(function* () { agentCapabilities: { loadSession: true, promptCapabilities: { embeddedContext: true, image: true }, - sessionCapabilities: { list: {} }, + sessionCapabilities: { list: {}, fork: {} }, }, }), @@ -123,12 +143,10 @@ export const make = Effect.gen(function* () { loadSession: ({ sessionId: id }) => run( Effect.gen(function* () { - // An ACP session is a CodeWork session's main thread. - const main = yield* Session.attach({ sessionId: sessionId(id) }); - const row = yield* found(id); - const hostDir = Option.getOrUndefined(row.hostDir); - const current = yield* Session.configuration(main.id); - for (const entry of yield* main.history()) { + const { thread, hostDir } = yield* attach(id); + const current = yield* Session.configuration(thread.id); + // A fork replays its whole line, the part it inherits included. + for (const entry of yield* thread.history()) { for (const update of Feed.replay(entry)) { yield* client.sessionUpdate({ sessionId: id, update }); } @@ -140,53 +158,88 @@ export const make = Effect.gen(function* () { listSessions: ({ cwd, cursor }) => run( Effect.gen(function* () { - const rows = (yield* sessions.list()) - .filter((row) => cwd == null || Option.getOrUndefined(row.hostDir) === cwd) - .sort((a, b) => DateTime.Order(b.updatedAt ?? b.createdAt, a.updatedAt ?? a.createdAt)); - const titles = new Map(); - for (const thread of yield* threads.list()) { - if (thread.originKind === "main" && Option.isSome(thread.title)) - titles.set(thread.sessionId, thread.title.value); - } + const owners = new Map((yield* sessions.list()).map((row) => [row.id, row])); + const all = yield* threads.list(); + const titles = new Map(all.map((thread) => [thread.id, Option.getOrUndefined(thread.title)])); + const rows = all + .flatMap((thread) => { + const session = owners.get(thread.sessionId); + return session === undefined ? [] : [{ thread, session }]; + }) + .filter(({ session }) => cwd == null || Option.getOrUndefined(session.hostDir) === cwd) + .sort((a, b) => + DateTime.Order( + b.thread.updatedAt ?? b.thread.createdAt, + a.thread.updatedAt ?? a.thread.createdAt, + ), + ); const offset = cursor == null ? 0 : Number(cursor); if (!Number.isSafeInteger(offset) || offset < 0) { return yield* Agent.RequestError.invalidParams(`Invalid cursor: ${cursor}`); } const next = offset + PAGE_SIZE; return { - sessions: rows.slice(offset, next).map((row) => ({ - sessionId: row.id, - cwd: Option.getOrElse(row.hostDir, () => row.directory), - title: titles.get(row.id) ?? null, - updatedAt: DateTime.formatIso(row.updatedAt ?? row.createdAt), + sessions: rows.slice(offset, next).map(({ thread, session }) => ({ + sessionId: acpId(thread), + cwd: Option.getOrElse(session.hostDir, () => session.directory), + // A fork is untitled until its own first prompt; it reads as its source until then. + title: + titles.get(thread.id) ?? + Option.match(thread.originThreadId, { + onNone: () => undefined, + onSome: (origin) => titles.get(origin), + }) ?? + null, + updatedAt: DateTime.formatIso(thread.updatedAt ?? thread.createdAt), })), ...(next < rows.length ? { nextCursor: String(next) } : {}), }; }), ), + forkSession: ({ sessionId: id }) => + run( + Effect.gen(function* () { + const { thread, hostDir } = yield* attach(id); + // ACP forks the conversation as it stands: at the last entry that is settled. + const last = (yield* thread.history()).findLast( + ({ entry }) => + (entry.type === "user" || entry.type === "assistant") && entry.state === "committed", + ); + if (last === undefined) { + return yield* Agent.RequestError.invalidRequest( + "Nothing to fork yet: the session has no messages", + ); + } + const forked = yield* thread.fork({ entryId: last.entry.id }); + const current = yield* Session.configuration(forked.thread.id); + return { sessionId: forked.thread.id, configOptions: yield* Config.options(current, hostDir) }; + }), + ), + setConfigOption: (request) => run( Effect.gen(function* () { - const row = yield* found(request.sessionId); - const hostDir = Option.getOrUndefined(row.hostDir); + const { session, threadId } = yield* resolve(request.sessionId); + const hostDir = Option.getOrUndefined(session.hostDir); const value = String(request.value); + let runtime: Session.RuntimeInput; if (request.configId === Config.MODEL) { const model = Option.getOrUndefined(Config.parseModel(value)); if (model === undefined || !(yield* Config.known(model, hostDir))) { return yield* Agent.RequestError.invalidParams(`Unknown model: ${value}`); } - yield* Session.attach({ sessionId: row.id, model }); + runtime = { model }; } else if (request.configId === Config.THOUGHT_LEVEL) { if (!Config.isThinkingLevel(value)) { return yield* Agent.RequestError.invalidParams(`Unknown thinking level: ${value}`); } - yield* Session.attach({ sessionId: row.id, thinkingLevel: value }); + runtime = { thinkingLevel: value }; } else { return yield* Agent.RequestError.invalidParams(`Unknown config option: ${request.configId}`); } - const main = yield* Session.attach({ sessionId: row.id }); - return { configOptions: yield* Config.options(yield* Session.configuration(main.id), hostDir) }; + const thread = yield* Session.attach({ sessionId: session.id, threadId, ...runtime }); + return { configOptions: yield* Config.options(yield* Session.configuration(thread.id), hostDir) }; }), ), @@ -194,11 +247,7 @@ export const make = Effect.gen(function* () { run( Effect.gen(function* () { const parts = yield* promptParts(prompt); - const session = Option.getOrUndefined(yield* Session.get(sessionId(id))); - if (session === undefined) { - return yield* new SessionStore.SessionNotFoundError({ sessionId: sessionId(id) }); - } - const handle = session.main; + const { thread: handle } = yield* attach(id); if (running.has(id)) { return yield* Agent.RequestError.invalidRequest("A prompt is already running for this session"); } @@ -245,7 +294,12 @@ export const make = Effect.gen(function* () { }).pipe(Effect.scoped), ), - cancel: ({ sessionId: id }) => control.interruptSession(sessionId(id), { reason: "user" }).pipe(Effect.asVoid), + cancel: ({ sessionId: id }) => + resolve(id).pipe( + Effect.flatMap((found) => control.interrupt(found.threadId, { reason: "user" })), + Effect.ignore, + Effect.provide(context), + ), }; }; }); diff --git a/packages/codework/src/cli/cmd/cmd.ts b/packages/codework/src/cli/cmd/cmd.ts index 6add7f14..f7140d43 100644 --- a/packages/codework/src/cli/cmd/cmd.ts +++ b/packages/codework/src/cli/cmd/cmd.ts @@ -43,6 +43,12 @@ const ServerAddress = { ), }; +/** For commands that only talk to a server that is already running. */ +const RunningServer = Flag.String("server").pipe( + Flag.withDescription("Base URL of the running codework server"), + Flag.withDefault("http://127.0.0.1:7433"), +); + const JsonFlag = Flag.Boolean("json").pipe( Flag.withDescription("Print machine-readable output"), Flag.withDefault(false), @@ -254,10 +260,7 @@ export const Cmd = Spec.make("codework", { Flag.withDescription("Clear the anchor, leaving the session with no host directory"), Flag.withDefault(false), ), - server: Flag.String("server").pipe( - Flag.withDescription("Base URL of the running codework server"), - Flag.withDefault("http://127.0.0.1:7433"), - ), + server: RunningServer, }, examples: [ { @@ -274,6 +277,80 @@ export const Cmd = Spec.make("codework", { }, ], }), + Spec.make("relink", { + description: "Move where a session's work, or one thread's, happens", + params: { + session: Argument.String("session-id").pipe(Argument.withDescription("The session to move")), + thread: Flag.String("thread").pipe( + Flag.withDescription( + "Move only this thread: a thread ID, or main; omitted moves the session's default", + ), + Flag.optional, + ), + directory: Flag.String("directory").pipe( + Flag.withAlias("C"), + Flag.withDescription("Directory inside the target space to land in"), + Flag.optional, + ), + sandboxId: Flag.String("sandbox-id").pipe( + Flag.withDescription("Sandbox instance to move to (default: local)"), + Flag.optional, + ), + json: JsonFlag, + server: RunningServer, + }, + examples: [ + { + command: "codework session relink ses_01h9 -C ~/work/api", + description: "Move the session to a local checkout", + }, + { + command: "codework session relink ses_01h9 --thread thr_01ja --sandbox-id sbx_01k2", + description: "Run one thread in a sandbox, leaving the others where they are", + }, + ], + }), + ], + }), + Spec.make("thread", { + description: "Manage a session's threads", + commands: [ + Spec.make("list", { + description: "List a session's threads, newest first", + params: { + session: Argument.String("session-id").pipe(Argument.withDescription("The session")), + json: JsonFlag, + server: RunningServer, + }, + examples: [{ command: "codework thread list ses_01h9", description: "List the session's threads" }], + }), + Spec.make("fork", { + description: "Start a new thread from a committed entry of a thread's history", + params: { + session: Argument.String("session-id").pipe(Argument.withDescription("The session")), + thread: Flag.String("thread").pipe( + Flag.withDescription("Thread to fork: a thread ID, or main (default)"), + Flag.optional, + ), + at: Flag.String("at").pipe(Flag.withDescription("Keep history through this entry"), Flag.optional), + before: Flag.String("before").pipe( + Flag.withDescription("Keep history up to this user entry, and print its text to edit"), + Flag.optional, + ), + json: JsonFlag, + server: RunningServer, + }, + examples: [ + { + command: "codework thread fork ses_01h9 --at 01jb", + description: "Continue the main thread's history through an entry in a new thread", + }, + { + command: "codework thread fork ses_01h9 --thread thr_01ja --before 01jc", + description: "Branch just before a prompt, to send it again differently", + }, + ], + }), ], }), Spec.make("plugin", { @@ -371,10 +448,7 @@ export const Cmd = Spec.make("codework", { Spec.make("reload", { description: "Re-import configured plugins in a running server", params: { - server: Flag.String("server").pipe( - Flag.withDescription("Base URL of the running codework server"), - Flag.withDefault("http://127.0.0.1:7433"), - ), + server: RunningServer, }, examples: [ { diff --git a/packages/codework/src/cli/cmd/handlers/run.ts b/packages/codework/src/cli/cmd/handlers/run.ts index 78afdd83..09126a1d 100644 --- a/packages/codework/src/cli/cmd/handlers/run.ts +++ b/packages/codework/src/cli/cmd/handlers/run.ts @@ -14,6 +14,7 @@ import { writeError, writeOut, } from "../../output.ts"; +import { threadFlag } from "../../thread.ts"; import { Cmd } from "../cmd.ts"; interface RenderState { @@ -106,13 +107,7 @@ export default Runtime.handler( if (Option.isSome(thread) && Option.isNone(session)) { return yield* new InvalidInputError({ message: "--thread continues a thread of --session" }); } - if ( - Option.isSome(thread) && - thread.value !== Session.ThreadSchema.MAIN && - !Schema.is(Session.ThreadSchema.ID)(thread.value) - ) { - return yield* new InvalidInputError({ message: "--thread takes a thread ID (thr_…) or main" }); - } + const threadId = yield* threadFlag(thread); if (Option.isSome(provider) !== Option.isSome(model)) { return yield* new InvalidInputError({ message: "--provider and --model must be provided together" }); } @@ -151,11 +146,6 @@ export default Runtime.handler( : { model: { provider: provider.value, id: model.value } }), ...(Option.isNone(thinking) ? {} : { thinkingLevel: thinking.value }), }; - // `main` names the session's main thread; anything else is a thread ID. - const threadId = - Option.isNone(thread) || thread.value === Session.ThreadSchema.MAIN - ? undefined - : Session.ThreadSchema.ID.make(thread.value); const remote = Effect.gen(function* () { const rpc = yield* Client.make; const info = Option.isSome(session) diff --git a/packages/codework/src/cli/cmd/handlers/session/relink.ts b/packages/codework/src/cli/cmd/handlers/session/relink.ts new file mode 100644 index 00000000..90704839 --- /dev/null +++ b/packages/codework/src/cli/cmd/handlers/session/relink.ts @@ -0,0 +1,34 @@ +import { Sandbox, Session } from "@codeworksh/harness/effect"; +import { Effect, Option } from "effect"; +import { Runtime } from "../../../../framework/runtime.ts"; +import { Client } from "../../../../server/client.ts"; +import { ThreadInfo } from "../../../../server/contract.ts"; +import { reportFailure } from "../../../error.ts"; +import { writeJson, writeOut } from "../../../output.ts"; +import { threadFlag } from "../../../thread.ts"; +import { Cmd } from "../../cmd.ts"; + +export default Runtime.handler( + Cmd.commands.session.commands.relink, + Effect.fn("CLI.session.relink")(function* ({ session, thread, directory, sandboxId, json, server }) { + const program = Effect.gen(function* () { + const threadId = yield* threadFlag(thread); + const rpc = yield* Client.make; + const info = yield* rpc["session.relink"]({ + sessionId: Session.SessionSchema.ID.make(session), + ...(threadId === undefined ? {} : { threadId }), + ...(Option.isNone(sandboxId) ? {} : { sandbox: { id: Sandbox.SandboxInstance.ID.make(sandboxId.value) } }), + ...(Option.isNone(directory) ? {} : { directory: directory.value }), + }); + if (json) return yield* writeJson(ThreadInfo, info); + // Without `--thread` the session's default moved; a thread with its own placement stays put. + yield* writeOut( + threadId === undefined + ? `Moved ${info.session.id} to ${info.session.directory}\n` + : `Moved thread ${info.id} of ${info.session.id} to ${info.placement?.directory ?? info.session.directory}\n`, + ); + }); + + return yield* program.pipe(Effect.provide(Client.layer(server)), Effect.scoped, Effect.catch(reportFailure)); + }), +); diff --git a/packages/codework/src/cli/cmd/handlers/thread/fork.ts b/packages/codework/src/cli/cmd/handlers/thread/fork.ts new file mode 100644 index 00000000..b3d3b3ee --- /dev/null +++ b/packages/codework/src/cli/cmd/handlers/thread/fork.ts @@ -0,0 +1,39 @@ +import { Session } from "@codeworksh/harness/effect"; +import { Effect, Option, Schema } from "effect"; +import { Runtime } from "../../../../framework/runtime.ts"; +import { Client } from "../../../../server/client.ts"; +import { ThreadInfo } from "../../../../server/contract.ts"; +import { InvalidInputError, reportFailure } from "../../../error.ts"; +import { writeJson, writeOut } from "../../../output.ts"; +import { threadFlag } from "../../../thread.ts"; +import { Cmd } from "../../cmd.ts"; + +const Forked = Schema.Struct({ thread: ThreadInfo, text: Schema.optional(Schema.String) }); + +export default Runtime.handler( + Cmd.commands.thread.commands.fork, + Effect.fn("CLI.thread.fork")(function* ({ session, thread, at, before, json, server }) { + const program = Effect.gen(function* () { + const point = Option.isSome(at) + ? Option.isNone(before) + ? { entryId: at.value } + : undefined + : Option.map(before, (entryId) => ({ entryId, mode: "before" as const })).pipe(Option.getOrUndefined); + if (point === undefined) { + return yield* new InvalidInputError({ message: "Pass exactly one of --at or --before" }); + } + const threadId = yield* threadFlag(thread); + const rpc = yield* Client.make; + const forked = yield* rpc["thread.fork"]({ + sessionId: Session.SessionSchema.ID.make(session), + ...(threadId === undefined ? {} : { threadId }), + ...point, + }); + if (json) return yield* writeJson(Forked, forked); + yield* writeOut(`${forked.thread.id}\n`); + if (forked.text !== undefined) yield* writeOut(`\n${forked.text}\n`); + }); + + return yield* program.pipe(Effect.provide(Client.layer(server)), Effect.scoped, Effect.catch(reportFailure)); + }), +); diff --git a/packages/codework/src/cli/cmd/handlers/thread/list.ts b/packages/codework/src/cli/cmd/handlers/thread/list.ts new file mode 100644 index 00000000..fef41555 --- /dev/null +++ b/packages/codework/src/cli/cmd/handlers/thread/list.ts @@ -0,0 +1,49 @@ +import { Session } from "@codeworksh/harness/effect"; +import { Effect, Schema } from "effect"; +import { Runtime } from "../../../../framework/runtime.ts"; +import { Client } from "../../../../server/client.ts"; +import { type ThreadInfo, ThreadInfo as ThreadInfoSchema } from "../../../../server/contract.ts"; +import { reportFailure } from "../../../error.ts"; +import { writeJson, writeOut } from "../../../output.ts"; +import { Cmd } from "../../cmd.ts"; + +const origin = (info: ThreadInfo): string => { + switch (info.origin.kind) { + case "main": + return "main"; + case "fork": + return `fork of ${info.origin.threadId}`; + case "subagent": + return `subagent of ${info.origin.threadId}`; + } +}; + +const cost = (info: ThreadInfo) => `$${info.usage.cost.toFixed(4)}`; + +export default Runtime.handler( + Cmd.commands.thread.commands.list, + Effect.fn("CLI.thread.list")(function* ({ session, json, server }) { + const program = Effect.gen(function* () { + const rpc = yield* Client.make; + const threads = yield* rpc["thread.list"]({ sessionId: Session.SessionSchema.ID.make(session) }); + if (json) return yield* writeJson(Schema.Array(ThreadInfoSchema), threads); + if (threads.length === 0) return yield* writeOut(`No threads in ${session}.\n`); + const rows = threads.map((info) => [ + info.id, + origin(info), + info.model === undefined ? "-" : `${info.model.provider}/${info.model.id}`, + `${info.usage.input + info.usage.output} tok ${cost(info)}`, + info.title ?? "(untitled)", + ]); + const widths = rows[0]?.map((_, column) => Math.max(...rows.map((row) => row[column]?.length ?? 0))) ?? []; + for (const row of rows) { + const last = row.length - 1; + yield* writeOut( + `${row.map((cell, column) => (column === last ? cell : cell.padEnd(widths[column] ?? 0))).join(" ")}\n`, + ); + } + }); + + return yield* program.pipe(Effect.provide(Client.layer(server)), Effect.scoped, Effect.catch(reportFailure)); + }), +); diff --git a/packages/codework/src/cli/output.ts b/packages/codework/src/cli/output.ts index 6afb5b71..78c94042 100644 --- a/packages/codework/src/cli/output.ts +++ b/packages/codework/src/cli/output.ts @@ -1,5 +1,5 @@ import type { Message } from "@codeworksh/aikit"; -import { Effect } from "effect"; +import { Effect, Schema } from "effect"; export interface UsageSummary { readonly turns: number; @@ -79,5 +79,11 @@ export const usage = (summary: UsageSummary, columns?: number): string => { }; export const writeOut = (value: string) => Effect.sync(() => void process.stdout.write(value)); +/** A value in its wire form, as indented JSON. */ +export const writeJson = (schema: Schema.Codec, value: A) => + Schema.encodeEffect(schema)(value).pipe( + Effect.orDie, + Effect.flatMap((encoded) => writeOut(`${JSON.stringify(encoded, null, "\t")}\n`)), + ); export const writeError = (value: string) => Effect.sync(() => void process.stderr.write(value)); export const terminalColumns = () => (process.stderr.isTTY ? (process.stderr.columns ?? 72) : 72); diff --git a/packages/codework/src/cli/thread.ts b/packages/codework/src/cli/thread.ts new file mode 100644 index 00000000..733cb36b --- /dev/null +++ b/packages/codework/src/cli/thread.ts @@ -0,0 +1,14 @@ +import { Session } from "@codeworksh/harness/effect"; +import { Effect, Option, Schema } from "effect"; +import { InvalidInputError } from "./error.ts"; + +const isThreadId = Schema.is(Session.ThreadSchema.ID); + +/** A `--thread` value; `main`, like no flag at all, is the session's main thread and reads as absent. */ +export const threadFlag = Effect.fn("CLI.threadFlag")(function* (flag: Option.Option) { + if (Option.isNone(flag) || flag.value === Session.ThreadSchema.MAIN) return undefined; + if (!isThreadId(flag.value)) { + return yield* new InvalidInputError({ message: "--thread takes a thread ID (thr_…) or main" }); + } + return Session.ThreadSchema.ID.make(flag.value); +}); diff --git a/packages/codework/src/index.ts b/packages/codework/src/index.ts index 00ecfae5..42ce075c 100644 --- a/packages/codework/src/index.ts +++ b/packages/codework/src/index.ts @@ -27,6 +27,11 @@ const Handlers = Runtime.handlers(Cmd, { }, session: { link: () => import("./cli/cmd/handlers/session/link.ts"), + relink: () => import("./cli/cmd/handlers/session/relink.ts"), + }, + thread: { + list: () => import("./cli/cmd/handlers/thread/list.ts"), + fork: () => import("./cli/cmd/handlers/thread/fork.ts"), }, acp: () => import("./cli/cmd/handlers/acp.ts"), plugin: { diff --git a/packages/codework/src/server/client.ts b/packages/codework/src/server/client.ts index 64a473fa..43948386 100644 --- a/packages/codework/src/server/client.ts +++ b/packages/codework/src/server/client.ts @@ -1,6 +1,6 @@ import { EventList, type EventSchema, optional, Session } from "@codeworksh/harness/effect"; import { NodeSocket } from "@effect/platform-node"; -import { Deferred, Effect, Layer, Predicate, Schema, Stream } from "effect"; +import { Deferred, Effect, Layer, Schema, Stream } from "effect"; import { RpcClient, RpcSerialization } from "effect/rpc"; import { Contract } from "./contract.ts"; import { Envelope } from "./envelope.ts"; @@ -61,7 +61,7 @@ export const run = Effect.fn("Client.run")(function* ( return undefined; }; - const consume = rpc["event.subscribe"]({}).pipe( + const consume = rpc["event.subscribe"]({ threadId: input.threadId }).pipe( Stream.mapEffect( Effect.fnUntraced(function* (envelope) { if (envelope.type === Envelope.Connected.type) { @@ -71,12 +71,7 @@ export const run = Effect.fn("Client.run")(function* ( const event = yield* Envelope.decode(envelope).pipe( Effect.catchTag("UnknownEventTypeError", () => Effect.void), ); - if ( - event === undefined || - !Predicate.hasProperty(event.data, "threadId") || - event.data.threadId !== input.threadId - ) - return; + if (event === undefined) return; if (Schema.is(EventList.PromptAdmitted)(event) && event.data.messageId === id) admitted = true; if (Schema.is(EventList.Prompted)(event) && event.data.messageId === id) { promoted = true; diff --git a/packages/codework/src/server/contract.ts b/packages/codework/src/server/contract.ts index 25f0360b..af858eb8 100644 --- a/packages/codework/src/server/contract.ts +++ b/packages/codework/src/server/contract.ts @@ -64,6 +64,17 @@ export const ThreadOrigin = Schema.Union([ }), ]); +/** Billed usage of a thread's own entries; what it inherits through a fork point counts for its source. */ +export const ThreadUsage = Schema.Struct({ + /** Total cost in the provider's currency units. */ + cost: Schema.Finite, + input: Schema.Int, + output: Schema.Int, + cacheRead: Schema.Int, + cacheWrite: Schema.Int, +}); +export type ThreadUsage = typeof ThreadUsage.Type; + /** One linear transcript of a session, with the session embedded. */ export const ThreadInfo = Schema.Struct({ id: ThreadSchema.ID, @@ -80,6 +91,7 @@ export const ThreadInfo = Schema.Struct({ placement: optional(Schema.Struct({ spaceId: Schema.String, directory: Session.AbsolutePath })), /** Its unfinished run was cut off by restarts too often to resume on its own; the next prompt runs it. */ parked: optional(Schema.Boolean), + usage: ThreadUsage, session: SessionInfo, }); export type ThreadInfo = typeof ThreadInfo.Type; @@ -333,6 +345,8 @@ export const Api = RpcGroup.make( /** * Moves where the work happens. Without `threadId`, the session's default space and directory, * which every thread without its own placement follows; with it, that thread's placement only. + * Answers with the addressed thread (`main` when absent): its `placement` and embedded session + * show where it now runs. */ Rpc.make("session.relink", { payload: { @@ -341,7 +355,7 @@ export const Api = RpcGroup.make( sandbox: optional(SandboxRef), directory: optional(Schema.String), }, - success: SessionInfo, + success: ThreadInfo, error: Schema.Union([SessionErrors, SandboxErrors, LocationErrors]), }), /** Stops every thread, then removes the session with its log. `deleted` is false when it did not exist. */ @@ -362,9 +376,15 @@ export const Api = RpcGroup.make( * Ephemeral events (text and tool progress deltas) are never stored, so they are not here; * `event.subscribe` carries them live. To resume, pass the higher of the last event's * `durable.seq` and the last marker's `seq`: the marker can sit past the last event sent. + * With `threadId`, only that thread's events; the marker still names the session's head. */ Rpc.make("session.log", { - payload: { sessionId: Session.SessionSchema.ID, after: optional(Schema.Int), follow: optional(Schema.Boolean) }, + payload: { + sessionId: Session.SessionSchema.ID, + threadId: optional(ThreadSchema.ID), + after: optional(Schema.Int), + follow: optional(Schema.Boolean), + }, success: Schema.Union([EventEnvelope, LogSynced]), error: Schema.Union([SessionStore.SessionNotFoundError, EncodingError]), stream: true, @@ -502,8 +522,12 @@ export const Api = RpcGroup.make( success: Schema.Void, error: SandboxErrors, }), + /** + * Every event the server publishes, live, after a `server.connected` frame. With `threadId`, + * only the events naming that thread; the frame still comes first. + */ Rpc.make("event.subscribe", { - payload: {}, + payload: { threadId: optional(ThreadSchema.ID) }, success: EventEnvelope, error: Schema.Union([Event.SubscriptionOverflowError, EncodingError]), stream: true, diff --git a/packages/codework/src/server/envelope.ts b/packages/codework/src/server/envelope.ts index 71c54ef9..fb71c96b 100644 --- a/packages/codework/src/server/envelope.ts +++ b/packages/codework/src/server/envelope.ts @@ -1,5 +1,5 @@ import { EventList, EventSchema, optional } from "@codeworksh/harness/effect"; -import { Effect, Schema } from "effect"; +import { Effect, Predicate, Schema } from "effect"; /** * The wire form of an `EventSchema.Payload`. `data` is carried in its encoded @@ -16,6 +16,12 @@ export const EventEnvelope = Schema.Struct({ }); export type EventEnvelope = typeof EventEnvelope.Type; +/** Whether an event belongs to a thread: every thread-scoped event names its `threadId`. */ +export const ofThread = + (threadId: string) => + (event: { readonly data: unknown }): boolean => + Predicate.hasProperty(event.data, "threadId") && event.data.threadId === threadId; + export class UnknownEventTypeError extends Schema.TaggedError()("UnknownEventTypeError", { type: Schema.String, }) {} diff --git a/packages/codework/src/server/handlers.ts b/packages/codework/src/server/handlers.ts index d885c655..fbd334c7 100644 --- a/packages/codework/src/server/handlers.ts +++ b/packages/codework/src/server/handlers.ts @@ -64,6 +64,7 @@ const toThreadInfo = (info: Session.ThreadInfo): ThreadInfo => ({ ...(info.thinkingLevel === undefined ? {} : { thinkingLevel: info.thinkingLevel }), ...(info.placement === undefined ? {} : { placement: info.placement }), ...(info.parked ? { parked: true } : {}), + usage: info.usage, session: toSessionInfo(info.session), }); @@ -188,7 +189,8 @@ export const layer = Contract.Api.toLayer( ...(selected === undefined ? {} : { sandbox: selected }), ...(directory === undefined ? {} : { directory }), }).pipe(Effect.onError(() => releaseOnFailure(selection))); - return toSessionInfo(yield* handle.info); + const thread = yield* handle.thread(threadId ?? ThreadSchema.MAIN); + return toThreadInfo(yield* thread.info); }), "session.delete": Effect.fnUntraced(function* ({ sessionId }) { return { deleted: yield* Session.remove(sessionId) }; @@ -198,7 +200,7 @@ export const layer = Contract.Api.toLayer( // uses `thread.wait` when it needs cleanup to have finished. return { interrupted: yield* control.interruptSession(sessionId, { reason: "user" }) }; }), - "session.log": ({ sessionId, after, follow }) => + "session.log": ({ sessionId, threadId, after, follow }) => Stream.unwrap( Effect.gen(function* () { if (Option.isNone(yield* sessions.get(sessionId))) { @@ -210,7 +212,13 @@ export const layer = Contract.Api.toLayer( follow: follow ?? false, ...(after === undefined ? {} : { after }), }) - .pipe(Stream.mapEffect(toLogItem(registry.get))); + .pipe( + Stream.filter( + (item) => + threadId === undefined || Event.isSynced(item) || Envelope.ofThread(threadId)(item), + ), + Stream.mapEffect(toLogItem(registry.get)), + ); }), ), "thread.list": Effect.fnUntraced(function* ({ sessionId }) { @@ -331,12 +339,14 @@ export const layer = Contract.Api.toLayer( // Acquiring the feed subscription is the readiness barrier: `server.connected` // is only emitted once this client is registered, so a prompt admitted after // it cannot land in the gap. - "event.subscribe": () => + "event.subscribe": ({ threadId }) => Stream.unwrap( feed.subscribe.pipe( Effect.map((events) => Stream.make({ id: EventSchema.ID.create(), type: Envelope.Connected.type, data: {} }).pipe( - Stream.concat(events), + Stream.concat( + threadId === undefined ? events : events.pipe(Stream.filter(Envelope.ofThread(threadId))), + ), ), ), ), diff --git a/packages/codework/test/__artifacts__/acp.fork.json b/packages/codework/test/__artifacts__/acp.fork.json new file mode 100644 index 00000000..0a48193c --- /dev/null +++ b/packages/codework/test/__artifacts__/acp.fork.json @@ -0,0 +1,27 @@ +{ + "forkEmpty": { + "code": -32600, + "message": "Nothing to fork yet: the session has no messages" + }, + "mainReply": "reply 1", + "forkReply": "reply 2", + "list": [ + { + "sessionId": "", + "title": "branch" + }, + { + "sessionId": "
", + "title": "hello" + } + ], + "loadFork": { + "user": "hellobranch", + "agent": "reply 1reply 2" + }, + "loadMain": { + "user": "hello", + "agent": "reply 1" + }, + "cancelIdleFork": true +} diff --git a/packages/codework/test/__artifacts__/acp.json b/packages/codework/test/__artifacts__/acp.json index e3345ce3..ee86335c 100644 --- a/packages/codework/test/__artifacts__/acp.json +++ b/packages/codework/test/__artifacts__/acp.json @@ -11,7 +11,8 @@ "image": true }, "sessionCapabilities": { - "list": {} + "list": {}, + "fork": {} } } }, diff --git a/packages/codework/test/__artifacts__/server.cli-threads.json b/packages/codework/test/__artifacts__/server.cli-threads.json new file mode 100644 index 00000000..ec493d82 --- /dev/null +++ b/packages/codework/test/__artifacts__/server.cli-threads.json @@ -0,0 +1,73 @@ +{ + "forkAt": { + "status": 0, + "stdout": "\n" + }, + "forkBefore": { + "status": 0, + "stdout": "\n\nbranch\n" + }, + "relink": { + "status": 0, + "stdout": "Moved thread of to /clone-b/packages/x\n" + }, + "list": { + "status": 0, + "stdout": " fork of
openai/gpt-6-luna 0 tok $0.0000 (untitled)\n fork of
openai/gpt-6-luna 2 tok $0.0000 branch\n
main openai/gpt-6-luna 2 tok $0.0000 hello\n" + }, + "listJson": [ + { + "id": "", + "origin": "fork", + "placement": "/clone-b/packages/x", + "usage": { + "cost": 0, + "input": 1, + "output": 1, + "cacheRead": 0, + "cacheWrite": 0 + } + }, + { + "id": "", + "origin": "fork", + "placement": null, + "usage": { + "cost": 0, + "input": 0, + "output": 0, + "cacheRead": 0, + "cacheWrite": 0 + } + }, + { + "id": "
", + "origin": "main", + "placement": null, + "usage": { + "cost": 0, + "input": 1, + "output": 1, + "cacheRead": 0, + "cacheWrite": 0 + } + } + ], + "errors": { + "bothPoints": { + "status": 1, + "stdout": "", + "stderr": "error: Pass exactly one of --at or --before\n" + }, + "badThread": { + "status": 1, + "stdout": "", + "stderr": "error: --thread takes a thread ID (thr_…) or main\n" + }, + "unknownEntry": { + "status": 1, + "stdout": "", + "stderr": "error: cannot fork
at missing-entry: entry not found\n" + } + } +} diff --git a/packages/codework/test/__artifacts__/server.threads.json b/packages/codework/test/__artifacts__/server.threads.json new file mode 100644 index 00000000..3903a972 --- /dev/null +++ b/packages/codework/test/__artifacts__/server.threads.json @@ -0,0 +1,115 @@ +{ + "usage": { + "fork": { + "cost": 0, + "input": 1, + "output": 1, + "cacheRead": 0, + "cacheWrite": 0 + }, + "main": { + "cost": 0, + "input": 2, + "output": 2, + "cacheRead": 0, + "cacheWrite": 0 + } + }, + "live": [ + { + "type": "server.connected", + "thread": "" + }, + { + "type": "session.prompt.admitted", + "thread": "" + }, + { + "type": "session.execution.started", + "thread": "" + }, + { + "type": "session.prompt.promoted", + "thread": "" + }, + { + "type": "session.turn.started", + "thread": "" + }, + { + "type": "session.llm.started", + "thread": "" + }, + { + "type": "session.llm.text.start", + "thread": "" + }, + { + "type": "session.llm.text.delta", + "thread": "" + }, + { + "type": "session.llm.text.end", + "thread": "" + }, + { + "type": "session.llm.ended", + "thread": "" + }, + { + "type": "session.turn.ended", + "thread": "" + }, + { + "type": "session.execution.succeeded", + "thread": "" + } + ], + "forkLog": [ + { + "type": "thread.forked", + "thread": "" + }, + { + "type": "session.prompt.admitted", + "thread": "" + }, + { + "type": "session.prompt.promoted", + "thread": "" + }, + { + "type": "session.llm.started", + "thread": "" + }, + { + "type": "session.llm.ended", + "thread": "" + }, + { + "type": "session.turn.ended", + "thread": "" + }, + { + "type": "log.synced" + } + ], + "sessionLogThreads": [ + "", + "
" + ], + "relink": { + "thread": { + "returned": "", + "placement": "/clone-b/packages/x", + "sessionDirectory": "/clone-a/packages/x" + }, + "mainAfterThreadMove": { + "directory": "/clone-a/packages/x" + }, + "session": { + "returned": "
", + "directory": "/clone-b/packages/x" + } + } +} diff --git a/packages/codework/test/acp.test.ts b/packages/codework/test/acp.test.ts index fdc67482..73900979 100644 --- a/packages/codework/test/acp.test.ts +++ b/packages/codework/test/acp.test.ts @@ -6,6 +6,8 @@ import { type Cause, Effect, Exit, Fiber, Option, Queue, type Scope, Stream } fr import * as EffectCause from "effect/Cause"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; import { tmpdir } from "node:os"; import { crc32, deflateSync } from "node:zlib"; import { dirname, join } from "node:path"; @@ -121,6 +123,7 @@ const connect = (handle: ChildProcessSpawner.ChildProcessHandle, updates: Queue. createSession: request("session/new"), loadSession: request("session/load"), listSessions: request("session/list"), + forkSession: request("session/fork"), setSessionConfigOption: request("session/set_config_option"), prompt: request("session/prompt"), cancel: (params: Acp.CancelNotification) => @@ -201,6 +204,38 @@ const solidPng = ([r, g, b]: readonly [number, number, number], size = 64): stri ]).toString("base64"); }; +/** + * A chat-completions endpoint that answers every request with `reply ` and one token each way, + * for cases that need a conversation but not a real model. Its base URL closes with the scope. + */ +const fakeModel = Effect.acquireRelease( + Effect.callback<{ readonly url: string; readonly close: () => void }>((resume) => { + let count = 0; + const server = createServer((request, response) => { + request.resume(); + request.on("end", () => { + count += 1; + const chunk = (body: Record) => + `data: ${JSON.stringify({ id: `c${count}`, ...body })}\n\n`; + response.writeHead(200, { "content-type": "text/event-stream" }); + response.end( + chunk({ choices: [{ index: 0, delta: { role: "assistant", content: `reply ${count}` } }] }) + + chunk({ + choices: [{ index: 0, delta: {}, finish_reason: "stop" }], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, + }) + + "data: [DONE]\n\n", + ); + }); + }); + server.listen(0, "127.0.0.1", () => { + const { port } = server.address() as AddressInfo; + resume(Effect.succeed({ url: `http://127.0.0.1:${port}/v1`, close: () => server.close() })); + }); + }), + (endpoint) => Effect.sync(endpoint.close), +); + const artifact = (record: Record) => `${JSON.stringify(record, null, "\t")}\n`; describe("codework acp", () => { @@ -269,6 +304,68 @@ describe("codework acp", () => { ); }); + it("reaches every thread of a session, a fork included, as a session of its own", () => { + const { home, project } = workspace(); + return run( + Effect.gen(function* () { + const endpoint = yield* fakeModel; + writeSettings(join(home, "settings.jsonc"), { + model: { provider: "fake", id: "echo" }, + models: [newModel({ id: "fake", name: "Fake" }, "echo", { baseUrl: endpoint.url })], + }); + yield* withAgent( + home, + (acp, updates) => + Effect.gen(function* () { + const prompt = (sessionId: string, value: string) => + acp.agent + .prompt({ sessionId, prompt: [{ type: "text", text: value }] }) + .pipe(Effect.andThen(Queue.clear(updates))); + const load = (sessionId: string) => + acp.agent.loadSession({ sessionId, cwd: project, mcpServers: [] }).pipe( + Effect.andThen(Queue.clear(updates)), + Effect.map((replayed) => ({ + user: text(replayed, "user_message_chunk"), + agent: text(replayed, "agent_message_chunk"), + })), + ); + const fork = (sessionId: string) => + acp.agent.forkSession({ sessionId, cwd: project, mcpServers: [] }); + + const { sessionId } = yield* acp.agent.createSession({ cwd: project, mcpServers: [] }); + const forkEmpty = yield* settle(fork(sessionId)); + const mainReply = text(yield* prompt(sessionId, "hello"), "agent_message_chunk"); + const forked = yield* fork(sessionId); + const forkReply = text(yield* prompt(forked.sessionId, "branch"), "agent_message_chunk"); + const listed = yield* acp.agent.listSessions({ cwd: project }); + const label = (id: string) => + id === sessionId ? "
" : id === forked.sessionId ? "" : id; + + const record = { + forkEmpty, + mainReply, + forkReply, + list: listed.sessions.map((session) => ({ + sessionId: label(session.sessionId), + title: session.title, + })), + loadFork: yield* load(forked.sessionId), + loadMain: yield* load(sessionId), + cancelIdleFork: "ok" in (yield* settle(acp.agent.cancel({ sessionId: forked.sessionId }))), + }; + expect(forked.sessionId.startsWith("thr_")).toBe(true); + expect(record.loadFork.user).toBe("hellobranch"); + expect(record.loadMain.user).toBe("hello"); + yield* Effect.promise(() => + expect(artifact(record)).toMatchFileSnapshot("./__artifacts__/acp.fork.json"), + ); + }), + withoutProviderKeys(), + ); + }), + ); + }); + it("offers the models its credentials reach, and starts from the project's model", () => { const { home, project } = workspace(); // A Copilot login in the home's own credential file: `--home` must be where it is looked for. diff --git a/packages/codework/test/server.test.ts b/packages/codework/test/server.test.ts index f6e5f460..c73d83d6 100644 --- a/packages/codework/test/server.test.ts +++ b/packages/codework/test/server.test.ts @@ -396,7 +396,7 @@ describe("server", () => { expect(first.session.sandbox?.id).toBe(sandbox.id); expect(second.session.sandbox?.id).toBe(sandbox.id); const relinked = yield* rpc["session.relink"]({ sessionId: first.session.id, sandbox: { id: sandbox.id } }); - expect(relinked.sandbox?.id).toBe(sandbox.id); + expect(relinked.session.sandbox?.id).toBe(sandbox.id); yield* rpc["session.relink"]({ sessionId: Session.SessionSchema.ID.create(), sandbox: { id: sandbox.id }, @@ -649,6 +649,17 @@ const connectedClient = Effect.gen(function* () { return yield* Client.make.pipe(Effect.provideContext(context)); }); +/** Two checkouts of one project, each with `packages/x`: a session can move between them. */ +const clones = async (root: string) => { + const checkouts = [join(root, "clone-a"), join(root, "clone-b")] as const; + for (const dir of checkouts) { + mkdirSync(join(dir, "packages", "x"), { recursive: true }); + await exec("git", ["init", "-q", "-b", "main"], { cwd: dir }); + await exec("git", ["remote", "add", "origin", "git@example.com:org/threads.git"], { cwd: dir }); + } + return checkouts; +}; + describe("WebSocket client", () => { it("stores OpenAI Codex credentials explicitly over RPC", () => Effect.gen(function* () { @@ -1053,6 +1064,203 @@ describe("WebSocket client", () => { if (error._tag === "Client.ExecutionError") expect(error.type).toBe("model-not-found-error"); }).pipe(Effect.scoped, Effect.provide(websocket()), Effect.timeout("10 seconds"), Effect.runPromise)); + it("reports per-thread usage, follows one thread's events, and relinks one thread", () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), "codework-server-threads-"))); + homes.push(root); + return Effect.gen(function* () { + const [a, b] = yield* Effect.promise(() => clones(root)); + const rpc = yield* connectedClient; + const main = yield* rpc["session.create"]({ + directory: join(a, "packages", "x"), + runtime: { model: { provider: "openai", id: "gpt-6-luna" } }, + }); + const sessionId = main.session.id; + const quiet = () => Effect.void; + yield* Client.run(rpc, { sessionId, threadId: main.id, text: "hello" }, quiet); + const reply = (yield* rpc["thread.history"]({ sessionId })).entries.at(-1); + if (reply === undefined) return yield* Effect.die("main thread has no reply"); + const fork = (yield* rpc["thread.fork"]({ sessionId, entryId: reply.id })).thread; + + // Subscribed to the fork alone while both threads run: main's turn must not show up. + const connected = yield* Deferred.make(); + const live = yield* rpc["event.subscribe"]({ threadId: fork.id }).pipe( + Stream.tap((envelope) => + envelope.type === Envelope.Connected.type ? Deferred.succeed(connected, undefined) : Effect.void, + ), + Stream.takeUntil((envelope) => envelope.type === "session.execution.succeeded"), + Stream.runCollect, + Effect.forkScoped, + ); + yield* Deferred.await(connected); + yield* Client.run(rpc, { sessionId, threadId: main.id, text: "again" }, quiet); + yield* Client.run(rpc, { sessionId, threadId: fork.id, text: "branch" }, quiet); + const liveEvents = yield* Fiber.join(live); + + const log = (threadId?: Session.ThreadSchema.ID) => + rpc["session.log"]({ sessionId, ...(threadId === undefined ? {} : { threadId }) }).pipe( + Stream.runCollect, + Effect.map((items) => Array.from(items)), + ); + const forkLog = yield* log(fork.id); + const sessionLog = yield* log(); + + const usage = Object.fromEntries( + (yield* rpc["thread.list"]({ sessionId })).map((info) => [ + info.id === main.id ? "main" : "fork", + info.usage, + ]), + ); + + // One thread moves to the other checkout and keeps its place under the new root; the + // session's default, which main follows, stays. + const movedFork = yield* rpc["session.relink"]({ sessionId, threadId: fork.id, directory: b }); + const mainAfterFork = yield* rpc["thread.info"]({ sessionId }); + const movedSession = yield* rpc["session.relink"]({ sessionId, directory: b }); + + const path = (value: string | undefined) => value?.replace(root, ""); + const threadOf = (data: unknown) => + typeof data === "object" && data !== null && "threadId" in data + ? data.threadId === fork.id + ? "" + : data.threadId === main.id + ? "
" + : "" + : ""; + const artifact = { + usage, + live: liveEvents.map((envelope) => ({ type: envelope.type, thread: threadOf(envelope.data) })), + forkLog: forkLog.map((item) => + "data" in item ? { type: item.type, thread: threadOf(item.data) } : { type: item.type }, + ), + sessionLogThreads: [ + ...new Set(sessionLog.flatMap((item) => ("data" in item ? [threadOf(item.data)] : []))), + ], + relink: { + thread: { + returned: movedFork.id === fork.id ? "" : movedFork.id, + placement: path(movedFork.placement?.directory), + sessionDirectory: path(movedFork.session.directory), + }, + mainAfterThreadMove: { + placement: path(mainAfterFork.placement?.directory), + directory: path(mainAfterFork.session.directory), + }, + session: { + returned: movedSession.id === main.id ? "
" : movedSession.id, + directory: path(movedSession.session.directory), + }, + }, + }; + expect(artifact.live[0]?.type).toBe(Envelope.Connected.type); + expect(artifact.live.slice(1).every(({ thread }) => thread === "")).toBe(true); + expect(artifact.live.at(-1)?.type).toBe("session.execution.succeeded"); + expect(artifact.forkLog.at(-1)).toEqual({ type: "log.synced" }); + expect(artifact.sessionLogThreads.sort()).toEqual(["", "
"]); + expect(usage.main).toMatchObject({ input: 2, output: 2 }); + expect(usage.fork).toMatchObject({ input: 1, output: 1 }); + expect(movedFork.placement?.directory).toBe(join(b, "packages", "x")); + expect(mainAfterFork.placement).toBeUndefined(); + expect(movedSession.session.directory).toBe(join(b, "packages", "x")); + return artifact; + }) + .pipe(Effect.scoped, Effect.provide(websocket()), Effect.timeout("20 seconds"), Effect.runPromise) + .then((artifact) => + expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot( + "./__artifacts__/server.threads.json", + ), + ); + }); + + it("lists, forks and relinks threads through the CLI", { timeout: 60_000 }, () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), "codework-cli-threads-"))); + homes.push(root); + return Effect.gen(function* () { + const server = yield* HttpServer.HttpServer; + if (server.address._tag === "UnixPathAddress") return yield* Effect.die("Expected TCP listener"); + const url = `ws://127.0.0.1:${server.address.port}/rpc/v1`; + const [a, b] = yield* Effect.promise(() => clones(root)); + const rpc = yield* connectedClient; + const main = yield* rpc["session.create"]({ + directory: join(a, "packages", "x"), + runtime: { model: { provider: "openai", id: "gpt-6-luna" } }, + }); + const sessionId = main.session.id; + const quiet = () => Effect.void; + yield* Client.run(rpc, { sessionId, threadId: main.id, text: "hello" }, quiet); + const reply = (yield* rpc["thread.history"]({ sessionId })).entries.at(-1); + if (reply === undefined) return yield* Effect.die("main thread has no reply"); + const cli = (...args: string[]) => Effect.promise(() => execCli([...args, "--server", url], root)); + + const at = yield* cli("thread", "fork", sessionId, "--at", reply.id); + const forkId = Session.ThreadSchema.ID.make(at.stdout.trim()); + yield* Client.run(rpc, { sessionId, threadId: forkId, text: "branch" }, quiet); + const branched = (yield* rpc["thread.history"]({ sessionId, threadId: forkId })).entries.at(-2); + if (branched === undefined) return yield* Effect.die("fork has no prompt"); + const before = yield* cli("thread", "fork", sessionId, "--thread", forkId, "--before", branched.id); + const beforeId = before.stdout.split("\n")[0] ?? ""; + + const relinked = yield* cli("session", "relink", sessionId, "--thread", forkId, "-C", b); + const listed = yield* cli("thread", "list", sessionId); + const listedJson = yield* cli("thread", "list", sessionId, "--json"); + const errors = { + bothPoints: yield* cli("thread", "fork", sessionId, "--at", reply.id, "--before", reply.id), + badThread: yield* cli("thread", "fork", sessionId, "--thread", "nope", "--at", reply.id), + unknownEntry: yield* cli("thread", "fork", sessionId, "--at", "missing-entry"), + }; + + const labels = new Map([ + [sessionId, ""], + [main.id, "
"], + [forkId, ""], + [beforeId, ""], + [reply.id, ""], + [branched.id, ""], + ]); + const scrub = (text: string) => { + let out = text.replaceAll(root, ""); + for (const [id, label] of labels) out = out.replaceAll(id, label); + return out; + }; + const result = (run: { status: number; stdout: string; stderr: string }) => ({ + status: run.status, + stdout: scrub(run.stdout), + ...(run.stderr === "" ? {} : { stderr: scrub(run.stderr) }), + }); + // Decoding with the contract proves `--json` prints the wire form. + const json = yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Array(Contract.ThreadInfo)))( + listedJson.stdout, + ); + const artifact = { + forkAt: result(at), + forkBefore: result(before), + relink: result(relinked), + list: result(listed), + listJson: json + .map((info) => ({ + id: scrub(info.id), + origin: info.origin.kind, + placement: info.placement === undefined ? null : scrub(info.placement.directory), + usage: info.usage, + })) + .sort((x, y) => x.id.localeCompare(y.id)), + errors: Object.fromEntries(Object.entries(errors).map(([name, run]) => [name, result(run)])), + }; + expect(at.status).toBe(0); + expect(Schema.is(Session.ThreadSchema.ID)(forkId)).toBe(true); + expect(before.stdout).toContain("\nbranch\n"); + expect(relinked.stdout).toBe(`Moved thread ${forkId} of ${sessionId} to ${join(b, "packages", "x")}\n`); + expect(json).toHaveLength(3); + expect(Object.values(errors).every((run) => run.status === 1)).toBe(true); + return artifact; + }) + .pipe(Effect.scoped, Effect.provide(websocket()), Effect.timeout("50 seconds"), Effect.runPromise) + .then((artifact) => + expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot( + "./__artifacts__/server.cli-threads.json", + ), + ); + }); + it("runs the CLI against the server without booting a local harness", () => Effect.gen(function* () { const server = yield* HttpServer.HttpServer; diff --git a/sites/www/content/docs/agent/sessions.mdx b/sites/www/content/docs/agent/sessions.mdx index 52c1decf..6285f9b2 100644 --- a/sites/www/content/docs/agent/sessions.mdx +++ b/sites/www/content/docs/agent/sessions.mdx @@ -61,7 +61,7 @@ Every interface that uses the same CodeWork home sees the same sessions: - **Terminal.** `codework run --session `. - **Editors.** ACP editors list past sessions for the open folder, including ones from `codework run`. -- **RPC server.** `codework serve` owns its sessions while it runs. Continue one with `codework run --server --session `, or list them with `session.list`. +- **RPC server.** `codework serve` owns its sessions while it runs. Continue one with `codework run --server --session `, or list their threads with `thread.list`. There's no CLI command to list sessions. Keep the printed ID, or use your editor's thread history. diff --git a/sites/www/content/docs/cli/reference.mdx b/sites/www/content/docs/cli/reference.mdx index 74597d33..caf1813d 100644 --- a/sites/www/content/docs/cli/reference.mdx +++ b/sites/www/content/docs/cli/reference.mdx @@ -25,6 +25,9 @@ Run `codework --help` or `codework --help` to see this from your termi | `codework plugin update [spec]` | Fetch newer revisions | | `codework plugin reload` | Re-import plugins in a running server | | `codework session link ` | Anchor a session to a project folder, through a running server | +| `codework session relink ` | Move where a session, or one thread, runs | +| `codework thread list ` | List a session's threads, with model and usage | +| `codework thread fork ` | Start a new thread from an entry, with `--at` or `--before` | | `codework tui` | Open the terminal UI, starting the background server if needed | | `codework service start` | Start the background server and print its URL | | `codework service restart` | Restart the background server and print its URL | @@ -38,6 +41,7 @@ Run `codework --help` or `codework --help` to see this from your termi | Flag | Description | | ---------------------------- | -------------------------------------------------------------------------------------- | | `-s`, `--session ` | Continue an existing session | +| `--thread ` | Thread of `--session` to continue (default `main`) | | `-C`, `--cwd ` | Working directory for a new session | | `--provider ` | Model catalog provider ID | | `--model ` | Model ID | diff --git a/sites/www/content/docs/integrations/acp.mdx b/sites/www/content/docs/integrations/acp.mdx index 332db816..646d83ff 100644 --- a/sites/www/content/docs/integrations/acp.mdx +++ b/sites/www/content/docs/integrations/acp.mdx @@ -33,6 +33,7 @@ You don't normally run this yourself. You tell your editor to run it, as in the 3. `session/prompt`: CodeWork streams its answer, reasoning, and tool calls back as `session/update` notifications, then returns a stop reason. 4. `session/cancel`: interrupts the running prompt. 5. `session/list` and `session/load`: list past sessions for the folder and reopen one, replaying its full history. +6. `session/fork`: starts a new thread from the conversation so far. When the editor closes the connection, CodeWork interrupts anything still running and stops any sandboxes it manages. @@ -48,7 +49,7 @@ Or pass an API key in the environment the editor launches CodeWork with, such as ## Sessions and Configuration -ACP sessions are regular CodeWork sessions, stored in the same database as the ones you start with `codework run`. Your editor's history and the CLI see the same sessions. +ACP sessions are regular CodeWork sessions, stored in the same database as the ones you start with `codework run`. Your editor's history and the CLI see the same sessions. Each thread of a session, a fork included, is an ACP session of its own. Each session exposes two selectors the editor shows as pickers: diff --git a/sites/www/content/docs/integrations/rpc.mdx b/sites/www/content/docs/integrations/rpc.mdx index 7b31794e..e7588b44 100644 --- a/sites/www/content/docs/integrations/rpc.mdx +++ b/sites/www/content/docs/integrations/rpc.mdx @@ -63,24 +63,27 @@ The endpoint speaks [Effect RPC](https://effect.website) over WebSocket at `/rpc ### Methods -| Group | Methods | -| --------- | ------------------------------------------------------------------------------------------------- | -| `session` | `create`, `list`, `info`, `configure`, `link`, `relink`, `prompt`, `interrupt`, `wait`, `message` | -| `sandbox` | `drivers`, `list`, `create`, `register`, `stop` | -| `auth` | `save`, `status`, `refresh`, `logout` | -| `plugin` | `reload` | -| `event` | `subscribe` (stream) | +| Group | Methods | +| --------- | --------------------------------------------------------------------------------------------------------------------- | +| `session` | `create`, `link`, `relink`, `delete`, `interrupt`, `log` (stream) | +| `thread` | `list`, `info`, `history`, `queue`, `configure`, `fork`, `prompt`, `cancel`, `update`, `interrupt`, `message`, `wait` | +| `sandbox` | `drivers`, `list`, `create`, `register`, `stop` | +| `auth` | `save`, `status`, `refresh`, `logout` | +| `plugin` | `reload` | +| `event` | `subscribe` (stream) | + +Thread methods take `sessionId` and an optional `threadId`; without it they address the session's `main` thread. ### Events -`event.subscribe` streams every event the server publishes. Events are live and not replayed, so subscribe before you send a prompt. +`event.subscribe` streams every event the server publishes. Events are live and not replayed, so subscribe before you send a prompt. Pass `threadId` to receive only that thread's events; `session.log` takes the same filter. Each busy period starts with `session.execution.started` and ends with exactly one of `succeeded`, `failed`, or `interrupted`. A failure carries a category such as `provider-authentication-error` or `sandbox-mount-error`. Plugins publish their own events under `plugin..*`; a client skips types it doesn't know. ### Lifecycle -- `session.prompt` returns once the prompt is admitted. Follow the event stream for the result. -- `session.interrupt` returns as soon as the stop is accepted; `session.wait` resolves when the session has settled. +- `thread.prompt` returns once the prompt is admitted. Follow the event stream for the result. +- `thread.interrupt` returns as soon as the stop is accepted; `thread.wait` resolves when the thread has settled. `session.interrupt` stops every thread. - Managed sandboxes stay up until you stop them or the server shuts down. External sandboxes are never stopped by the server. ## RPC or ACP? From 643810c0b77dedba706e04fe49d458e5f8a07142 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Fri, 30 Oct 2026 00:00:23 +0530 Subject: [PATCH 3/6] docs: describe threads in the codework and harness READMEs Leaves the docs site as it was; it is updated separately. Co-Authored-By: Claude Opus 5.5 --- packages/codework/README.md | 28 +++++++++++++++++++-- packages/harness/README.md | 10 ++++---- sites/www/content/docs/agent/sessions.mdx | 2 +- sites/www/content/docs/cli/reference.mdx | 4 --- sites/www/content/docs/integrations/acp.mdx | 3 +-- sites/www/content/docs/integrations/rpc.mdx | 23 ++++++++--------- 6 files changed, 43 insertions(+), 27 deletions(-) diff --git a/packages/codework/README.md b/packages/codework/README.md index cd6d47ea..a123aa55 100644 --- a/packages/codework/README.md +++ b/packages/codework/README.md @@ -39,9 +39,12 @@ codework run "Inspect and fix the failing tests" # Create a session with explicit provider and model codework run --provider openai --model gpt-5.5 --thinking high "Plan database migration" -# Continue an existing session +# Continue an existing session (its main thread) codework run --session ses_01a070f0 "Now implement the migration script" +# Continue one of its threads +codework run --session ses_01a070f0 --thread thr_01a071c2 "Try it without the cache" + # Run in an isolated sandbox (local, daytona, vercel, memory, sqldb) codework run --sandbox-driver daytona "Inspect repository" codework run --sandbox-driver daytona --sandbox-provider-id "Continue in sandbox" @@ -51,6 +54,7 @@ codework run --sandbox-driver daytona --sandbox-provider-id "Continu - `--server ` — Connect to a running RPC server, e.g. `ws://127.0.0.1:7433/rpc/v1`. - `-s, --session ` — Continue an existing session. +- `--thread ` — Thread of `--session` to continue: a thread ID, or `main` (default). - `-C, --cwd ` — Working directory for a new session. - `--sandbox-driver ` — Sandbox driver (`local`, `daytona`, `vercel`, `memory`, `sqldb`). Default: `local`. - `--sandbox-id ` — Reuse an existing sandbox instance; mutually exclusive with driver/provider coordinates. @@ -63,6 +67,26 @@ Global flags: `--user-config-dir`, `--home`, `--database`. --- +### `codework thread` + +A session holds one or more threads: its `main` thread, and the forks made from it. These commands talk to a running server (`--server`, default `http://127.0.0.1:7433`). + +```bash +# List a session's threads with their model and usage +codework thread list ses_01a070f0 + +# Start a new thread through an entry, or just before a prompt to send it again +codework thread fork ses_01a070f0 --at +codework thread fork ses_01a070f0 --thread thr_01a071c2 --before + +# Move where one thread runs, leaving the rest of the session where it is +codework session relink ses_01a070f0 --thread thr_01a071c2 -C ~/work/api +``` + +`thread fork` prints the new thread ID, then for `--before` the text of the prompt it left out. `--json` prints the wire form. + +--- + ### `codework serve` Start a persistent server that owns sessions and sandboxes: @@ -76,7 +100,7 @@ codework run --server ws://127.0.0.1:7433/rpc/v1 --sandbox-id "Star The default address is `127.0.0.1:7433`; `--port 0` picks an available port and prints the actual URL. Set `--home`, `--database`, and `--user-config-dir` on the server. Model credentials, plugins, and working directories are resolved by the server. A remote run does not boot a local harness. -Events are live and not replayed. The client subscribes before admitting its prompt and waits for execution completion after rendering. Lost connections and overflow fail the command; disconnecting leaves server work running. Ctrl-C sends `session.interrupt`, which interrupts the shared session. Remote runs print the sandbox ID for reuse. `session.interrupt` returns `{ interrupted }` as soon as the stop is accepted; `session.wait` is the separate cleanup barrier. A busy period reports itself as `session.execution.started` followed by exactly one of `succeeded`, `failed`, or `interrupted` -- a failure carries a category (`provider-authentication-error`, `model-not-found-error`, `sandbox-mount-error`, ...) that the client renders, and an interruption carries whether it was the user or a server shutdown. Managed sandboxes remain available until explicitly stopped or server shutdown; external sandboxes are not stopped. +Events are live and not replayed. The client subscribes before admitting its prompt and waits for execution completion after rendering. Lost connections and overflow fail the command; disconnecting leaves server work running. Ctrl-C sends `thread.interrupt`, which stops the thread the run prompted. Remote runs print the sandbox ID for reuse. `thread.interrupt` returns `{ interrupted }` as soon as the stop is accepted; `thread.wait` is the separate cleanup barrier, and `session.interrupt` stops every thread of a session. A busy period reports itself as `session.execution.started` followed by exactly one of `succeeded`, `failed`, or `interrupted` -- a failure carries a category (`provider-authentication-error`, `model-not-found-error`, `sandbox-mount-error`, ...) that the client renders, and an interruption carries whether it was the user or a server shutdown. Managed sandboxes remain available until explicitly stopped or server shutdown; external sandboxes are not stopped. The v0 endpoint has no authentication; its default binding is loopback. Plugins publish their own event types by declaring them (`Plugin.define({ events: [...] })`, namespaced `plugin..*`); the feed carries those and skips types nothing declared. Invalid payloads for declared types fail with a typed encoding error. diff --git a/packages/harness/README.md b/packages/harness/README.md index 5ac6d2e0..529fc72d 100644 --- a/packages/harness/README.md +++ b/packages/harness/README.md @@ -9,7 +9,7 @@ The initial public surface is the Effect SDK at `@codeworksh/harness/effect`. ## Features -- **Durable Sessions:** create, attach, resume, interrupt, and inspect agent sessions without rebuilding orchestration around every turn. +- **Durable Sessions:** create sessions, fork their threads, and attach, resume, interrupt, and inspect each thread without rebuilding orchestration around every turn. - **Streaming Agent Loop:** consume durable session events while the loop coordinates model output, tool calls, and continuations. - **Tool Execution:** use the built-in Bash tool or register typed tools with sequential or parallel execution. - **Model Flexibility:** select any provider and model available in Aikit's generated catalog, including its supported thinking levels. @@ -240,7 +240,7 @@ cost $0.014200 · 1 turn The model catalog lives at `/models.gen.json` and is refreshed once it is older than 15 minutes; `codework models refresh --force` downloads it now. Set `CODEWORK_MODELS_FILE` to pin a catalog you manage yourself. -The CLI prints the session ID to stderr. Provider, model, and thinking settings are stored with the session, so use the same home directory and session ID to continue it: +The CLI prints the session ID to stderr. Provider, model, and thinking settings are stored with the session's thread, so use the same home directory and session ID to continue it: ```sh pnpm dlx @codeworksh/harness@dev \ @@ -249,7 +249,7 @@ pnpm dlx @codeworksh/harness@dev \ "Continue with the implementation" ``` -Persisted settings are the fallback. A new CLI process can explicitly re-bind or change them while attaching; supplied values are recorded as the session's latest configuration: +Persisted settings are the fallback. A new CLI process can explicitly re-bind or change them while attaching; supplied values are recorded as the thread's latest configuration: ```sh pnpm dlx @codeworksh/harness@dev \ @@ -314,12 +314,12 @@ await program.pipe( ); ``` -Creating a session does not contact the provider. Call `session.run(prompt)` to execute a turn, and call `session.events()` directly to obtain its Effect `Stream`. +Creating a session does not contact the provider. A session runs its prompts in threads: call `session.main.run(prompt)` to execute a turn on its `main` thread, and `session.main.events()` to obtain that thread's Effect `Stream`. `fork({ entryId })` on a thread starts a new one, and `session.thread(id)` reaches it later. The Effect SDK currently includes: - `Harness.layer` for process configuration and service wiring -- `Session` handles for create, attach, prompt, run, resume, interrupt, events, and history +- `Session.create` and `relink`, which return a session handle, and `attach`, which returns a thread handle; a thread handle prompts, runs, resumes, interrupts, configures, forks, and exposes its events and history - `Sandbox` drivers and lifecycle operations for in-memory, SQLite, Vercel, and Daytona environments - Local host execution for sessions without a configured sandbox - Effect-native errors, layers, streams, and resource scopes diff --git a/sites/www/content/docs/agent/sessions.mdx b/sites/www/content/docs/agent/sessions.mdx index 6285f9b2..52c1decf 100644 --- a/sites/www/content/docs/agent/sessions.mdx +++ b/sites/www/content/docs/agent/sessions.mdx @@ -61,7 +61,7 @@ Every interface that uses the same CodeWork home sees the same sessions: - **Terminal.** `codework run --session `. - **Editors.** ACP editors list past sessions for the open folder, including ones from `codework run`. -- **RPC server.** `codework serve` owns its sessions while it runs. Continue one with `codework run --server --session `, or list their threads with `thread.list`. +- **RPC server.** `codework serve` owns its sessions while it runs. Continue one with `codework run --server --session `, or list them with `session.list`. There's no CLI command to list sessions. Keep the printed ID, or use your editor's thread history. diff --git a/sites/www/content/docs/cli/reference.mdx b/sites/www/content/docs/cli/reference.mdx index caf1813d..74597d33 100644 --- a/sites/www/content/docs/cli/reference.mdx +++ b/sites/www/content/docs/cli/reference.mdx @@ -25,9 +25,6 @@ Run `codework --help` or `codework --help` to see this from your termi | `codework plugin update [spec]` | Fetch newer revisions | | `codework plugin reload` | Re-import plugins in a running server | | `codework session link ` | Anchor a session to a project folder, through a running server | -| `codework session relink ` | Move where a session, or one thread, runs | -| `codework thread list ` | List a session's threads, with model and usage | -| `codework thread fork ` | Start a new thread from an entry, with `--at` or `--before` | | `codework tui` | Open the terminal UI, starting the background server if needed | | `codework service start` | Start the background server and print its URL | | `codework service restart` | Restart the background server and print its URL | @@ -41,7 +38,6 @@ Run `codework --help` or `codework --help` to see this from your termi | Flag | Description | | ---------------------------- | -------------------------------------------------------------------------------------- | | `-s`, `--session ` | Continue an existing session | -| `--thread ` | Thread of `--session` to continue (default `main`) | | `-C`, `--cwd ` | Working directory for a new session | | `--provider ` | Model catalog provider ID | | `--model ` | Model ID | diff --git a/sites/www/content/docs/integrations/acp.mdx b/sites/www/content/docs/integrations/acp.mdx index 646d83ff..332db816 100644 --- a/sites/www/content/docs/integrations/acp.mdx +++ b/sites/www/content/docs/integrations/acp.mdx @@ -33,7 +33,6 @@ You don't normally run this yourself. You tell your editor to run it, as in the 3. `session/prompt`: CodeWork streams its answer, reasoning, and tool calls back as `session/update` notifications, then returns a stop reason. 4. `session/cancel`: interrupts the running prompt. 5. `session/list` and `session/load`: list past sessions for the folder and reopen one, replaying its full history. -6. `session/fork`: starts a new thread from the conversation so far. When the editor closes the connection, CodeWork interrupts anything still running and stops any sandboxes it manages. @@ -49,7 +48,7 @@ Or pass an API key in the environment the editor launches CodeWork with, such as ## Sessions and Configuration -ACP sessions are regular CodeWork sessions, stored in the same database as the ones you start with `codework run`. Your editor's history and the CLI see the same sessions. Each thread of a session, a fork included, is an ACP session of its own. +ACP sessions are regular CodeWork sessions, stored in the same database as the ones you start with `codework run`. Your editor's history and the CLI see the same sessions. Each session exposes two selectors the editor shows as pickers: diff --git a/sites/www/content/docs/integrations/rpc.mdx b/sites/www/content/docs/integrations/rpc.mdx index e7588b44..7b31794e 100644 --- a/sites/www/content/docs/integrations/rpc.mdx +++ b/sites/www/content/docs/integrations/rpc.mdx @@ -63,27 +63,24 @@ The endpoint speaks [Effect RPC](https://effect.website) over WebSocket at `/rpc ### Methods -| Group | Methods | -| --------- | --------------------------------------------------------------------------------------------------------------------- | -| `session` | `create`, `link`, `relink`, `delete`, `interrupt`, `log` (stream) | -| `thread` | `list`, `info`, `history`, `queue`, `configure`, `fork`, `prompt`, `cancel`, `update`, `interrupt`, `message`, `wait` | -| `sandbox` | `drivers`, `list`, `create`, `register`, `stop` | -| `auth` | `save`, `status`, `refresh`, `logout` | -| `plugin` | `reload` | -| `event` | `subscribe` (stream) | - -Thread methods take `sessionId` and an optional `threadId`; without it they address the session's `main` thread. +| Group | Methods | +| --------- | ------------------------------------------------------------------------------------------------- | +| `session` | `create`, `list`, `info`, `configure`, `link`, `relink`, `prompt`, `interrupt`, `wait`, `message` | +| `sandbox` | `drivers`, `list`, `create`, `register`, `stop` | +| `auth` | `save`, `status`, `refresh`, `logout` | +| `plugin` | `reload` | +| `event` | `subscribe` (stream) | ### Events -`event.subscribe` streams every event the server publishes. Events are live and not replayed, so subscribe before you send a prompt. Pass `threadId` to receive only that thread's events; `session.log` takes the same filter. +`event.subscribe` streams every event the server publishes. Events are live and not replayed, so subscribe before you send a prompt. Each busy period starts with `session.execution.started` and ends with exactly one of `succeeded`, `failed`, or `interrupted`. A failure carries a category such as `provider-authentication-error` or `sandbox-mount-error`. Plugins publish their own events under `plugin..*`; a client skips types it doesn't know. ### Lifecycle -- `thread.prompt` returns once the prompt is admitted. Follow the event stream for the result. -- `thread.interrupt` returns as soon as the stop is accepted; `thread.wait` resolves when the thread has settled. `session.interrupt` stops every thread. +- `session.prompt` returns once the prompt is admitted. Follow the event stream for the result. +- `session.interrupt` returns as soon as the stop is accepted; `session.wait` resolves when the session has settled. - Managed sandboxes stay up until you stop them or the server shuts down. External sandboxes are never stopped by the server. ## RPC or ACP? From 3cbbd2d656243859e09ec02479a08f87d86f4ab0 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Fri, 30 Oct 2026 10:16:43 +0530 Subject: [PATCH 4/6] fix(codework): address review of the thread consumers - ACP `session/fork` cuts at the last committed entry of any type, as the harness does, so a trailing tool result or compaction comes along. - The ACP one-prompt-at-a-time guard is keyed by thread, since main answers to both its session id and its thread id. - `session relink -C` says what it does: the checkout to move into, with the work keeping its position under it. - Contract docs: cost is in US dollars; a fork's filtered `session.log` starts at its `thread.forked`. - The ACP fork artifact no longer records an idle cancel that proved nothing. Co-Authored-By: Claude Opus 5.5 --- packages/codework/README.md | 3 ++- packages/codework/src/acp/handlers.ts | 15 +++++++-------- packages/codework/src/cli/cmd/cmd.ts | 4 +++- packages/codework/src/server/contract.ts | 5 +++-- .../codework/test/__artifacts__/acp.fork.json | 3 +-- packages/codework/test/acp.test.ts | 1 - 6 files changed, 16 insertions(+), 15 deletions(-) diff --git a/packages/codework/README.md b/packages/codework/README.md index a123aa55..caca1608 100644 --- a/packages/codework/README.md +++ b/packages/codework/README.md @@ -79,7 +79,8 @@ codework thread list ses_01a070f0 codework thread fork ses_01a070f0 --at codework thread fork ses_01a070f0 --thread thr_01a071c2 --before -# Move where one thread runs, leaving the rest of the session where it is +# Move one thread into another checkout of the project, keeping its position under it; +# the rest of the session stays where it is codework session relink ses_01a070f0 --thread thr_01a071c2 -C ~/work/api ``` diff --git a/packages/codework/src/acp/handlers.ts b/packages/codework/src/acp/handlers.ts index 1c0b43bc..d624adce 100644 --- a/packages/codework/src/acp/handlers.ts +++ b/packages/codework/src/acp/handlers.ts @@ -201,11 +201,9 @@ export const make = Effect.gen(function* () { run( Effect.gen(function* () { const { thread, hostDir } = yield* attach(id); - // ACP forks the conversation as it stands: at the last entry that is settled. - const last = (yield* thread.history()).findLast( - ({ entry }) => - (entry.type === "user" || entry.type === "assistant") && entry.state === "committed", - ); + // ACP forks the conversation as it stands: at its last committed entry, of any type, so + // a trailing tool result or compaction comes along. + const last = (yield* thread.history()).findLast(({ entry }) => entry.state === "committed"); if (last === undefined) { return yield* Agent.RequestError.invalidRequest( "Nothing to fork yet: the session has no messages", @@ -248,11 +246,12 @@ export const make = Effect.gen(function* () { Effect.gen(function* () { const parts = yield* promptParts(prompt); const { thread: handle } = yield* attach(id); - if (running.has(id)) { + // Keyed by thread: main answers to its session id and its own thread id alike. + if (running.has(handle.id)) { return yield* Agent.RequestError.invalidRequest("A prompt is already running for this session"); } - running.add(id); - yield* Effect.addFinalizer(() => Effect.sync(() => running.delete(id))); + running.add(handle.id); + yield* Effect.addFinalizer(() => Effect.sync(() => running.delete(handle.id))); // Forward this execution's updates until it settles; the settling event decides the answer. let reason: EventList.LLMEnded["data"]["reason"] | undefined; diff --git a/packages/codework/src/cli/cmd/cmd.ts b/packages/codework/src/cli/cmd/cmd.ts index f7140d43..2e3340c3 100644 --- a/packages/codework/src/cli/cmd/cmd.ts +++ b/packages/codework/src/cli/cmd/cmd.ts @@ -289,7 +289,9 @@ export const Cmd = Spec.make("codework", { ), directory: Flag.String("directory").pipe( Flag.withAlias("C"), - Flag.withDescription("Directory inside the target space to land in"), + Flag.withDescription( + "Checkout to move into; the work keeps its position under it when that path exists there", + ), Flag.optional, ), sandboxId: Flag.String("sandbox-id").pipe( diff --git a/packages/codework/src/server/contract.ts b/packages/codework/src/server/contract.ts index af858eb8..52eb37b9 100644 --- a/packages/codework/src/server/contract.ts +++ b/packages/codework/src/server/contract.ts @@ -66,7 +66,7 @@ export const ThreadOrigin = Schema.Union([ /** Billed usage of a thread's own entries; what it inherits through a fork point counts for its source. */ export const ThreadUsage = Schema.Struct({ - /** Total cost in the provider's currency units. */ + /** Total cost in US dollars, from the catalog's prices. */ cost: Schema.Finite, input: Schema.Int, output: Schema.Int, @@ -376,7 +376,8 @@ export const Api = RpcGroup.make( * Ephemeral events (text and tool progress deltas) are never stored, so they are not here; * `event.subscribe` carries them live. To resume, pass the higher of the last event's * `durable.seq` and the last marker's `seq`: the marker can sit past the last event sent. - * With `threadId`, only that thread's events; the marker still names the session's head. + * With `threadId`, only that thread's events; the marker still names the session's head. A fork's + * own log starts at its `thread.forked`: what it inherits is in `thread.history`. */ Rpc.make("session.log", { payload: { diff --git a/packages/codework/test/__artifacts__/acp.fork.json b/packages/codework/test/__artifacts__/acp.fork.json index 0a48193c..3d07cff1 100644 --- a/packages/codework/test/__artifacts__/acp.fork.json +++ b/packages/codework/test/__artifacts__/acp.fork.json @@ -22,6 +22,5 @@ "loadMain": { "user": "hello", "agent": "reply 1" - }, - "cancelIdleFork": true + } } diff --git a/packages/codework/test/acp.test.ts b/packages/codework/test/acp.test.ts index 73900979..c4eb7df4 100644 --- a/packages/codework/test/acp.test.ts +++ b/packages/codework/test/acp.test.ts @@ -351,7 +351,6 @@ describe("codework acp", () => { })), loadFork: yield* load(forked.sessionId), loadMain: yield* load(sessionId), - cancelIdleFork: "ok" in (yield* settle(acp.agent.cancel({ sessionId: forked.sessionId }))), }; expect(forked.sessionId.startsWith("thr_")).toBe(true); expect(record.loadFork.user).toBe("hellobranch"); From ae55aa2ac181e6d68b412f0ba93530005e1f1f61 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Fri, 30 Oct 2026 10:31:42 +0530 Subject: [PATCH 5/6] refactor(harness): name thread events under the session aggregate `thread.forked` and `thread.configured` become `session.thread.forked` and `session.thread.configured`, like every other event in the session's log. Co-Authored-By: Claude Opus 5.5 --- packages/codework/src/server/contract.ts | 2 +- .../codework/test/__artifacts__/server.threads.json | 2 +- packages/harness/src/event/list.ts | 4 ++-- packages/harness/src/thread/thread.ts | 2 +- packages/harness/test/__artifacts__/thread.fork.json | 6 +++--- .../harness/test/__artifacts__/thread.recovery.json | 2 +- .../harness/test/__artifacts__/thread.walkthrough.json | 10 +++++----- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/packages/codework/src/server/contract.ts b/packages/codework/src/server/contract.ts index 52eb37b9..42e6a2c5 100644 --- a/packages/codework/src/server/contract.ts +++ b/packages/codework/src/server/contract.ts @@ -377,7 +377,7 @@ export const Api = RpcGroup.make( * `event.subscribe` carries them live. To resume, pass the higher of the last event's * `durable.seq` and the last marker's `seq`: the marker can sit past the last event sent. * With `threadId`, only that thread's events; the marker still names the session's head. A fork's - * own log starts at its `thread.forked`: what it inherits is in `thread.history`. + * own log starts at its `session.thread.forked`: what it inherits is in `thread.history`. */ Rpc.make("session.log", { payload: { diff --git a/packages/codework/test/__artifacts__/server.threads.json b/packages/codework/test/__artifacts__/server.threads.json index 3903a972..ef9dfa9c 100644 --- a/packages/codework/test/__artifacts__/server.threads.json +++ b/packages/codework/test/__artifacts__/server.threads.json @@ -67,7 +67,7 @@ ], "forkLog": [ { - "type": "thread.forked", + "type": "session.thread.forked", "thread": "" }, { diff --git a/packages/harness/src/event/list.ts b/packages/harness/src/event/list.ts index a048a796..37e82e79 100644 --- a/packages/harness/src/event/list.ts +++ b/packages/harness/src/event/list.ts @@ -93,7 +93,7 @@ export type SessionCreated = typeof SessionCreated.Type; * the thread the fork was asked of; the origin is the thread that owns the entry. */ export const ThreadForked = EventSchema.define({ - type: "thread.forked", + type: "session.thread.forked", ...durableOptions, schema: { ...baseOptions, @@ -106,7 +106,7 @@ export type ThreadForked = typeof ThreadForked.Type; /** A change to a thread's `agent` document; one revision at this event's seq. */ export const ThreadConfigured = EventSchema.define({ - type: "thread.configured", + type: "session.thread.configured", ...durableOptions, schema: { ...baseOptions, change: DocumentSchema.AgentChange }, }); diff --git a/packages/harness/src/thread/thread.ts b/packages/harness/src/thread/thread.ts index 71336ea3..ce5bf81b 100644 --- a/packages/harness/src/thread/thread.ts +++ b/packages/harness/src/thread/thread.ts @@ -166,7 +166,7 @@ export interface Interface { readonly abort: (input: EndAssistant & { readonly data: string }) => Effect.Effect; /** Cut a new thread off `threadId`'s line at a committed entry. */ readonly fork: (input: ForkInput) => Effect.Effect; - /** Projector of `thread.forked`: the thread and its copied documents, at the event's seq. */ + /** Projector of `session.thread.forked`: the thread and its copied documents, at the event's seq. */ readonly projectForked: (input: EventList.ThreadForked["data"], seq: number) => Effect.Effect; /** Names an untitled thread. Returns whether the title changed. */ readonly retitle: (threadId: ThreadSchema.ID, title: string) => Effect.Effect; diff --git a/packages/harness/test/__artifacts__/thread.fork.json b/packages/harness/test/__artifacts__/thread.fork.json index e4df1332..54ebb14d 100644 --- a/packages/harness/test/__artifacts__/thread.fork.json +++ b/packages/harness/test/__artifacts__/thread.fork.json @@ -18,9 +18,9 @@ "9 session.llm.started.1 T1", "10 session.llm.ended.1 T1", "11 session.turn.ended.1 T1", - "12 thread.forked.1 T2", - "13 thread.forked.1 T3", - "14 thread.forked.1 T4", + "12 session.thread.forked.1 T2", + "13 session.thread.forked.1 T3", + "14 session.thread.forked.1 T4", "15 session.prompt.admitted.1 T1", "16 session.prompt.promoted.1 T1", "17 session.llm.started.1 T1", diff --git a/packages/harness/test/__artifacts__/thread.recovery.json b/packages/harness/test/__artifacts__/thread.recovery.json index 7633fce6..4faffb68 100644 --- a/packages/harness/test/__artifacts__/thread.recovery.json +++ b/packages/harness/test/__artifacts__/thread.recovery.json @@ -6,7 +6,7 @@ "4 session.llm.started.1 T1", "5 session.llm.ended.1 T1", "6 session.turn.ended.1 T1", - "7 thread.forked.1 T2", + "7 session.thread.forked.1 T2", "8 session.prompt.admitted.1 T2", "9 session.prompt.promoted.1 T2", "10 session.llm.started.1 T2", diff --git a/packages/harness/test/__artifacts__/thread.walkthrough.json b/packages/harness/test/__artifacts__/thread.walkthrough.json index dc02c7c5..6faf4ee8 100644 --- a/packages/harness/test/__artifacts__/thread.walkthrough.json +++ b/packages/harness/test/__artifacts__/thread.walkthrough.json @@ -1,12 +1,12 @@ { "events": [ "1 session.created.1 T1", - "2 thread.configured.1 T1", + "2 session.thread.configured.1 T1", "3 session.prompt.admitted.1 T1", "4 session.prompt.promoted.1 T1", "5 session.llm.started.1 T1", "6 session.llm.ended.1 T1", - "7 thread.configured.1 T1", + "7 session.thread.configured.1 T1", "8 session.tool.settled.1 T1", "9 session.turn.ended.1 T1", "10 session.llm.started.1 T1", @@ -17,14 +17,14 @@ "15 session.llm.started.1 T1", "16 session.llm.ended.1 T1", "17 session.turn.ended.1 T1", - "18 thread.forked.1 T2", + "18 session.thread.forked.1 T2", "19 session.prompt.admitted.1 T2", "20 session.prompt.promoted.1 T2", "21 session.llm.started.1 T2", "22 session.llm.ended.1 T2", "23 session.turn.ended.1 T2", - "24 thread.configured.1 T2", - "25 thread.forked.1 T3" + "24 session.thread.configured.1 T2", + "25 session.thread.forked.1 T3" ], "threads": [ { From 1542167aad9a9827f7991d310ad3a6b3525166d8 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Fri, 30 Oct 2026 10:59:11 +0530 Subject: [PATCH 6/6] docs: add unreleased notes and breaking changes for threads Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f607e811..9fbf75f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,18 @@ This file is the canonical source for unreleased changes and published release n - Prompts queued while the agent works can be read and changed before it takes them in. `Control.pending` lists them, steers and follow-ups, in the order they were sent. `Control.cancel` withdraws one, recorded as a `session.prompt.cancelled` event; it returns `false` when the prompt was already taken in, and a cancelled message id may be sent again. `Control.update` moves one to the other lane or rewrites its text, keeping its place, recorded as a `session.prompt.updated` event; moving it to the steer lane also wakes the session, so a prompt left queued by a stop runs now. - Tools declare an `exposure`. Only `"direct"` and `"model"` tools reach the request, the `` list and the tool rules, and only they run; a call to any other tool gets `Unknown tool: `. The bash file-ops rule and the skills hint name only declared tools, and `` is left out when neither `read` nor `bash` is declared. A plugin registering an unknown exposure fails in its `setup`. - `read` tells a model without image input that the image it read is left out of the request: `[Current model does not support images. The image will be omitted from this request.]` is added to its note. -- A run cut off by a crash or a shutdown resumes when the server starts again (`Control.resumeUnfinished`). A crash counts as a restart and a shutdown does not; a committed turn starts the count over. After 5 restarts (`Control.RESTART_LIMIT`) the session is parked instead of resumed: `Session.Info.parked` is `true`, and its next prompt runs it again. A resumed run answers the reply it was cut off in before a queued follow-up goes in; steers join it at once. A run the user stopped is not resumed, and what was queued behind it stays queued. +- A run cut off by a crash or a shutdown resumes when the server starts again (`Control.resumeUnfinished`). A crash counts as a restart and a shutdown does not; a committed turn starts the count over. After 5 restarts (`Control.RESTART_LIMIT`) the thread is parked instead of resumed: `Session.ThreadInfo.parked` is `true`, and its next prompt runs it again. A resumed run answers the reply it was cut off in before a queued follow-up goes in; steers join it at once. A run the user stopped is not resumed, and what was queued behind it stays queued. + +- `Session.ThreadInfo.usage`: the billed cost and tokens of the thread's own entries, without what it inherits from the thread it was forked from. + +#### Breaking Changes + +- A session is a container of threads: one event log and one default place to run, holding a `main` thread created with it and the threads forked from it. A thread is a linear transcript; `fork` at or before a committed entry is the only way to branch. Branch, clone, leaf and `parentId` are gone. +- `Session.create` returns a session handle with `main`, `thread(id | "main")` and `threads`. Prompting, running, waiting, resuming, interrupting, configuring, forking, events and history (was `path()`) are on thread handles. `Session.attach` returns a thread handle, `main` when `threadId` is absent. `Session.relink` with `threadId` moves only that thread. +- Title, model, thinking level, usage, execution and `parked` belong to a thread (`Session.ThreadInfo`). `Session.Info` has none of them and gains `mainThreadId`. A thread is titled by its first own prompt; a fork has no title until then. +- `Control` addresses threads: `prompt` and `run` take an optional `threadId` (absent = `main`); `wait`, `resume`, `interrupt`, `pending`, `cancel` and `update` take a thread id. `interruptSession` stops every thread of a session. +- Events: every thread-scoped event carries `threadId`. `session.created`, `session.thread.forked` and `session.thread.configured` are new; `session.thread.configured` replaces `session.config.changed`, and `session.next.forked` is removed. Entry types `configChange` and `branchSummary` are removed. +- Storage starts over with a single new migration; databases from earlier versions are not carried forward. #### Fixed @@ -38,10 +49,21 @@ This file is the canonical source for unreleased changes and published release n #### Added -- Added the `session.queue` RPC (`{ sessionId }`): the prompts sent while the agent works and not yet taken in, steers and follow-ups, in the order they were sent. -- Added the `session.cancel` RPC (`{ sessionId, messageId }`), which withdraws a queued prompt. `cancelled` is `false` when the prompt was already taken in. -- Added the `session.update` RPC (`{ sessionId, messageId, delivery?, text? }`), which moves a queued prompt to the other lane or rewrites its text, keeping its place. `delivery: "steer"` also wakes the session. `updated` is `false` when the prompt was already taken in. -- `codework serve` resumes the sessions a crash or a shutdown cut off when it starts. Session info carries `parked: true` for a session that restarted too often to resume on its own; its next prompt runs it again. +- Added the `thread.queue` RPC (`{ sessionId, threadId? }`): the prompts sent while the agent works and not yet taken in, steers and follow-ups, in the order they were sent. +- Added the `thread.cancel` RPC (`{ sessionId, threadId?, messageId }`), which withdraws a queued prompt. `cancelled` is `false` when the prompt was already taken in. +- Added the `thread.update` RPC (`{ sessionId, threadId?, messageId, delivery?, text? }`), which moves a queued prompt to the other lane or rewrites its text, keeping its place. `delivery: "steer"` also wakes the thread. `updated` is `false` when the prompt was already taken in. +- `codework serve` resumes the sessions a crash or a shutdown cut off when it starts. Thread info carries `parked: true` for a thread that restarted too often to resume on its own; its next prompt runs it again. + +- `codework run --thread ` continues one thread of `--session`. +- `codework thread list ` lists a session's threads with their model, usage and title. `codework thread fork --at ` or `--before ` starts a new thread and prints its id, then for `--before` the text of the prompt it left out. `codework session relink --thread ` moves one thread to another checkout. All three take `--json`. +- `ThreadInfo.usage` reports a thread's own cost and tokens. `event.subscribe` and `session.log` take `threadId` to keep only that thread's events. +- ACP: every thread of a session is an ACP session of its own, so forks can be listed, loaded and prompted; the main thread keeps the session's id. `session/fork` starts a new thread from the last committed entry. + +#### Breaking Changes + +- The RPC is split by what it addresses. `session.*` keeps `create`, `link`, `relink`, `delete`, `interrupt` (every thread) and `log`. `list`, `info`, `history`, `queue`, `configure`, `prompt`, `cancel`, `update`, `interrupt`, `message` and `wait` move to `thread.*`, with `fork` new there; they take `{ sessionId, threadId? }`, and an absent `threadId` means the session's `main` thread. +- `session.create` and `session.relink` return the addressed thread's `ThreadInfo`, with its session embedded. `SessionInfo` has no title, model, thinking level or `parked`, and gains `mainThreadId`. +- ACP `session/cancel` stops only the thread its session names, not every thread of the CodeWork session. #### Fixed @@ -93,6 +115,7 @@ This file is the canonical source for unreleased changes and published release n #### Added - `ToolCallContext.modelInput`: the input modalities of the model the tool call answers, such as `["text"]` or `["text", "image"]`. It is optional, and tool hooks receive it too. +- `ThreadID` in `@codeworksh/plugin/ids`, and `threadId` next to `sessionId` on the plugin context and the tool hooks: the thread the call belongs to. - `exposure` on tool definitions: `"direct"` (default), `"model"`, `"codemode"`, `"deferred"` or `"hidden"`, as the `ToolExposure` schema. `declared(def)` is true for `"direct"` and `"model"`, the tools declared to the model. ## [@codeworksh/cli@0.4.0] - 2026-10-20