Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat(server): delegate work between bots (#64)
Leo4049020f3975
diff --git a/apps/server/src/orchestration/Layers/DelegationPersistence.test.ts b/apps/server/src/orchestration/Layers/DelegationPersistence.test.tsnew file mode 100644index 000000000..a8acd964c--- /dev/null+++ b/apps/server/src/orchestration/Layers/DelegationPersistence.test.ts@@ -0,0 +1,132 @@+import * as NodeServices from "@effect/platform-node/NodeServices";+import {+ BotId,+ CommandId,+ DelegationId,+ EventId,+ ThreadId,+ TurnId,+ type AkeruDelegationRecord,+} from "@t3tools/contracts";+import { assert, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as SqlClient from "effect/unstable/sql/SqlClient";++import { ServerConfig } from "../../config.ts";+import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";+import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";+import { makeSqlitePersistenceLive } from "../../persistence/Layers/Sqlite.ts";+import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";+import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";+import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";+import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";+import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";+import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";+import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";+import {+ ORCHESTRATION_PROJECTOR_NAMES,+ OrchestrationProjectionPipelineLive,+} from "./ProjectionPipeline.ts";+import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";++const NOW = "2026-08-31T12:00:00.000Z";+const COMPLETED_AT = "2026-08-31T12:01:00.000Z";+const SOURCE_BOT_ID = BotId.make("bot-source");+const TARGET_BOT_ID = BotId.make("bot-target");+const SOURCE_THREAD_ID = ThreadId.make("thread-source");+const CHILD_THREAD_ID = ThreadId.make("thread-child");++const delegation: AkeruDelegationRecord = {+ delegationId: DelegationId.make("delegation-restart"),+ sourceThreadId: SOURCE_THREAD_ID,+ sourceTurnId: TurnId.make("turn-source"),+ sourceBotId: SOURCE_BOT_ID,+ targetBotId: TARGET_BOT_ID,+ childThreadId: CHILD_THREAD_ID,+ childTurnId: TurnId.make("turn-child"),+ depth: 1,+ billedBotId: TARGET_BOT_ID,+ task: "Compare three flights.",+ expectedResult: "A short comparison with sources.",+ outcome: null,+ createdAt: NOW,+ completedAt: null,+};++const completedDelegation: AkeruDelegationRecord = {+ ...delegation,+ outcome: { status: "succeeded", result: "Flight B is the best fit." },+ completedAt: COMPLETED_AT,+};++const makeLayer = (dbPath: string) =>+ OrchestrationEngineLive.pipe(+ Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),+ Layer.provide(ThreadBackgroundLiveness.layer),+ Layer.provide(ThreadPlanProgress.layer),+ Layer.provideMerge(OrchestrationProjectionPipelineLive),+ Layer.provideMerge(OrchestrationEventStoreLive),+ Layer.provide(OrchestrationCommandReceiptRepositoryLive),+ Layer.provide(RepositoryIdentityResolver.layer),+ Layer.provideMerge(makeSqlitePersistenceLive(dbPath)),+ );++it.effect("replays the completed delegation after a restart", () =>+ Effect.gen(function* () {+ const { dbPath } = yield* ServerConfig;++ yield* Effect.gen(function* () {+ const eventStore = yield* OrchestrationEventStore;+ yield* eventStore.append({+ type: "delegation.created",+ eventId: EventId.make("event-delegation-created"),+ aggregateKind: "delegation",+ aggregateId: delegation.delegationId,+ occurredAt: NOW,+ commandId: CommandId.make("command-delegation-create"),+ causationEventId: null,+ correlationId: CommandId.make("command-delegation-create"),+ metadata: {},+ payload: { delegation },+ });+ yield* eventStore.append({+ type: "delegation.completed",+ eventId: EventId.make("event-delegation-completed"),+ aggregateKind: "delegation",+ aggregateId: delegation.delegationId,+ occurredAt: COMPLETED_AT,+ commandId: CommandId.make("command-delegation-complete"),+ causationEventId: null,+ correlationId: CommandId.make("command-delegation-complete"),+ metadata: {},+ payload: { delegation: completedDelegation },+ });+ }).pipe(Effect.provide(makeLayer(dbPath)));++ yield* Effect.gen(function* () {+ const pipeline = yield* OrchestrationProjectionPipeline;+ const snapshots = yield* ProjectionSnapshotQuery;+ const sql = yield* SqlClient.SqlClient;++ yield* sql`DELETE FROM projection_delegations`;+ yield* sql`+ DELETE FROM projection_state+ WHERE projector = ${ORCHESTRATION_PROJECTOR_NAMES.delegations}+ `;+ yield* pipeline.bootstrap;++ const snapshot = yield* snapshots.getSnapshot();+ const commandReadModel = yield* snapshots.getCommandReadModel();+ assert.deepEqual(snapshot.delegations, [completedDelegation]);+ assert.deepEqual(commandReadModel.delegations, [completedDelegation]);+ }).pipe(Effect.provide(makeLayer(dbPath)));+ }).pipe(+ Effect.provide(+ Layer.provideMerge(+ ServerConfig.layerTest(process.cwd(), { prefix: "akeru-delegation-persistence-test-" }),+ NodeServices.layer,+ ),+ ),+ ),+);diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.tsindex 5f07280cb..94a288521 100644--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts@@ -120,6 +120,7 @@ describe("OrchestrationEngine", () => {updatedAt: "2026-03-03T00:00:04.000Z",bots: [],groups: [],+ delegations: [],projects: [{id: asProjectId("project-bootstrap"),diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.tsindex ceda5ce25..9155cc618 100644--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts@@ -1,12 +1,7 @@import type {- BotId,- GroupId,- McpServerId,OrchestrationClientOrigin,OrchestrationEvent,OrchestrationReadModel,- ProjectId,- ThreadId,} from "@t3tools/contracts";import { OrchestrationCommand } from "@t3tools/contracts";import * as Cause from "effect/Cause";@@ -64,8 +59,8 @@ interface CommandEnvelope {}function commandToAggregateRef(command: OrchestrationCommand): {- readonly aggregateKind: "project" | "bot" | "group" | "mcp-server" | "thread";- readonly aggregateId: ProjectId | BotId | GroupId | McpServerId | ThreadId;+ readonly aggregateKind: OrchestrationEvent["aggregateKind"];+ readonly aggregateId: OrchestrationEvent["aggregateId"];} {switch (command.type) {case "project.create":@@ -102,6 +97,12 @@ function commandToAggregateRef(command: OrchestrationCommand): {aggregateKind: "mcp-server",aggregateId: command.mcpServerId,};+ case "delegation.create":+ case "delegation.complete":+ return {+ aggregateKind: "delegation",+ aggregateId: command.delegation.delegationId,+ };default:return {aggregateKind: "thread",diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex 7c880ef41..76f3811f7 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -65,6 +65,7 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {projects: "projection.projects",bots: "projection.bots",groups: "projection.groups",+ delegations: "projection.delegations",mcpServers: "projection.mcp-servers",threads: "projection.threads",threadMessages: "projection.thread-messages",@@ -762,6 +763,27 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti}},);+ const applyDelegationsProjection: ProjectorDefinition["apply"] = Effect.fn(+ "applyDelegationsProjection",+ )((event, _attachmentSideEffects) => {+ if (event.type !== "delegation.created" && event.type !== "delegation.completed") {+ return Effect.void;+ }+ return sql`+ INSERT INTO projection_delegations (delegation_id, record_json)+ VALUES (+ ${event.payload.delegation.delegationId},+ ${JSON.stringify(event.payload.delegation)}+ )+ ON CONFLICT (delegation_id) DO UPDATE SET+ record_json = excluded.record_json+ `.pipe(+ Effect.mapError(+ toPersistenceSqlError("ProjectionPipeline.applyDelegationsProjection:query"),+ ),+ Effect.asVoid,+ );+ });const applyMcpServersProjection: ProjectorDefinition["apply"] = Effect.fn("applyMcpServersProjection",)(function* (event, _attachmentSideEffects) {@@ -1895,6 +1917,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectiname: ORCHESTRATION_PROJECTOR_NAMES.groups,apply: applyGroupsProjection,},+ {+ name: ORCHESTRATION_PROJECTOR_NAMES.delegations,+ apply: applyDelegationsProjection,+ },{name: ORCHESTRATION_PROJECTOR_NAMES.mcpServers,apply: applyMcpServersProjection,diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.tsindex f2a40cd85..fbb643060 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts@@ -1,4 +1,5 @@import {+ AkeruDelegationRecord,BotAvatar,BotEngine,BotId,@@ -98,6 +99,9 @@ const ProjectionBotDbRowSchema = ProjectionBot.mapFields(const ProjectionGroupDbRowSchema = ProjectionGroup.mapFields(Struct.assign({ members: Schema.fromJsonString(Schema.Array(GroupMembership)) }),);+const ProjectionDelegationDbRowSchema = Schema.Struct({+ delegation: Schema.fromJsonString(AkeruDelegationRecord),+});const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(Struct.assign({defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),@@ -224,6 +228,7 @@ const REQUIRED_SNAPSHOT_PROJECTORS = [ORCHESTRATION_PROJECTOR_NAMES.projects,ORCHESTRATION_PROJECTOR_NAMES.bots,ORCHESTRATION_PROJECTOR_NAMES.groups,+ ORCHESTRATION_PROJECTOR_NAMES.delegations,ORCHESTRATION_PROJECTOR_NAMES.mcpServers,ORCHESTRATION_PROJECTOR_NAMES.threads,ORCHESTRATION_PROJECTOR_NAMES.threadMessages,@@ -503,6 +508,16 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {`,});+ const listDelegationRows = SqlSchema.findAll({+ Request: Schema.Void,+ Result: ProjectionDelegationDbRowSchema,+ execute: () => sql`+ SELECT record_json AS delegation+ FROM projection_delegations+ ORDER BY json_extract(record_json, '$.createdAt') ASC, delegation_id ASC+ `,+ });+const listThreadRows = SqlSchema.findAll({Request: Schema.Void,Result: ProjectionThreadDbRowSchema,@@ -1595,6 +1610,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {),),),+ listDelegationRows(undefined).pipe(+ Effect.mapError(+ toPersistenceSqlOrDecodeError(+ "ProjectionSnapshotQuery.getSnapshot:listDelegations:query",+ "ProjectionSnapshotQuery.getSnapshot:listDelegations:decodeRows",+ ),+ ),+ ),projectionMcpServerRepository.listAll(),listThreadRows(undefined).pipe(Effect.mapError(@@ -1668,6 +1691,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {projectRows,botRows,groupRows,+ delegationRows,mcpServers,threadRows,messageRows,@@ -1697,6 +1721,12 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {for (const row of groupRows) {updatedAt = maxIso(updatedAt, row.updatedAt);}+ for (const row of delegationRows) {+ updatedAt = maxIso(+ updatedAt,+ row.delegation.completedAt ?? row.delegation.createdAt,+ );+ }for (const mcpServer of mcpServers) {updatedAt = maxIso(updatedAt, mcpServer.updatedAt);}@@ -1859,6 +1889,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {projects,bots: botRows.map(mapBotRow),groups: groupRows.map(mapGroupRow),+ delegations: delegationRows.map((row) => row.delegation),mcpServers,threads,updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",@@ -1907,6 +1938,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {),),),+ listDelegationRows(undefined).pipe(+ Effect.mapError(+ toPersistenceSqlOrDecodeError(+ "ProjectionSnapshotQuery.getCommandReadModel:listDelegations:query",+ "ProjectionSnapshotQuery.getCommandReadModel:listDelegations:decodeRows",+ ),+ ),+ ),projectionMcpServerRepository.listAll(),listThreadRows(undefined).pipe(Effect.mapError(@@ -1956,6 +1995,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {projectRows,botRows,groupRows,+ delegationRows,mcpServers,threadRows,proposedPlanRows,@@ -1993,6 +2033,12 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {for (const row of groupRows) {updatedAt = maxIso(updatedAt, row.updatedAt);}+ for (const row of delegationRows) {+ updatedAt = maxIso(+ updatedAt,+ row.delegation.completedAt ?? row.delegation.createdAt,+ );+ }for (const mcpServer of mcpServers) {updatedAt = maxIso(updatedAt, mcpServer.updatedAt);}@@ -2113,6 +2159,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {projects,bots: botRows.map(mapBotRow),groups: groupRows.map(mapGroupRow),+ delegations: delegationRows.map((row) => row.delegation),mcpServers,threads,updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.tsindex 9e8f4f496..589918291 100644--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts@@ -340,6 +340,15 @@ const make = Effect.gen(function* () {const textGeneration = yield* TextGeneration;const serverSettingsService = yield* ServerSettingsService;const botUsageLedger = yield* BotUsageLedger;+ const runPromise = Effect.runPromiseWith(yield* Effect.context<never>());+ const failDelegation = (threadId: ThreadId, error: string) =>+ agentController.failDelegation?.({ threadId, error }) ?? Effect.void;+ if (agentController.configureDelegation) {+ yield* agentController.configureDelegation({+ readSnapshot: () => runPromise(projectionSnapshotQuery.getCommandReadModel()),+ dispatch: (command) => runPromise(orchestrationEngine.dispatch(command)),+ });+ }const serverCommandId = (tag: string) =>crypto.randomUUIDv4.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));const serverEventId = () => crypto.randomUUIDv4.pipe(Effect.map(EventId.make));@@ -1247,7 +1256,14 @@ const make = Effect.gen(function* () {turnId: null,createdAt: event.payload.createdAt,requestId: event.payload.messageId,- });+ }).pipe(+ Effect.ensuring(+ failDelegation(+ event.payload.threadId,+ `User message '${event.payload.messageId}' was not found for turn start request.`,+ ),+ ),+ );return;}@@ -1306,6 +1322,7 @@ const make = Effect.gen(function* () {}),),Effect.asVoid,+ Effect.ensuring(failDelegation(event.payload.threadId, detail)),);};diff --git a/apps/server/src/orchestration/commandInvariants.test.ts b/apps/server/src/orchestration/commandInvariants.test.tsindex 7fd6b6c35..153a81bfd 100644--- a/apps/server/src/orchestration/commandInvariants.test.ts+++ b/apps/server/src/orchestration/commandInvariants.test.ts@@ -25,6 +25,7 @@ const readModel: OrchestrationReadModel = {updatedAt: now,bots: [],groups: [],+ delegations: [],projects: [{id: ProjectId.make("project-a"),diff --git a/apps/server/src/orchestration/commandInvariants.ts b/apps/server/src/orchestration/commandInvariants.tsindex 5ecae54eb..a7131a996 100644--- a/apps/server/src/orchestration/commandInvariants.ts+++ b/apps/server/src/orchestration/commandInvariants.ts@@ -1,5 +1,7 @@import type {+ AkeruDelegationRecord,BotId,+ DelegationId,GroupId,OrchestrationBot,McpServer,@@ -59,6 +61,13 @@ export function findMcpServerById(return readModel.mcpServers?.find((mcpServer) => mcpServer.id === mcpServerId);}+export function findDelegationById(+ readModel: OrchestrationReadModel,+ delegationId: DelegationId,+): AkeruDelegationRecord | undefined {+ return readModel.delegations.find((delegation) => delegation.delegationId === delegationId);+}+export function listThreadsByProjectId(readModel: OrchestrationReadModel,projectId: ProjectId,@@ -154,6 +163,37 @@ export function requireBotAbsent(input: {: Effect.void;}+export function requireDelegation(input: {+ readonly readModel: OrchestrationReadModel;+ readonly command: OrchestrationCommand;+ readonly delegationId: DelegationId;+}): Effect.Effect<AkeruDelegationRecord, OrchestrationCommandInvariantError> {+ const delegation = findDelegationById(input.readModel, input.delegationId);+ return delegation+ ? Effect.succeed(delegation)+ : Effect.fail(+ invariantError(+ input.command.type,+ `Delegation '${input.delegationId}' does not exist for command '${input.command.type}'.`,+ ),+ );+}++export function requireDelegationAbsent(input: {+ readonly readModel: OrchestrationReadModel;+ readonly command: OrchestrationCommand;+ readonly delegationId: DelegationId;+}): Effect.Effect<void, OrchestrationCommandInvariantError> {+ return findDelegationById(input.readModel, input.delegationId)+ ? Effect.fail(+ invariantError(+ input.command.type,+ `Delegation '${input.delegationId}' already exists and cannot be created twice.`,+ ),+ )+ : Effect.void;+}+export function requireBotArchived(input: {readonly readModel: OrchestrationReadModel;readonly command: OrchestrationCommand;diff --git a/apps/server/src/orchestration/decider.delegation.test.ts b/apps/server/src/orchestration/decider.delegation.test.tsnew file mode 100644index 000000000..3cd3831a7--- /dev/null+++ b/apps/server/src/orchestration/decider.delegation.test.ts@@ -0,0 +1,260 @@+import * as NodeServices from "@effect/platform-node/NodeServices";+import {+ BotId,+ CommandId,+ DelegationId,+ ProjectId,+ ProviderInstanceId,+ ThreadId,+ TurnId,+ type AkeruDelegationRecord,+ type OrchestrationBot,+ type OrchestrationCommand,+ type OrchestrationReadModel,+ type OrchestrationThread,+} from "@t3tools/contracts";+import { expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";++import { decideOrchestrationCommand } from "./decider.ts";++const NOW = "2026-08-31T12:00:00.000Z";+const LATER = "2026-08-31T12:01:00.000Z";+const SOURCE_BOT_ID = BotId.make("bot-source");+const TARGET_BOT_ID = BotId.make("bot-target");+const SOURCE_THREAD_ID = ThreadId.make("thread-source");+const CHILD_THREAD_ID = ThreadId.make("thread-child");+const SOURCE_TURN_ID = TurnId.make("turn-source");+const CHILD_TURN_ID = TurnId.make("turn-child");++function makeBot(id: BotId): OrchestrationBot {+ return {+ id,+ name: id,+ title: "Agent",+ label: null,+ description: null,+ disabledMcpServerIds: [],+ avatar: { kind: "dither", seed: id },+ engine: null,+ sandbox: "local",+ runtimeMode: "full-access",+ usageCap: null,+ voiceEnabled: false,+ groupId: null,+ archivedAt: null,+ createdAt: NOW,+ updatedAt: NOW,+ };+}++function makeThread(input: {+ id: ThreadId;+ botId: BotId;+ turnId: TurnId | null;+ projectId?: ProjectId;+}): OrchestrationThread {+ return {+ id: input.id,+ projectId: input.projectId ?? ProjectId.make("project-1"),+ botId: input.botId,+ groupId: null,+ respondingBotId: null,+ title: input.id,+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6" },+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ latestTurn:+ input.turnId === null+ ? null+ : {+ turnId: input.turnId,+ state: "running",+ requestedAt: NOW,+ startedAt: NOW,+ completedAt: null,+ assistantMessageId: null,+ },+ createdAt: NOW,+ updatedAt: NOW,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ deletedAt: null,+ messages: [],+ proposedPlans: [],+ activities: [],+ checkpoints: [],+ session: null,+ };+}++function makeDelegation(overrides: Partial<AkeruDelegationRecord> = {}): AkeruDelegationRecord {+ return {+ delegationId: DelegationId.make("delegation-1"),+ sourceThreadId: SOURCE_THREAD_ID,+ sourceTurnId: SOURCE_TURN_ID,+ sourceBotId: SOURCE_BOT_ID,+ targetBotId: TARGET_BOT_ID,+ childThreadId: CHILD_THREAD_ID,+ childTurnId: null,+ depth: 1,+ billedBotId: TARGET_BOT_ID,+ task: "Compare three flights.",+ expectedResult: "A short comparison with sources.",+ outcome: null,+ createdAt: NOW,+ completedAt: null,+ ...overrides,+ };+}++function makeReadModel(+ input: {+ childBotId?: BotId;+ childProjectId?: ProjectId;+ targetArchived?: boolean;+ delegations?: ReadonlyArray<AkeruDelegationRecord>;+ } = {},+): OrchestrationReadModel {+ return {+ snapshotSequence: 0,+ projects: [],+ bots: [+ makeBot(SOURCE_BOT_ID),+ {+ ...makeBot(TARGET_BOT_ID),+ archivedAt: input.targetArchived ? LATER : null,+ },+ ],+ groups: [],+ delegations: input.delegations ?? [],+ threads: [+ makeThread({ id: SOURCE_THREAD_ID, botId: SOURCE_BOT_ID, turnId: SOURCE_TURN_ID }),+ makeThread({+ id: CHILD_THREAD_ID,+ botId: input.childBotId ?? TARGET_BOT_ID,+ turnId: null,+ ...(input.childProjectId !== undefined ? { projectId: input.childProjectId } : {}),+ }),+ ],+ updatedAt: NOW,+ };+}++const decide = (readModel: OrchestrationReadModel, command: OrchestrationCommand) =>+ decideOrchestrationCommand({ readModel, command });++it.layer(NodeServices.layer)("delegation decider", (it) => {+ it.effect("creates and completes a delegation", () =>+ Effect.gen(function* () {+ const delegation = makeDelegation();+ const created = yield* decide(makeReadModel(), {+ type: "delegation.create",+ commandId: CommandId.make("command-create"),+ delegation,+ });+ expect(created).toMatchObject({+ type: "delegation.created",+ aggregateKind: "delegation",+ aggregateId: delegation.delegationId,+ payload: { delegation },+ });++ const completedDelegation = makeDelegation({+ childTurnId: CHILD_TURN_ID,+ outcome: { status: "succeeded", result: "Compared the flights." },+ completedAt: LATER,+ });+ const completed = yield* decide(makeReadModel({ delegations: [delegation] }), {+ type: "delegation.complete",+ commandId: CommandId.make("command-complete"),+ delegation: completedDelegation,+ });+ expect(completed).toMatchObject({+ type: "delegation.completed",+ payload: { delegation: completedDelegation },+ });+ }),+ );++ it.effect("records a failed dispatch without a child turn", () =>+ Effect.gen(function* () {+ const delegation = makeDelegation();+ const failed = makeDelegation({+ outcome: { status: "failed", error: "Turn dispatch failed." },+ completedAt: LATER,+ });+ const event = yield* decide(makeReadModel({ delegations: [delegation] }), {+ type: "delegation.complete",+ commandId: CommandId.make("command-failed"),+ delegation: failed,+ });+ expect(event).toMatchObject({+ type: "delegation.completed",+ payload: { delegation: failed },+ });+ }),+ );++ it.effect("rejects invalid delegation ownership and boundaries", () =>+ Effect.gen(function* () {+ const cases: ReadonlyArray<{+ command: AkeruDelegationRecord;+ readModel: OrchestrationReadModel;+ message: string;+ }> = [+ {+ command: makeDelegation({ sourceTurnId: TurnId.make("wrong-turn") }),+ readModel: makeReadModel(),+ message: "source thread, turn, and bot",+ },+ {+ command: makeDelegation({+ targetBotId: SOURCE_BOT_ID,+ billedBotId: SOURCE_BOT_ID,+ }),+ readModel: makeReadModel(),+ message: "delegate to itself",+ },+ {+ command: makeDelegation(),+ readModel: makeReadModel({ childProjectId: ProjectId.make("project-2") }),+ message: "cross projects",+ },+ {+ command: makeDelegation({ depth: 3 as AkeruDelegationRecord["depth"] }),+ readModel: makeReadModel(),+ message: "maximum depth",+ },+ {+ command: makeDelegation(),+ readModel: makeReadModel({ childBotId: SOURCE_BOT_ID }),+ message: "target bot",+ },+ {+ command: makeDelegation(),+ readModel: makeReadModel({ targetArchived: true }),+ message: "archived",+ },+ {+ command: makeDelegation({ billedBotId: SOURCE_BOT_ID }),+ readModel: makeReadModel(),+ message: "must bill target bot",+ },+ ];++ for (const testCase of cases) {+ const error = yield* decide(testCase.readModel, {+ type: "delegation.create",+ commandId: CommandId.make(`command-${testCase.message.replaceAll(" ", "-")}`),+ delegation: testCase.command,+ }).pipe(Effect.flip);+ if (error._tag !== "OrchestrationCommandInvariantError") throw error;+ expect(error.detail).toContain(testCase.message);+ }+ }),+ );+});diff --git a/apps/server/src/orchestration/decider.pinned.test.ts b/apps/server/src/orchestration/decider.pinned.test.tsindex 03fe7f8af..a49a83c91 100644--- a/apps/server/src/orchestration/decider.pinned.test.ts+++ b/apps/server/src/orchestration/decider.pinned.test.ts@@ -27,6 +27,7 @@ function makeReadModel(input: {snapshotSequence: 0,bots: [],groups: [],+ delegations: [],projects: [],threads: [{diff --git a/apps/server/src/orchestration/decider.settled.test.ts b/apps/server/src/orchestration/decider.settled.test.tsindex 9a553857c..271dd1189 100644--- a/apps/server/src/orchestration/decider.settled.test.ts+++ b/apps/server/src/orchestration/decider.settled.test.ts@@ -36,6 +36,7 @@ function makeReadModel(snapshotSequence: 0,bots: [],groups: [],+ delegations: [],projects: [],threads: [{diff --git a/apps/server/src/orchestration/decider.snoozed.test.ts b/apps/server/src/orchestration/decider.snoozed.test.tsindex a1c7e3676..d72bf2fdb 100644--- a/apps/server/src/orchestration/decider.snoozed.test.ts+++ b/apps/server/src/orchestration/decider.snoozed.test.ts@@ -32,6 +32,7 @@ function makeReadModel(input: {snapshotSequence: 0,bots: [],groups: [],+ delegations: [],projects: [],threads: [{diff --git a/apps/server/src/orchestration/decider.titleRegeneration.test.ts b/apps/server/src/orchestration/decider.titleRegeneration.test.tsindex 7b8b9c137..0eddec8da 100644--- a/apps/server/src/orchestration/decider.titleRegeneration.test.ts+++ b/apps/server/src/orchestration/decider.titleRegeneration.test.ts@@ -17,6 +17,7 @@ const readModel: OrchestrationReadModel = {snapshotSequence: 0,bots: [],groups: [],+ delegations: [],projects: [],threads: [{diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.tsindex f3314fe11..221482230 100644--- a/apps/server/src/orchestration/decider.ts+++ b/apps/server/src/orchestration/decider.ts@@ -1,4 +1,5 @@import {+ AKERU_DELEGATION_MAX_DEPTH,BotId,DEFAULT_LOCAL_EXECUTION_MODE,DEFAULT_RUNTIME_MODE,@@ -9,6 +10,7 @@ import {type OrchestrationEvent,type OrchestrationReadModel,} from "@t3tools/contracts";+import * as NodeUtil from "node:util";import * as DateTime from "effect/DateTime";import * as Crypto from "effect/Crypto";import * as Effect from "effect/Effect";@@ -23,6 +25,8 @@ import {requireBotAbsent,requireBotArchived,requireBotNotArchived,+ requireDelegation,+ requireDelegationAbsent,requireGroup,requireGroupAbsent,requireMcpServer,@@ -986,6 +990,143 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"};}+ case "delegation.create": {+ const delegation = command.delegation;+ yield* requireDelegationAbsent({+ readModel,+ command,+ delegationId: delegation.delegationId,+ });+ const sourceThread = yield* requireThread({+ readModel,+ command,+ threadId: delegation.sourceThreadId,+ });+ const childThread = yield* requireThread({+ readModel,+ command,+ threadId: delegation.childThreadId,+ });+ yield* requireBotNotArchived({+ readModel,+ command,+ botId: delegation.targetBotId,+ });++ if (+ sourceThread.botId !== delegation.sourceBotId ||+ sourceThread.latestTurn?.turnId !== delegation.sourceTurnId+ ) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `Delegation '${delegation.delegationId}' does not match its source thread, turn, and bot.`,+ });+ }+ if (delegation.sourceBotId === delegation.targetBotId) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `Bot '${delegation.sourceBotId}' cannot delegate to itself.`,+ });+ }+ if (sourceThread.projectId !== childThread.projectId) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `Delegation '${delegation.delegationId}' cannot cross projects.`,+ });+ }+ if (+ childThread.botId !== delegation.targetBotId ||+ (delegation.childTurnId !== null &&+ childThread.latestTurn?.turnId !== delegation.childTurnId)+ ) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `Delegation '${delegation.delegationId}' child thread and turn must belong to target bot '${delegation.targetBotId}'.`,+ });+ }+ if (delegation.depth < 1 || delegation.depth > AKERU_DELEGATION_MAX_DEPTH) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `Delegation '${delegation.delegationId}' exceeds the maximum depth of ${AKERU_DELEGATION_MAX_DEPTH}.`,+ });+ }+ if (delegation.billedBotId !== delegation.targetBotId) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `Delegation '${delegation.delegationId}' must bill target bot '${delegation.targetBotId}'.`,+ });+ }+ if (delegation.outcome !== null || delegation.completedAt !== null) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `Delegation '${delegation.delegationId}' cannot be completed when created.`,+ });+ }++ return {+ ...(yield* withEventBase({+ aggregateKind: "delegation",+ aggregateId: delegation.delegationId,+ occurredAt: delegation.createdAt,+ commandId: command.commandId,+ })),+ type: "delegation.created",+ payload: { delegation },+ };+ }++ case "delegation.complete": {+ const delegation = command.delegation;+ const current = yield* requireDelegation({+ readModel,+ command,+ delegationId: delegation.delegationId,+ });+ if (+ !NodeUtil.isDeepStrictEqual(current, {+ ...delegation,+ childTurnId: current.childTurnId,+ outcome: current.outcome,+ completedAt: current.completedAt,+ }) ||+ (current.childTurnId !== null && current.childTurnId !== delegation.childTurnId)+ ) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `Delegation '${delegation.delegationId}' ownership fields are immutable.`,+ });+ }+ if (delegation.outcome === null || delegation.completedAt === null) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `Delegation '${delegation.delegationId}' requires an outcome and completion time.`,+ });+ }+ if (delegation.outcome.status === "succeeded" && delegation.childTurnId === null) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `Successful delegation '${delegation.delegationId}' requires a child turn.`,+ });+ }+ if (Date.parse(delegation.completedAt) < Date.parse(delegation.createdAt)) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `Delegation '${delegation.delegationId}' cannot complete before it was created.`,+ });+ }++ return {+ ...(yield* withEventBase({+ aggregateKind: "delegation",+ aggregateId: delegation.delegationId,+ occurredAt: delegation.completedAt,+ commandId: command.commandId,+ })),+ type: "delegation.completed",+ payload: { delegation },+ };+ }+case "thread.create": {yield* requireProject({readModel,diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.tsindex f87dbeae8..e4dec07c1 100644--- a/apps/server/src/orchestration/projector.ts+++ b/apps/server/src/orchestration/projector.ts@@ -7,6 +7,8 @@ import type {ThreadId,} from "@t3tools/contracts";import {+ DelegationCompletedPayload,+ DelegationCreatedPayload,OrchestrationCheckpointSummary,OrchestrationMessage,OrchestrationSession,@@ -227,6 +229,7 @@ export function createEmptyReadModel(nowIso: string): OrchestrationReadModel {projects: [],bots: [],groups: [],+ delegations: [],mcpServers: [],threads: [],updatedAt: nowIso,@@ -244,6 +247,26 @@ export function projectEvent(};switch (event.type) {+ case "delegation.created":+ case "delegation.completed":+ return decodeForEvent(+ event.type === "delegation.created" ? DelegationCreatedPayload : DelegationCompletedPayload,+ event.payload,+ event.type,+ "payload",+ ).pipe(+ Effect.map((payload) => ({+ ...nextBase,+ delegations: nextBase.delegations.some(+ (entry) => entry.delegationId === payload.delegation.delegationId,+ )+ ? nextBase.delegations.map((entry) =>+ entry.delegationId === payload.delegation.delegationId ? payload.delegation : entry,+ )+ : [...nextBase.delegations, payload.delegation],+ })),+ );+case "project.created":return decodeForEvent(ProjectCreatedPayload, event.payload, event.type, "payload").pipe(Effect.map((payload) => {diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.tsindex 8e09ac462..46ed11f98 100644--- a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts+++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts@@ -1,6 +1,7 @@import {BotId,CommandId,+ DelegationId,EventId,GroupId,IsoDateTime,@@ -38,7 +39,7 @@ const EventMetadataFromJsonString = Schema.fromJsonString(OrchestrationEventMetaconst AppendEventRequestSchema = Schema.Struct({eventId: EventId,aggregateKind: OrchestrationAggregateKind,- streamId: Schema.Union([ProjectId, BotId, GroupId, McpServerId, ThreadId]),+ streamId: Schema.Union([ProjectId, BotId, GroupId, McpServerId, ThreadId, DelegationId]),type: OrchestrationEventType,causationEventId: Schema.NullOr(EventId),correlationId: Schema.NullOr(CommandId),@@ -54,7 +55,7 @@ const OrchestrationEventPersistedRowSchema = Schema.Struct({eventId: EventId,type: OrchestrationEventType,aggregateKind: OrchestrationAggregateKind,- aggregateId: Schema.Union([ProjectId, BotId, GroupId, McpServerId, ThreadId]),+ aggregateId: Schema.Union([ProjectId, BotId, GroupId, McpServerId, ThreadId, DelegationId]),occurredAt: IsoDateTime,commandId: Schema.NullOr(CommandId),causationEventId: Schema.NullOr(EventId),diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.tsindex 095cd7989..ca403b510 100644--- a/apps/server/src/persistence/Migrations.ts+++ b/apps/server/src/persistence/Migrations.ts@@ -70,6 +70,7 @@ import Migration0054 from "./Migrations/054_AkeruEntityMemory.ts";import Migration0055 from "./Migrations/055_AkeruMemoryCandidates.ts";import Migration0056 from "./Migrations/056_AkeruBotUsageLedger.ts";import Migration0057 from "./Migrations/057_AkeruMemoryCandidateUpdates.ts";+import Migration0058 from "./Migrations/058_ProjectionDelegations.ts";/*** Migration loader with all migrations defined inline.@@ -139,6 +140,7 @@ export const migrationEntries = [[55, "AkeruMemoryCandidates", Migration0055],[56, "AkeruBotUsageLedger", Migration0056],[57, "AkeruMemoryCandidateUpdates", Migration0057],+ [58, "ProjectionDelegations", Migration0058],] as const;export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);diff --git a/apps/server/src/persistence/Migrations/058_ProjectionDelegations.test.ts b/apps/server/src/persistence/Migrations/058_ProjectionDelegations.test.tsnew file mode 100644index 000000000..0de251d2f--- /dev/null+++ b/apps/server/src/persistence/Migrations/058_ProjectionDelegations.test.ts@@ -0,0 +1,37 @@+import { assert, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as SqlClient from "effect/unstable/sql/SqlClient";++import { migrationManifest, runMigrations } from "../Migrations.ts";+import * as NodeSqliteClient from "../NodeSqliteClient.ts";++it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()))("058_ProjectionDelegations", (it) => {+ it.effect("adds the delegation projection to an existing database", () =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ yield* runMigrations({ toMigrationInclusive: 57 });++ const before = yield* sql<{ readonly name: string }>`+ SELECT name FROM sqlite_master+ WHERE type = 'table' AND name = 'projection_delegations'+ `;+ assert.deepEqual(before, []);++ yield* runMigrations();+ assert.deepEqual(migrationManifest.at(-1), [58, "ProjectionDelegations"]);++ yield* sql`+ INSERT INTO projection_delegations (delegation_id, record_json)+ VALUES ('delegation-1', '{"delegationId":"delegation-1","state":"queued"}')+ `;+ const rows = yield* sql<{ readonly delegationId: string; readonly state: string }>`+ SELECT+ delegation_id AS "delegationId",+ json_extract(record_json, '$.state') AS state+ FROM projection_delegations+ `;+ assert.deepEqual(rows, [{ delegationId: "delegation-1", state: "queued" }]);+ }),+ );+});diff --git a/apps/server/src/persistence/Migrations/058_ProjectionDelegations.ts b/apps/server/src/persistence/Migrations/058_ProjectionDelegations.tsnew file mode 100644index 000000000..e6f0644c2--- /dev/null+++ b/apps/server/src/persistence/Migrations/058_ProjectionDelegations.ts@@ -0,0 +1,13 @@+import * as Effect from "effect/Effect";+import * as SqlClient from "effect/unstable/sql/SqlClient";++export default Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;++ yield* sql`+ CREATE TABLE projection_delegations (+ delegation_id TEXT PRIMARY KEY,+ record_json TEXT NOT NULL+ )+ `;+});diff --git a/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts b/apps/server/src/persistence/Services/OrchestrationCommandReceipts.tsindex 9035095aa..ce5823ffa 100644--- a/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts+++ b/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts@@ -9,6 +9,7 @@import {BotId,CommandId,+ DelegationId,GroupId,IsoDateTime,McpServerId,@@ -28,7 +29,7 @@ import type { OrchestrationCommandReceiptRepositoryError } from "../Errors.ts";export const OrchestrationCommandReceipt = Schema.Struct({commandId: CommandId,aggregateKind: OrchestrationAggregateKind,- aggregateId: Schema.Union([ProjectId, BotId, GroupId, McpServerId, ThreadId]),+ aggregateId: Schema.Union([ProjectId, BotId, GroupId, McpServerId, ThreadId, DelegationId]),acceptedAt: IsoDateTime,resultSequence: NonNegativeInt,status: OrchestrationCommandReceiptStatus,diff --git a/apps/server/src/portability.ts b/apps/server/src/portability.tsindex e3e1236d8..8176a7b6f 100644--- a/apps/server/src/portability.ts+++ b/apps/server/src/portability.ts@@ -1292,6 +1292,9 @@ function itemForCommand(case "mcp-server.enable":case "mcp-server.disable":return `mcp-server:${command.mcpServerId}`;+ case "delegation.create":+ case "delegation.complete":+ return `thread:${command.delegation.sourceThreadId}`;default:return `thread:${command.threadId}`;}diff --git a/apps/server/src/provider/AkeruDelegationRuntime.test.ts b/apps/server/src/provider/AkeruDelegationRuntime.test.tsnew file mode 100644index 000000000..bb4b2fea5--- /dev/null+++ b/apps/server/src/provider/AkeruDelegationRuntime.test.ts@@ -0,0 +1,185 @@+import { describe, expect, it, vi } from "@effect/vitest";++import {+ BotId,+ ProjectId,+ ProviderInstanceId,+ ThreadId,+ TurnId,+ type OrchestrationBot,+ type OrchestrationReadModel,+ type OrchestrationThread,+} from "@t3tools/contracts";++import { createAkeruDelegationRuntime } from "./AkeruDelegationRuntime.ts";++const sourceBotId = BotId.make("source-bot");+const targetBotId = BotId.make("target-bot");+const sourceThreadId = ThreadId.make("source-thread");+const sourceTurnId = TurnId.make("source-turn");+const now = "2026-09-01T00:00:00.000Z";++const targetBot: OrchestrationBot = {+ id: targetBotId,+ name: "Reviewer",+ title: "Reviewer",+ label: null,+ description: null,+ disabledMcpServerIds: [],+ avatar: { kind: "dither", seed: "reviewer" },+ engine: null,+ sandbox: "local",+ runtimeMode: "approval-required",+ usageCap: null,+ voiceEnabled: false,+ groupId: null,+ archivedAt: null,+ createdAt: now,+ updatedAt: now,+};++const sourceThread: OrchestrationThread = {+ id: sourceThreadId,+ projectId: ProjectId.make("project-1"),+ botId: sourceBotId,+ groupId: null,+ respondingBotId: null,+ title: "Source thread",+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },+ runtimeMode: "approval-required",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ latestTurn: null,+ createdAt: now,+ updatedAt: now,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ deletedAt: null,+ messages: [],+ proposedPlans: [],+ activities: [],+ checkpoints: [],+ session: null,+};++const snapshot: OrchestrationReadModel = {+ snapshotSequence: 0,+ projects: [],+ bots: [targetBot],+ groups: [],+ delegations: [],+ threads: [sourceThread],+ updatedAt: now,+};++const request = { botId: targetBotId, task: "Review the patch", expectedResult: "A verdict" };++describe("AkeruDelegationRuntime", () => {+ it("enforces depth from the server-owned parent context", async () => {+ const dispatch = vi.fn();+ const runtime = createAkeruDelegationRuntime({+ readSnapshot: async () => snapshot,+ dispatch,+ awaitChild: vi.fn(),+ });++ await expect(+ runtime.send(+ { threadId: sourceThreadId, turnId: sourceTurnId, botId: sourceBotId, depth: 2 },+ request,+ ),+ ).rejects.toThrow("Delegation depth cannot exceed 2");+ expect(dispatch).not.toHaveBeenCalled();+ });++ it("dispatches the child turn and bills its performing bot", async () => {+ const commands: Array<{ type: string; [key: string]: unknown }> = [];+ const runtime = createAkeruDelegationRuntime({+ readSnapshot: async () => snapshot,+ dispatch: async (command) => commands.push(command),+ awaitChild: async () => ({+ turnId: TurnId.make("child-turn"),+ result: "The patch is correct.",+ usage: { inputTokens: 11, outputTokens: 7 },+ }),+ now: () => now,+ id: (() => {+ let value = 0;+ return () => String(++value);+ })(),+ });++ const receipt = await runtime.send(+ { threadId: sourceThreadId, turnId: sourceTurnId, botId: sourceBotId, depth: 0 },+ request,+ );++ expect(commands.map((command) => command.type)).toEqual([+ "thread.create",+ "delegation.create",+ "thread.turn.start",+ "delegation.complete",+ ]);+ expect(receipt).toMatchObject({+ phase: "success",+ fatalToThread: false,+ botId: sourceBotId,+ billedBotId: targetBotId,+ usage: { inputTokens: 11, outputTokens: 7 },+ });+ });++ it("returns a nonfatal receipt when the child fails", async () => {+ const runtime = createAkeruDelegationRuntime({+ readSnapshot: async () => snapshot,+ dispatch: async () => undefined,+ awaitChild: async () => ({ turnId: null, error: "Provider unavailable" }),+ });++ await expect(+ runtime.send(+ { threadId: sourceThreadId, turnId: sourceTurnId, botId: sourceBotId, depth: 1 },+ request,+ ),+ ).resolves.toMatchObject({+ phase: "failure",+ failureCode: "internal",+ fatalToThread: false,+ billedBotId: targetBotId,+ summary: "Provider unavailable",+ });+ });++ it("records a failed delegation when child dispatch fails", async () => {+ const commands: Array<{ type: string; [key: string]: unknown }> = [];+ let resolveChild: (outcome: { turnId: null; error: string }) => void = () => undefined;+ const runtime = createAkeruDelegationRuntime({+ readSnapshot: async () => snapshot,+ dispatch: async (command) => {+ commands.push(command);+ if (command.type === "thread.turn.start") throw new Error("Provider unavailable");+ },+ awaitChild: () => new Promise((resolve) => (resolveChild = resolve)),+ failChild: (_threadId, error) => resolveChild({ turnId: null, error }),+ });++ await expect(+ runtime.send(+ { threadId: sourceThreadId, turnId: sourceTurnId, botId: sourceBotId, depth: 0 },+ request,+ ),+ ).resolves.toMatchObject({+ phase: "failure",+ fatalToThread: false,+ summary: "Provider unavailable",+ });+ expect(commands.map((command) => command.type)).toEqual([+ "thread.create",+ "delegation.create",+ "thread.turn.start",+ "delegation.complete",+ ]);+ });+});diff --git a/apps/server/src/provider/AkeruDelegationRuntime.ts b/apps/server/src/provider/AkeruDelegationRuntime.tsnew file mode 100644index 000000000..b0bc2efaf--- /dev/null+++ b/apps/server/src/provider/AkeruDelegationRuntime.ts@@ -0,0 +1,167 @@+// @effect-diagnostics globalDate:off globalRandom:off nodeBuiltinImport:off+import * as NodeCrypto from "node:crypto";++import {+ AKERU_DELEGATION_MAX_DEPTH,+ CommandId,+ DelegationId,+ MessageId,+ ProviderInstanceId,+ ThreadId,+ type AkeruDelegationRecord,+ type AkeruToolInputSchemas,+ type AkeruToolReceipt,+ type BotId,+ type OrchestrationCommand,+ type OrchestrationReadModel,+ type TurnId,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";++export interface AkeruDelegationParent {+ readonly threadId: ThreadId;+ readonly turnId: TurnId;+ readonly botId: BotId;+ readonly depth: number;+}++export interface AkeruDelegationChildOutcome {+ readonly turnId: TurnId | null;+ readonly result?: string;+ readonly error?: string;+ readonly usage?: { readonly inputTokens?: number; readonly outputTokens?: number };+}++export interface AkeruDelegationRuntimeOptions {+ readonly readSnapshot: () => Promise<OrchestrationReadModel>;+ readonly dispatch: (command: OrchestrationCommand) => Promise<unknown>;+ readonly awaitChild: (threadId: ThreadId) => Promise<AkeruDelegationChildOutcome>;+ readonly failChild?: (threadId: ThreadId, error: string) => void;+ readonly now?: () => string;+ readonly id?: () => string;+}++export function createAkeruDelegationRuntime(options: AkeruDelegationRuntimeOptions) {+ const now = options.now ?? (() => DateTime.formatIso(DateTime.nowUnsafe()));+ const id = options.id ?? (() => NodeCrypto.randomUUID());+ const commandId = (label: string) => CommandId.make(`delegation:${label}:${id()}`);++ const send = async (+ parent: AkeruDelegationParent,+ request: (typeof AkeruToolInputSchemas.SendToAgent)["Type"],+ ): Promise<AkeruToolReceipt> => {+ if (parent.depth >= AKERU_DELEGATION_MAX_DEPTH) {+ throw new Error(`Delegation depth cannot exceed ${AKERU_DELEGATION_MAX_DEPTH}.`);+ }+ const snapshot = await options.readSnapshot();+ const sourceThread = snapshot.threads.find((thread) => thread.id === parent.threadId);+ const targetBot = snapshot.bots.find((bot) => bot.id === request.botId);+ if (!sourceThread || !targetBot || targetBot.archivedAt !== null) {+ throw new Error("The target bot is not available.");+ }+ if (targetBot.id === parent.botId) throw new Error("A bot cannot delegate to itself.");++ const childThreadId = ThreadId.make(`delegation-thread-${id()}`);+ const createdAt = now();+ await options.dispatch({+ type: "thread.create",+ commandId: commandId("thread"),+ threadId: childThreadId,+ projectId: sourceThread.projectId,+ botId: targetBot.id,+ groupId: null,+ title: `Delegation to ${targetBot.name}`,+ modelSelection:+ targetBot.engine === null+ ? sourceThread.modelSelection+ : {+ instanceId: ProviderInstanceId.make(targetBot.engine.provider),+ model: targetBot.engine.model,+ },+ runtimeMode: targetBot.runtimeMode,+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ createdAt,+ });+ const delegationId = DelegationId.make(`delegation-${id()}`);+ const active = {+ delegationId,+ sourceThreadId: parent.threadId,+ sourceTurnId: parent.turnId,+ sourceBotId: parent.botId,+ targetBotId: targetBot.id,+ childThreadId,+ childTurnId: null,+ depth: parent.depth + 1,+ billedBotId: targetBot.id,+ task: request.task,+ expectedResult: request.expectedResult,+ outcome: null,+ createdAt,+ completedAt: null,+ } satisfies AkeruDelegationRecord;+ await options.dispatch({+ type: "delegation.create",+ commandId: commandId("create"),+ delegation: active,+ });+ const childOutcome = options.awaitChild(childThreadId);+ try {+ await options.dispatch({+ type: "thread.turn.start",+ commandId: commandId("turn"),+ threadId: childThreadId,+ message: {+ messageId: MessageId.make(`delegation-message-${id()}`),+ role: "user",+ text: `${request.task}\n\nExpected result: ${request.expectedResult}`,+ attachments: [],+ },+ runtimeMode: targetBot.runtimeMode,+ interactionMode: "default",+ createdAt: now(),+ });+ } catch (cause) {+ options.failChild?.(childThreadId, cause instanceof Error ? cause.message : String(cause));+ }++ const child = await childOutcome;+ const completedAt = now();+ const result = child.result?.trim();+ const completed: AkeruDelegationRecord = {+ ...active,+ childTurnId: child.turnId,+ outcome: result+ ? { status: "succeeded", result }+ : { status: "failed", error: child.error ?? "The delegated bot did not return a result." },+ completedAt,+ };+ await options.dispatch({+ type: "delegation.complete",+ commandId: commandId("complete"),+ delegation: completed,+ });++ return {+ receiptId: `delegation:${delegationId}`,+ toolId: "SendToAgent",+ phase: result ? "success" : "failure",+ threadId: parent.threadId,+ botId: parent.botId,+ summary: result ?? child.error ?? "The delegated bot did not return a result.",+ ...(result ? {} : { failureCode: "internal" as const }),+ fatalToThread: false,+ billedBotId: targetBot.id,+ usage: {+ inputTokens: child.usage?.inputTokens ?? 0,+ outputTokens: child.usage?.outputTokens ?? 0,+ },+ createdAt: completedAt,+ };+ };++ return { send, readSnapshot: options.readSnapshot };+}++export type AkeruDelegationRuntime = ReturnType<typeof createAkeruDelegationRuntime>;diff --git a/apps/server/src/provider/AkeruToolRuntime.test.ts b/apps/server/src/provider/AkeruToolRuntime.test.tsindex 2ae38e375..b85fb28cf 100644--- a/apps/server/src/provider/AkeruToolRuntime.test.ts+++ b/apps/server/src/provider/AkeruToolRuntime.test.ts@@ -243,6 +243,40 @@ describe("AkeruToolRuntime", () => {]);});+ it("isolates delegation failures from the parent thread", async () => {+ const runtime = createAkeruToolRuntime();+ const execution = {+ threadId: "thread-1",+ toolId: "SendToAgent" as const,+ toolCallId: "tool-delegate",+ input: {+ botId: BotId.make("reviewer"),+ task: "Review the patch",+ expectedResult: "A verdict",+ },+ approvalMode: "require-grant" as const,+ };+ runtime.registerSession("thread-1", {+ botId: BotId.make("parent"),+ runtimeMode: "full-access",+ workspaceType: "local",+ delegation: {+ send: async () => {+ throw new Error("Provider unavailable");+ },+ },+ });+ runtime.grantApproval(execution);++ await expect(runtime.execute(execution)).resolves.toMatchObject({+ phase: "failure",+ failureCode: "internal",+ fatalToThread: false,+ billedBotId: "reviewer",+ summary: "Provider unavailable",+ });+ });+it("translates await handles to workspace process ids", async () => {const runtime = createAkeruToolRuntime();runtime.registerSession("thread-1", {diff --git a/apps/server/src/provider/AkeruToolRuntime.ts b/apps/server/src/provider/AkeruToolRuntime.tsindex f300b95e9..f469faa76 100644--- a/apps/server/src/provider/AkeruToolRuntime.ts+++ b/apps/server/src/provider/AkeruToolRuntime.ts@@ -2,15 +2,18 @@ import { RequestContext } from "@mastra/core/request-context";import { createWorkspaceTools, type Workspace } from "@mastra/core/workspace";import {AkeruToolInputSchemas,+ type AkeruToolReceipt,type BotId,type AkeruToolDefinition,type AkeruToolId,type AkeruToolWorkspaceType,type RuntimeMode,+ ThreadId,akeruToolRequiresApproval,decodeAkeruToolInput,filterAkeruTools,} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";import * as Schema from "effect/Schema";import type { UserActionIncidentInput } from "../bot-inbox/userActionIncidents.ts";@@ -54,10 +57,16 @@ export interface AkeruToolSession {readonly workspace?: Workspace;readonly userComputerWorkspace?: Workspace;readonly memoryHandlers?: Record<AkeruMemoryToolId, AkeruMemoryToolHandler>;+ readonly delegation?: {+ readonly send: (+ input: (typeof AkeruToolInputSchemas.SendToAgent)["Type"],+ ) => Promise<AkeruToolReceipt>;+ };}export interface AkeruToolRuntimeOptions {readonly onUserActionRequired?: (input: UserActionIncidentInput) => void | Promise<void>;+ readonly now?: () => string;}export interface AkeruToolExecution {@@ -83,7 +92,7 @@ export interface AkeruToolRuntime {}const BACKEND_NAMES: Record<- Exclude<AkeruToolId, "CopyToBox" | "CopyFromBox" | "request_box_help">,+ Exclude<AkeruToolId, "CopyToBox" | "CopyFromBox" | "request_box_help" | "SendToAgent">,ReadonlyArray<string>> = {Shell: ["execute_command", "mastra_workspace_execute_command"],@@ -176,6 +185,7 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akeruif (options?.onUserActionRequired && session.workspace && session.botId && session.botName) {tools.add("request_box_help");}+ if (session.delegation) tools.add("SendToAgent");return tools;};@@ -279,6 +289,27 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akerureturn handler({ ...input, toolId: input.toolId, input: decoded });}+ if (input.toolId === "SendToAgent") {+ if (!session.delegation) throw new Error("Delegation is not available for this session.");+ const delegationInput = decodeAkeruToolInput("SendToAgent", decoded);+ try {+ return await session.delegation.send(delegationInput);+ } catch (cause) {+ return {+ receiptId: input.toolCallId,+ toolId: input.toolId,+ phase: "failure",+ threadId: ThreadId.make(input.threadId),+ botId: session.botId,+ summary: cause instanceof Error ? cause.message : String(cause),+ failureCode: "internal",+ fatalToThread: false,+ billedBotId: delegationInput.botId,+ createdAt: options?.now?.() ?? DateTime.formatIso(DateTime.nowUnsafe()),+ } satisfies AkeruToolReceipt;+ }+ }+if (input.toolId === "CopyToBox" || input.toolId === "CopyFromBox") {const source =input.toolId === "CopyToBox" ? session.userComputerWorkspace : session.workspace;diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.tsindex 27485521f..9b4e7d2d4 100644--- a/apps/server/src/provider/Layers/AgentController.ts+++ b/apps/server/src/provider/Layers/AgentController.ts@@ -62,6 +62,11 @@ import {type AkeruMastraSession,} from "../AkeruMastraHarness.ts";import { AKERU_BOT_TURN_INSTRUCTIONS } from "../AkeruAgentInstructions.ts";+import {+ createAkeruDelegationRuntime,+ type AkeruDelegationChildOutcome,+ type AkeruDelegationRuntime,+} from "../AkeruDelegationRuntime.ts";import {createAkeruToolRuntime,isMemoryToolId,@@ -105,6 +110,9 @@ interface ActiveTurn {waiting: boolean;finished: boolean;memoryQueued: boolean;+ assistantText: string;+ inputTokens: number;+ outputTokens: number;}interface ActiveSession {@@ -304,6 +312,15 @@ const make = (options?: AgentControllerLiveOptions) =>const runtimeEvents = yield* PubSub.unbounded<ProviderRuntimeEvent>();const resolvedByThread = new Map<string, ResolvedEngine>();const sessions = new Map<string, ActiveSession>();+ let delegationRuntime: AkeruDelegationRuntime | undefined;+ const childWaiters = new Map<+ string,+ { readonly resolve: (outcome: AkeruDelegationChildOutcome) => void }+ >();+ const resolveChildWaiter = (threadId: ThreadId, outcome: AkeruDelegationChildOutcome) => {+ childWaiters.get(String(threadId))?.resolve(outcome);+ childWaiters.delete(String(threadId));+ };const runMastra = <A>(operation: string, run: () => Promise<A>) =>Effect.tryPromise({@@ -472,6 +489,13 @@ const make = (options?: AgentControllerLiveOptions) =>...(errorMessage ? { errorMessage } : {}),},});+ resolveChildWaiter(threadId, {+ turnId: turn.turnId,+ ...(state === "completed" && turn.assistantText.trim()+ ? { result: turn.assistantText.trim() }+ : { error: errorMessage ?? `The delegated turn ${state}.` }),+ usage: { inputTokens: turn.inputTokens, outputTokens: turn.outputTokens },+ });active.approvalRequests.clear();toolRuntime.clearApprovals(String(threadId));active.activeTurn = null;@@ -488,6 +512,7 @@ const make = (options?: AgentControllerLiveOptions) =>const turn = active.activeTurn;if (!turn) return;const text = messageText(message);+ turn.assistantText = text;const messageKey = String(message.id);let activeMessage = turn.assistantMessages.get(messageKey);if (!activeMessage) {@@ -666,6 +691,8 @@ const make = (options?: AgentControllerLiveOptions) =>return;case "usage_update":if (!turn) return;+ turn.inputTokens = Math.max(0, event.usage.promptTokens ?? 0);+ turn.outputTokens = Math.max(0, event.usage.completionTokens ?? 0);publish({...baseEvent(threadId, active, turn.turnId),type: "thread.token-usage.updated",@@ -883,6 +910,31 @@ const make = (options?: AgentControllerLiveOptions) =>? { userComputerWorkspace: resources.userComputerWorkspace }: {}),...(registeredMemoryHandlers ? { memoryHandlers: registeredMemoryHandlers } : {}),+ ...(input.botId && delegationRuntime+ ? {+ delegation: {+ send: async (request) => {+ const active = sessions.get(key);+ const turnId = active?.activeTurn?.turnId;+ if (!turnId) throw new Error("Delegation requires an active parent turn.");+ const snapshot = await delegationRuntime!.readSnapshot();+ const parentDelegation = snapshot.delegations.find(+ (delegation) =>+ delegation.childThreadId === threadId && delegation.outcome === null,+ );+ return delegationRuntime!.send(+ {+ threadId,+ turnId,+ botId: input.botId!,+ depth: parentDelegation?.depth ?? 0,+ },+ request,+ );+ },+ },+ }+ : {}),};toolRuntime.registerSession(key, toolSession);const session = yield* runMastra("createSession", () =>@@ -1046,6 +1098,9 @@ const make = (options?: AgentControllerLiveOptions) =>waiting: false,finished: false,memoryQueued: false,+ assistantText: "",+ inputTokens: 0,+ outputTokens: 0,};active.status = "running";publish({@@ -1253,6 +1308,24 @@ const make = (options?: AgentControllerLiveOptions) =>);return AgentController.of({+ configureDelegation: (input) =>+ Effect.sync(() => {+ delegationRuntime = createAkeruDelegationRuntime({+ ...input,+ failChild: (threadId, error) => resolveChildWaiter(threadId, { turnId: null, error }),+ awaitChild: (threadId) =>+ new Promise((resolve, reject) => {+ const key = String(threadId);+ if (childWaiters.has(key)) {+ reject(new Error(`Delegation waiter already exists for '${threadId}'.`));+ return;+ }+ childWaiters.set(key, { resolve });+ }),+ });+ }),+ failDelegation: ({ threadId, error }) =>+ Effect.sync(() => resolveChildWaiter(threadId, { turnId: null, error })),readConversationMemory: (threadId) =>bundle.readObservationalMemory? runMastra("memory.read", () =>diff --git a/apps/server/src/provider/Services/AgentController.ts b/apps/server/src/provider/Services/AgentController.tsindex 2d57dd3d8..bbd45cbe8 100644--- a/apps/server/src/provider/Services/AgentController.ts+++ b/apps/server/src/provider/Services/AgentController.ts@@ -15,6 +15,8 @@ import type {ProviderTurnStartResult,ProviderUploadFeedbackInput,ProviderUploadFeedbackResult,+ OrchestrationCommand,+ OrchestrationReadModel,ThreadId,} from "@t3tools/contracts";import * as Context from "effect/Context";@@ -36,6 +38,15 @@ export interface AgentControllerEngineSelection extends AgentControllerAvailable}export interface AgentControllerShape {+ readonly configureDelegation?: (input: {+ readonly readSnapshot: () => Promise<OrchestrationReadModel>;+ readonly dispatch: (command: OrchestrationCommand) => Promise<unknown>;+ }) => Effect.Effect<void>;+ readonly failDelegation?: (input: {+ readonly threadId: ThreadId;+ readonly error: string;+ }) => Effect.Effect<void>;+readonly readConversationMemory?: (threadId: ThreadId,) => Effect.Effect<AkeruConversationMemorySnapshot, AgentControllerError>;diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.tsindex 7436b676c..1049e51a6 100644--- a/apps/server/src/server.test.ts+++ b/apps/server/src/server.test.ts@@ -216,6 +216,7 @@ const makeDefaultOrchestrationReadModel = () => {updatedAt: now,bots: [],groups: [],+ delegations: [],projects: [{id: defaultProjectId,@@ -6229,6 +6230,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {updatedAt: now,bots: [],groups: [],+ delegations: [],projects: [{id: ProjectId.make("project-a"),diff --git a/packages/contracts/src/akeruTools.test.ts b/packages/contracts/src/akeruTools.test.tsindex 6cd2aa334..cfddaed01 100644--- a/packages/contracts/src/akeruTools.test.ts+++ b/packages/contracts/src/akeruTools.test.ts@@ -37,6 +37,18 @@ describe("Akeru tool contracts", () => {expect(AKERU_TOOL_CATALOG.map((tool) => tool.id)).not.toContain("RestartMcpServers");});+ it("decodes SendToAgent input and rejects server-owned fields", () => {+ const input = {+ botId: "bot-research",+ task: "Compare three flights.",+ expectedResult: "A short comparison with sources.",+ };++ expect(decodeAkeruToolInput("SendToAgent", input)).toEqual(input);+ expect(() => decodeAkeruToolInput("SendToAgent", { ...input, depth: 2 })).toThrow();+ expect(AKERU_TOOL_CATALOG.find((tool) => tool.id === "SendToAgent")?.approval).toBe("send");+ });+it("never lets full access bypass protected commands or paths", () => {const shell = AKERU_TOOL_CATALOG.find((tool) => tool.id === "ExternalShell")!;const read = AKERU_TOOL_CATALOG.find((tool) => tool.id === "ExternalRead")!;diff --git a/packages/contracts/src/akeruTools.ts b/packages/contracts/src/akeruTools.tsindex 14fe5511e..b15db64cf 100644--- a/packages/contracts/src/akeruTools.ts+++ b/packages/contracts/src/akeruTools.ts@@ -42,9 +42,24 @@ export const AkeruToolInputSchemas = {ExternalRead: PathInput,AwaitShell: Schema.Struct({ handleId: AkeruAwaitHandleId }),AwaitExternalShell: Schema.Struct({ handleId: AkeruAwaitHandleId }),+ SendToAgent: Schema.Struct({+ botId: BotId,+ task: TrimmedNonEmptyString,+ expectedResult: TrimmedNonEmptyString,+ }),} as const;export type AkeruToolId = keyof typeof AkeruToolInputSchemas;+const AkeruToolInputDecoders = Object.fromEntries(+ Object.entries(AkeruToolInputSchemas).map(([toolId, schema]) => [+ toolId,+ Schema.decodeUnknownSync(schema),+ ]),+) as Record<+ AkeruToolId,+ (input: unknown, options: { readonly onExcessProperty: "error" }) => unknown+>;+export const AkeruProtectedApprovalClass = Schema.Literals(["send","pay",@@ -160,6 +175,9 @@ export const AKERU_TOOL_CATALOG = [workspace: "user-computer",requiresUserComputer: true,}),+ define("SendToAgent", "bot-workspace", "Delegate a task to another bot.", {+ approval: "send",+ }),] satisfies ReadonlyArray<AkeruToolDefinition>;export interface AkeruToolAvailabilityContext {@@ -259,7 +277,7 @@ export function decodeAkeruToolInput<Name extends AkeruToolId>(toolId: Name,input: unknown,): (typeof AkeruToolInputSchemas)[Name]["Type"] {- return Schema.decodeUnknownSync(AkeruToolInputSchemas[toolId])(input, {+ return AkeruToolInputDecoders[toolId](input, {onExcessProperty: "error",}) as (typeof AkeruToolInputSchemas)[Name]["Type"];}diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.tsindex 7e4d635c7..866b3974d 100644--- a/packages/contracts/src/orchestration.test.ts+++ b/packages/contracts/src/orchestration.test.ts@@ -4,6 +4,7 @@ import * as Schema from "effect/Schema";import { MessageId } from "./baseSchemas.ts";import {+ AkeruDelegationRecord,BotAvatar,DEFAULT_LOCAL_EXECUTION_MODE,DEFAULT_PROVIDER_INTERACTION_MODE,@@ -16,6 +17,7 @@ import {OrchestrationGetFullThreadDiffInput,OrchestrationGetTurnDiffInput,OrchestrationLatestTurn,+ OrchestrationReadModel,ProjectCreatedPayload,ProjectMetaUpdatedPayload,OrchestrationProposedPlan,@@ -45,6 +47,8 @@ const decodeThreadTurnStartRequestedPayload = Schema.decodeUnknownEffect(ThreadTurnStartRequestedPayload,);const decodeOrchestrationLatestTurn = Schema.decodeUnknownEffect(OrchestrationLatestTurn);+const decodeOrchestrationReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);+const decodeAkeruDelegationRecord = Schema.decodeUnknownEffect(AkeruDelegationRecord);const decodeOrchestrationProposedPlan = Schema.decodeUnknownEffect(OrchestrationProposedPlan);const decodeOrchestrationSession = Schema.decodeUnknownEffect(OrchestrationSession);const decodeOrchestrationThread = Schema.decodeUnknownEffect(OrchestrationThread);@@ -596,6 +600,38 @@ it.effect("defaults settled fields when decoding historical thread data", () =>}),);+it.effect("decodes delegation records and defaults historical read models", () =>+ Effect.gen(function* () {+ const delegation = yield* decodeAkeruDelegationRecord({+ delegationId: "delegation-1",+ sourceThreadId: "thread-source",+ sourceTurnId: "turn-source",+ sourceBotId: "bot-source",+ targetBotId: "bot-target",+ childThreadId: "thread-child",+ childTurnId: null,+ depth: 1,+ billedBotId: "bot-target",+ task: "Compare three flights.",+ expectedResult: "A short comparison with sources.",+ outcome: null,+ createdAt: "2026-08-31T12:00:00.000Z",+ completedAt: null,+ });+ assert.strictEqual(delegation.targetBotId, "bot-target");++ const readModel = yield* decodeOrchestrationReadModel({+ snapshotSequence: 0,+ projects: [],+ bots: [],+ groups: [],+ threads: [],+ updatedAt: "2026-08-31T12:00:00.000Z",+ });+ assert.deepEqual(readModel.delegations, []);+ }),+);+it.effect("decodes thread archived and unarchived events", () =>Effect.gen(function* () {const archived = yield* decodeOrchestrationEvent({diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.tsindex 90dc7d3cc..0816cc820 100644--- a/packages/contracts/src/orchestration.ts+++ b/packages/contracts/src/orchestration.ts@@ -553,11 +553,49 @@ export const OrchestrationThread = Schema.Struct({});export type OrchestrationThread = typeof OrchestrationThread.Type;+export const AKERU_DELEGATION_MAX_DEPTH = 2;++export const DelegationId = TrimmedNonEmptyString.pipe(Schema.brand("DelegationId"));+export type DelegationId = typeof DelegationId.Type;++export const AkeruDelegationOutcome = Schema.Union([+ Schema.Struct({+ status: Schema.Literal("succeeded"),+ result: TrimmedNonEmptyString,+ }),+ Schema.Struct({+ status: Schema.Literal("failed"),+ error: TrimmedNonEmptyString,+ }),+]);+export type AkeruDelegationOutcome = typeof AkeruDelegationOutcome.Type;++export const AkeruDelegationRecord = Schema.Struct({+ delegationId: DelegationId,+ sourceThreadId: ThreadId,+ sourceTurnId: TurnId,+ sourceBotId: BotId,+ targetBotId: BotId,+ childThreadId: ThreadId,+ childTurnId: Schema.NullOr(TurnId),+ depth: PositiveInt.check(Schema.isLessThanOrEqualTo(AKERU_DELEGATION_MAX_DEPTH)),+ billedBotId: BotId,+ task: TrimmedNonEmptyString,+ expectedResult: TrimmedNonEmptyString,+ outcome: Schema.NullOr(AkeruDelegationOutcome),+ createdAt: IsoDateTime,+ completedAt: Schema.NullOr(IsoDateTime),+});+export type AkeruDelegationRecord = typeof AkeruDelegationRecord.Type;+export const OrchestrationReadModel = Schema.Struct({snapshotSequence: NonNegativeInt,projects: Schema.Array(OrchestrationProject),bots: Schema.Array(OrchestrationBot).pipe(Schema.withDecodingDefault(Effect.succeed([]))),groups: Schema.Array(OrchestrationGroup).pipe(Schema.withDecodingDefault(Effect.succeed([]))),+ delegations: Schema.Array(AkeruDelegationRecord).pipe(+ Schema.withDecodingDefault(Effect.succeed([])),+ ),mcpServers: Schema.optional(Schema.Array(McpServer)),threads: Schema.Array(OrchestrationThread),updatedAt: IsoDateTime,@@ -1445,6 +1483,18 @@ const ThreadTitleRegenerationCompleteCommand = Schema.Struct({title: Schema.optional(TrimmedNonEmptyString),});+export const DelegationCreateCommand = Schema.Struct({+ type: Schema.Literal("delegation.create"),+ commandId: CommandId,+ delegation: AkeruDelegationRecord,+});++export const DelegationCompleteCommand = Schema.Struct({+ type: Schema.Literal("delegation.complete"),+ commandId: CommandId,+ delegation: AkeruDelegationRecord,+});+const InternalOrchestrationCommand = Schema.Union([ThreadSessionSetCommand,ThreadMessageAssistantDeltaCommand,@@ -1455,6 +1505,8 @@ const InternalOrchestrationCommand = Schema.Union([ThreadHistoryRestoreCommand,ThreadRevertCompleteCommand,ThreadTitleRegenerationCompleteCommand,+ DelegationCreateCommand,+ DelegationCompleteCommand,]);export type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;@@ -1509,6 +1561,8 @@ export const OrchestrationEventType = Schema.Literals(["thread.proposed-plan-upserted","thread.turn-diff-completed","thread.activity-appended",+ "delegation.created",+ "delegation.completed",]);export type OrchestrationEventType = typeof OrchestrationEventType.Type;@@ -1518,6 +1572,7 @@ export const OrchestrationAggregateKind = Schema.Literals(["group","mcp-server","thread",+ "delegation",]);export type OrchestrationAggregateKind = typeof OrchestrationAggregateKind.Type;export const OrchestrationActorKind = Schema.Literals(["client", "server", "provider"]);@@ -1866,6 +1921,11 @@ export const ThreadActivityAppendedPayload = Schema.Struct({activity: OrchestrationThreadActivity,});+export const DelegationCreatedPayload = Schema.Struct({+ delegation: AkeruDelegationRecord,+});+export const DelegationCompletedPayload = DelegationCreatedPayload;+/*** Which client connection dispatched the command that produced an event.* Stamped by the orchestration engine on client-dispatched commands; absent on@@ -1893,7 +1953,7 @@ const EventBaseFields = {sequence: NonNegativeInt,eventId: EventId,aggregateKind: OrchestrationAggregateKind,- aggregateId: Schema.Union([ProjectId, BotId, GroupId, McpServerId, ThreadId]),+ aggregateId: Schema.Union([ProjectId, BotId, GroupId, McpServerId, ThreadId, DelegationId]),occurredAt: IsoDateTime,commandId: Schema.NullOr(CommandId),causationEventId: Schema.NullOr(EventId),@@ -2122,6 +2182,16 @@ export const OrchestrationEvent = Schema.Union([type: Schema.Literal("thread.activity-appended"),payload: ThreadActivityAppendedPayload,}),+ Schema.Struct({+ ...EventBaseFields,+ type: Schema.Literal("delegation.created"),+ payload: DelegationCreatedPayload,+ }),+ Schema.Struct({+ ...EventBaseFields,+ type: Schema.Literal("delegation.completed"),+ payload: DelegationCompletedPayload,+ }),]);export type OrchestrationEvent = typeof OrchestrationEvent.Type;