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): enforce bounded bot delegation (#77)
Leoa7558a518e94
diff --git a/apps/server/src/memory/MemoryToolHandlers.test.ts b/apps/server/src/memory/MemoryToolHandlers.test.tsindex bde37a42a..fda3e7e5c 100644--- a/apps/server/src/memory/MemoryToolHandlers.test.ts+++ b/apps/server/src/memory/MemoryToolHandlers.test.ts@@ -105,6 +105,37 @@ it.layer(layer)("MemoryToolHandlers", (it) => {}),);+ it.effect("enforces delegated memory scopes on reads and writes", () =>+ Effect.gen(function* () {+ const repository = yield* EntityMemoryRepository;+ const candidates = yield* MemoryCandidateRepository;+ const unrestricted = createMemoryToolHandlers(repository, candidates, access);+ yield* Effect.promise(() =>+ execute("remember", unrestricted.remember, {+ fact: "Private delegated detail.",+ scope: "private",+ }),+ );+ const restricted = createMemoryToolHandlers(repository, candidates, access, undefined, [+ "project",+ ]);+ const recalled = (yield* Effect.promise(() =>+ execute("recall_memory", restricted.recall_memory, { query: "Private delegated detail" }),+ )) as ReadonlyArray<{ readonly scope: string }>;+ assert.deepEqual(recalled, []);+ const rejected = yield* Effect.promise(() =>+ execute("remember", restricted.remember, {+ fact: "Another private detail.",+ scope: "private",+ }).then(+ () => false,+ () => true,+ ),+ );+ assert.isTrue(rejected);+ }),+ );+it.effect("updates private non-sensitive facts directly", () =>Effect.gen(function* () {const repository = yield* EntityMemoryRepository;diff --git a/apps/server/src/memory/MemoryToolHandlers.ts b/apps/server/src/memory/MemoryToolHandlers.tsindex b05f212bb..0a497c28a 100644--- a/apps/server/src/memory/MemoryToolHandlers.ts+++ b/apps/server/src/memory/MemoryToolHandlers.ts@@ -249,7 +249,26 @@ export function createMemoryToolHandlers(readonly rootId: AkeruMemoryRootId;readonly affectedBotIds: ReadonlyArray<string>;}) => void | Promise<void>,+ allowedScopes?: ReadonlyArray<AkeruMemoryTargetScope>,): Record<AkeruMemoryToolId, AkeruMemoryToolHandler> {+ const allowed = allowedScopes ? new Set(allowedScopes) : undefined;+ const requireAllowed = (scope: AkeruMemoryTargetScope) => {+ if (allowed && !allowed.has(scope)) {+ throw new Error(`Memory scope '${scope}' is outside this delegation's grant.`);+ }+ };+ const revisionScope = (revision: AkeruMemoryRevision) => {+ const scope = revision.partition.scope;+ if (scope === "bot-user" || scope === "user") return "private" as const;+ return scope === "bot" || scope === "project" || scope === "group" || scope === "workspace"+ ? scope+ : undefined;+ };+ const requireAllowedRevision = (revision: AkeruMemoryRevision) => {+ const scope = revisionScope(revision);+ if (!scope) throw new Error("This memory scope is outside the delegation grant.");+ requireAllowed(scope);+ };const createCandidate = async (fact: string,scope: AkeruMemoryTargetScope,@@ -294,6 +313,7 @@ export function createMemoryToolHandlers();const includeSensitive = field(input, "includeSensitive") === true;return rows+ .filter((revision) => !allowed || allowed.has(revisionScope(revision)!)).filter((revision) => includeSensitive || !revision.sensitive).map((revision) => ({memoryId: revision.rootId,@@ -307,6 +327,7 @@ export function createMemoryToolHandlers(},remember: async ({ input }) => {const scope = targetScope(input);+ requireAllowed(scope);const sensitive = field(input, "sensitive") === true;const fact = stringField(input, "fact");const now = nowIso();@@ -323,6 +344,8 @@ export function createMemoryToolHandlers(const expected = expectedRevision(input);const current = await Effect.runPromise(repository.getCurrent({ access, rootId }));const scope = targetScope(input);+ requireAllowedRevision(current);+ requireAllowed(scope);const sensitive =typeof field(input, "sensitive") === "boolean"? field(input, "sensitive") === true@@ -353,6 +376,7 @@ export function createMemoryToolHandlers(},forget_memory: async ({ input }) => {const rootId = AkeruMemoryRootId.make(stringField(input, "memoryId"));+ requireAllowedRevision(await Effect.runPromise(repository.getCurrent({ access, rootId })));const tombstone = await Effect.runPromise(repository.tombstone({access,diff --git a/apps/server/src/orchestration/Layers/DelegationPersistence.test.ts b/apps/server/src/orchestration/Layers/DelegationPersistence.test.tsindex a8acd964c..8479ae0e4 100644--- a/apps/server/src/orchestration/Layers/DelegationPersistence.test.ts+++ b/apps/server/src/orchestration/Layers/DelegationPersistence.test.ts@@ -3,7 +3,8 @@ import {BotId,CommandId,DelegationId,- EventId,+ ProjectId,+ ProviderInstanceId,ThreadId,TurnId,type AkeruDelegationRecord,@@ -17,10 +18,10 @@ 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 { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";@@ -31,76 +32,111 @@ import {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 PARENT_BOT_ID = BotId.make("bot-parent");+const CHILD_BOT_ID = BotId.make("bot-child");+const PARENT_THREAD_ID = ThreadId.make("thread-parent");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"),+ parentDelegationId: null,+ parentBotId: PARENT_BOT_ID,+ childBotId: CHILD_BOT_ID,+ parentThreadId: PARENT_THREAD_ID,+ childThreadId: null,+ parentTurnId: TurnId.make("turn-parent"),+ childTurnId: null,+ ancestorBotIds: [PARENT_BOT_ID],depth: 1,- billedBotId: TARGET_BOT_ID,task: "Compare three flights.",expectedResult: "A short comparison with sources.",- outcome: null,+ deadline: null,+ access: {+ allowedToolIds: ["Read"],+ memoryScopes: ["project"],+ sandbox: "daytona",+ runtimeMode: "approval-required",+ hasUserComputer: false,+ enabledMcpServerIds: [],+ disabledMcpServerIds: [],+ approvalCeiling: "send",+ },+ state: "queued",+ billedBotId: CHILD_BOT_ID,+ result: null,+ failure: null,+ keep: false,createdAt: NOW,+ updatedAt: NOW,+ startedAt: null,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(OrchestrationEventStoreLive),Layer.provide(OrchestrationCommandReceiptRepositoryLive),Layer.provide(RepositoryIdentityResolver.layer),Layer.provideMerge(makeSqlitePersistenceLive(dbPath)),);-it.effect("replays the completed delegation after a restart", () =>+it.effect("rebuilds the full delegation record 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 },+ const engine = yield* OrchestrationEngineService;+ const projectId = ProjectId.make("project-1");+ for (const [id, name] of [+ [PARENT_BOT_ID, "Parent"],+ [CHILD_BOT_ID, "Child"],+ ] as const) {+ yield* engine.dispatch({+ type: "bot.create",+ commandId: CommandId.make(`command-${name.toLowerCase()}-bot`),+ botId: id,+ name,+ title: "Agent",+ avatar: { kind: "dither", seed: id },+ engine: null,+ sandbox: "local",+ runtimeMode: "approval-required",+ usageCap: null,+ groupId: null,+ createdAt: NOW,+ });+ }+ yield* engine.dispatch({+ type: "project.create",+ commandId: CommandId.make("command-project"),+ projectId,+ title: "Delegation project",+ workspaceRoot: "/tmp/delegation-project",+ defaultModelSelection: null,+ createdAt: NOW,+ });+ yield* engine.dispatch({+ type: "thread.create",+ commandId: CommandId.make("command-parent-thread"),+ threadId: PARENT_THREAD_ID,+ projectId,+ botId: PARENT_BOT_ID,+ groupId: null,+ title: "Parent thread",+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6" },+ runtimeMode: "approval-required",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ createdAt: NOW,});- 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 },+ yield* engine.dispatch({+ type: "delegation.create",+ commandId: CommandId.make("command-delegation"),+ delegation,});}).pipe(Effect.provide(makeLayer(dbPath)));@@ -118,13 +154,13 @@ it.effect("replays the completed delegation after a restart", () =>const snapshot = yield* snapshots.getSnapshot();const commandReadModel = yield* snapshots.getCommandReadModel();- assert.deepEqual(snapshot.delegations, [completedDelegation]);- assert.deepEqual(commandReadModel.delegations, [completedDelegation]);+ assert.deepEqual(snapshot.delegations, [delegation]);+ assert.deepEqual(commandReadModel.delegations, [delegation]);}).pipe(Effect.provide(makeLayer(dbPath)));}).pipe(Effect.provide(Layer.provideMerge(- ServerConfig.layerTest(process.cwd(), { prefix: "akeru-delegation-persistence-test-" }),+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-delegation-persistence-test-" }),NodeServices.layer,),),diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.tsindex 9155cc618..9beb24fc9 100644--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts@@ -98,11 +98,16 @@ function commandToAggregateRef(command: OrchestrationCommand): {aggregateId: command.mcpServerId,};case "delegation.create":- case "delegation.complete":+ case "delegation.state.set":return {aggregateKind: "delegation",aggregateId: command.delegation.delegationId,};+ case "delegation.cancel":+ return {+ aggregateKind: "delegation",+ aggregateId: command.delegationId,+ };default:return {aggregateKind: "thread",diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex 6de74143a..7b36274be 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -766,7 +766,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecticonst applyDelegationsProjection: ProjectorDefinition["apply"] = Effect.fn("applyDelegationsProjection",)((event, _attachmentSideEffects) => {- if (event.type !== "delegation.created" && event.type !== "delegation.completed") {+ if (event.type !== "delegation.created" && event.type !== "delegation.updated") {return Effect.void;}return sql`diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.tsindex 06b77fe27..00ffef97a 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts@@ -2490,12 +2490,14 @@ projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) =const detailWithPinnedRequests = yield* snapshotQuery.getThreadDetailById(threadW);assert.equal(detailWithPinnedRequests._tag, "Some");if (detailWithPinnedRequests._tag === "Some") {- const ids = detailWithPinnedRequests.value.activities.map((activity) => activity.id);+ const ids = new Set(+ detailWithPinnedRequests.value.activities.map((activity) => activity.id),+ );assert.equal(detailWithPinnedRequests.value.activities.length, 503);- assert.equal(ids.includes(asEventId("approval-old")), true);- assert.equal(ids.includes(asEventId("user-input-old")), true);- assert.equal(ids.includes(asEventId("user-input-closed")), false);- assert.equal(ids.includes(asEventId("user-input-tied-z-request")), true);+ assert.equal(ids.has(asEventId("approval-old")), true);+ assert.equal(ids.has(asEventId("user-input-old")), true);+ assert.equal(ids.has(asEventId("user-input-closed")), false);+ assert.equal(ids.has(asEventId("user-input-tied-z-request")), true);}const windowWithPinnedRequests = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {@@ -2503,12 +2505,14 @@ projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) =});assert.equal(windowWithPinnedRequests._tag, "Some");if (windowWithPinnedRequests._tag === "Some") {- const ids = windowWithPinnedRequests.value.thread.activities.map((activity) => activity.id);+ const ids = new Set(+ windowWithPinnedRequests.value.thread.activities.map((activity) => activity.id),+ );assert.equal(windowWithPinnedRequests.value.thread.activities.length, 503);- assert.equal(ids.includes(asEventId("approval-old")), true);- assert.equal(ids.includes(asEventId("user-input-old")), true);- assert.equal(ids.includes(asEventId("user-input-closed")), false);- assert.equal(ids.includes(asEventId("user-input-tied-z-request")), true);+ assert.equal(ids.has(asEventId("approval-old")), true);+ assert.equal(ids.has(asEventId("user-input-old")), true);+ assert.equal(ids.has(asEventId("user-input-closed")), false);+ assert.equal(ids.has(asEventId("user-input-tied-z-request")), true);}}),);diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.tsindex 65723b7aa..16ef07867 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts@@ -1745,10 +1745,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {updatedAt = maxIso(updatedAt, row.updatedAt);}for (const row of delegationRows) {- updatedAt = maxIso(- updatedAt,- row.delegation.completedAt ?? row.delegation.createdAt,- );+ updatedAt = maxIso(updatedAt, row.delegation.updatedAt);}for (const mcpServer of mcpServers) {updatedAt = maxIso(updatedAt, mcpServer.updatedAt);@@ -2046,10 +2043,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {updatedAt = maxIso(updatedAt, row.updatedAt);}for (const row of delegationRows) {- updatedAt = maxIso(- updatedAt,- row.delegation.completedAt ?? row.delegation.createdAt,- );+ updatedAt = maxIso(updatedAt, row.delegation.updatedAt);}for (const mcpServer of mcpServers) {updatedAt = maxIso(updatedAt, mcpServer.updatedAt);diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.tsindex 3859a5608..5c149228e 100644--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts@@ -16,6 +16,7 @@ import {BotId,CommandId,DEFAULT_PROVIDER_INTERACTION_MODE,+ DelegationId,EventId,MessageId,ProjectId,@@ -2899,6 +2900,131 @@ describe("ProviderCommandReactor", () => {});});+ effectIt.effect("interrupts canceled delegation children and preserves kept children", () =>+ Effect.gen(function* () {+ const harness = yield* Effect.promise(() => createHarness({ botEngine: null }));+ const now = "2026-01-01T00:00:00.000Z";+ const later = "2026-01-01T00:00:01.000Z";+ const parentBotId = BotId.make("bot-1");+ const childBotId = BotId.make("bot-child");++ yield* harness.engine.dispatch({+ type: "bot.create",+ commandId: CommandId.make("cmd-delegation-child-bot"),+ botId: childBotId,+ name: "Child bot",+ title: "Child bot",+ avatar: { kind: "dither", seed: "child-bot" },+ engine: null,+ sandbox: "local",+ runtimeMode: "approval-required",+ usageCap: null,+ groupId: null,+ createdAt: now,+ });++ const createDelegation = (suffix: string) =>+ Effect.gen(function* () {+ const childThreadId = ThreadId.make(`delegation-child-${suffix}`);+ const childTurnId = TurnId.make(`delegation-turn-${suffix}`);+ const delegationId = DelegationId.make(`delegation-${suffix}`);+ yield* harness.engine.dispatch({+ type: "thread.create",+ commandId: CommandId.make(`cmd-delegation-thread-${suffix}`),+ threadId: childThreadId,+ projectId: asProjectId("project-1"),+ botId: childBotId,+ title: "Delegated work",+ modelSelection: {+ instanceId: ProviderInstanceId.make("codex"),+ model: "gpt-5-codex",+ },+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,+ runtimeMode: "approval-required",+ branch: null,+ worktreePath: null,+ createdAt: now,+ });+ const queued = {+ delegationId,+ parentDelegationId: null,+ parentBotId,+ childBotId,+ parentThreadId: ThreadId.make("thread-1"),+ childThreadId: null,+ parentTurnId: TurnId.make("turn-parent"),+ childTurnId: null,+ ancestorBotIds: [parentBotId],+ depth: 1,+ task: "Research the answer.",+ expectedResult: "A concise answer.",+ deadline: null,+ access: {+ allowedToolIds: ["Read" as const],+ memoryScopes: [],+ sandbox: "local" as const,+ runtimeMode: "approval-required" as const,+ hasUserComputer: false,+ enabledMcpServerIds: [],+ disabledMcpServerIds: [],+ approvalCeiling: "send" as const,+ },+ state: "queued" as const,+ billedBotId: childBotId,+ result: null,+ failure: null,+ keep: false,+ createdAt: now,+ updatedAt: now,+ startedAt: null,+ completedAt: null,+ };+ yield* harness.engine.dispatch({+ type: "delegation.create",+ commandId: CommandId.make(`cmd-delegation-create-${suffix}`),+ delegation: queued,+ });+ yield* harness.engine.dispatch({+ type: "delegation.state.set",+ commandId: CommandId.make(`cmd-delegation-running-${suffix}`),+ delegation: {+ ...queued,+ childThreadId,+ childTurnId,+ state: "running",+ startedAt: now,+ },+ });+ return { delegationId, childThreadId, childTurnId };+ });++ const kept = yield* createDelegation("kept");+ yield* harness.engine.dispatch({+ type: "delegation.cancel",+ commandId: CommandId.make("cmd-delegation-keep"),+ delegationId: kept.delegationId,+ keep: true,+ createdAt: later,+ });+ yield* Effect.promise(() => harness.drain());+ expect(harness.interruptTurn).not.toHaveBeenCalled();++ const canceled = yield* createDelegation("canceled");+ yield* harness.engine.dispatch({+ type: "delegation.cancel",+ commandId: CommandId.make("cmd-delegation-cancel"),+ delegationId: canceled.delegationId,+ keep: false,+ createdAt: later,+ });+ yield* Effect.promise(() => waitFor(() => harness.interruptTurn.mock.calls.length === 1));+ expect(harness.interruptTurn).toHaveBeenCalledWith({+ threadId: canceled.childThreadId,+ turnId: canceled.childTurnId,+ });+ }),+ );+effectIt.effect("stops a running session and records the failure when provider interrupt fails",() =>diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.tsindex 4c080d613..31a8371d1 100644--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts@@ -88,7 +88,8 @@ type ProviderIntentEvent = Extract<| "thread.turn-interrupt-requested"| "thread.approval-response-requested"| "thread.user-input-response-requested"- | "thread.session-stop-requested";+ | "thread.session-stop-requested"+ | "delegation.updated";}>;@@ -1686,13 +1687,25 @@ const make = Effect.gen(function* () {) {yield* Effect.annotateCurrentSpan({"orchestration.event_type": event.type,- "orchestration.thread_id": event.payload.threadId,+ ...(event.type === "delegation.updated"+ ? { "orchestration.thread_id": event.payload.delegation.childThreadId ?? "unassigned" }+ : { "orchestration.thread_id": event.payload.threadId }),...(event.commandId ? { "orchestration.command_id": event.commandId } : {}),});yield* increment(orchestrationEventsProcessedTotal, {eventType: event.type,});switch (event.type) {+ case "delegation.updated": {+ const delegation = event.payload.delegation;+ if (delegation.state === "canceled" && delegation.childThreadId !== null) {+ yield* agentController.interruptTurn({+ threadId: delegation.childThreadId,+ ...(delegation.childTurnId ? { turnId: delegation.childTurnId } : {}),+ });+ }+ return;+ }case "thread.meta-updated":yield* threadTitleRegenerationWorker.enqueue(event);return;@@ -1762,7 +1775,8 @@ const make = Effect.gen(function* () {event.type === "thread.turn-interrupt-requested" ||event.type === "thread.approval-response-requested" ||event.type === "thread.user-input-response-requested" ||- event.type === "thread.session-stop-requested"+ event.type === "thread.session-stop-requested" ||+ event.type === "delegation.updated") {return yield* worker.enqueue(event);}diff --git a/apps/server/src/orchestration/decider.delegation.test.ts b/apps/server/src/orchestration/decider.delegation.test.tsindex 3cd3831a7..c65420b04 100644--- a/apps/server/src/orchestration/decider.delegation.test.ts+++ b/apps/server/src/orchestration/decider.delegation.test.ts@@ -10,6 +10,7 @@ import {type AkeruDelegationRecord,type OrchestrationBot,type OrchestrationCommand,+ type OrchestrationEvent,type OrchestrationReadModel,type OrchestrationThread,} from "@t3tools/contracts";@@ -17,15 +18,19 @@ import { expect, it } from "@effect/vitest";import * as Effect from "effect/Effect";import { decideOrchestrationCommand } from "./decider.ts";+import { createEmptyReadModel, projectEvent } from "./projector.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 PARENT_BOT_ID = BotId.make("bot-parent");+const CHILD_BOT_ID = BotId.make("bot-child");+const OTHER_BOT_ID = BotId.make("bot-other");+const PARENT_THREAD_ID = ThreadId.make("thread-parent");const CHILD_THREAD_ID = ThreadId.make("thread-child");-const SOURCE_TURN_ID = TurnId.make("turn-source");-const CHILD_TURN_ID = TurnId.make("turn-child");+type PlannedDelegationEvent = Omit<+ Extract<OrchestrationEvent, { type: "delegation.created" | "delegation.updated" }>,+ "sequence"+>;function makeBot(id: BotId): OrchestrationBot {return {@@ -38,7 +43,7 @@ function makeBot(id: BotId): OrchestrationBot {avatar: { kind: "dither", seed: id },engine: null,sandbox: "local",- runtimeMode: "full-access",+ runtimeMode: "approval-required",usageCap: null,voiceEnabled: false,groupId: null,@@ -48,35 +53,20 @@ function makeBot(id: BotId): OrchestrationBot {};}-function makeThread(input: {- id: ThreadId;- botId: BotId;- turnId: TurnId | null;- projectId?: ProjectId;-}): OrchestrationThread {+function makeThread(id: ThreadId, botId: BotId): OrchestrationThread {return {- id: input.id,- projectId: input.projectId ?? ProjectId.make("project-1"),- botId: input.botId,+ id,+ projectId: ProjectId.make("project-1"),+ botId,groupId: null,respondingBotId: null,- title: input.id,+ title: id,modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6" },- runtimeMode: "full-access",+ runtimeMode: "approval-required",interactionMode: "default",branch: null,worktreePath: null,- latestTurn:- input.turnId === null- ? null- : {- turnId: input.turnId,- state: "running",- requestedAt: NOW,- startedAt: NOW,- completedAt: null,- assistantMessageId: null,- },+ latestTurn: null,createdAt: NOW,updatedAt: NOW,archivedAt: null,@@ -94,167 +84,333 @@ function makeThread(input: {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,+ parentDelegationId: null,+ parentBotId: PARENT_BOT_ID,+ childBotId: CHILD_BOT_ID,+ parentThreadId: PARENT_THREAD_ID,+ childThreadId: null,+ parentTurnId: TurnId.make("turn-parent"),childTurnId: null,+ ancestorBotIds: [PARENT_BOT_ID],depth: 1,- billedBotId: TARGET_BOT_ID,task: "Compare three flights.",expectedResult: "A short comparison with sources.",- outcome: null,+ deadline: null,+ access: {+ allowedToolIds: ["Read"],+ memoryScopes: ["project"],+ sandbox: "daytona",+ runtimeMode: "approval-required",+ hasUserComputer: false,+ enabledMcpServerIds: [],+ disabledMcpServerIds: [],+ approvalCeiling: "send",+ },+ state: "queued",+ billedBotId: CHILD_BOT_ID,+ result: null,+ failure: null,+ keep: false,createdAt: NOW,+ updatedAt: NOW,+ startedAt: null,completedAt: null,...overrides,};}function makeReadModel(- input: {- childBotId?: BotId;- childProjectId?: ProjectId;- targetArchived?: boolean;- delegations?: ReadonlyArray<AkeruDelegationRecord>;- } = {},+ 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 ?? [],+ ...createEmptyReadModel(NOW),+ bots: [makeBot(PARENT_BOT_ID), makeBot(CHILD_BOT_ID), makeBot(OTHER_BOT_ID)],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 } : {}),- }),+ makeThread(PARENT_THREAD_ID, PARENT_BOT_ID),+ makeThread(CHILD_THREAD_ID, CHILD_BOT_ID),],- updatedAt: NOW,+ delegations,};}-const decide = (readModel: OrchestrationReadModel, command: OrchestrationCommand) =>- decideOrchestrationCommand({ readModel, command });+const decideOne = Effect.fn("decideDelegationTestCommand")(function* (+ readModel: OrchestrationReadModel,+ command: OrchestrationCommand,+) {+ const decided = yield* decideOrchestrationCommand({ readModel, command });+ const event = Array.isArray(decided) ? decided[0] : decided;+ if (event === undefined) throw new Error("Expected one event");+ if (event.type !== "delegation.created" && event.type !== "delegation.updated") {+ throw new Error(`Expected a delegation event, received '${event.type}'`);+ }+ return event as PlannedDelegationEvent;+});++const project = Effect.fn("projectDelegationTestEvent")(function* (+ readModel: OrchestrationReadModel,+ event: PlannedDelegationEvent,+) {+ return yield* projectEvent(readModel, {+ ...event,+ sequence: readModel.snapshotSequence + 1,+ });+});it.layer(NodeServices.layer)("delegation decider", (it) => {- it.effect("creates and completes a delegation", () =>+ it.effect("creates and projects the full delegation record", () =>Effect.gen(function* () {const delegation = makeDelegation();- const created = yield* decide(makeReadModel(), {+ const event = yield* decideOne(makeReadModel(), {type: "delegation.create",commandId: CommandId.make("command-create"),delegation,});- expect(created).toMatchObject({++ expect(event).toMatchObject({type: "delegation.created",aggregateKind: "delegation",aggregateId: delegation.delegationId,payload: { delegation },});+ const projected = yield* project(makeReadModel(), event);+ expect(projected.delegations).toEqual([delegation]);+ }),+ );++ it.effect("accepts every legal state and cancels unfinished work idempotently", () =>+ Effect.gen(function* () {+ let readModel = makeReadModel([makeDelegation()]);+ const states: AkeruDelegationRecord["state"][] = ["queued"];+ const update = Effect.fn("updateDelegationState")(function* (+ delegation: AkeruDelegationRecord,+ commandId: string,+ ) {+ const event = yield* decideOne(readModel, {+ type: "delegation.state.set",+ commandId: CommandId.make(commandId),+ delegation,+ });+ readModel = yield* project(readModel, event);+ states.push(delegation.state);+ });++ const running = makeDelegation({+ childThreadId: CHILD_THREAD_ID,+ childTurnId: TurnId.make("turn-child"),+ state: "running",+ updatedAt: LATER,+ startedAt: LATER,+ });+ yield* update(running, "command-running");+ yield* update({ ...running, state: "blocked" }, "command-blocked");+ yield* update(running, "command-resumed");+ yield* update(+ {+ ...running,+ state: "completed",+ result: {+ summary: "Compared the flights.",+ childThreadId: CHILD_THREAD_ID,+ childTurnId: running.childTurnId,+ },+ completedAt: "2026-08-31T12:02:00.000Z",+ updatedAt: "2026-08-31T12:02:00.000Z",+ },+ "command-completed",+ );+ expect(states).toEqual(["queued", "running", "blocked", "running", "completed"]);- const completedDelegation = makeDelegation({- childTurnId: CHILD_TURN_ID,- outcome: { status: "succeeded", result: "Compared the flights." },+ const failed = makeDelegation({+ state: "failed",+ failure: { failureCode: "internal", message: "Child process failed." },completedAt: LATER,+ updatedAt: LATER,+ });+ const failedEvent = yield* decideOne(makeReadModel([makeDelegation()]), {+ type: "delegation.state.set",+ commandId: CommandId.make("command-failed"),+ delegation: failed,});- const completed = yield* decide(makeReadModel({ delegations: [delegation] }), {- type: "delegation.complete",- commandId: CommandId.make("command-complete"),- delegation: completedDelegation,+ expect(failedEvent.payload.delegation.state).toBe("failed");++ const cancelEvent = yield* decideOne(makeReadModel([makeDelegation()]), {+ type: "delegation.cancel",+ commandId: CommandId.make("command-cancel"),+ delegationId: DelegationId.make("delegation-1"),+ keep: false,+ createdAt: LATER,+ });+ expect(cancelEvent.payload.delegation.state).toBe("canceled");++ const keepEvent = yield* decideOne(makeReadModel([makeDelegation()]), {+ type: "delegation.cancel",+ commandId: CommandId.make("command-keep"),+ delegationId: DelegationId.make("delegation-1"),+ keep: true,+ createdAt: LATER,});- expect(completed).toMatchObject({- type: "delegation.completed",- payload: { delegation: completedDelegation },+ expect(keepEvent.payload.delegation).toMatchObject({ state: "queued", keep: true });++ const canceledModel = yield* project(makeReadModel([makeDelegation()]), cancelEvent);+ const repeated = yield* decideOne(canceledModel, {+ type: "delegation.cancel",+ commandId: CommandId.make("command-cancel-again"),+ delegationId: DelegationId.make("delegation-1"),+ keep: false,+ createdAt: "2026-08-31T12:03:00.000Z",});+ expect(repeated.payload.delegation).toEqual(cancelEvent.payload.delegation);}),);- it.effect("records a failed dispatch without a child turn", () =>+ it.effect("assigns child ownership once and keeps lifecycle timestamps monotonic", () =>Effect.gen(function* () {- const delegation = makeDelegation();- const failed = makeDelegation({- outcome: { status: "failed", error: "Turn dispatch failed." },- completedAt: LATER,+ const running = makeDelegation({+ childThreadId: CHILD_THREAD_ID,+ state: "running",+ updatedAt: LATER,+ startedAt: LATER,});- const event = yield* decide(makeReadModel({ delegations: [delegation] }), {- type: "delegation.complete",- commandId: CommandId.make("command-failed"),- delegation: failed,+ const assigned = {+ ...running,+ childTurnId: TurnId.make("turn-child"),+ updatedAt: "2026-08-31T12:02:00.000Z",+ };+ const assignedEvent = yield* decideOne(makeReadModel([running]), {+ type: "delegation.state.set",+ commandId: CommandId.make("command-assign-child-turn"),+ delegation: assigned,});- expect(event).toMatchObject({- type: "delegation.completed",- payload: { delegation: failed },+ expect(assignedEvent.payload.delegation).toEqual(assigned);++ const cancelEvent = yield* decideOne(makeReadModel([assigned]), {+ type: "delegation.cancel",+ commandId: CommandId.make("command-stale-cancel"),+ delegationId: assigned.delegationId,+ keep: false,+ createdAt: NOW,+ });+ expect(cancelEvent.payload.delegation).toMatchObject({+ state: "canceled",+ updatedAt: assigned.updatedAt,+ completedAt: assigned.updatedAt,});}),);- it.effect("rejects invalid delegation ownership and boundaries", () =>+ it.effect("rejects cycles, bad depth, missing records, and excess concurrency", () =>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",+ const parent = makeDelegation();+ const cycle = makeDelegation({+ delegationId: DelegationId.make("delegation-cycle"),+ parentDelegationId: parent.delegationId,+ parentBotId: CHILD_BOT_ID,+ childBotId: PARENT_BOT_ID,+ parentThreadId: CHILD_THREAD_ID,+ childThreadId: PARENT_THREAD_ID,+ ancestorBotIds: [PARENT_BOT_ID, CHILD_BOT_ID],+ depth: 2,+ billedBotId: PARENT_BOT_ID,+ });+ const cycleError = yield* decideOrchestrationCommand({+ readModel: makeReadModel([parent]),+ command: {+ type: "delegation.create",+ commandId: CommandId.make("command-cycle"),+ delegation: cycle,},- {- command: makeDelegation({- targetBotId: SOURCE_BOT_ID,- billedBotId: SOURCE_BOT_ID,- }),- readModel: makeReadModel(),- message: "delegate to itself",+ }).pipe(Effect.flip);+ expect(String(cycleError)).toContain("cycle");++ const depthError = yield* decideOrchestrationCommand({+ readModel: makeReadModel(),+ command: {+ type: "delegation.create",+ commandId: CommandId.make("command-depth"),+ delegation: makeDelegation({ depth: 2 }),},- {- command: makeDelegation(),- readModel: makeReadModel({ childProjectId: ProjectId.make("project-2") }),- message: "cross projects",+ }).pipe(Effect.flip);+ expect(String(depthError)).toContain("ancestor chain or depth");++ const missingError = yield* decideOrchestrationCommand({+ readModel: makeReadModel(),+ command: {+ type: "delegation.create",+ commandId: CommandId.make("command-missing"),+ delegation: makeDelegation({ childBotId: BotId.make("bot-missing") }),},- {- command: makeDelegation({ depth: 3 as AkeruDelegationRecord["depth"] }),- readModel: makeReadModel(),- message: "maximum depth",+ }).pipe(Effect.flip);+ expect(String(missingError)).toContain("bot-missing");++ const archivedChildError = yield* decideOrchestrationCommand({+ readModel: {+ ...makeReadModel(),+ bots: [+ makeBot(PARENT_BOT_ID),+ { ...makeBot(CHILD_BOT_ID), archivedAt: LATER },+ makeBot(OTHER_BOT_ID),+ ],},- {- command: makeDelegation(),- readModel: makeReadModel({ childBotId: SOURCE_BOT_ID }),- message: "target bot",+ command: {+ type: "delegation.create",+ commandId: CommandId.make("command-archived-child"),+ delegation: makeDelegation(),},- {- command: makeDelegation(),- readModel: makeReadModel({ targetArchived: true }),- message: "archived",+ }).pipe(Effect.flip);+ expect(String(archivedChildError)).toContain("archived");++ const active = [1, 2, 3].map((index) =>+ makeDelegation({ delegationId: DelegationId.make(`delegation-${index}`) }),+ );+ const concurrencyError = yield* decideOrchestrationCommand({+ readModel: makeReadModel(active),+ command: {+ type: "delegation.create",+ commandId: CommandId.make("command-concurrency"),+ delegation: makeDelegation({ delegationId: DelegationId.make("delegation-4") }),},- {- command: makeDelegation({ billedBotId: SOURCE_BOT_ID }),- readModel: makeReadModel(),- message: "must bill target bot",+ }).pipe(Effect.flip);+ expect(String(concurrencyError)).toContain("3 active delegations");+ }),+ );++ it.effect("rejects illegal transitions and ownership changes", () =>+ Effect.gen(function* () {+ const queued = makeDelegation();+ const completed = makeDelegation({+ childThreadId: CHILD_THREAD_ID,+ state: "completed",+ startedAt: NOW,+ completedAt: LATER,+ updatedAt: LATER,+ result: {+ summary: "Done.",+ childThreadId: CHILD_THREAD_ID,+ childTurnId: null,+ },+ });+ const transitionError = yield* decideOrchestrationCommand({+ readModel: makeReadModel([queued]),+ command: {+ type: "delegation.state.set",+ commandId: CommandId.make("command-illegal"),+ delegation: completed,},- ];+ }).pipe(Effect.flip);+ expect(String(transitionError)).toContain("cannot transition");- 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);- }+ const ownershipError = yield* decideOrchestrationCommand({+ readModel: makeReadModel([queued]),+ command: {+ type: "delegation.state.set",+ commandId: CommandId.make("command-owner-change"),+ delegation: makeDelegation({+ childBotId: OTHER_BOT_ID,+ billedBotId: OTHER_BOT_ID,+ }),+ },+ }).pipe(Effect.flip);+ expect(String(ownershipError)).toContain("immutable");}),);});diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.tsindex 77303c1c0..74f7e5872 100644--- a/apps/server/src/orchestration/decider.ts+++ b/apps/server/src/orchestration/decider.ts@@ -1,5 +1,8 @@import {+ AKERU_DELEGATION_MAX_CONCURRENCY,AKERU_DELEGATION_MAX_DEPTH,+ type AkeruDelegationRecord,+ type AkeruDelegationState,BotId,DEFAULT_LOCAL_EXECUTION_MODE,DEFAULT_RUNTIME_MODE,@@ -46,6 +49,79 @@ const nowIso = Effect.map(DateTime.now, DateTime.formatIso);// window is a failed/stale start, not pending work. Mirrors the client's// QUEUED_TURN_START_GRACE_MS in client-runtime threadSettled.ts.const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;+const TERMINAL_DELEGATION_STATES = new Set<AkeruDelegationState>([+ "failed",+ "canceled",+ "completed",+]);+const DELEGATION_STATE_TRANSITIONS: Record<+ Exclude<AkeruDelegationState, "failed" | "canceled" | "completed">,+ ReadonlySet<AkeruDelegationState>+> = {+ queued: new Set(["running", "failed"]),+ running: new Set(["blocked", "failed", "completed"]),+ blocked: new Set(["running", "failed"]),+};++function delegationStateError(delegation: AkeruDelegationRecord): string | null {+ switch (delegation.state) {+ case "queued":+ return delegation.startedAt === null &&+ delegation.completedAt === null &&+ delegation.result === null &&+ delegation.failure === null+ ? null+ : "Queued delegations cannot have start, completion, result, or failure data.";+ case "running":+ case "blocked":+ return delegation.childThreadId !== null &&+ delegation.startedAt !== null &&+ delegation.completedAt === null &&+ delegation.result === null &&+ delegation.failure === null+ ? null+ : `${delegation.state} delegations require childThreadId and startedAt without completion data.`;+ case "failed":+ return delegation.completedAt !== null &&+ delegation.result === null &&+ delegation.failure !== null+ ? null+ : "Failed delegations require completedAt and failure without a result.";+ case "canceled":+ return delegation.completedAt !== null &&+ delegation.result === null &&+ delegation.failure === null+ ? null+ : "Canceled delegations require completedAt without result or failure data.";+ case "completed":+ return delegation.childThreadId !== null &&+ delegation.startedAt !== null &&+ delegation.completedAt !== null &&+ delegation.result !== null &&+ delegation.result.childThreadId === delegation.childThreadId &&+ delegation.result.childTurnId === delegation.childTurnId &&+ delegation.failure === null+ ? null+ : "Completed delegations require start, completion, and result data without a failure.";+ }+}++function hasSameDelegationOwnership(+ current: AkeruDelegationRecord,+ next: AkeruDelegationRecord,+): boolean {+ return NodeUtil.isDeepStrictEqual(current, {+ ...next,+ childThreadId: current.childThreadId,+ childTurnId: current.childTurnId,+ state: current.state,+ result: current.result,+ failure: current.failure,+ updatedAt: current.updatedAt,+ startedAt: current.startedAt,+ completedAt: current.completedAt,+ });+}/*** Blocked-on-you work derived from the thread's retained activities: an@@ -997,69 +1073,73 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"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.`,- });+ yield* requireBotNotArchived({ readModel, command, botId: delegation.parentBotId });+ yield* requireBotNotArchived({ readModel, command, botId: delegation.childBotId });+ yield* requireThread({ readModel, command, threadId: delegation.parentThreadId });+ if (delegation.childThreadId !== null) {+ yield* requireThread({ readModel, command, threadId: delegation.childThreadId });}- if (delegation.sourceBotId === delegation.targetBotId) {++ if (delegation.billedBotId !== delegation.childBotId) {return yield* new OrchestrationCommandInvariantError({commandType: command.type,- detail: `Bot '${delegation.sourceBotId}' cannot delegate to itself.`,+ detail: `Delegation '${delegation.delegationId}' must bill child bot '${delegation.childBotId}'.`,});}- if (sourceThread.projectId !== childThread.projectId) {++ const parentDelegation =+ delegation.parentDelegationId === null+ ? null+ : yield* requireDelegation({+ readModel,+ command,+ delegationId: delegation.parentDelegationId,+ });+ if (parentDelegation !== null && parentDelegation.childBotId !== delegation.parentBotId) {return yield* new OrchestrationCommandInvariantError({commandType: command.type,- detail: `Delegation '${delegation.delegationId}' cannot cross projects.`,+ detail: `Parent delegation '${parentDelegation.delegationId}' does not belong to bot '${delegation.parentBotId}'.`,});}++ const expectedDepth = parentDelegation === null ? 1 : parentDelegation.depth + 1;+ const expectedAncestorBotIds =+ parentDelegation === null+ ? [delegation.parentBotId]+ : [...parentDelegation.ancestorBotIds, delegation.parentBotId];if (- childThread.botId !== delegation.targetBotId ||- (delegation.childTurnId !== null &&- childThread.latestTurn?.turnId !== delegation.childTurnId)+ expectedDepth > AKERU_DELEGATION_MAX_DEPTH ||+ delegation.depth !== expectedDepth ||+ !NodeUtil.isDeepStrictEqual(delegation.ancestorBotIds, expectedAncestorBotIds)) {return yield* new OrchestrationCommandInvariantError({commandType: command.type,- detail: `Delegation '${delegation.delegationId}' child thread and turn must belong to target bot '${delegation.targetBotId}'.`,+ detail: `Delegation '${delegation.delegationId}' has an invalid ancestor chain or depth.`,});}- if (delegation.depth < 1 || delegation.depth > AKERU_DELEGATION_MAX_DEPTH) {+ if (delegation.ancestorBotIds.includes(delegation.childBotId)) {return yield* new OrchestrationCommandInvariantError({commandType: command.type,- detail: `Delegation '${delegation.delegationId}' exceeds the maximum depth of ${AKERU_DELEGATION_MAX_DEPTH}.`,+ detail: `Delegation '${delegation.delegationId}' would create a bot cycle.`,});}- if (delegation.billedBotId !== delegation.targetBotId) {++ const activeDelegationCount = readModel.delegations.filter(+ (candidate) =>+ candidate.parentBotId === delegation.parentBotId &&+ !TERMINAL_DELEGATION_STATES.has(candidate.state),+ ).length;+ if (activeDelegationCount >= AKERU_DELEGATION_MAX_CONCURRENCY) {return yield* new OrchestrationCommandInvariantError({commandType: command.type,- detail: `Delegation '${delegation.delegationId}' must bill target bot '${delegation.targetBotId}'.`,+ detail: `Bot '${delegation.parentBotId}' already has ${activeDelegationCount} active delegations.`,});}- if (delegation.outcome !== null || delegation.completedAt !== null) {+ const stateError = delegationStateError(delegation);+ if (delegation.state !== "queued" || stateError !== null) {return yield* new OrchestrationCommandInvariantError({commandType: command.type,- detail: `Delegation '${delegation.delegationId}' cannot be completed when created.`,+ detail: stateError ?? "New delegations must start queued.",});}@@ -1075,54 +1155,118 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"};}- case "delegation.complete": {- const delegation = command.delegation;+ case "delegation.state.set": {const current = yield* requireDelegation({readModel,command,- delegationId: delegation.delegationId,+ delegationId: command.delegation.delegationId,});+ const next = command.delegation;+ if (!hasSameDelegationOwnership(current, next)) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `Delegation '${next.delegationId}' ownership and access fields are immutable.`,+ });+ }if (- !NodeUtil.isDeepStrictEqual(current, {- ...delegation,- childTurnId: current.childTurnId,- outcome: current.outcome,- completedAt: current.completedAt,- }) ||- (current.childTurnId !== null && current.childTurnId !== delegation.childTurnId)+ (current.childThreadId !== null && next.childThreadId !== current.childThreadId) ||+ (current.childTurnId !== null && next.childTurnId !== current.childTurnId)) {return yield* new OrchestrationCommandInvariantError({commandType: command.type,- detail: `Delegation '${delegation.delegationId}' ownership fields are immutable.`,+ detail: `Delegation '${next.delegationId}' child ownership is immutable once assigned.`,});}- if (delegation.outcome === null || delegation.completedAt === null) {+ if (next.childThreadId !== null) {+ yield* requireThread({ readModel, command, threadId: next.childThreadId });+ }+ if (!(Date.parse(next.updatedAt) >= Date.parse(current.updatedAt))) {return yield* new OrchestrationCommandInvariantError({commandType: command.type,- detail: `Delegation '${delegation.delegationId}' requires an outcome and completion time.`,+ detail: `Delegation '${next.delegationId}' cannot move updatedAt backward.`,});}- if (delegation.outcome.status === "succeeded" && delegation.childTurnId === null) {+ if (current.state === next.state) {+ const assignsChildOwnership =+ (current.childThreadId === null && next.childThreadId !== null) ||+ (current.childTurnId === null && next.childTurnId !== null);+ const changesOnlyChildOwnership = NodeUtil.isDeepStrictEqual(current, {+ ...next,+ childThreadId: current.childThreadId,+ childTurnId: current.childTurnId,+ updatedAt: current.updatedAt,+ });+ if (+ !NodeUtil.isDeepStrictEqual(current, next) &&+ (!assignsChildOwnership || !changesOnlyChildOwnership)+ ) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `Delegation '${next.delegationId}' cannot change data without a state transition.`,+ });+ }+ } else if (+ TERMINAL_DELEGATION_STATES.has(current.state) ||+ !DELEGATION_STATE_TRANSITIONS[+ current.state as keyof typeof DELEGATION_STATE_TRANSITIONS+ ].has(next.state)+ ) {return yield* new OrchestrationCommandInvariantError({commandType: command.type,- detail: `Successful delegation '${delegation.delegationId}' requires a child turn.`,+ detail: `Delegation '${next.delegationId}' cannot transition from '${current.state}' to '${next.state}'.`,});}- if (Date.parse(delegation.completedAt) < Date.parse(delegation.createdAt)) {+ const stateError = delegationStateError(next);+ if (stateError !== null) {return yield* new OrchestrationCommandInvariantError({commandType: command.type,- detail: `Delegation '${delegation.delegationId}' cannot complete before it was created.`,+ detail: stateError,});}return {...(yield* withEventBase({aggregateKind: "delegation",- aggregateId: delegation.delegationId,- occurredAt: delegation.completedAt,+ aggregateId: next.delegationId,+ occurredAt: next.updatedAt,+ commandId: command.commandId,+ })),+ type: "delegation.updated",+ payload: { delegation: next },+ };+ }++ case "delegation.cancel": {+ const current = yield* requireDelegation({+ readModel,+ command,+ delegationId: command.delegationId,+ });+ const canceledAt =+ Date.parse(command.createdAt) >= Date.parse(current.updatedAt)+ ? command.createdAt+ : current.updatedAt;+ const delegation = command.keep+ ? { ...current, keep: true, updatedAt: canceledAt }+ : TERMINAL_DELEGATION_STATES.has(current.state)+ ? current+ : {+ ...current,+ state: "canceled" as const,+ result: null,+ failure: null,+ updatedAt: canceledAt,+ completedAt: canceledAt,+ };++ return {+ ...(yield* withEventBase({+ aggregateKind: "delegation",+ aggregateId: command.delegationId,+ occurredAt: delegation.updatedAt,commandId: command.commandId,})),- type: "delegation.completed",+ type: "delegation.updated",payload: { delegation },};}diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.tsindex e4dec07c1..a0c45003f 100644--- a/apps/server/src/orchestration/projector.ts+++ b/apps/server/src/orchestration/projector.ts@@ -7,8 +7,8 @@ import type {ThreadId,} from "@t3tools/contracts";import {- DelegationCompletedPayload,DelegationCreatedPayload,+ DelegationUpdatedPayload,OrchestrationCheckpointSummary,OrchestrationMessage,OrchestrationSession,@@ -248,9 +248,9 @@ export function projectEvent(switch (event.type) {case "delegation.created":- case "delegation.completed":+ case "delegation.updated":return decodeForEvent(- event.type === "delegation.created" ? DelegationCreatedPayload : DelegationCompletedPayload,+ event.type === "delegation.created" ? DelegationCreatedPayload : DelegationUpdatedPayload,event.payload,event.type,"payload",diff --git a/apps/server/src/portability.ts b/apps/server/src/portability.tsindex 0433fe574..c590278d4 100644--- a/apps/server/src/portability.ts+++ b/apps/server/src/portability.ts@@ -1309,8 +1309,10 @@ function itemForCommand(case "mcp-server.disable":return `mcp-server:${command.mcpServerId}`;case "delegation.create":- case "delegation.complete":- return `thread:${command.delegation.sourceThreadId}`;+ case "delegation.state.set":+ return `delegation:${command.delegation.delegationId}`;+ case "delegation.cancel":+ return `delegation:${command.delegationId}`;default:return `thread:${command.threadId}`;}diff --git a/apps/server/src/provider/AkeruCatalogToolHandlers.ts b/apps/server/src/provider/AkeruCatalogToolHandlers.tsindex 27247e555..650422e54 100644--- a/apps/server/src/provider/AkeruCatalogToolHandlers.ts+++ b/apps/server/src/provider/AkeruCatalogToolHandlers.ts@@ -93,7 +93,7 @@ export function createAkeruCatalogToolHandlers(return {...(installPlugin? {- InstallPlugin: async ({ input, emitProgress }) => {+ InstallPlugin: async ({ input, emitProgress }: AkeruCatalogToolHandlerInput) => {const name = requiredString(input, "name");await emitProgress(`Installing plugin '${name}'.`);return installPlugin(input as (typeof AkeruToolInputSchemas.InstallPlugin)["Type"]);diff --git a/apps/server/src/provider/AkeruDelegationRuntime.test.ts b/apps/server/src/provider/AkeruDelegationRuntime.test.tsindex 1fe396f55..e1f60190f 100644--- a/apps/server/src/provider/AkeruDelegationRuntime.test.ts+++ b/apps/server/src/provider/AkeruDelegationRuntime.test.ts@@ -1,260 +1,610 @@-import { describe, expect, it, vi } from "@effect/vitest";-import {BotId,+ DelegationId,+ GroupId,+ McpServerId,ProjectId,ProviderInstanceId,ThreadId,TurnId,+ type AkeruDelegationAccessGrant,+ type AkeruDelegationRecord,type OrchestrationBot,+ type OrchestrationCommand,type OrchestrationReadModel,type OrchestrationThread,} from "@t3tools/contracts";+import { describe, expect, it, vi } from "vite-plus/test";-import { createAkeruDelegationRuntime } from "./AkeruDelegationRuntime.ts";+import {+ createAkeruDelegationRuntime,+ type AkeruDelegationChildOutcome,+ type AkeruDelegationParent,+} from "./AkeruDelegationRuntime.ts";+import { intersectDelegationAccess } from "./AkeruToolRuntime.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 NOW = "2026-08-31T12:00:00.000Z";+const PROJECT_ID = ProjectId.make("project-1");+const PARENT_BOT_ID = BotId.make("bot-parent");+const CHILD_BOT_ID = BotId.make("bot-child");+const OTHER_BOT_ID = BotId.make("bot-other");+const PARENT_THREAD_ID = ThreadId.make("thread-parent");+const PARENT_TURN_ID = TurnId.make("turn-parent");+const CHILD_TURN_ID = TurnId.make("turn-child");-const targetBot: OrchestrationBot = {- id: targetBotId,- name: "Reviewer",- title: "Reviewer",- label: null,- description: null,+const access = (overrides: Partial<AkeruDelegationAccessGrant> = {}) => ({+ allowedToolIds: ["Read", "Shell", "SendToAgent"] as const,+ memoryScopes: ["private", "bot", "project"] as const,+ sandbox: "local" as const,+ runtimeMode: "approval-required" as const,+ hasUserComputer: false,+ enabledMcpServerIds: [],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 sourceBot: OrchestrationBot = {- ...targetBot,- id: sourceBotId,- name: "Source",- title: "Source",-};--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: [sourceBot, targetBot],- groups: [],- delegations: [],- threads: [sourceThread],- updatedAt: now,-};--const request = { botId: targetBotId, task: "Review the patch", expectedResult: "A verdict" };+ approvalCeiling: "send" as const,+ ...overrides,+});++function bot(id: BotId, overrides: Partial<OrchestrationBot> = {}): OrchestrationBot {+ return {+ id,+ name: id,+ title: "Agent",+ label: null,+ description: null,+ disabledMcpServerIds: [],+ avatar: { kind: "dither", seed: id },+ engine: null,+ sandbox: "local",+ runtimeMode: "approval-required",+ usageCap: null,+ voiceEnabled: false,+ groupId: null,+ archivedAt: null,+ createdAt: NOW,+ updatedAt: NOW,+ ...overrides,+ };+}++function thread(+ id: ThreadId,+ botId: BotId | null,+ overrides: Partial<OrchestrationThread> = {},+): OrchestrationThread {+ return {+ id,+ projectId: PROJECT_ID,+ botId,+ groupId: null,+ respondingBotId: null,+ title: id,+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" },+ 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,+ ...overrides,+ };+}++function delegation(+ delegationId: DelegationId,+ overrides: Partial<AkeruDelegationRecord> = {},+): AkeruDelegationRecord {+ return {+ delegationId,+ parentDelegationId: null,+ parentBotId: PARENT_BOT_ID,+ childBotId: CHILD_BOT_ID,+ parentThreadId: PARENT_THREAD_ID,+ childThreadId: null,+ parentTurnId: PARENT_TURN_ID,+ childTurnId: null,+ ancestorBotIds: [PARENT_BOT_ID],+ depth: 1,+ task: "Research the answer.",+ expectedResult: "A concise answer.",+ deadline: null,+ access: access(),+ state: "queued",+ billedBotId: CHILD_BOT_ID,+ result: null,+ failure: null,+ keep: false,+ createdAt: NOW,+ updatedAt: NOW,+ startedAt: null,+ completedAt: null,+ ...overrides,+ };+}++function snapshot(overrides: Partial<OrchestrationReadModel> = {}): OrchestrationReadModel {+ return {+ snapshotSequence: 0,+ projects: [],+ bots: [bot(PARENT_BOT_ID), bot(CHILD_BOT_ID), bot(OTHER_BOT_ID)],+ groups: [],+ delegations: [],+ mcpServers: [],+ threads: [thread(PARENT_THREAD_ID, PARENT_BOT_ID)],+ updatedAt: NOW,+ ...overrides,+ };+}++const parent = (overrides: Partial<AkeruDelegationParent> = {}): AkeruDelegationParent => ({+ threadId: PARENT_THREAD_ID,+ turnId: PARENT_TURN_ID,+ botId: PARENT_BOT_ID,+ parentDelegationId: null,+ ancestorBotIds: [],+ depth: 0,+ access: access(),+ ...overrides,+});++const request = (overrides: Record<string, unknown> = {}) => ({+ botId: CHILD_BOT_ID,+ task: "Research the answer.",+ expectedResult: "A concise answer.",+ ...overrides,+});++function harness(+ initial = snapshot(),+ outcome: AkeruDelegationChildOutcome = {+ state: "completed",+ turnId: CHILD_TURN_ID,+ summary: "The delegated answer.",+ },+) {+ const state = {+ ...initial,+ delegations: [...initial.delegations],+ threads: [...initial.threads],+ };+ const commands: OrchestrationCommand[] = [];+ const interrupts: Array<{ threadId: ThreadId; turnId: TurnId | null }> = [];+ const usage: Array<Record<string, unknown>> = [];+ let nextId = 0;+ const dispatch = vi.fn(async (command: OrchestrationCommand) => {+ commands.push(command);+ if (command.type === "delegation.create") state.delegations.push(command.delegation);+ if (command.type === "delegation.state.set") {+ const index = state.delegations.findIndex(+ (entry) => entry.delegationId === command.delegation.delegationId,+ );+ if (index >= 0) state.delegations[index] = command.delegation;+ }+ if (command.type === "delegation.cancel") {+ const index = state.delegations.findIndex(+ (entry) => entry.delegationId === command.delegationId,+ );+ if (index >= 0) {+ state.delegations[index] = command.keep+ ? { ...state.delegations[index]!, keep: true }+ : {+ ...state.delegations[index]!,+ state: "canceled",+ completedAt: command.createdAt,+ };+ }+ }+ if (command.type === "thread.create") {+ state.threads.push(+ thread(command.threadId, command.botId ?? null, {+ groupId: command.groupId ?? null,+ runtimeMode: command.runtimeMode,+ }),+ );+ }+ });+ const recordUsage = vi.fn(async (entry: Record<string, unknown>) => {+ usage.push(entry);+ });+ const runtime = createAkeruDelegationRuntime({+ readSnapshot: async () => state as OrchestrationReadModel,+ dispatch,+ awaitChild: async () => outcome,+ interruptChild: async (threadId, turnId) => {+ interrupts.push({ threadId, turnId });+ },+ recordUsage,+ now: () => NOW,+ id: () => String(++nextId),+ });+ return { runtime, state, commands, interrupts, usage, dispatch };+}++describe("delegation access", () => {+ it("intersects MCP disables, user-computer capability, tools, and memory scopes", () => {+ const grant = intersectDelegationAccess({+ parent: access({+ allowedToolIds: ["Read", "ExternalRead", "SendToAgent"],+ memoryScopes: ["private", "project"],+ hasUserComputer: false,+ enabledMcpServerIds: [McpServerId.make("web"), McpServerId.make("email")],+ disabledMcpServerIds: [McpServerId.make("parent-disabled")],+ }),+ child: access({+ allowedToolIds: ["Read", "ExternalRead"],+ memoryScopes: ["project", "group"],+ hasUserComputer: true,+ enabledMcpServerIds: [McpServerId.make("web")],+ disabledMcpServerIds: [McpServerId.make("child-disabled")],+ }),+ requested: request({+ allowedToolIds: ["Read", "ExternalRead"],+ memoryScopes: ["project"],+ mcpServerIds: [McpServerId.make("web"), McpServerId.make("email")],+ }) as never,+ });+ expect(grant).toMatchObject({+ allowedToolIds: ["Read", "ExternalRead"],+ memoryScopes: ["project"],+ hasUserComputer: false,+ enabledMcpServerIds: ["web"],+ disabledMcpServerIds: ["parent-disabled", "child-disabled"],+ });+ });++ it("rejects extra memory, tools, full access, and approval upgrades", () => {+ for (const requested of [+ { memoryScopes: ["workspace"] },+ { allowedToolIds: ["ExternalShell"] },+ { runtimeMode: "full-access" },+ { approvalCeiling: "production" },+ ]) {+ expect(() =>+ intersectDelegationAccess({+ parent: access(),+ child: access({ runtimeMode: "full-access", approvalCeiling: "secrets" }),+ requested: request(requested) as never,+ }),+ ).toThrow("parent turn grant");+ }+ });++ it("allows a delegation to remove sandbox access", () => {+ expect(+ intersectDelegationAccess({+ parent: access({ sandbox: "local" }),+ child: access({ sandbox: "local" }),+ requested: request({ sandbox: null }) as never,+ }).sandbox,+ ).toBeNull();+ });+});describe("AkeruDelegationRuntime", () => {- it("sends a bot message through the current thread assistant-message path", async () => {- const commands: Array<{ type: string; [key: string]: unknown }> = [];- const runtime = createAkeruDelegationRuntime({- readSnapshot: async () => ({- ...snapshot,+ it("sends a bot message through its active thread", async () => {+ const test = harness(+ snapshot({threads: [- {- ...sourceThread,+ thread(PARENT_THREAD_ID, PARENT_BOT_ID, {latestTurn: {- turnId: sourceTurnId,+ turnId: PARENT_TURN_ID,state: "running",- requestedAt: now,- startedAt: now,+ requestedAt: NOW,+ startedAt: NOW,completedAt: null,assistantMessageId: null,},- },+ }),],}),- dispatch: async (command) => commands.push(command),- awaitChild: vi.fn(),- now: () => now,- id: () => "1",- });+ );await expect(- runtime.sendToUser(- { threadId: sourceThreadId, turnId: sourceTurnId, botId: sourceBotId, depth: 0 },- { message: "The export is ready." },- ),+ test.runtime.sendToUser(parent(), { message: "The export is ready." }),).resolves.toMatchObject({toolId: "SendToUser",phase: "success",- threadId: sourceThreadId,- botId: sourceBotId,- fatalToThread: false,+ threadId: PARENT_THREAD_ID,+ botId: PARENT_BOT_ID,});- expect(commands).toMatchObject([+ expect(test.commands.slice(-2)).toMatchObject([{type: "thread.message.assistant.delta",- threadId: sourceThreadId,- turnId: sourceTurnId,+ threadId: PARENT_THREAD_ID,+ turnId: PARENT_TURN_ID,delta: "The export is ready.",},{type: "thread.message.assistant.complete",- threadId: sourceThreadId,- turnId: sourceTurnId,+ threadId: PARENT_THREAD_ID,+ turnId: PARENT_TURN_ID,},]);});- it("rejects a bot that does not own the active thread", async () => {- const dispatch = vi.fn();- const runtime = createAkeruDelegationRuntime({- readSnapshot: async () => snapshot,- dispatch,- awaitChild: vi.fn(),- });+ it("rejects user messages from a bot that does not own the active thread", async () => {+ const test = harness(+ snapshot({+ threads: [+ thread(PARENT_THREAD_ID, PARENT_BOT_ID, {+ latestTurn: {+ turnId: PARENT_TURN_ID,+ state: "running",+ requestedAt: NOW,+ startedAt: NOW,+ completedAt: null,+ assistantMessageId: null,+ },+ }),+ ],+ }),+ );await expect(- runtime.sendToUser(- { threadId: sourceThreadId, turnId: sourceTurnId, botId: targetBotId, depth: 0 },- { message: "Wrong thread." },- ),+ test.runtime.sendToUser(parent({ botId: OTHER_BOT_ID }), { message: "Wrong thread." }),).rejects.toThrow("not authorized");- expect(dispatch).not.toHaveBeenCalled();});- it("enforces depth from the server-owned parent context", async () => {- const dispatch = vi.fn();- const runtime = createAkeruDelegationRuntime({- readSnapshot: async () => snapshot,- dispatch,- awaitChild: vi.fn(),+ it("delivers the result with a child link and bills the child bot", async () => {+ const test = harness(+ snapshot({+ threads: [+ thread(PARENT_THREAD_ID, PARENT_BOT_ID, { worktreePath: "/tmp/parent-worktree" }),+ thread(ThreadId.make("child"), CHILD_BOT_ID),+ ],+ }),+ {+ state: "completed",+ turnId: CHILD_TURN_ID,+ summary: "The delegated answer.",+ usage: { inputTokens: 12, outputTokens: 8 },+ },+ );+ const result = await test.runtime.send(parent(), request() as never);+ expect(result).toMatchObject({+ summary: "The delegated answer.",+ childTurnId: CHILD_TURN_ID,+ });+ expect(result && "childThreadId" in result ? result.childThreadId : null).not.toBe(+ ThreadId.make("child"),+ );+ const create = test.commands.find((command) => command.type === "thread.create");+ expect(create).toMatchObject({ worktreePath: null });+ expect(create && "threadId" in create ? create.threadId : null).not.toBe(PARENT_THREAD_ID);+ expect(test.usage).toEqual([+ expect.objectContaining({ botId: CHILD_BOT_ID, category: "delegated", inputTokens: 12 }),+ ]);+ expect(+ test.commands.find(+ (command) =>+ command.type === "thread.activity.append" &&+ command.activity.kind === "delegation.completed",+ ),+ ).toMatchObject({+ threadId: PARENT_THREAD_ID,+ activity: { payload: { childBotId: CHILD_BOT_ID } },});+ });+ it("rejects A to B to A cycles, depth, and concurrency caps", async () => {await expect(- runtime.send(- { threadId: sourceThreadId, turnId: sourceTurnId, botId: sourceBotId, depth: 2 },- request,+ harness().runtime.send(+ parent({ botId: CHILD_BOT_ID, ancestorBotIds: [PARENT_BOT_ID] }),+ request({ botId: PARENT_BOT_ID }) as never,),- ).rejects.toThrow("Delegation depth cannot exceed 2");- expect(dispatch).not.toHaveBeenCalled();+ ).rejects.toThrow("cycle");+ await expect(harness().runtime.send(parent({ depth: 2 }), request() as never)).rejects.toThrow(+ "depth",+ );+ const active = [1, 2, 3].map((index) => delegation(DelegationId.make(`active-${index}`)));+ await expect(+ harness(snapshot({ delegations: active })).runtime.send(parent(), request() as never),+ ).rejects.toThrow("more than 3");});- it("dispatches the child turn and bills its performing bot", async () => {- const commands: Array<{ type: string; [key: string]: unknown }> = [];+ it("deletes the child thread when authoritative delegation admission fails", async () => {+ const commands: OrchestrationCommand[] = [];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);- })(),+ readSnapshot: async () => snapshot(),+ dispatch: async (command) => {+ commands.push(command);+ if (command.type === "delegation.create") throw new Error("Delegation limit reached.");+ },+ awaitChild: async () => ({ state: "completed", turnId: CHILD_TURN_ID, summary: "Done." }),+ interruptChild: async () => undefined,+ now: () => NOW,+ id: () => String(commands.length + 1),});- const receipt = await runtime.send(- { threadId: sourceThreadId, turnId: sourceTurnId, botId: sourceBotId, depth: 0 },- request,+ await expect(runtime.send(parent(), request() as never)).rejects.toThrow(+ "Delegation limit reached.",);-expect(commands.map((command) => command.type)).toEqual(["thread.create","delegation.create",- "thread.turn.start",- "delegation.complete",+ "thread.delete",]);- 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" }),+ it("rejects delegated memory until a bounded child packet exists", async () => {+ await expect(+ harness().runtime.send(parent(), request({ memoryScopes: ["project"] }) as never),+ ).rejects.toThrow("memory is unavailable");+ });++ it("preserves blocked state and persists child failure", async () => {+ const blocked = harness(snapshot(), {+ state: "blocked",+ turnId: CHILD_TURN_ID,+ error: "Access denied.",+ });+ await blocked.runtime.send(parent(), request() as never);+ expect(blocked.state.delegations.at(-1)).toMatchObject({+ state: "blocked",+ failure: null,+ billedBotId: CHILD_BOT_ID,});- 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",+ const failed = harness(snapshot(), {+ state: "failed",+ turnId: CHILD_TURN_ID,+ error: "Provider failed.",+ });+ await failed.runtime.send(parent(), request() as never);+ expect(failed.state.delegations.at(-1)).toMatchObject({+ state: "failed",+ failure: { failureCode: "child_failed" },+ billedBotId: CHILD_BOT_ID,});});- 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;+ it("enforces timeout and interrupts the child", async () => {+ const test = harness();const runtime = createAkeruDelegationRuntime({- readSnapshot: async () => snapshot,- dispatch: async (command) => {- commands.push(command);- if (command.type === "thread.turn.start") throw new Error("Provider unavailable");+ readSnapshot: async () => test.state,+ dispatch: async (command) => test.dispatch(command),+ awaitChild: async () => {+ throw new Error("The delegation deadline expired.");+ },+ interruptChild: async (threadId, turnId) => {+ test.interrupts.push({ threadId, turnId });},- awaitChild: () => new Promise((resolve) => (resolveChild = resolve)),- failChild: (_threadId, error) => resolveChild({ turnId: null, error }),+ now: () => NOW,+ id: (() => {+ let value = 0;+ return () => String(++value);+ })(),});+ await runtime.send(parent(), request({ deadline: "2020-01-01T00:00:00.000Z" }) as never);+ expect(test.state.delegations.at(-1)).toMatchObject({+ state: "failed",+ failure: { failureCode: "timeout" },+ });+ expect(test.interrupts).toHaveLength(1);+ });- await expect(- runtime.send(- { threadId: sourceThreadId, turnId: sourceTurnId, botId: sourceBotId, depth: 0 },- request,- ),- ).resolves.toMatchObject({- phase: "failure",- fatalToThread: false,- summary: "Provider unavailable",+ it("cancels children on parent interrupt, preserves kept children, and marks parent failure", async () => {+ const checks = async (mode: "cancel" | "keep" | "fail") => {+ let release!: (outcome: AkeruDelegationChildOutcome) => void;+ const started = Promise.withResolvers<void>();+ const test = harness();+ const runtime = createAkeruDelegationRuntime({+ readSnapshot: async () => test.state,+ dispatch: async (command) => {+ await test.dispatch(command);+ },+ awaitChild: () =>+ new Promise((resolve) => {+ release = resolve;+ started.resolve();+ }),+ interruptChild: async (threadId, turnId) => {+ test.interrupts.push({ threadId, turnId });+ release({ state: "failed", turnId, error: "Interrupted." });+ },+ now: () => NOW,+ id: (() => {+ let value = 0;+ return () => String(++value);+ })(),+ });+ const pending = runtime.send(parent(), request() as never);+ await started.promise;+ const id = test.state.delegations[0]!.delegationId;+ await runtime.parentFinished({+ threadId: PARENT_THREAD_ID,+ failed: mode === "fail",+ ...(mode === "keep" ? { keep: new Set([id]) } : {}),+ });+ if (mode === "keep") {+ expect(test.interrupts).toEqual([]);+ release({ state: "completed", turnId: CHILD_TURN_ID, summary: "Kept result." });+ } else if (mode === "cancel") {+ release({ state: "failed", turnId: CHILD_TURN_ID, error: "Interrupted." });+ }+ await pending;+ return test;+ };++ const canceled = await checks("cancel");+ expect(canceled.commands.some((command) => command.type === "delegation.cancel")).toBe(true);+ expect(canceled.state.delegations.at(-1)?.state).toBe("canceled");+ const kept = await checks("keep");+ expect(+ kept.commands.some((command) => command.type === "delegation.cancel" && command.keep),+ ).toBe(true);+ expect(kept.state.delegations.at(-1)?.state).toBe("completed");+ expect((await checks("fail")).state.delegations.at(-1)).toMatchObject({+ state: "failed",+ failure: { failureCode: "parent_failed" },});- expect(commands.map((command) => command.type)).toEqual([- "thread.create",- "delegation.create",- "thread.turn.start",- "delegation.complete",- ]);+ });++ it("persists child cancellation for the reactor after the runtime restarts", async () => {+ const childThreadId = ThreadId.make("persisted-child");+ const active = delegation(DelegationId.make("persisted-delegation"), {+ childThreadId,+ state: "running",+ startedAt: NOW,+ });+ const test = harness(snapshot({ delegations: [active] }));++ await test.runtime.parentFinished({ threadId: PARENT_THREAD_ID, failed: false });++ expect(test.state.delegations[0]?.state).toBe("canceled");+ expect(test.commands.at(-1)).toMatchObject({+ type: "delegation.cancel",+ delegationId: active.delegationId,+ keep: false,+ });+ expect(test.interrupts).toEqual([]);+ });++ it("uses group-thread routing and does not treat a bot thread as a group", async () => {+ const groupId = GroupId.make("group-1");+ const group = {+ id: groupId,+ name: "Research",+ bossBotId: PARENT_BOT_ID,+ members: [+ { botId: PARENT_BOT_ID, role: "boss" as const },+ { botId: CHILD_BOT_ID, role: "specialist" as const },+ ],+ createdAt: NOW,+ updatedAt: NOW,+ };+ const grouped = snapshot({+ bots: [bot(PARENT_BOT_ID, { groupId }), bot(CHILD_BOT_ID, { groupId })],+ groups: [group],+ threads: [+ thread(PARENT_THREAD_ID, null, { groupId, respondingBotId: PARENT_BOT_ID }),+ thread(ThreadId.make("group-child"), null, { groupId }),+ ],+ });+ const test = harness(grouped);+ await test.runtime.send(parent(), request() as never);+ const groupTurn = test.commands.find((command) => command.type === "thread.turn.start");+ expect(groupTurn).toMatchObject({ respondingBotId: CHILD_BOT_ID });+ expect(groupTurn && "threadId" in groupTurn ? groupTurn.threadId : null).not.toBe(+ ThreadId.make("group-child"),+ );++ await expect(+ harness(+ snapshot({+ bots: [bot(PARENT_BOT_ID), bot(CHILD_BOT_ID, { groupId })],+ groups: [group],+ }),+ ).runtime.send(parent(), request() as never),+ ).rejects.toThrow("current group");});});diff --git a/apps/server/src/provider/AkeruDelegationRuntime.ts b/apps/server/src/provider/AkeruDelegationRuntime.tsindex a90c636d0..c4d1dc5cc 100644--- a/apps/server/src/provider/AkeruDelegationRuntime.ts+++ b/apps/server/src/provider/AkeruDelegationRuntime.ts@@ -2,48 +2,120 @@import * as NodeCrypto from "node:crypto";import {+ AKERU_DELEGATION_MAX_CONCURRENCY,AKERU_DELEGATION_MAX_DEPTH,+ AKERU_TOOL_CATALOG,+ BotId,CommandId,DelegationId,+ EventId,MessageId,ProviderInstanceId,ThreadId,+ type AkeruDelegationAccessGrant,+ type AkeruDelegationFailureCode,type AkeruDelegationRecord,type AkeruToolInputSchemas,type AkeruToolReceipt,- type BotId,+ type OrchestrationBot,type OrchestrationCommand,type OrchestrationReadModel,type TurnId,} from "@t3tools/contracts";-import * as DateTime from "effect/DateTime";++import { intersectDelegationAccess } from "./AkeruToolRuntime.ts";++const TERMINAL_STATES = new Set<AkeruDelegationRecord["state"]>([+ "completed",+ "failed",+ "canceled",+]);export interface AkeruDelegationParent {readonly threadId: ThreadId;readonly turnId: TurnId;readonly botId: BotId;+ readonly parentDelegationId: DelegationId | null;+ readonly ancestorBotIds: ReadonlyArray<BotId>;readonly depth: number;+ readonly access: AkeruDelegationAccessGrant;}export interface AkeruDelegationChildOutcome {+ readonly state: "completed" | "failed" | "blocked";readonly turnId: TurnId | null;- readonly result?: string;+ readonly summary?: string;readonly error?: string;- readonly usage?: { readonly inputTokens?: number; readonly outputTokens?: number };+ 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 awaitChild: (+ threadId: ThreadId,+ deadline: string | null,+ ) => Promise<AkeruDelegationChildOutcome>;+ readonly interruptChild: (threadId: ThreadId, turnId: TurnId | null) => Promise<void>;+ readonly recordUsage?: (input: {+ readonly botId: BotId;+ readonly threadId: ThreadId;+ readonly turnId: TurnId | null;+ readonly category: "delegated";+ readonly inputTokens: number;+ readonly outputTokens: number;+ }) => Promise<void>;readonly now?: () => string;readonly id?: () => string;}+function childAccess(+ bot: OrchestrationBot,+ parentMcpServerIds: ReadonlyArray<AkeruDelegationAccessGrant["enabledMcpServerIds"][number]>,+): AkeruDelegationAccessGrant {+ return {+ allowedToolIds: AKERU_TOOL_CATALOG.map((tool) => tool.id),+ memoryScopes: [],+ sandbox: bot.sandbox,+ runtimeMode: bot.runtimeMode,+ hasUserComputer: bot.sandbox === "local",+ enabledMcpServerIds: parentMcpServerIds.filter(+ (serverId) => !bot.disabledMcpServerIds.includes(serverId),+ ),+ disabledMcpServerIds: bot.disabledMcpServerIds,+ approvalCeiling: "secrets",+ };+}++function childInstructions(input: {+ readonly task: string;+ readonly expectedResult: string;+ readonly deadline: string | null;+ readonly parentThreadId: ThreadId;+}): string {+ return [+ `Delegated task from thread ${input.parentThreadId}.`,+ `Task: ${input.task}`,+ `Expected result: ${input.expectedResult}`,+ ...(input.deadline ? [`Deadline: ${input.deadline}`] : []),+ "Return a concise final result to the parent thread. Report a concrete blocker or failure.",+ ].join("\n");+}+export function createAkeruDelegationRuntime(options: AkeruDelegationRuntimeOptions) {- const now = options.now ?? (() => DateTime.formatIso(DateTime.nowUnsafe()));+ const now = options.now ?? (() => new Date().toISOString());const id = options.id ?? (() => NodeCrypto.randomUUID());+ const accessByThread = new Map<ThreadId, AkeruDelegationAccessGrant>();+ const activeByParent = new Map<+ ThreadId,+ Map<DelegationId, { threadId: ThreadId; turnId: TurnId | null }>+ >();++ const dispatch = (command: OrchestrationCommand) =>+ options.dispatch(command).then(() => undefined);const commandId = (label: string) => CommandId.make(`delegation:${label}:${id()}`);const sendToUser = async (@@ -98,122 +170,321 @@ export function createAkeruDelegationRuntime(options: AkeruDelegationRuntimeOpti};};+ const deliver = async (+ delegation: AkeruDelegationRecord,+ state: AkeruDelegationRecord["state"],+ detail: string,+ ) => {+ const createdAt = now();+ await dispatch({+ type: "thread.activity.append",+ commandId: commandId("delivery"),+ threadId: delegation.parentThreadId,+ activity: {+ id: EventId.make(`delegation:${delegation.delegationId}:${state}:${id()}`),+ tone: state === "failed" ? "error" : "info",+ kind: `delegation.${state}`,+ summary: detail,+ payload: {+ delegationId: delegation.delegationId,+ childThreadId: delegation.childThreadId,+ childTurnId: delegation.childTurnId,+ childBotId: delegation.childBotId,+ state,+ result: delegation.result,+ failure: delegation.failure,+ },+ turnId: delegation.parentTurnId,+ createdAt,+ },+ createdAt,+ });+ };++ const setState = async (delegation: AkeruDelegationRecord) => {+ await dispatch({+ type: "delegation.state.set",+ commandId: commandId(delegation.state),+ delegation,+ });+ };++ const fail = async (+ delegation: AkeruDelegationRecord,+ failureCode: AkeruDelegationFailureCode,+ message: string,+ ) => {+ const completedAt = now();+ const failed: AkeruDelegationRecord = {+ ...delegation,+ state: "failed",+ result: null,+ failure: { failureCode, message },+ updatedAt: completedAt,+ completedAt,+ };+ await setState(failed);+ await deliver(failed, "failed", message);+ return failed;+ };+const send = async (parent: AkeruDelegationParent,request: (typeof AkeruToolInputSchemas.SendToAgent)["Type"],- ): Promise<AkeruToolReceipt> => {+ ) => {+ const snapshot = await options.readSnapshot();+ const parentThread = snapshot.threads.find((thread) => thread.id === parent.threadId);+ const bot = snapshot.bots.find((candidate) => candidate.id === request.botId);+ if (!parentThread || !bot || bot.archivedAt !== null) {+ throw new Error("The target bot is not available in this workspace.");+ }+ if (bot.id === parent.botId || parent.ancestorBotIds.includes(bot.id)) {+ throw new Error("Delegation would create a self-call or cycle.");+ }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.");+ const active = snapshot.delegations.filter(+ (delegation) =>+ delegation.parentThreadId === parent.threadId && !TERMINAL_STATES.has(delegation.state),+ );+ if (active.length >= AKERU_DELEGATION_MAX_CONCURRENCY) {+ throw new Error(+ `A turn cannot run more than ${AKERU_DELEGATION_MAX_CONCURRENCY} delegations.`,+ );+ }+ if (request.memoryScopes && request.memoryScopes.length > 0) {+ throw new Error("Delegated memory is unavailable until the child memory packet is bounded.");}- if (targetBot.id === parent.botId) throw new Error("A bot cannot delegate to itself.");+ const group = bot.groupId+ ? snapshot.groups.find((candidate) => candidate.id === bot.groupId)+ : undefined;+ if (+ bot.groupId !== null &&+ (!group ||+ parentThread.groupId !== group.id ||+ !group.members.some((member) => member.botId === bot.id))+ ) {+ throw new Error("The target bot is not available in the current group.");+ }++ const grant = intersectDelegationAccess({+ parent: parent.access,+ child: childAccess(bot, parent.access.enabledMcpServerIds),+ requested: request,+ });const childThreadId = ThreadId.make(`delegation-thread-${id()}`);const createdAt = now();- await options.dispatch({+ await dispatch({type: "thread.create",commandId: commandId("thread"),threadId: childThreadId,- projectId: sourceThread.projectId,- botId: targetBot.id,- groupId: null,- title: `Delegation to ${targetBot.name}`,+ projectId: parentThread.projectId,+ botId: group ? null : bot.id,+ groupId: group?.id ?? null,+ title: `Delegation to ${bot.name}`,modelSelection:- targetBot.engine === null- ? sourceThread.modelSelection+ bot.engine === null+ ? parentThread.modelSelection: {- instanceId: ProviderInstanceId.make(targetBot.engine.provider),- model: targetBot.engine.model,+ instanceId: ProviderInstanceId.make(bot.engine.provider),+ model: bot.engine.model,},- runtimeMode: targetBot.runtimeMode,+ runtimeMode: grant.runtimeMode,interactionMode: "default",branch: null,worktreePath: null,createdAt,});+const delegationId = DelegationId.make(`delegation-${id()}`);- const active = {+ let delegation: AkeruDelegationRecord = {delegationId,- sourceThreadId: parent.threadId,- sourceTurnId: parent.turnId,- sourceBotId: parent.botId,- targetBotId: targetBot.id,- childThreadId,+ parentDelegationId: parent.parentDelegationId,+ parentBotId: parent.botId,+ childBotId: bot.id,+ parentThreadId: parent.threadId,+ childThreadId: null,+ parentTurnId: parent.turnId,childTurnId: null,+ ancestorBotIds: [...parent.ancestorBotIds, parent.botId],depth: parent.depth + 1,- billedBotId: targetBot.id,task: request.task,expectedResult: request.expectedResult,- outcome: null,+ deadline: request.deadline ?? null,+ access: grant,+ state: "queued",+ billedBotId: bot.id,+ result: null,+ failure: null,+ keep: false,createdAt,+ updatedAt: createdAt,+ startedAt: null,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(),+ await dispatch({+ type: "delegation.create",+ commandId: commandId("create"),+ delegation,});} catch (cause) {- options.failChild?.(childThreadId, cause instanceof Error ? cause.message : String(cause));+ await dispatch({+ type: "thread.delete",+ commandId: commandId("cleanup"),+ threadId: childThreadId,+ });+ throw 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,+ const startedAt = now();+ delegation = {+ ...delegation,+ childThreadId,+ state: "running",+ updatedAt: startedAt,+ startedAt,};- await options.dispatch({- type: "delegation.complete",- commandId: commandId("complete"),- delegation: completed,- });+ await setState(delegation);+ accessByThread.set(childThreadId, grant);+ const byParent = activeByParent.get(parent.threadId) ?? new Map();+ byParent.set(delegationId, { threadId: childThreadId, turnId: null });+ activeByParent.set(parent.threadId, byParent);+ await deliver(delegation, "running", `Delegated to ${bot.name}.`);- 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,+ await dispatch({+ type: "thread.turn.start",+ commandId: commandId("turn"),+ threadId: childThreadId,+ message: {+ messageId: MessageId.make(`delegation-message-${id()}`),+ role: "user",+ text: childInstructions({+ task: request.task,+ expectedResult: request.expectedResult,+ deadline: request.deadline ?? null,+ parentThreadId: parent.threadId,+ }),+ attachments: [],},- createdAt: completedAt,- };+ runtimeMode: grant.runtimeMode,+ interactionMode: "default",+ ...(group ? { respondingBotId: bot.id } : {}),+ createdAt: now(),+ });++ try {+ const outcome = await options.awaitChild(childThreadId, request.deadline ?? null);+ const current = activeByParent.get(parent.threadId)?.get(delegationId);+ if (!current) {+ return { canceled: true, childThreadId, childTurnId: outcome.turnId };+ }+ current.turnId = outcome.turnId;+ if (outcome.state !== "completed" || !outcome.summary?.trim()) {+ if (outcome.state === "blocked") {+ const blocked: AkeruDelegationRecord = {+ ...delegation,+ childTurnId: outcome.turnId,+ state: "blocked",+ updatedAt: now(),+ };+ await setState(blocked);+ await deliver(blocked, "blocked", outcome.error ?? "The delegated bot is blocked.");+ return { blocked: true, childThreadId, childTurnId: outcome.turnId };+ }+ return await fail(+ { ...delegation, childTurnId: outcome.turnId },+ "child_failed",+ outcome.error ?? "The delegated bot did not return a result.",+ );+ }+ const completedAt = now();+ const completed: AkeruDelegationRecord = {+ ...delegation,+ childTurnId: outcome.turnId,+ state: "completed",+ result: {+ summary: outcome.summary.trim(),+ childThreadId,+ childTurnId: outcome.turnId,+ },+ failure: null,+ updatedAt: completedAt,+ completedAt,+ };+ await setState(completed);+ await options.recordUsage?.({+ botId: bot.id,+ threadId: childThreadId,+ turnId: outcome.turnId,+ category: "delegated",+ inputTokens: outcome.usage?.inputTokens ?? 0,+ outputTokens: outcome.usage?.outputTokens ?? 0,+ });+ await deliver(completed, "completed", outcome.summary.trim());+ return completed.result;+ } catch (cause) {+ const timeout =+ request.deadline !== undefined && Date.parse(request.deadline) <= Date.parse(now());+ if (timeout) await options.interruptChild(childThreadId, null);+ return await fail(+ delegation,+ timeout ? "timeout" : "internal",+ cause instanceof Error ? cause.message : String(cause),+ );+ } finally {+ accessByThread.delete(childThreadId);+ byParent.delete(delegationId);+ if (byParent.size === 0) activeByParent.delete(parent.threadId);+ }+ };++ const parentFinished = async (input: {+ readonly threadId: ThreadId;+ readonly failed: boolean;+ readonly keep?: ReadonlySet<DelegationId>;+ }) => {+ const snapshot = await options.readSnapshot();+ const records = snapshot.delegations.filter(+ (delegation) =>+ delegation.parentThreadId === input.threadId && !TERMINAL_STATES.has(delegation.state),+ );+ const children = activeByParent.get(input.threadId);+ for (const record of records) {+ const keep = record.keep || input.keep?.has(record.delegationId) === true;+ const child = children?.get(record.delegationId);+ const childThreadId = child?.threadId ?? record.childThreadId;+ if (keep || !input.failed) {+ await dispatch({+ type: "delegation.cancel",+ commandId: commandId("cancel"),+ delegationId: record.delegationId,+ keep,+ createdAt: now(),+ });+ }+ if (keep) continue;+ children?.delete(record.delegationId);+ if (childThreadId) accessByThread.delete(childThreadId);+ if (input.failed) {+ await fail(record, "parent_failed", "The parent turn failed.");+ if (childThreadId) {+ await options.interruptChild(childThreadId, child?.turnId ?? record.childTurnId);+ }+ }+ }+ if (children?.size === 0) activeByParent.delete(input.threadId);};- return { send, sendToUser, readSnapshot: options.readSnapshot };+ return {+ send,+ sendToUser,+ parentFinished,+ readSnapshot: options.readSnapshot,+ accessForThread: (threadId: ThreadId) => accessByThread.get(threadId),+ };}export type AkeruDelegationRuntime = ReturnType<typeof createAkeruDelegationRuntime>;diff --git a/apps/server/src/provider/AkeruToolRuntime.test.ts b/apps/server/src/provider/AkeruToolRuntime.test.tsindex b5eb1a30a..491307391 100644--- a/apps/server/src/provider/AkeruToolRuntime.test.ts+++ b/apps/server/src/provider/AkeruToolRuntime.test.ts@@ -21,14 +21,25 @@ vi.mock("@mastra/core/workspace", async (importOriginal) => {});const directories = new Set<string>();+const workspaceRoots = new WeakMap<Workspace, string>();function workspace(name: string) {- const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), `akeru-tool-${name}-`));- directories.add(root);- return new Workspace({+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), `akeru-tool-${name}-`));+ const root = NodePath.join(directory, "workspace");+ NodeFS.mkdirSync(root);+ directories.add(directory);+ const value = new Workspace({filesystem: new LocalFilesystem({ basePath: root }),sandbox: new LocalSandbox({ workingDirectory: root }),});+ workspaceRoots.set(value, root);+ return value;+}++function workspaceRoot(value: Workspace) {+ const root = workspaceRoots.get(value);+ if (!root) throw new Error("Workspace root is unavailable.");+ return root;}describe("AkeruToolRuntime", () => {@@ -88,6 +99,49 @@ describe("AkeruToolRuntime", () => {expect([...frame.data]).toEqual([0, 0, 0, 255]);});+ it("limits delegated tools and requires a one-shot send grant", async () => {+ const send = vi.fn(async () => ({ delivered: true }));+ const runtime = createAkeruToolRuntime();+ runtime.registerSession("thread-delegated", {+ runtimeMode: "full-access",+ workspaceType: "local",+ workspace: workspace("delegated"),+ delegation: {+ depth: 0,+ activeDelegations: 0,+ access: {+ allowedToolIds: ["SendToAgent"],+ memoryScopes: [],+ sandbox: "local",+ runtimeMode: "full-access",+ hasUserComputer: false,+ enabledMcpServerIds: [],+ disabledMcpServerIds: [],+ approvalCeiling: "send",+ },+ send,+ },+ });+ expect(runtime.toolsForThread("thread-delegated").map((tool) => tool.id)).toEqual([+ "SendToAgent",+ ]);+ const execution = {+ threadId: "thread-delegated",+ toolId: "SendToAgent" as const,+ toolCallId: "tool-send",+ input: {+ botId: BotId.make("child-bot"),+ task: "Research the issue.",+ expectedResult: "Return the cause.",+ },+ approvalMode: "require-grant" as const,+ };+ await expect(runtime.execute(execution)).rejects.toThrow("requires approval");+ runtime.grantApproval(execution);+ await expect(runtime.execute(execution)).resolves.toEqual({ delivered: true });+ expect(send).toHaveBeenCalledOnce();+ });+it("exposes registered memory handlers and protects sensitive writes", async () => {const remember = vi.fn(async () => ({ saved: true }));const unavailable = vi.fn(async () => undefined);@@ -244,6 +298,74 @@ describe("AkeruToolRuntime", () => {});});+ it("rejects shell working directories outside both workspace boundaries", async () => {+ const runtime = createAkeruToolRuntime();+ const bot = workspace("cwd-bot");+ const user = workspace("cwd-user");+ NodeFS.mkdirSync(NodePath.join(workspaceRoot(user), "nested"));+ runtime.registerSession("thread-1", {+ runtimeMode: "full-access",+ workspaceType: "local",+ workspace: bot,+ userComputerWorkspace: user,+ });++ await expect(+ runtime.execute({+ threadId: "thread-1",+ toolId: "ExternalShell",+ toolCallId: "tool-safe-external",+ input: { command: "pwd", cwd: "nested" },+ approvalMode: "require-grant",+ }),+ ).resolves.toBeDefined();++ for (const toolId of ["Shell", "ExternalShell"] as const) {+ for (const cwd of ["/", ".."]) {+ const execution = {+ threadId: "thread-1",+ toolId,+ toolCallId: `tool-${toolId}-${cwd}`,+ input: { command: "pwd", cwd },+ approvalMode: "require-grant" as const,+ };+ if (toolId === "Shell") runtime.grantApproval(execution);+ await expect(runtime.execute(execution)).rejects.toThrow("must stay inside its workspace");+ }+ }+ });++ it("allows a safe read without approval and rejects path traversal", async () => {+ const runtime = createAkeruToolRuntime();+ const bot = workspace("read");+ NodeFS.writeFileSync(NodePath.join(workspaceRoot(bot), "report.txt"), "report");+ NodeFS.writeFileSync(NodePath.join(workspaceRoot(bot), "..", "outside.txt"), "secret");+ runtime.registerSession("thread-1", {+ runtimeMode: "full-access",+ workspaceType: "local",+ workspace: bot,+ });++ await expect(+ runtime.execute({+ threadId: "thread-1",+ toolId: "Read",+ toolCallId: "tool-read",+ input: { path: "report.txt" },+ approvalMode: "require-grant",+ }),+ ).resolves.toBeDefined();+ await expect(+ runtime.execute({+ threadId: "thread-1",+ toolId: "Read",+ toolCallId: "tool-read-outside",+ input: { path: "../outside.txt" },+ approvalMode: "require-grant",+ }),+ ).rejects.toThrow();+ });+it("copies files only when both boundaries are registered", async () => {const runtime = createAkeruToolRuntime();const bot = workspace("copy-bot");@@ -267,6 +389,14 @@ describe("AkeruToolRuntime", () => {expect(await bot.filesystem?.readFile("inbox/report.txt", { encoding: "utf-8" })).toBe("report",);+ NodeFS.writeFileSync(NodePath.join(workspaceRoot(user), "..", "outside.txt"), "secret");+ await expect(+ runtime.execute({+ ...execution,+ toolCallId: "tool-copy-outside",+ input: { sourcePath: "../outside.txt", destinationPath: "inbox/outside.txt" },+ }),+ ).rejects.toThrow();});it("invalidates approvals when the thread workspace changes", async () => {@@ -353,6 +483,18 @@ describe("AkeruToolRuntime", () => {runtimeMode: "full-access",workspaceType: "local",delegation: {+ depth: 0,+ activeDelegations: 0,+ access: {+ allowedToolIds: ["SendToAgent"],+ memoryScopes: [],+ sandbox: "local",+ runtimeMode: "full-access",+ hasUserComputer: false,+ enabledMcpServerIds: [],+ disabledMcpServerIds: [],+ approvalCeiling: "send",+ },send: async () => {throw new Error("Provider unavailable");},diff --git a/apps/server/src/provider/AkeruToolRuntime.ts b/apps/server/src/provider/AkeruToolRuntime.tsindex 630d9f311..0fc3cb065 100644--- a/apps/server/src/provider/AkeruToolRuntime.ts+++ b/apps/server/src/provider/AkeruToolRuntime.ts@@ -2,6 +2,8 @@import { RequestContext } from "@mastra/core/request-context";import { createWorkspaceTools, type Workspace } from "@mastra/core/workspace";import {+ type AkeruDelegationAccessGrant,+ type AkeruMemoryTargetScope,AkeruToolInputSchemas,type BotId,type AkeruToolDefinition,@@ -10,6 +12,7 @@ import {type AkeruToolWorkspaceType,type RuntimeMode,ThreadId,+ akeruToolApprovalForInput,akeruToolRequiresApproval,decodeAkeruToolInput,filterAkeruTools,@@ -55,15 +58,17 @@ export function isMemoryToolId(toolId: string): toolId is AkeruMemoryToolId {export interface AkeruToolSession {readonly botId?: BotId;readonly botName?: string;+ readonly billedBotId?: BotId;readonly runtimeMode: RuntimeMode;readonly workspaceType: AkeruToolWorkspaceType;readonly workspace?: Workspace;readonly userComputerWorkspace?: Workspace;readonly memoryHandlers?: Record<AkeruMemoryToolId, AkeruMemoryToolHandler>;readonly delegation?: {- readonly send: (- input: (typeof AkeruToolInputSchemas.SendToAgent)["Type"],- ) => Promise<AkeruToolReceipt>;+ readonly depth: number;+ readonly activeDelegations: number;+ readonly access: AkeruDelegationAccessGrant;+ readonly send: (input: (typeof AkeruToolInputSchemas.SendToAgent)["Type"]) => Promise<unknown>;};readonly channels?: {readonly create: (@@ -164,6 +169,21 @@ function canonicalInput(value: unknown): string {return JSON.stringify(value) ?? "undefined";}+function ensureWorkspaceCwd(toolId: AkeruToolId, input: unknown): void {+ if (toolId !== "Shell" && toolId !== "ExternalShell") return;+ const cwd = field(input, "cwd");+ if (cwd === undefined) return;+ if (typeof cwd !== "string") throw new Error(`Tool '${toolId}' cwd must be a relative path.`);+ if (+ cwd.startsWith("/") ||+ cwd.startsWith("\\") ||+ /^[A-Za-z]:/.test(cwd) ||+ cwd.split(/[\\/]+/).includes("..")+ ) {+ throw new Error(`Tool '${toolId}' cwd must stay inside its workspace.`);+ }+}+function workspaceForTool(toolId: AkeruToolId, session: AkeruToolSession) {return toolId === "ExternalShell" || toolId === "ExternalRead" || toolId === "AwaitExternalShell"? session.userComputerWorkspace@@ -189,6 +209,89 @@ function executable(value: unknown): value is {);}+const APPROVAL_RANK = [+ "none",+ "user-computer",+ "send",+ "pay",+ "delete",+ "production",+ "secrets",+] as const;+const RUNTIME_RANK = ["approval-required", "auto-accept-edits", "auto", "full-access"] as const;++function requestedSubset<T>(+ requested: ReadonlyArray<T> | undefined,+ ceiling: ReadonlyArray<T>,+ label: string,+): ReadonlyArray<T> {+ if (requested?.some((value) => !ceiling.includes(value))) {+ throw new Error(`Delegation requested ${label} outside the parent turn grant.`);+ }+ return requested ?? ceiling;+}++export function intersectDelegationAccess(input: {+ readonly parent: AkeruDelegationAccessGrant;+ readonly child: AkeruDelegationAccessGrant;+ readonly requested: (typeof AkeruToolInputSchemas.SendToAgent)["Type"];+}): AkeruDelegationAccessGrant {+ const requestedTools = requestedSubset(+ input.requested.allowedToolIds,+ input.parent.allowedToolIds,+ "tools",+ );+ const requestedMemory = requestedSubset<AkeruMemoryTargetScope>(+ input.requested.memoryScopes,+ input.parent.memoryScopes,+ "memory scopes",+ );+ const requestedMcpServers = requestedSubset(+ input.requested.mcpServerIds,+ input.parent.enabledMcpServerIds,+ "MCP servers",+ );+ const requestedRuntime = input.requested.runtimeMode ?? input.parent.runtimeMode;+ if (RUNTIME_RANK.indexOf(requestedRuntime) > RUNTIME_RANK.indexOf(input.parent.runtimeMode)) {+ throw new Error("Delegation requested a runtime mode above the parent turn grant.");+ }+ const requestedApproval = input.requested.approvalCeiling ?? input.parent.approvalCeiling;+ if (+ APPROVAL_RANK.indexOf(requestedApproval) > APPROVAL_RANK.indexOf(input.parent.approvalCeiling)+ ) {+ throw new Error("Delegation requested approvals above the parent turn grant.");+ }+ if (+ input.requested.sandbox !== undefined &&+ input.requested.sandbox !== null &&+ input.requested.sandbox !== input.parent.sandbox+ ) {+ throw new Error("Delegation requested a sandbox outside the parent turn grant.");+ }+ const sandbox =+ input.requested.sandbox === undefined ? input.parent.sandbox : input.requested.sandbox;+ return {+ allowedToolIds: requestedTools.filter((toolId) => input.child.allowedToolIds.includes(toolId)),+ memoryScopes: requestedMemory.filter((scope) => input.child.memoryScopes.includes(scope)),+ sandbox: sandbox === input.child.sandbox ? sandbox : null,+ runtimeMode:+ RUNTIME_RANK.indexOf(requestedRuntime) <= RUNTIME_RANK.indexOf(input.child.runtimeMode)+ ? requestedRuntime+ : input.child.runtimeMode,+ hasUserComputer: input.parent.hasUserComputer && input.child.hasUserComputer,+ enabledMcpServerIds: requestedMcpServers.filter((serverId) =>+ input.child.enabledMcpServerIds.includes(serverId),+ ),+ disabledMcpServerIds: [+ ...new Set([...input.parent.disabledMcpServerIds, ...input.child.disabledMcpServerIds]),+ ],+ approvalCeiling:+ APPROVAL_RANK.indexOf(requestedApproval) <= APPROVAL_RANK.indexOf(input.child.approvalCeiling)+ ? requestedApproval+ : input.child.approvalCeiling,+ };+}+export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): AkeruToolRuntime {const sessions = new Map<string, AkeruToolSession>();const grants = new Map<string, { readonly toolId: AkeruRuntimeToolId; readonly input: string }>();@@ -250,6 +353,11 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akerufor (const toolId of Object.keys(session.catalogHandlers ?? {}) as AkeruToolId[]) {tools.add(toolId);}+ if (session.delegation) {+ for (const toolId of tools) {+ if (!session.delegation.access.allowedToolIds.includes(toolId)) tools.delete(toolId);+ }+ }return tools;};@@ -263,6 +371,12 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): AkeruhasUserComputer: Boolean(session.userComputerWorkspace),localFullAccess: session.runtimeMode === "full-access",implementedTools: implemented,+ ...(session.delegation+ ? {+ delegationDepth: session.delegation.depth,+ activeDelegations: session.delegation.activeDelegations,+ }+ : {}),});return session.memoryHandlers? [...workspaceTools, ...MEMORY_TOOL_DEFINITIONS]@@ -291,8 +405,19 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akerureturn field(input, "scope") !== "private" || field(input, "sensitive") === true;}if (tool.id === "update_memory" || tool.id === "forget_memory") return true;+ const akeruTool = tool as AkeruToolDefinition;+ ensureWorkspaceCwd(akeruTool.id, input);+ const ceiling = session.delegation?.access.approvalCeiling;+ if (+ ceiling &&+ APPROVAL_RANK.indexOf(+ akeruToolApprovalForInput(akeruTool, input, { workspaceType: session.workspaceType }),+ ) > APPROVAL_RANK.indexOf(ceiling)+ ) {+ throw new Error(`Tool '${tool.id}' exceeds this delegation's approval ceiling.`);+ }return akeruToolRequiresApproval(- tool as AkeruToolDefinition,+ akeruTool,{localFullAccess: session.runtimeMode === "full-access",workspaceType: session.workspaceType,diff --git a/apps/server/src/provider/Layers/AgentController.test.ts b/apps/server/src/provider/Layers/AgentController.test.tsindex 5fc2410ec..0a8d8a1d6 100644--- a/apps/server/src/provider/Layers/AgentController.test.ts+++ b/apps/server/src/provider/Layers/AgentController.test.ts@@ -20,6 +20,7 @@ import {RuntimeItemId,ThreadId,TurnId,+ type AkeruDelegationAccessGrant,type ProviderRuntimeEvent,type ProviderSession,} from "@t3tools/contracts";@@ -47,6 +48,7 @@ import { LegacyProviderBridge } from "../Services/LegacyProviderBridge.ts";import type { ProviderServiceShape } from "../Services/ProviderService.ts";import {createAkeruMastraAuthStorage,+ delegatedUsageReceipt,makeAgentControllerLive,mcpServerIdForToolName,recordProviderAccessHealth,@@ -295,11 +297,13 @@ function makeLayer(AgentControllerLiveOptions,"resolveComputerUseServer" | "entityMemoryRepository" | "memoryCandidateRepository">,+ delegationRuntime?: AgentControllerLiveOptions["delegationRuntime"],) {return makeAgentControllerLive({makeMastraHarness: factory,...(makeMcpManager ? { makeMcpManager } : {}),...overrides,+ ...(delegationRuntime ? { delegationRuntime } : {}),makeBotBrowser: () =>({tools: {},@@ -517,6 +521,78 @@ describe("provider access health", () => {});describe("AgentControllerLive", () => {+ it("bills delegated usage receipts to the child bot", () => {+ const childBotId = BotId.make("bot-child");+ const childThreadId = ThreadId.make("thread-child");+ const childTurnId = TurnId.make("turn-child");+ const receipt = delegatedUsageReceipt(+ {+ botId: childBotId,+ threadId: childThreadId,+ turnId: childTurnId,+ category: "delegated",+ inputTokens: 12,+ outputTokens: 8,+ },+ { provider: ProviderDriverKind.make("codex"), providerInstanceId: codexInstanceId },+ "2026-01-01T00:00:00.000Z",+ );++ expect(receipt).toMatchObject({+ type: "tool.receipt",+ threadId: childThreadId,+ turnId: childTurnId,+ payload: {+ toolId: "SendToAgent",+ threadId: childThreadId,+ botId: childBotId,+ billedBotId: childBotId,+ fatalToThread: false,+ usage: { inputTokens: 12, outputTokens: 8 },+ },+ });+ });++ it.effect("runs parent-finished cleanup when a parent turn is interrupted", () => {+ const bridge = makeBridge();+ const mastra = makeMastraHarness();+ const parentFinished = vi.fn(async () => undefined);+ const layer = makeLayer(+ bridge.service,+ mastra.factory,+ undefined,+ undefined,+ undefined,+ undefined,+ {+ send: vi.fn(async () => null),+ sendToUser: vi.fn(async () => {+ throw new Error("not used");+ }),+ parentFinished,+ accessForThread: () => undefined,+ },+ );++ return Effect.gen(function* () {+ const controller = yield* AgentController;+ yield* resolveCodex(controller);+ yield* controller.startSession(codexThreadId, {+ threadId: codexThreadId,+ provider: ProviderDriverKind.make("codex"),+ providerInstanceId: codexInstanceId,+ cwd: process.cwd(),+ modelSelection: codexSelection,+ runtimeMode: "approval-required",+ });+ yield* controller.sendTurn({ threadId: codexThreadId, input: "Delegate work." });+ yield* controller.interruptTurn({ threadId: codexThreadId });+ yield* Effect.yieldNow;++ expect(parentFinished).toHaveBeenCalledWith({ threadId: codexThreadId, failed: false });+ }).pipe(Effect.provide(layer), Effect.orDie);+ });+it.effect("reads Akeru subscription credentials through Mastra AuthStorage", () =>Effect.gen(function* () {const config = yield* ServerConfig;@@ -1893,6 +1969,133 @@ describe("AgentControllerLive", () => {);});+ it.effect("exposes only MCP servers in the persisted delegation grant", () => {+ const bridge = makeBridge();+ const mastra = makeMastraHarness();+ const mcpManager = {+ init: vi.fn(async () => undefined),+ disconnect: vi.fn(async () => undefined),+ getTools: vi.fn(() => ({ exa_search: {} })),+ getServerStatuses: vi.fn(() => [{ name: "web", connected: true }]),+ };+ const makeMcpManagerMock = vi.fn((_dataDir, _configDir, _servers) => mcpManager as never);+ const makeMcpManager: NonNullable<AgentControllerLiveOptions["makeMcpManager"]> =+ makeMcpManagerMock;+ const webId = McpServerId.make("web");+ const emailId = McpServerId.make("email");+ const access: AkeruDelegationAccessGrant = {+ allowedToolIds: ["Read", "ExternalRead", "CopyToBox", "CopyFromBox"],+ memoryScopes: [],+ sandbox: "local",+ runtimeMode: "approval-required",+ hasUserComputer: false,+ enabledMcpServerIds: [webId],+ disabledMcpServerIds: [emailId],+ approvalCeiling: "send",+ };+ const runtime = {+ send: vi.fn(async () => null),+ sendToUser: vi.fn(async () => {+ throw new Error("not used");+ }),+ parentFinished: vi.fn(async () => undefined),+ accessForThread: () => access,+ };+ const layer = makeLayer(+ bridge.service,+ mastra.factory,+ makeMcpManager,+ undefined,+ undefined,+ undefined,+ runtime,+ );+ const server = (id: typeof webId, name: string) => ({+ id,+ name,+ transport: "url" as const,+ url: `https://${name}.example/mcp`,+ enabled: true,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ });++ return Effect.gen(function* () {+ const controller = yield* AgentController;+ yield* resolveCodex(controller);+ const session = yield* controller.startSession(codexThreadId, {+ threadId: codexThreadId,+ provider: ProviderDriverKind.make("codex"),+ providerInstanceId: codexInstanceId,+ cwd: process.cwd(),+ modelSelection: codexSelection,+ runtimeMode: "approval-required",+ mcpServers: [server(webId, "web"), server(emailId, "email")],+ });++ expect(session.mcpServerIds).toEqual([webId]);+ expect(makeMcpManagerMock.mock.calls[0]?.[2]).toEqual({+ web: { url: "https://web.example/mcp" },+ });+ const toolIds = mastra.harnessOptions[0]?.toolRuntime+ .toolsForThread(String(codexThreadId))+ .map((tool) => tool.id);+ expect(toolIds).not.toContain("ExternalRead");+ expect(toolIds).not.toContain("CopyToBox");+ expect(toolIds).not.toContain("CopyFromBox");+ }).pipe(Effect.provide(layer), Effect.orDie);+ });++ it.effect("creates no workspace for a delegated sandbox denial", () => {+ const bridge = makeBridge();+ const mastra = makeMastraHarness();+ const access: AkeruDelegationAccessGrant = {+ allowedToolIds: ["Shell", "Read"],+ memoryScopes: [],+ sandbox: null,+ runtimeMode: "approval-required",+ hasUserComputer: false,+ enabledMcpServerIds: [],+ disabledMcpServerIds: [],+ approvalCeiling: "send",+ };+ const layer = makeLayer(+ bridge.service,+ mastra.factory,+ undefined,+ undefined,+ undefined,+ undefined,+ {+ send: vi.fn(async () => null),+ sendToUser: vi.fn(async () => {+ throw new Error("not used");+ }),+ parentFinished: vi.fn(async () => undefined),+ accessForThread: () => access,+ },+ );++ return Effect.gen(function* () {+ const controller = yield* AgentController;+ yield* resolveCodex(controller);+ yield* controller.startSession(codexThreadId, {+ threadId: codexThreadId,+ provider: ProviderDriverKind.make("codex"),+ providerInstanceId: codexInstanceId,+ cwd: process.cwd(),+ botId: BotId.make("delegated-child"),+ modelSelection: codexSelection,+ runtimeMode: "approval-required",+ });++ expect(mastra.createSession.mock.calls[0]?.[0]).not.toHaveProperty("workspace");+ expect(mastra.harnessOptions[0]?.toolRuntime.toolsForThread(String(codexThreadId))).toEqual(+ [],+ );+ }).pipe(Effect.provide(layer), Effect.orDie);+ });+it.effect("creates a remote Mastra workspace for the bot sandbox provider", () => {const bridge = makeBridge();const mastra = makeMastraHarness();diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.tsindex 0c3c31cc3..178e1d935 100644--- a/apps/server/src/provider/Layers/AgentController.ts+++ b/apps/server/src/provider/Layers/AgentController.ts@@ -1,4 +1,4 @@-// @effect-diagnostics globalDate:off globalConsole:off globalRandom:off nodeBuiltinImport:off+// @effect-diagnostics globalDate:off globalConsole:off globalRandom:off nodeBuiltinImport:off globalTimers:offimport * as NodeCrypto from "node:crypto";import * as NodeFS from "node:fs";import * as NodePath from "node:path";@@ -13,6 +13,7 @@ import type {import { Workspace } from "@mastra/core/workspace";import {AkeruUsageReservationId,+ CommandId,EventId,ProviderDriverKind,ProviderInstanceId,@@ -30,11 +31,16 @@ import {type RuntimeMode,ThreadId,AKERU_PRODUCT_FEEDBACK_TOOL_NAME,+ type AkeruDelegationAccessGrant,+ type AkeruDelegationRecord,type AkeruMemoryThreadAccess,+ type OrchestrationCommand,+ type OrchestrationReadModel,} from "@t3tools/contracts";import { HostProcessPlatform } from "@t3tools/shared/hostProcess";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";+import * as Option from "effect/Option";import * as PubSub from "effect/PubSub";import * as Semaphore from "effect/Semaphore";import * as Stream from "effect/Stream";@@ -52,6 +58,8 @@ import {MemoryCandidateRepository,type MemoryCandidateRepositoryShape,} from "../../memory/Services/MemoryCandidateRepository.ts";+import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";+import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";import { AKERU_TURN_USAGE_RESERVATION_TOKENS, BotUsageLedger } from "../../usage/BotUsageLedger.ts";import {SubscriptionAuthService,@@ -72,6 +80,7 @@ import {createAkeruDelegationRuntime,type AkeruDelegationChildOutcome,type AkeruDelegationRuntime,+ type AkeruDelegationRuntimeOptions,} from "../AkeruDelegationRuntime.ts";import {createAkeruCatalogToolHandlers,@@ -161,6 +170,10 @@ export interface AgentControllerLiveOptions {readonly resolveComputerUseServer?: typeof resolveCodexComputerUseServer;readonly entityMemoryRepository?: EntityMemoryRepositoryShape;readonly memoryCandidateRepository?: MemoryCandidateRepositoryShape;+ readonly delegationRuntime?: Pick<+ AkeruDelegationRuntime,+ "send" | "sendToUser" | "parentFinished" | "accessForThread"+ >;}export function createAkeruMastraAuthStorage(secretsDir: string): AuthStorage {@@ -185,6 +198,38 @@ function eventId(): EventId {return EventId.make(`mastra-${NodeCrypto.randomUUID()}`);}+type DelegatedUsage = Parameters<NonNullable<AkeruDelegationRuntimeOptions["recordUsage"]>>[0];++export function delegatedUsageReceipt(+ usage: DelegatedUsage,+ active: {+ readonly provider: ProviderDriverKind;+ readonly providerInstanceId: ProviderInstanceId;+ },+ createdAt = nowIso(),+): Extract<ProviderRuntimeEvent, { readonly type: "tool.receipt" }> {+ return {+ eventId: eventId(),+ provider: active.provider,+ providerInstanceId: active.providerInstanceId,+ threadId: usage.threadId,+ ...(usage.turnId ? { turnId: usage.turnId } : {}),+ createdAt,+ type: "tool.receipt",+ payload: {+ receiptId: `delegation:usage:${NodeCrypto.randomUUID()}`,+ toolId: "SendToAgent",+ phase: "success",+ threadId: usage.threadId,+ botId: usage.botId,+ billedBotId: usage.botId,+ fatalToThread: false,+ usage: { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens },+ createdAt,+ },+ };+}+function messageText(message: MastraDBMessage): string {return message.content.parts.filter(@@ -340,23 +385,31 @@ const make = (options?: AgentControllerLiveOptions) =>const runPromise = Effect.runPromiseWith(runtimeContext);const mutationLock = yield* Semaphore.make(1);const runtimeEvents = yield* PubSub.unbounded<ProviderRuntimeEvent>();+ const orchestrationEngine = yield* Effect.serviceOption(OrchestrationEngineService);+ const projectionSnapshotQuery = yield* Effect.serviceOption(ProjectionSnapshotQuery);const resolvedByThread = new Map<string, ResolvedEngine>();const sessions = new Map<string, ActiveSession>();const memoryUsageByThread = new Map<string,{ readonly botId: BotId; readonly capLimit: number; turnId: TurnId }>();- let delegationRuntime: AkeruDelegationRuntime | undefined;let channelRuntime: AkeruChannelRuntime | undefined;let pluginRuntime: ReturnType<typeof createAkeruPluginRuntime> | undefined;let botStateRuntime: AkeruBotStateRuntime | undefined;const childWaiters = new Map<string,- { readonly resolve: (outcome: AkeruDelegationChildOutcome) => void }+ {+ readonly resolve: (outcome: AkeruDelegationChildOutcome) => void;+ readonly reject: (cause: Error) => void;+ readonly timer: ReturnType<typeof setTimeout> | undefined;+ }>();const resolveChildWaiter = (threadId: ThreadId, outcome: AkeruDelegationChildOutcome) => {- childWaiters.get(String(threadId))?.resolve(outcome);+ const waiter = childWaiters.get(String(threadId));+ if (!waiter) return;+ if (waiter.timer) clearTimeout(waiter.timer);childWaiters.delete(String(threadId));+ waiter.resolve(outcome);};const runMastra = <A>(operation: string, run: () => Promise<A>) =>@@ -427,12 +480,17 @@ const make = (options?: AgentControllerLiveOptions) =>});},});- const memoryHandlers = (access: AkeruMemoryThreadAccess | undefined) =>+ const memoryHandlers = (+ access: AkeruMemoryThreadAccess | undefined,+ allowedScopes?: AkeruDelegationAccessGrant["memoryScopes"],+ ) =>access && options?.entityMemoryRepository && options.memoryCandidateRepository? createMemoryToolHandlers(options.entityMemoryRepository,options.memoryCandidateRepository,access,+ undefined,+ allowedScopes,): undefined;const legacyResourceIdentity = new Map<@@ -444,6 +502,43 @@ const make = (options?: AgentControllerLiveOptions) =>readonly providerInstanceId: ProviderInstanceId;}>();+ let delegationRuntime = options?.delegationRuntime;+ const delegationFor = (input: {+ readonly threadId: ThreadId;+ readonly botId: BotId;+ readonly parentDelegation: AkeruDelegationRecord | undefined;+ readonly access: AkeruDelegationAccessGrant;+ readonly snapshot: OrchestrationReadModel | undefined;+ }): NonNullable<AkeruToolSession["delegation"]> => {+ const parent = () => {+ const turnId = sessions.get(String(input.threadId))?.activeTurn?.turnId;+ if (!turnId || !delegationRuntime) {+ throw new Error("Bot management requires an active parent turn.");+ }+ return {+ threadId: input.threadId,+ turnId,+ botId: input.botId,+ parentDelegationId: input.parentDelegation?.delegationId ?? null,+ ancestorBotIds: input.parentDelegation?.ancestorBotIds ?? [],+ depth: input.parentDelegation?.depth ?? 0,+ access: input.access,+ };+ };+ return {+ depth: input.parentDelegation?.depth ?? 0,+ activeDelegations:+ input.snapshot?.delegations.filter(+ (candidate) =>+ candidate.parentThreadId === input.threadId &&+ candidate.state !== "completed" &&+ candidate.state !== "failed" &&+ candidate.state !== "canceled",+ ).length ?? 0,+ access: input.access,+ send: (request) => delegationRuntime!.send(parent(), request),+ };+ };const makeMastraHarness = options?.makeMastraHarness ?? createAkeruMastraHarness;const bundle = yield* runMastra("construct", () =>makeMastraHarness({@@ -521,6 +616,55 @@ const make = (options?: AgentControllerLiveOptions) =>const publish = (event: ProviderRuntimeEvent) => {PubSub.publishUnsafe(runtimeEvents, event);};+ const makeDelegationRuntime = (input: {+ readonly readSnapshot: () => Promise<OrchestrationReadModel>;+ readonly dispatch: (command: OrchestrationCommand) => Promise<unknown>;+ }) =>+ createAkeruDelegationRuntime({+ ...input,+ awaitChild: (threadId, deadline) =>+ new Promise((resolve, reject) => {+ const key = String(threadId);+ if (childWaiters.has(key)) {+ reject(new Error(`Delegation waiter already exists for '${threadId}'.`));+ return;+ }+ const delay = deadline === null ? undefined : Date.parse(deadline) - Date.now();+ if (delay !== undefined && delay <= 0) {+ reject(new Error("The delegation deadline expired."));+ return;+ }+ const timer =+ delay === undefined+ ? undefined+ : setTimeout(() => {+ childWaiters.delete(key);+ reject(new Error("The delegation deadline expired."));+ }, delay);+ childWaiters.set(key, { resolve, reject, timer });+ }),+ interruptChild: (threadId, turnId) =>+ input+ .dispatch({+ type: "thread.turn.interrupt",+ commandId: CommandId.make(`delegation:interrupt:${NodeCrypto.randomUUID()}`),+ threadId,+ ...(turnId ? { turnId } : {}),+ createdAt: nowIso(),+ })+ .then(() => undefined),+ recordUsage: async (usage) => {+ const active = sessions.get(String(usage.threadId));+ if (active) publish(delegatedUsageReceipt(usage, active));+ },+ });+ delegationRuntime ??=+ Option.isSome(orchestrationEngine) && Option.isSome(projectionSnapshotQuery)+ ? makeDelegationRuntime({+ readSnapshot: () => Effect.runPromise(projectionSnapshotQuery.value.getSnapshot()),+ dispatch: (command) => Effect.runPromise(orchestrationEngine.value.dispatch(command)),+ })+ : undefined;const queueTurnMemory = (threadId: ThreadId, active: ActiveSession, turn: ActiveTurn) => {const resolved = resolvedByThread.get(String(threadId));@@ -603,6 +747,7 @@ const make = (options?: AgentControllerLiveOptions) =>type: "content.delta",payload: { streamKind: "assistant_text", delta: text },});+ turn.assistantText += text;publish({...baseEvent(threadId, active, turn.turnId),itemId,@@ -657,12 +802,24 @@ const make = (options?: AgentControllerLiveOptions) =>},});resolveChildWaiter(threadId, {+ state: state === "completed" ? "completed" : "failed",turnId: turn.turnId,...(state === "completed" && turn.assistantText.trim()- ? { result: turn.assistantText.trim() }+ ? { summary: turn.assistantText.trim() }: { error: errorMessage ?? `The delegated turn ${state}.` }),usage: { inputTokens: turn.inputTokens, outputTokens: turn.outputTokens },});+ if (state !== "completed") {+ void delegationRuntime+ ?.parentFinished({ threadId, failed: state === "failed" })+ .catch((cause) => {+ publish({+ ...baseEvent(threadId, active, turn.turnId),+ type: "runtime.error",+ payload: { message: failureDetail(cause), class: "provider_error" },+ });+ });+ }active.activeTurn = null;publishSessionState(threadId, active, "ready");};@@ -677,7 +834,6 @@ 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) {@@ -700,6 +856,29 @@ const make = (options?: AgentControllerLiveOptions) =>event: AgentControllerEvent,) => {const turn = active.activeTurn;+ const publishToolReceipt = (+ toolCallId: string,+ toolId: string,+ phase: "start" | "progress" | "success" | "failure",+ ) => {+ const billedBotId = active.toolSession.billedBotId;+ if (!billedBotId || !turn) return;+ const createdAt = nowIso();+ publish({+ ...baseEvent(threadId, active, turn.turnId),+ type: "tool.receipt",+ payload: {+ receiptId: `${toolCallId}:${phase}`,+ toolId,+ phase,+ threadId,+ botId: billedBotId,+ billedBotId,+ fatalToThread: false,+ createdAt,+ },+ });+ };switch (event.type) {case "message_update":publishAssistantText(threadId, active, event.message, false);@@ -711,6 +890,7 @@ const make = (options?: AgentControllerLiveOptions) =>if (!turn) return;completeAssistantMessages(threadId, active, turn);active.toolNames.set(event.toolCallId, event.toolName);+ publishToolReceipt(event.toolCallId, event.toolName, "start");publish({...baseEvent(threadId, active, turn.turnId),itemId: RuntimeItemId.make(event.toolCallId),@@ -728,6 +908,11 @@ const make = (options?: AgentControllerLiveOptions) =>}case "tool_update":if (!turn) return;+ publishToolReceipt(+ event.toolCallId,+ active.toolNames.get(event.toolCallId) ?? "tool",+ "progress",+ );publish({...baseEvent(threadId, active, turn.turnId),itemId: RuntimeItemId.make(event.toolCallId),@@ -761,6 +946,11 @@ const make = (options?: AgentControllerLiveOptions) =>subscriptionAuth.recordMcpRequestSuccess(mcpServerId);}}+ publishToolReceipt(+ event.toolCallId,+ toolName,+ event.isError || event.denied ? "failure" : "success",+ );publish({...baseEvent(threadId, active, turn.turnId),itemId: RuntimeItemId.make(event.toolCallId),@@ -963,19 +1153,60 @@ const make = (options?: AgentControllerLiveOptions) =>"AgentController.startSession",)(function* (threadId, input) {const key = String(threadId);+ const snapshot = Option.isSome(projectionSnapshotQuery)+ ? yield* projectionSnapshotQuery.value.getSnapshot()+ : undefined;+ const thread = snapshot?.threads.find((candidate) => candidate.id === threadId);+ const parentDelegation = snapshot?.delegations.find(+ (candidate) =>+ candidate.childThreadId === threadId &&+ candidate.state !== "completed" &&+ candidate.state !== "failed" &&+ candidate.state !== "canceled",+ );+ const respondingBotId = thread?.respondingBotId ?? thread?.botId ?? input.botId ?? null;+ const group = thread?.groupId+ ? snapshot?.groups.find((candidate) => candidate.id === thread.groupId)+ : undefined;+ const botId = respondingBotId ?? group?.bossBotId ?? null;+ const bot = snapshot?.bots.find((candidate) => candidate.id === botId);+ const delegatedAccess =+ delegationRuntime?.accessForThread(threadId) ?? parentDelegation?.access;+ const access: AkeruDelegationAccessGrant = delegatedAccess ?? {+ allowedToolIds: AKERU_TOOL_CATALOG.map((tool) => tool.id),+ memoryScopes: ["private", "bot", "project", "group", "workspace"],+ sandbox: input.botSandbox ?? null,+ runtimeMode: input.runtimeMode,+ hasUserComputer: Boolean(input.cwd),+ enabledMcpServerIds: (input.mcpServers ?? [])+ .map((server) => server.id)+ .filter((serverId) => !bot?.disabledMcpServerIds.includes(serverId)),+ disabledMcpServerIds: bot?.disabledMcpServerIds ?? [],+ approvalCeiling: "secrets",+ };+ const mcpServers = (input.mcpServers ?? []).filter(+ (server) =>+ access.enabledMcpServerIds.includes(server.id) &&+ !access.disabledMcpServerIds.includes(server.id),+ );+ const workspaceType =+ delegatedAccess && access.sandbox === null+ ? "none"+ : access.sandbox === null || access.sandbox === "local"+ ? "local"+ : "cloud";const resourceScope = botRuntimeResourceScope({sharing: input.botSandboxBrowserSharing ?? DEFAULT_BOT_SANDBOX_BROWSER_SHARING,- ...(input.botId ? { botId: input.botId } : {}),+ ...(botId ? { botId } : {}),threadId: key,});const workspaceResourceKey = botWorkspaceResourceKey({resourceScope,- ...(input.botSandbox !== undefined ? { sandbox: input.botSandbox } : {}),+ sandbox: access.sandbox,});const workspaceId = botWorkspaceIdentity(workspaceResourceKey);const existing = sessions.get(key);const resolved = resolvedByThread.get(key);- const mcpServers = input.mcpServers ?? [];if (!resolved) {return yield* new AgentControllerRuntimeError({operation: "startSession",@@ -994,25 +1225,45 @@ const make = (options?: AgentControllerLiveOptions) =>if (existing?.workspaceResourceKey === workspaceResourceKey &&existing.cwd === input.cwd &&+ existing.toolSession.workspaceType === workspaceType &&+ existing.mcpServerIds.length === mcpServers.length &&+ existing.mcpServerIds.every((id) => mcpServers.some((server) => server.id === id)) &&resolved &&existing.provider === resolved.provider &&existing.providerInstanceId === resolved.providerInstanceId &&existing.mcpServerIds.length === (input.mcpServers?.length ?? 0) &&existing.mcpServerIds.every((id) => input.mcpServers?.some((server) => server.id === id))) {- existing.runtimeMode = input.runtimeMode;+ existing.runtimeMode = access.runtimeMode;const toolSession = { ...existing.toolSession };delete toolSession.botId;delete toolSession.botName;+ delete toolSession.billedBotId;+ delete toolSession.delegation;delete toolSession.memoryHandlers;delete toolSession.botState;- const nextMemoryHandlers = memoryHandlers(input.memoryAccess);+ const nextMemoryHandlers =+ access.memoryScopes.length > 0+ ? memoryHandlers(input.memoryAccess, access.memoryScopes)+ : undefined;existing.toolSession = {...toolSession,- runtimeMode: input.runtimeMode,- ...(input.botId ? { botId: input.botId } : {}),+ runtimeMode: access.runtimeMode,+ ...(botId ? { botId } : {}),...(input.botName ? { botName: input.botName } : {}),...(nextMemoryHandlers ? { memoryHandlers: nextMemoryHandlers } : {}),+ ...(delegatedAccess && botId ? { billedBotId: botId } : {}),+ ...(delegationRuntime && botId+ ? {+ delegation: delegationFor({+ threadId,+ botId,+ parentDelegation,+ access,+ snapshot,+ }),+ }+ : {}),...(input.botId && botStateRuntime ? { botState: botStateRuntime } : {}),};toolRuntime.registerSession(key, existing.toolSession);@@ -1044,17 +1295,28 @@ const make = (options?: AgentControllerLiveOptions) =>previousWorkspaceResourceKey !== workspaceResourceKey,);}- const resources = yield* runMastra("resources.acquire", () =>- sessionResources.acquire({- threadId: key,- resourceScope,- workspaceResourceKey,- workspaceId,- ...(input.botSandbox !== undefined ? { botSandbox: input.botSandbox } : {}),- ...(input.cwd ? { userComputerCwd: input.cwd } : {}),- mcpServers,- }),- );+ if (delegatedAccess && !usesMastraCode(resolved.provider)) {+ return yield* new AgentControllerRuntimeError({+ operation: "startSession",+ detail: `Provider '${resolved.provider}' cannot enforce delegated access.`,+ });+ }+ const resources =+ delegatedAccess && access.sandbox === null+ ? ({ workspaceType: "none" } as const)+ : yield* runMastra("resources.acquire", () =>+ sessionResources.acquire({+ threadId: key,+ resourceScope,+ workspaceResourceKey,+ workspaceId,+ ...(access.sandbox !== null ? { botSandbox: access.sandbox } : {}),+ ...((!delegatedAccess || access.hasUserComputer) && input.cwd+ ? { userComputerCwd: input.cwd }+ : {}),+ mcpServers,+ }),+ );if (!usesMastraCode(resolved.provider)) {return yield* legacyProviderBridge.startSession(threadId, input).pipe(Effect.tap((session) =>@@ -1075,17 +1337,21 @@ const make = (options?: AgentControllerLiveOptions) =>),);}- const workspaceType: "cloud" | "local" =- input.botSandbox && input.botSandbox !== "local" ? "cloud" : "local";+ const workspace = "botWorkspace" in resources ? resources.botWorkspace : undefined;const userComputerWorkspace =- workspaceType === "local" && input.cwd ? resources.workspace : undefined;- const registeredMemoryHandlers = memoryHandlers(input.memoryAccess);+ "workspace" in resources && access.hasUserComputer && workspaceType === "local" && input.cwd+ ? resources.workspace+ : undefined;+ const registeredMemoryHandlers =+ access.memoryScopes.length > 0+ ? memoryHandlers(input.memoryAccess, access.memoryScopes)+ : undefined;const toolSession: AkeruToolSession = {- ...(input.botId ? { botId: input.botId } : {}),+ ...(botId ? { botId } : {}),...(input.botName ? { botName: input.botName } : {}),- runtimeMode: input.runtimeMode,+ runtimeMode: access.runtimeMode,workspaceType,- workspace: resources.botWorkspace,+ ...(workspace ? { workspace } : {}),...(userComputerWorkspace ? { userComputerWorkspace } : {}),...(registeredMemoryHandlers ? { memoryHandlers: registeredMemoryHandlers } : {}),...(input.botId && botStateRuntime ? { botState: botStateRuntime } : {}),@@ -1093,38 +1359,27 @@ const make = (options?: AgentControllerLiveOptions) =>sessionResources.getMcpManager(key),pluginRuntime,),- ...(input.botId && delegationRuntime+ ...(delegatedAccess && botId ? { billedBotId: botId } : {}),+ ...(delegationRuntime && botId? {sendToUser: async (request) => {const active = sessions.get(key);const turnId = active?.activeTurn?.turnId;if (!turnId) throw new Error("User messaging requires an active turn.");return delegationRuntime!.sendToUser(- { threadId, turnId, botId: input.botId!, depth: 0 },+ {+ threadId,+ turnId,+ botId,+ parentDelegationId: parentDelegation?.delegationId ?? null,+ ancestorBotIds: parentDelegation?.ancestorBotIds ?? [],+ depth: parentDelegation?.depth ?? 0,+ access,+ },request,);},- 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,- );- },- },+ delegation: delegationFor({ threadId, botId, parentDelegation, access, snapshot }),}: {}),...(input.botId && channelRuntime@@ -1144,7 +1399,7 @@ const make = (options?: AgentControllerLiveOptions) =>resourceId: key,threadId: key,...(input.cwd ? { tags: { projectPath: input.cwd } } : {}),- workspace: resources.workspace,+ ...(workspace ? { workspace } : {}),}),).pipe(Effect.tapError(() =>@@ -1189,7 +1444,7 @@ const make = (options?: AgentControllerLiveOptions) =>runMastra("permissions.setForCategory", () =>session.permissions.setForCategory({category,- policy: permissionPolicy(input.runtimeMode, category),+ policy: permissionPolicy(access.runtimeMode, category),}),),{ discard: true },@@ -1218,7 +1473,7 @@ const make = (options?: AgentControllerLiveOptions) =>cwd: input.cwd,createdAt: nowIso(),mcpServerIds: mcpServers.map((server) => server.id),- runtimeMode: input.runtimeMode,+ runtimeMode: access.runtimeMode,model: resolved.modelSelection.model,status: "ready" as const,activeTurn: null,@@ -1486,6 +1741,7 @@ const make = (options?: AgentControllerLiveOptions) =>}cancelPendingApprovals(input.threadId, active);active.session.abort();+ if (active.activeTurn) finishTurn(input.threadId, active, "interrupted");active.unsubscribe();publishSessionState(input.threadId, active, "stopped");yield* runMastra("deleteSession", () =>@@ -1527,6 +1783,9 @@ const make = (options?: AgentControllerLiveOptions) =>Effect.gen(function* () {for (const [threadId, active] of sessions) {active.session.abort();+ if (active.activeTurn) {+ finishTurn(ThreadId.make(threadId), active, "interrupted");+ }active.unsubscribe();yield* runMastra("deleteSession", () =>bundle.controller.deleteSession({ resourceId: threadId }),@@ -1535,6 +1794,11 @@ const make = (options?: AgentControllerLiveOptions) =>}legacyResourceIdentity.clear();sessions.clear();+ for (const waiter of childWaiters.values()) {+ if (waiter.timer) clearTimeout(waiter.timer);+ waiter.reject(new Error("The agent controller stopped."));+ }+ childWaiters.clear();yield* runMastra("resources.shutdown", () => sessionResources.shutdown()).pipe(Effect.ignoreCause({ log: true }),);@@ -1556,22 +1820,10 @@ const make = (options?: AgentControllerLiveOptions) =>Effect.sync(() => {botStateRuntime = createAkeruBotStateRuntime(input);channelRuntime = createAkeruChannelRuntime(input);- 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 });- }),- });+ delegationRuntime ??= makeDelegationRuntime(input);}),failDelegation: ({ threadId, error }) =>- Effect.sync(() => resolveChildWaiter(threadId, { turnId: null, error })),+ Effect.sync(() => resolveChildWaiter(threadId, { state: "failed", turnId: null, error })),readConversationMemory: (threadId) =>bundle.readObservationalMemory? runMastra("memory.read", () =>diff --git a/packages/contracts/src/akeruDelegation.test.ts b/packages/contracts/src/akeruDelegation.test.tsnew file mode 100644index 000000000..bcc4917e4--- /dev/null+++ b/packages/contracts/src/akeruDelegation.test.ts@@ -0,0 +1,124 @@+import * as Schema from "effect/Schema";+import { describe, expect, it } from "vite-plus/test";++import {+ AKERU_DELEGATION_MAX_CONCURRENCY,+ AKERU_DELEGATION_MAX_DEPTH,+ AkeruDelegationRecord,+ AkeruDelegationState,+} from "./akeruDelegation.ts";+import { OrchestrationCommand, OrchestrationEvent } from "./orchestration.ts";++const decodeDelegationRecord = Schema.decodeUnknownSync(AkeruDelegationRecord);+const decodeDelegationState = Schema.decodeUnknownSync(AkeruDelegationState);+const decodeOrchestrationCommand = Schema.decodeUnknownSync(OrchestrationCommand);+const decodeOrchestrationEvent = Schema.decodeUnknownSync(OrchestrationEvent);++const record = {+ delegationId: "delegation-1",+ parentDelegationId: null,+ parentBotId: "bot-parent",+ childBotId: "bot-child",+ parentThreadId: "thread-parent",+ childThreadId: "thread-child",+ parentTurnId: "turn-parent",+ childTurnId: "turn-child",+ ancestorBotIds: ["bot-parent"],+ depth: 1,+ task: "Compare three flights.",+ expectedResult: "A short comparison with sources.",+ deadline: null,+ access: {+ allowedToolIds: ["Read"],+ memoryScopes: ["project"],+ sandbox: "daytona",+ runtimeMode: "approval-required",+ hasUserComputer: false,+ enabledMcpServerIds: [],+ disabledMcpServerIds: ["email"],+ approvalCeiling: "send",+ },+ state: "completed",+ billedBotId: "bot-child",+ result: {+ summary: "Compared the three requested flights.",+ childThreadId: "thread-child",+ childTurnId: "turn-child",+ },+ failure: null,+ keep: false,+ createdAt: "2026-08-31T00:00:00.000Z",+ updatedAt: "2026-08-31T00:01:00.000Z",+ startedAt: "2026-08-31T00:00:10.000Z",+ completedAt: "2026-08-31T00:01:00.000Z",+} as const;++describe("Akeru delegation contracts", () => {+ it("decodes a durable delegation record", () => {+ expect(decodeDelegationRecord(record)).toMatchObject({+ delegationId: "delegation-1",+ billedBotId: "bot-child",+ result: { childThreadId: "thread-child" },+ });+ });++ it("decodes every lifecycle state", () => {+ expect(+ ["queued", "running", "blocked", "failed", "canceled", "completed"].map((state) =>+ decodeDelegationState(state),+ ),+ ).toEqual(["queued", "running", "blocked", "failed", "canceled", "completed"]);+ });++ it("caps delegation depth and publishes the concurrency limit", () => {+ expect(() =>+ decodeDelegationRecord({+ ...record,+ depth: AKERU_DELEGATION_MAX_DEPTH + 1,+ }),+ ).toThrow();+ expect(AKERU_DELEGATION_MAX_CONCURRENCY).toBe(3);+ });++ it("decodes delegation commands and events", () => {+ expect(+ [+ decodeOrchestrationCommand({+ type: "delegation.create",+ commandId: "command-create",+ delegation: record,+ }),+ decodeOrchestrationCommand({+ type: "delegation.state.set",+ commandId: "command-update",+ delegation: record,+ }),+ decodeOrchestrationCommand({+ type: "delegation.cancel",+ commandId: "command-cancel",+ delegationId: "delegation-1",+ createdAt: "2026-08-31T00:01:00.000Z",+ }),+ ].map((command) => command.type),+ ).toEqual(["delegation.create", "delegation.state.set", "delegation.cancel"]);++ const eventBase = {+ sequence: 1,+ eventId: "event-1",+ aggregateKind: "delegation",+ aggregateId: "delegation-1",+ occurredAt: "2026-08-31T00:00:00.000Z",+ commandId: "command-create",+ causationEventId: null,+ correlationId: "command-create",+ metadata: {},+ payload: { delegation: record },+ };+ expect(+ [+ decodeOrchestrationEvent({ ...eventBase, type: "delegation.created" }),+ decodeOrchestrationEvent({ ...eventBase, eventId: "event-2", type: "delegation.updated" }),+ ].map((event) => event.type),+ ).toEqual(["delegation.created", "delegation.updated"]);+ });+});diff --git a/packages/contracts/src/akeruDelegation.ts b/packages/contracts/src/akeruDelegation.tsnew file mode 100644index 000000000..64243d0f5--- /dev/null+++ b/packages/contracts/src/akeruDelegation.ts@@ -0,0 +1,94 @@+import * as Effect from "effect/Effect";+import * as Schema from "effect/Schema";++import { AkeruMemoryTargetScope } from "./akeruMemory.ts";+import { AkeruToolApprovalClass, AkeruToolId } from "./akeruTools.ts";+import {+ BotId,+ IsoDateTime,+ PositiveInt,+ ThreadId,+ TrimmedNonEmptyString,+ TurnId,+} from "./baseSchemas.ts";+import { McpServerId } from "./mcpServer.ts";+import { BotSandbox, RuntimeMode } from "./orchestration.ts";++export const AKERU_DELEGATION_MAX_DEPTH = 2;+export const AKERU_DELEGATION_MAX_CONCURRENCY = 3;++export const DelegationId = TrimmedNonEmptyString.pipe(Schema.brand("DelegationId"));+export type DelegationId = typeof DelegationId.Type;++export const AkeruDelegationState = Schema.Literals([+ "queued",+ "running",+ "blocked",+ "failed",+ "canceled",+ "completed",+]);+export type AkeruDelegationState = typeof AkeruDelegationState.Type;++export const AkeruDelegationAccessGrant = Schema.Struct({+ allowedToolIds: Schema.Array(Schema.suspend(() => AkeruToolId)),+ memoryScopes: Schema.Array(AkeruMemoryTargetScope),+ sandbox: Schema.NullOr(Schema.suspend((): Schema.Codec<BotSandbox> => BotSandbox)),+ runtimeMode: Schema.suspend((): Schema.Codec<RuntimeMode> => RuntimeMode),+ hasUserComputer: Schema.Boolean,+ enabledMcpServerIds: Schema.Array(McpServerId).pipe(+ Schema.withDecodingDefault(Effect.succeed([])),+ ),+ disabledMcpServerIds: Schema.Array(McpServerId),+ approvalCeiling: Schema.suspend(() => AkeruToolApprovalClass),+});+export type AkeruDelegationAccessGrant = typeof AkeruDelegationAccessGrant.Type;++export const AkeruDelegationFailureCode = Schema.Literals([+ "timeout",+ "denied",+ "child_failed",+ "parent_failed",+ "internal",+]);+export type AkeruDelegationFailureCode = typeof AkeruDelegationFailureCode.Type;++export const AkeruDelegationResult = Schema.Struct({+ summary: TrimmedNonEmptyString,+ childThreadId: ThreadId,+ childTurnId: Schema.NullOr(TurnId),+});+export type AkeruDelegationResult = typeof AkeruDelegationResult.Type;++export const AkeruDelegationFailure = Schema.Struct({+ failureCode: AkeruDelegationFailureCode,+ message: TrimmedNonEmptyString,+});+export type AkeruDelegationFailure = typeof AkeruDelegationFailure.Type;++export const AkeruDelegationRecord = Schema.Struct({+ delegationId: DelegationId,+ parentDelegationId: Schema.NullOr(DelegationId),+ parentBotId: BotId,+ childBotId: BotId,+ parentThreadId: ThreadId,+ childThreadId: Schema.NullOr(ThreadId),+ parentTurnId: TurnId,+ childTurnId: Schema.NullOr(TurnId),+ ancestorBotIds: Schema.Array(BotId),+ depth: PositiveInt.check(Schema.isLessThanOrEqualTo(AKERU_DELEGATION_MAX_DEPTH)),+ task: TrimmedNonEmptyString,+ expectedResult: TrimmedNonEmptyString,+ deadline: Schema.NullOr(IsoDateTime),+ access: AkeruDelegationAccessGrant,+ state: AkeruDelegationState,+ billedBotId: BotId,+ result: Schema.NullOr(AkeruDelegationResult),+ failure: Schema.NullOr(AkeruDelegationFailure),+ keep: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),+ createdAt: IsoDateTime,+ updatedAt: IsoDateTime,+ startedAt: Schema.NullOr(IsoDateTime),+ completedAt: Schema.NullOr(IsoDateTime),+});+export type AkeruDelegationRecord = typeof AkeruDelegationRecord.Type;diff --git a/packages/contracts/src/akeruTools.test.ts b/packages/contracts/src/akeruTools.test.tsindex fa8522775..9281d31de 100644--- a/packages/contracts/src/akeruTools.test.ts+++ b/packages/contracts/src/akeruTools.test.ts@@ -45,15 +45,40 @@ describe("Akeru tool contracts", () => {);});- it("decodes SendToAgent input and rejects server-owned fields", () => {+ it("hides SendToAgent at delegation limits", () => {+ const context = {+ capabilities: new Set(["bot-workspace"] as const),+ workspaceType: "local" as const,+ hasUserComputer: false,+ localFullAccess: false,+ implementedTools: new Set(["SendToAgent"]),+ };++ expect(+ filterAkeruTools({ ...context, delegationDepth: 1, activeDelegations: 2 }).map(+ (tool) => tool.id,+ ),+ ).toEqual(["SendToAgent"]);+ expect(filterAkeruTools({ ...context, delegationDepth: 2, activeDelegations: 2 })).toEqual([]);+ expect(filterAkeruTools({ ...context, delegationDepth: 1, activeDelegations: 3 })).toEqual([]);+ });++ it("decodes the approval limit and keeps escalation fields server-owned", () => {const input = {botId: "bot-research",task: "Compare three flights.",expectedResult: "A short comparison with sources.",+ approvalCeiling: "send" as const,};- expect(decodeAkeruToolInput("SendToAgent", input)).toEqual(input);+ expect(decodeAkeruToolInput("SendToAgent", input)).toMatchObject(input);expect(() => decodeAkeruToolInput("SendToAgent", { ...input, depth: 2 })).toThrow();+ expect(() =>+ decodeAkeruToolInput("SendToAgent", {+ ...input,+ hasUserComputer: true,+ }),+ ).toThrow();expect(AKERU_TOOL_CATALOG.find((tool) => tool.id === "SendToAgent")?.approval).toBe("send");});diff --git a/packages/contracts/src/akeruTools.ts b/packages/contracts/src/akeruTools.tsindex 1b2b0f93d..7e443e8b1 100644--- a/packages/contracts/src/akeruTools.ts+++ b/packages/contracts/src/akeruTools.ts@@ -10,7 +10,10 @@ import {ThreadId,TrimmedNonEmptyString,} from "./baseSchemas.ts";-import { McpServerUrl } from "./mcpServer.ts";+import { AkeruMemoryTargetScope } from "./akeruMemory.ts";+import { AKERU_DELEGATION_MAX_CONCURRENCY, AKERU_DELEGATION_MAX_DEPTH } from "./akeruDelegation.ts";+import { McpServerId, McpServerUrl } from "./mcpServer.ts";+import { BotSandbox, RuntimeMode } from "./orchestration.ts";export const AKERU_COMMAND_MAX_CHARS = 32_000;export const AKERU_PATH_MAX_CHARS = 512;@@ -48,6 +51,39 @@ const UpdateBotProfileInput = Schema.Struct({),);+export const AkeruToolId = Schema.Literals([+ "Shell",+ "Read",+ "Screenshot",+ "CopyToBox",+ "CopyFromBox",+ "request_box_help",+ "ExternalShell",+ "ExternalRead",+ "AwaitShell",+ "AwaitExternalShell",+ "SendToAgent",+ "CreateChannel",+ "UpdateChannel",+ "SendToUser",+ "InstallPlugin",+ "UpdateBotProfile",+ "AuthenticateMcpServer",+ "RestartMcpServers",+]);+export type AkeruToolId = typeof AkeruToolId.Type;++export const AkeruToolApprovalClass = Schema.Literals([+ "none",+ "user-computer",+ "send",+ "pay",+ "delete",+ "production",+ "secrets",+]);+export type AkeruToolApprovalClass = typeof AkeruToolApprovalClass.Type;+export const AkeruToolInputSchemas = {Shell: CommandInput,Read: PathInput,@@ -66,6 +102,15 @@ export const AkeruToolInputSchemas = {botId: BotId,task: TrimmedNonEmptyString,expectedResult: TrimmedNonEmptyString,+ deadline: Schema.optional(IsoDateTime),+ allowedToolIds: Schema.optional(Schema.Array(AkeruToolId)),+ memoryScopes: Schema.optional(Schema.Array(AkeruMemoryTargetScope)),+ mcpServerIds: Schema.optional(Schema.Array(McpServerId)),+ sandbox: Schema.optional(+ Schema.NullOr(Schema.suspend((): Schema.Codec<BotSandbox> => BotSandbox)),+ ),+ runtimeMode: Schema.optional(Schema.suspend((): Schema.Codec<RuntimeMode> => RuntimeMode)),+ approvalCeiling: Schema.optional(AkeruToolApprovalClass),}),CreateChannel: Schema.Struct({name: TrimmedNonEmptyString,@@ -89,8 +134,7 @@ export const AkeruToolInputSchemas = {RestartMcpServers: Schema.Struct({serverIds: Schema.optional(Schema.Array(TrimmedNonEmptyString)),}),-} as const;-export type AkeruToolId = keyof typeof AkeruToolInputSchemas;+} as const satisfies Record<AkeruToolId, Schema.Top>;const AkeruToolInputDecoders = Object.fromEntries(Object.entries(AkeruToolInputSchemas).map(([toolId, schema]) => [@@ -118,16 +162,6 @@ export const AKERU_PROTECTED_APPROVAL_CLASSES: ReadonlySet<AkeruProtectedApprova"secrets",]);-export const AkeruToolApprovalClass = Schema.Literals([- "none",- "user-computer",- "send",- "pay",- "delete",- "production",- "secrets",-]);-export type AkeruToolApprovalClass = typeof AkeruToolApprovalClass.Type;export const AkeruToolCapability = Schema.Literals(["bot-workspace", "user-computer"]);export type AkeruToolCapability = typeof AkeruToolCapability.Type;export const AkeruToolWorkspaceType = Schema.Literals(["none", "local", "cloud"]);@@ -243,6 +277,8 @@ export interface AkeruToolAvailabilityContext {readonly hasUserComputer: boolean;readonly localFullAccess: boolean;readonly implementedTools: ReadonlySet<string>;+ readonly delegationDepth?: number;+ readonly activeDelegations?: number;}export function filterAkeruTools(@@ -251,6 +287,12 @@ export function filterAkeruTools(return AKERU_TOOL_CATALOG.filter((tool) => {if (!context.capabilities.has(tool.capability)) return false;if (!context.implementedTools.has(tool.id)) return false;+ if (+ tool.id === "SendToAgent" &&+ ((context.delegationDepth ?? 0) >= AKERU_DELEGATION_MAX_DEPTH ||+ (context.activeDelegations ?? 0) >= AKERU_DELEGATION_MAX_CONCURRENCY)+ )+ return false;if (tool.workspace === "bot-workspace" && context.workspaceType === "none") return false;if (tool.workspace === "user-computer" && !context.hasUserComputer) return false;return !(tool.requiresUserComputer && !context.hasUserComputer);diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.tsindex c6645937e..b9a10acf0 100644--- a/packages/contracts/src/index.ts+++ b/packages/contracts/src/index.ts@@ -1,6 +1,7 @@export * from "./baseSchemas.ts";export * from "./background.ts";export * from "./akeruTools.ts";+export * from "./akeruDelegation.ts";export * from "./productFeedback.ts";export * from "./akeruMemory.ts";export * from "./akeruUsage.ts";diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.tsindex 866b3974d..76a7eed0b 100644--- a/packages/contracts/src/orchestration.test.ts+++ b/packages/contracts/src/orchestration.test.ts@@ -4,7 +4,6 @@ import * as Schema from "effect/Schema";import { MessageId } from "./baseSchemas.ts";import {- AkeruDelegationRecord,BotAvatar,DEFAULT_LOCAL_EXECUTION_MODE,DEFAULT_PROVIDER_INTERACTION_MODE,@@ -48,7 +47,6 @@ const decodeThreadTurnStartRequestedPayload = Schema.decodeUnknownEffect();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);@@ -600,26 +598,8 @@ it.effect("defaults settled fields when decoding historical thread data", () =>}),);-it.effect("decodes delegation records and defaults historical read models", () =>+it.effect("defaults delegations when decoding 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: [],diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.tsindex e12a3a9aa..4e347a6df 100644--- a/packages/contracts/src/orchestration.ts+++ b/packages/contracts/src/orchestration.ts@@ -26,6 +26,7 @@ import {} from "./baseSchemas.ts";import { ProviderInstanceId } from "./providerInstance.ts";import { McpServer, McpServerId, McpServerUrl } from "./mcpServer.ts";+import { AkeruDelegationRecord, DelegationId } from "./akeruDelegation.ts";export const ORCHESTRATION_WS_METHODS = {dispatchCommand: "orchestration.dispatchCommand",@@ -554,47 +555,12 @@ 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(+ delegations: Schema.Array(Schema.suspend(() => AkeruDelegationRecord)).pipe(Schema.withDecodingDefault(Effect.succeed([])),),mcpServers: Schema.optional(Schema.Array(McpServer)),@@ -1307,6 +1273,14 @@ const ThreadSessionStopCommand = Schema.Struct({onlyIfSettled: Schema.optional(Schema.Boolean),});+export const DelegationCancelCommand = Schema.Struct({+ type: Schema.Literal("delegation.cancel"),+ commandId: CommandId,+ delegationId: Schema.suspend(() => DelegationId),+ keep: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),+ createdAt: IsoDateTime,+});+const DispatchableClientOrchestrationCommand = Schema.Union([ProjectCreateCommand,ProjectMetaUpdateCommand,@@ -1347,6 +1321,7 @@ const DispatchableClientOrchestrationCommand = Schema.Union([ThreadUserInputRespondCommand,ThreadCheckpointRevertCommand,ThreadSessionStopCommand,+ DelegationCancelCommand,]);export type DispatchableClientOrchestrationCommand =typeof DispatchableClientOrchestrationCommand.Type;@@ -1391,6 +1366,7 @@ export const ClientOrchestrationCommand = Schema.Union([ThreadUserInputRespondCommand,ThreadCheckpointRevertCommand,ThreadSessionStopCommand,+ DelegationCancelCommand,]);export type ClientOrchestrationCommand = typeof ClientOrchestrationCommand.Type;@@ -1487,13 +1463,13 @@ const ThreadTitleRegenerationCompleteCommand = Schema.Struct({export const DelegationCreateCommand = Schema.Struct({type: Schema.Literal("delegation.create"),commandId: CommandId,- delegation: AkeruDelegationRecord,+ delegation: Schema.suspend(() => AkeruDelegationRecord),});-export const DelegationCompleteCommand = Schema.Struct({- type: Schema.Literal("delegation.complete"),+export const DelegationStateSetCommand = Schema.Struct({+ type: Schema.Literal("delegation.state.set"),commandId: CommandId,- delegation: AkeruDelegationRecord,+ delegation: Schema.suspend(() => AkeruDelegationRecord),});const InternalOrchestrationCommand = Schema.Union([@@ -1507,7 +1483,7 @@ const InternalOrchestrationCommand = Schema.Union([ThreadRevertCompleteCommand,ThreadTitleRegenerationCompleteCommand,DelegationCreateCommand,- DelegationCompleteCommand,+ DelegationStateSetCommand,]);export type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;@@ -1563,7 +1539,7 @@ export const OrchestrationEventType = Schema.Literals(["thread.turn-diff-completed","thread.activity-appended","delegation.created",- "delegation.completed",+ "delegation.updated",]);export type OrchestrationEventType = typeof OrchestrationEventType.Type;@@ -1923,9 +1899,9 @@ export const ThreadActivityAppendedPayload = Schema.Struct({});export const DelegationCreatedPayload = Schema.Struct({- delegation: AkeruDelegationRecord,+ delegation: Schema.suspend(() => AkeruDelegationRecord),});-export const DelegationCompletedPayload = DelegationCreatedPayload;+export const DelegationUpdatedPayload = DelegationCreatedPayload;/*** Which client connection dispatched the command that produced an event.@@ -1954,7 +1930,14 @@ const EventBaseFields = {sequence: NonNegativeInt,eventId: EventId,aggregateKind: OrchestrationAggregateKind,- aggregateId: Schema.Union([ProjectId, BotId, GroupId, McpServerId, ThreadId, DelegationId]),+ aggregateId: Schema.Union([+ ProjectId,+ BotId,+ GroupId,+ McpServerId,+ ThreadId,+ Schema.suspend(() => DelegationId),+ ]),occurredAt: IsoDateTime,commandId: Schema.NullOr(CommandId),causationEventId: Schema.NullOr(EventId),@@ -2190,8 +2173,8 @@ export const OrchestrationEvent = Schema.Union([}),Schema.Struct({...EventBaseFields,- type: Schema.Literal("delegation.completed"),- payload: DelegationCompletedPayload,+ type: Schema.Literal("delegation.updated"),+ payload: DelegationUpdatedPayload,}),]);export type OrchestrationEvent = typeof OrchestrationEvent.Type;