Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(agent-runtime): carve principal, plan and host slots out of state.metadata (#19513)

Arvin Xu93fc45ff7712
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 83807656758..989912a997c 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -2883,8 +2883,10 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
group: agentGroup,
},
- metadata: {
- botContext: ctxWithConfig.botContext,
+ principal: {
+ actor: {
+ bot: ctxWithConfig.botContext as any,
+ },
},
origin: {
agentId: 'agent-support',
@@ -4967,8 +4969,10 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should pass clientIp from runtime metadata to executeTool', async () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState({
- metadata: {
- clientIp: '203.0.113.7',
+ principal: {
+ audit: {
+ clientIp: '203.0.113.7',
+ },
},
origin: {
agentId: 'agent-123',
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
index bac4aeba73e..e1238568b01 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts
@@ -332,16 +332,16 @@ export class ServerLLMTransport implements LLMTransport {
// Carry the originating request's client IP / user agent from the run's
// state.metadata into the attempt so the LLM-call metadata can surface them
// for auditing and spend attribution.
- clientIp: input.state.metadata?.clientIp,
- // Projected, not spread: `state.metadata.agentShareVisitor` also carries
+ clientIp: input.state.principal?.audit?.clientIp,
+ // Projected, not spread: `state.principal.actor.shareVisitor` also carries
// the run's tool/memory restrictions, which have no place in billing
// metadata. Only the three attribution ids travel.
- agentShareVisitorIds: input.state.metadata?.agentShareVisitor
- ? toAgentShareVisitorIds(input.state.metadata.agentShareVisitor)
+ agentShareVisitorIds: input.state.principal?.actor?.shareVisitor
+ ? toAgentShareVisitorIds(input.state.principal?.actor?.shareVisitor)
: undefined,
topicId: input.state.origin?.topicId,
trigger: input.state.origin?.trigger,
- userAgent: input.state.metadata?.userAgent,
+ userAgent: input.state.principal?.audit?.userAgent,
});
try {
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.ts
index 163a75b2d29..e7b0b6cb6b8 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.ts
@@ -28,7 +28,7 @@ export class ServerSubAgentTransport implements SubAgentTransport {
async execSubAgent(params: ExecSubAgentParams): Promise<ExecSubAgentResult> {
// Agent share (defensive layer): a share-visitor run's `ctx.agentShareVisitor` is
- // set from `state.metadata.agentShareVisitor` (see AgentRuntimeService).
+ // set from `state.principal.actor.shareVisitor` (see AgentRuntimeService).
// `callSubAgent`/`callAgent` children built via `execAgentThreadRun` don't
// thread the parent's `shareGate` through β€” they'd otherwise execute with
// the CREATOR's full, unrestricted tool/file/memory surface. The
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index f6b1419c4fb..f22b4fa69fb 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -89,7 +89,7 @@ export class ServerToolTransport implements ToolTransport {
stepIndex,
userId,
},
- context.state.metadata?._hooks,
+ context.state.host?.hooks,
)
.catch(() => {});
}
@@ -120,11 +120,11 @@ export class ServerToolTransport implements ToolTransport {
let toolCallMocked = false;
if (isDeviceToolIdentifier(chatToolPayload.identifier) && !hookResult?.isMocked) {
- const policy = context.state.metadata?.deviceAccessPolicy as
+ const policy = context.state.principal?.policy?.deviceAccess as
{ canUseDevice: boolean; reason: DeviceAccessReason } | undefined;
logDeviceToolAudit({
apiName: chatToolPayload.apiName,
- botContext: context.state.metadata?.botContext,
+ botContext: context.state.principal?.actor?.bot,
canUseDevice: policy?.canUseDevice ?? true,
messageId: context.state.origin?.sourceMessageId,
operationId,
@@ -198,7 +198,7 @@ export class ServerToolTransport implements ToolTransport {
toolExecutionService.executeTool(chatToolPayload, {
activatedSkills: context.activatedSkills as any,
activeDeviceId: resolveRunActiveDeviceId(context.state),
- activeDeviceScope: context.state.metadata?.activeDeviceScope,
+ activeDeviceScope: context.state.principal?.actor?.deviceScope,
agentId: context.state.origin?.agentId,
agentMember: buildServerAgentMemberRunner(
this.ctx,
@@ -212,10 +212,10 @@ export class ServerToolTransport implements ToolTransport {
...(agentVisibility !== undefined && { agentVisibility }),
// Assistant message owning this tool call (β‰  source user message).
assistantMessageId: context.parentMessageId,
- clientIp: context.state.metadata?.clientIp,
+ clientIp: context.state.principal?.audit?.clientIp,
currentTodos: context.currentTodos,
- deviceCapable: context.state.metadata?.executionPlan
- ? isDeviceCapablePlan(context.state.metadata.executionPlan)
+ deviceCapable: context.state.plan?.execution
+ ? isDeviceCapablePlan(context.state.plan?.execution)
: undefined,
documentId: context.state.origin?.documentId,
editingAgentId: context.state.metadata?.editingAgentId,
@@ -228,10 +228,10 @@ export class ServerToolTransport implements ToolTransport {
// resolved target rather than the stored flag: a config that says
// `localSandbox` but landed on `sandbox`/`device` was never fenced,
// and telling the device otherwise would fence the wrong run.
- localSandbox: context.state.metadata?.executionPlan
+ localSandbox: context.state.plan?.execution
? isLocalSandboxEnabled(
context.state.world?.agent?.agencyConfig,
- context.state.metadata.executionPlan.target,
+ context.state.plan?.execution.target,
)
: undefined,
localSandboxNetwork:
@@ -239,7 +239,7 @@ export class ServerToolTransport implements ToolTransport {
memoryToolPermission: context.state.world?.agent?.chatConfig?.memory?.toolPermission,
messageId: context.state.origin?.sourceMessageId,
operationId,
- projectSkills: resolveRunProjectSkills(context.state.metadata),
+ projectSkills: resolveRunProjectSkills(context.state.plan),
rootOperationId: operationId,
scope: context.state.origin?.scope,
serverDB,
@@ -358,7 +358,7 @@ export class ServerToolTransport implements ToolTransport {
stepIndex,
userId,
},
- context.state.metadata?._hooks,
+ context.state.host?.hooks,
)
.catch(() => {});
@@ -405,7 +405,7 @@ export class ServerToolTransport implements ToolTransport {
success: result.success,
userId,
},
- context.state.metadata?._hooks,
+ context.state.host?.hooks,
)
.catch(() => {});
}
diff --git a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts
index 8ab1dc18dab..94320433d07 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
import { resolveServerCallLlmTooling } from '../serverCallLlmTooling';
-const buildState = (state: Pick<AgentState, 'binding' | 'metadata'> = {}): AgentState =>
+const buildState = (state: Pick<AgentState, 'binding' | 'plan' | 'principal'> = {}): AgentState =>
state as AgentState;
describe('resolveServerCallLlmTooling', () => {
@@ -18,7 +18,7 @@ describe('resolveServerCallLlmTooling', () => {
{ operationId: 'op-1', stepIndex: 0 },
buildState({
binding: { device: { id: 'device-1' } },
- metadata: { executionPlan: { deviceId: 'device-1', kind: 'device' } },
+ plan: { execution: { deviceId: 'device-1', kind: 'device', target: 'device' } },
}),
);
@@ -28,7 +28,7 @@ describe('resolveServerCallLlmTooling', () => {
it('leaves the active device id undefined when no device is routed', () => {
const result = resolveServerCallLlmTooling(
{ operationId: 'op-1', stepIndex: 0 },
- buildState({ metadata: { executionPlan: { kind: 'sandbox' } } }),
+ buildState({ plan: { execution: { kind: 'sandbox', target: 'sandbox' } } }),
);
expect(result.activeDeviceId).toBeUndefined();
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts
index 82b829437f5..5b2fa7e1181 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts
@@ -32,7 +32,7 @@ export interface ServerCallLlmTooling {
activeDeviceId?: string;
/**
* The run's resolved execution target (`local`/`device`/`sandbox`/`auto`/
- * `none`), straight from `state.metadata.executionPlan.target`. Exposed
+ * `none`), straight from `state.plan.execution.target`. Exposed
* alongside `activeDeviceId` because `'auto'` is the one target where a
* device can be routed (`activeDeviceId` set) while the cloud sandbox is
* *also* reachable β€” see `AgentToolsEngine`'s `agentModeRules` gate for
@@ -58,7 +58,7 @@ export const resolveServerCallLlmTooling = (
// `resolveRunActiveDeviceId` swallows the id whenever the plan/policy
// forbids devices β€” the same filter the tool executors apply.
const activeDeviceId = resolveRunActiveDeviceId(state);
- const executionTarget = (state.metadata?.executionPlan as ExecutionPlan | undefined)?.target;
+ const executionTarget = (state.plan?.execution as ExecutionPlan | undefined)?.target;
const operationToolSet: OperationToolSet = state.operationToolSet ?? {
enabledToolIds: [],
executorMap: state.toolExecutorMap ?? {},
@@ -97,12 +97,8 @@ export const resolveServerCallLlmTooling = (
// Resolve skills via SkillResolver (unified skill injection).
const skillResolver = new SkillResolver();
const stepSkillDelta = buildStepSkillDelta();
- const resolvedSkills = state.metadata?.operationSkillSet
- ? skillResolver.resolve(
- state.metadata.operationSkillSet,
- stepSkillDelta,
- state.activatedStepSkills ?? [],
- )
+ const resolvedSkills = state.plan?.skills
+ ? skillResolver.resolve(state.plan?.skills, stepSkillDelta, state.activatedStepSkills ?? [])
: undefined;
return {
diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.ts
index 30aa2ac3812..bea69f4c4e4 100644
--- a/apps/server/src/modules/AgentRuntime/context.ts
+++ b/apps/server/src/modules/AgentRuntime/context.ts
@@ -26,7 +26,7 @@ export interface RuntimeExecutorContext {
abortSignal?: AbortSignal;
/**
* Shared-agent visitor marker, read back from
- * `state.metadata.agentShareVisitor`. Present ONLY for a share-visitor run;
+ * `state.principal.actor.shareVisitor`. Present ONLY for a share-visitor run;
* its presence alone is the signal every per-step consumer keys off. Forwarded
* into `ToolExecutionContext.agentShareVisitor` so
* `BuiltinToolsExecutor.execute` can re-check the visitor's grants right
diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
index a1a88fe2f2b..722bc7ad3d1 100644
--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts
+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
@@ -228,9 +228,8 @@ export const buildServerVirtualSubAgentRunner = (
// The model the parent run ACTUALLY uses. `world.agent` alone is not
// enough: when a run continues a topic whose model was switched, execAgent
// keeps the topic-pinned model only in `modelRuntimeConfig` while the
- // metadata config retains the agent default.
- const parentEffectiveModel =
- state.modelRuntimeConfig ?? state.metadata?.modelRuntimeConfig ?? parentAgentConfig;
+ // world config retains the agent default.
+ const parentEffectiveModel = state.modelRuntimeConfig ?? parentAgentConfig;
return {
run: async ({ agentId: targetAgentId, description, instruction, timeout }) => {
diff --git a/apps/server/src/modules/AgentRuntime/executors/__tests__/resolveRunActiveDeviceId.test.ts b/apps/server/src/modules/AgentRuntime/executors/__tests__/resolveRunActiveDeviceId.test.ts
index fc09c7927d1..a2aaf922e75 100644
--- a/apps/server/src/modules/AgentRuntime/executors/__tests__/resolveRunActiveDeviceId.test.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/__tests__/resolveRunActiveDeviceId.test.ts
@@ -7,7 +7,7 @@ describe('resolveRunActiveDeviceId', () => {
expect(
resolveRunActiveDeviceId({
binding: { device: { id: 'device-1' } },
- metadata: { executionPlan: { deviceId: 'device-1', kind: 'device' } },
+ plan: { execution: { deviceId: 'device-1', kind: 'device', target: 'device' } },
}),
).toBe('device-1');
});
@@ -19,17 +19,17 @@ describe('resolveRunActiveDeviceId', () => {
expect(
resolveRunActiveDeviceId({
binding: { device: { id: 'device-1' } },
- metadata: { executionPlan: { kind: 'device-unrouted', reason: 'no-bound-device' } },
+ plan: { execution: { kind: 'device-unrouted', reason: 'no-bound-device', target: 'auto' } },
}),
).toBe('device-1');
});
it('swallows a preset/stale id when the plan is not device-capable', () => {
- for (const kind of ['sandbox', 'none']) {
+ for (const kind of ['sandbox', 'none'] as const) {
expect(
resolveRunActiveDeviceId({
binding: { device: { id: 'device-1' } },
- metadata: { executionPlan: { kind } },
+ plan: { execution: { kind, target: kind } },
}),
).toBeUndefined();
}
@@ -39,9 +39,13 @@ describe('resolveRunActiveDeviceId', () => {
expect(
resolveRunActiveDeviceId({
binding: { device: { id: 'device-1' } },
- metadata: {
- deviceAccessPolicy: { canUseDevice: false, reason: 'external-bot' },
- executionPlan: { deviceId: 'device-1', kind: 'device' },
+ principal: {
+ policy: {
+ deviceAccess: { canUseDevice: false, reason: 'external-bot' },
+ },
+ },
+ plan: {
+ execution: { deviceId: 'device-1', kind: 'device', target: 'device' },
},
}),
).toBeUndefined();
diff --git a/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts b/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts
index d443efbb2c1..eb8a6c55e92 100644
--- a/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts
@@ -1,7 +1,6 @@
import type { AgentState } from '@lobechat/agent-runtime';
-import { type ExecutionPlan, isDeviceCapablePlan } from '@/helpers/executionTarget';
-import { type DeviceAccessReason } from '@/server/services/aiAgent/deviceToolAudit';
+import { isDeviceCapablePlan } from '@/helpers/executionTarget';
/**
* Single-track device gate shared by the run executors: the execution plan
@@ -22,11 +21,10 @@ import { type DeviceAccessReason } from '@/server/services/aiAgent/deviceToolAud
* `kind === 'device'` would swallow exactly that flow.
*/
export const resolveRunActiveDeviceId = (
- state: Pick<AgentState, 'binding' | 'metadata'>,
+ state: Pick<AgentState, 'binding' | 'plan' | 'principal'>,
): string | undefined => {
- const devicePolicy = state.metadata?.deviceAccessPolicy as
- { canUseDevice: boolean; reason: DeviceAccessReason } | undefined;
- const executionPlan = state.metadata?.executionPlan as ExecutionPlan | undefined;
+ const devicePolicy = state.principal?.policy?.deviceAccess;
+ const executionPlan = state.plan?.execution;
const planAllowsDevice = !executionPlan || isDeviceCapablePlan(executionPlan);
if (devicePolicy?.canUseDevice === false || !planAllowsDevice) return undefined;
diff --git a/apps/server/src/modules/AgentRuntime/executors/resolveRunProjectSkills.ts b/apps/server/src/modules/AgentRuntime/executors/resolveRunProjectSkills.ts
index 2ae0b46c1f6..d968c44c455 100644
--- a/apps/server/src/modules/AgentRuntime/executors/resolveRunProjectSkills.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/resolveRunProjectSkills.ts
@@ -5,10 +5,10 @@
* the same SKILL.md cwd as single calls β€” an unshared copy is exactly how the
* batch path silently dropped these fields once already.
*/
-export const resolveRunProjectSkills = (metadata?: {
- operationSkillSet?: { skills?: { location?: string; name: string; source?: string }[] };
+export const resolveRunProjectSkills = (plan?: {
+ skills?: { skills?: { location?: string; name: string; source?: string }[] };
}): { location: string; name: string; source: 'device' | 'project' }[] =>
- (metadata?.operationSkillSet?.skills ?? [])
+ (plan?.skills?.skills ?? [])
.filter(
(skill) => (skill.source === 'project' || skill.source === 'device') && !!skill.location,
)
diff --git a/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts b/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts
index d48150c3e81..d5cafbebd98 100644
--- a/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts
+++ b/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts
@@ -12,7 +12,7 @@ import { stripFinalStateInEventData } from './StreamEventManager';
/**
* Per-operation redaction policy for a shared-agent visitor run, derived from
* the share's `AgentShareConfig` (`showModelInfo` / `showErrorDetails`) and
- * carried on `state.metadata.agentShareVisitor`.
+ * carried on `state.principal.actor.shareVisitor`.
*
* `null` is the explicit "not a share run β€” push verbatim" marker, so a
* missing/undefined value can stay reserved for "not resolved yet".
@@ -56,7 +56,7 @@ export const isShareVisitorInit = (initialState: any): boolean =>
* its policy is unreadable.
*/
export const resolveRedactionFromState = (state: any): GatewayVisitorRedaction => {
- const share = state?.metadata?.agentShareVisitor as
+ const share = state?.principal?.actor?.shareVisitor as
{ showErrorDetails?: boolean; showModelInfo?: boolean; visitorUserId?: string } | undefined;
if (share?.visitorUserId) {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index 090f6940334..1f44ae67a96 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -450,9 +450,7 @@ describe('AgentRuntimeService', () => {
status: 'idle',
stepCount: 0,
messages: [],
- metadata: {
- modelRuntimeConfig: mockParams.modelRuntimeConfig,
- },
+ modelRuntimeConfig: mockParams.modelRuntimeConfig,
origin: expect.objectContaining({ userId: mockParams.userId }),
toolManifestMap: {},
world: expect.objectContaining({ agent: mockParams.agentConfig }),
@@ -755,8 +753,8 @@ describe('AgentRuntimeService', () => {
});
await (serviceWithFactory as any).createAgentRuntime({
- world: { agent: { chatConfig: { enableContextCompression: true } } as any },
- metadata: {
+ agentState: {
+ world: { agent: { chatConfig: { enableContextCompression: true } } as any },
modelRuntimeConfig: { model: 'gpt-4o-mini', provider: 'openai' },
},
operationId: 'test-operation-1',
@@ -790,8 +788,8 @@ describe('AgentRuntimeService', () => {
});
await (serviceWithFactory as any).createAgentRuntime({
- world: { agent: { chatConfig: { enableContextCompression: true } } as any },
- metadata: {
+ agentState: {
+ world: { agent: { chatConfig: { enableContextCompression: true } } as any },
modelRuntimeConfig: { model: 'unknown-model', provider: 'openai' },
},
operationId: 'test-operation-1',
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index e894e71478e..53c3483396b 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -746,11 +746,11 @@ export class AgentRuntimeService {
operationId,
priority: 'high',
retryDelay:
- typeof state.metadata?.queueRetryDelay === 'string'
- ? state.metadata.queueRetryDelay
+ typeof state.host?.queue?.retryDelay === 'string'
+ ? state.host?.queue?.retryDelay
: undefined,
retries:
- typeof state.metadata?.queueRetries === 'number' ? state.metadata.queueRetries : undefined,
+ typeof state.host?.queue?.retries === 'number' ? state.host?.queue?.retries : undefined,
stepIndex,
});
await this.persistInterventionDispatchAck({
@@ -1005,23 +1005,11 @@ export class AgentRuntimeService {
},
},
}),
- metadata: {
- activeDeviceScope,
- agentShareVisitor,
- botContext,
- clientIp: appContext?.clientIp,
- deviceAccessPolicy,
- evalRuntime,
- executionPlan,
- // need be removed
- modelRuntimeConfig,
- queueRetries,
- queueRetryDelay,
- stream,
- operationSkillSet,
- userAgent: appContext?.userAgent,
- workingDirectory: agentConfig?.chatConfig?.runtimeEnv?.workingDirectory,
- },
+ // What the host needs to deliver and retry the run. Hooks are stamped
+ // right after creation once the dispatcher has serialized them.
+ host: { queue: { retries: queueRetries, retryDelay: queueRetryDelay } },
+ // Run ledger β€” everything fixed at creation lives in the typed slots.
+ metadata: {},
// Where the run came from β€” frozen from here on. Mirrors the
// agent_operations row so the runtime can hang its output on the right
// conversation node without a lookup.
@@ -1059,6 +1047,25 @@ export class AgentRuntimeService {
toolExecutorMap: operationToolSet.executorMap,
toolManifestMap: operationToolSet.manifestMap,
toolSourceMap: operationToolSet.sourceMap,
+ // How the run executes β€” frozen from here on.
+ plan: {
+ eval: evalRuntime,
+ execution: executionPlan,
+ skills: operationSkillSet,
+ stream,
+ workingDirectory: agentConfig?.chatConfig?.runtimeEnv?.workingDirectory,
+ },
+ // Under whose authority the run acts and what it may do β€” decided here,
+ // re-presented (never re-derived) at each dispatch boundary.
+ principal: {
+ actor: {
+ bot: botContext,
+ deviceScope: activeDeviceScope,
+ shareVisitor: agentShareVisitor,
+ },
+ audit: { clientIp: appContext?.clientIp, userAgent: appContext?.userAgent },
+ policy: { deviceAccess: deviceAccessPolicy },
+ },
// What the model is told about the run's world β€” frozen from here on;
// the context engine reads it on every step.
world: {
@@ -1122,10 +1129,7 @@ export class AgentRuntimeService {
if (currentState) {
await this.coordinator.saveAgentState(operationId, {
...currentState,
- metadata: {
- ...currentState.metadata,
- _hooks: serializedHooks,
- },
+ host: { ...currentState.host, hooks: serializedHooks },
});
}
}
@@ -1486,12 +1490,12 @@ export class AgentRuntimeService {
},
priority: 'high',
retryDelay:
- typeof currentState?.metadata?.queueRetryDelay === 'string'
- ? currentState.metadata.queueRetryDelay
+ typeof currentState?.host?.queue?.retryDelay === 'string'
+ ? currentState.host?.queue?.retryDelay
: undefined,
retries:
- typeof currentState?.metadata?.queueRetries === 'number'
- ? currentState.metadata.queueRetries
+ typeof currentState?.host?.queue?.retries === 'number'
+ ? currentState.host?.queue?.retries
: undefined,
stepIndex,
});
@@ -1640,11 +1644,8 @@ export class AgentRuntimeService {
// Enrich invoke_agent span with agent identity now that state is loaded.
const stateAgentConfig = agentState.world?.agent as
{ description?: string | null; title?: string | null } | undefined;
- const stateModel =
- agentState.modelRuntimeConfig?.model ?? agentState.metadata?.modelRuntimeConfig?.model;
- const stateProvider =
- agentState.modelRuntimeConfig?.provider ??
- agentState.metadata?.modelRuntimeConfig?.provider;
+ const stateModel = agentState.modelRuntimeConfig?.model;
+ const stateProvider = agentState.modelRuntimeConfig?.provider;
invokeAgentSpan.updateName(invokeAgentSpanName(stateAgentConfig?.title ?? undefined));
invokeAgentSpan.setAttributes(
buildInvokeAgentAttributes({
@@ -1715,7 +1716,7 @@ export class AgentRuntimeService {
// why one query covers every revocation path (visibility flip β€” which
// is what turning sharing off does β€” share delete, agent delete).
if (this.delegate.verifyShareRunStillAuthorized) {
- const shareMarker = agentState.metadata?.agentShareVisitor as
+ const shareMarker = agentState.principal?.actor?.shareVisitor as
{ agentId?: string; shareId?: string } | undefined;
if (shareMarker?.agentId && shareMarker.shareId) {
let stillAuthorized = false;
@@ -1745,14 +1746,13 @@ export class AgentRuntimeService {
// Dispatch beforeStep hooks
try {
- const beforeStepMetadata = agentState?.metadata || {};
const beforeStepOrigin = agentState?.origin ?? {};
// Agent Share visitor runs execute AS the creator, so this
// `userId`-scoped source event would record creator-owned Agent
// Signal state for a turn an anonymous link visitor triggered β€” same
// reasoning (and same predicate) as the completion-signal guard in
// `CompletionLifecycle.emitSignalEvents`.
- const beforeStepSignalEmission = isAgentShareRun(beforeStepMetadata)
+ const beforeStepSignalEmission = isAgentShareRun(agentState)
? undefined
: await emitAgentSignalSourceEvent(
{
@@ -1787,7 +1787,7 @@ export class AgentRuntimeService {
steps: agentState?.stepCount || 0,
userId: beforeStepOrigin.userId || this.userId,
},
- beforeStepMetadata._hooks,
+ agentState?.host?.hooks,
);
} catch (hookError) {
log('[%s] beforeStep hook dispatch error: %O', operationId, hookError);
@@ -1859,7 +1859,6 @@ export class AgentRuntimeService {
const { runtime } = await this.createAgentRuntime({
abortSignal: stepAbortController.signal,
agentState,
- metadata: agentState?.metadata,
operationId,
stepIndex,
tracingContextEngine: (input, output) => {
@@ -2131,7 +2130,7 @@ export class AgentRuntimeService {
// See the `runtime.before_step` guard above β€” same share-visitor
// suppression at the sibling per-step emission.
afterStepSignalEvents = toAgentSignalSnapshotEvents(
- isAgentShareRun(metadata)
+ isAgentShareRun(stepResult.newState)
? undefined
: await emitAgentSignalSourceEvent(
{
@@ -2188,7 +2187,7 @@ export class AgentRuntimeService {
totalToolCalls: (tracking.totalToolCalls ?? 0) + (toolsCalling?.length ?? 0),
userId: origin.userId || this.userId,
},
- metadata._hooks,
+ stepResult.newState?.host?.hooks,
);
} catch (hookError) {
log('[%s] afterStep hook dispatch error: %O', operationId, hookError);
@@ -2208,7 +2207,7 @@ export class AgentRuntimeService {
});
// Update step tracking in state metadata for afterStep hooks (cross-step accumulator)
- const hasAfterStepHooks = stepResult.newState.metadata?._hooks?.some(
+ const hasAfterStepHooks = stepResult.newState.host?.hooks?.some(
(h: { type: string }) => h.type === 'afterStep',
);
logToolCallPc(operationId, stepIndex, 'post.trace_appended', () => ({}));
@@ -2250,12 +2249,12 @@ export class AgentRuntimeService {
operationId,
priority: this.calculatePriority(stepResult),
retries:
- typeof stepResult.newState.metadata?.queueRetries === 'number'
- ? stepResult.newState.metadata.queueRetries
+ typeof stepResult.newState.host?.queue?.retries === 'number'
+ ? stepResult.newState.host?.queue?.retries
: undefined,
retryDelay:
- typeof stepResult.newState.metadata?.queueRetryDelay === 'string'
- ? stepResult.newState.metadata.queueRetryDelay
+ typeof stepResult.newState.host?.queue?.retryDelay === 'string'
+ ? stepResult.newState.host?.queue?.retryDelay
: undefined,
stepIndex: nextStepIndex,
};
@@ -3809,7 +3808,6 @@ export class AgentRuntimeService {
private async createAgentRuntime({
abortSignal,
agentState,
- metadata,
operationId,
stepIndex,
tracingContextEngine,
@@ -3823,22 +3821,25 @@ export class AgentRuntimeService {
* Works, so loading should cover that window).
*/
agentState?: any;
- metadata?: any;
operationId: string;
stepIndex: number;
tracingContextEngine?: (input: unknown, output: unknown) => void;
}) {
+ const state = agentState as AgentState | undefined;
+ const modelRuntimeConfig = state?.modelRuntimeConfig;
const contextWindowTokens =
- metadata?.modelRuntimeConfig?.model && metadata?.modelRuntimeConfig?.provider
+ modelRuntimeConfig?.model && modelRuntimeConfig?.provider
? await getModelPropertyWithFallback<number | undefined>(
- metadata.modelRuntimeConfig.model,
+ modelRuntimeConfig.model,
'contextWindowTokens',
- metadata.modelRuntimeConfig.provider,
+ modelRuntimeConfig.provider,
)
: undefined;
- const world = (agentState as AgentState | undefined)?.world;
- const origin = (agentState as AgentState | undefined)?.origin;
+ const world = state?.world;
+ const origin = state?.origin;
+ const plan = state?.plan;
+ const principal = state?.principal;
// Create Agent instance β€” use custom factory if provided, otherwise default to GeneralChatAgent
const generalConfig = {
@@ -3848,21 +3849,18 @@ export class AgentRuntimeService {
maxWindowToken: contextWindowTokens ?? undefined,
},
dynamicInterventionAudits,
- modelRuntimeConfig: metadata?.modelRuntimeConfig,
+ modelRuntimeConfig,
operationId,
userId: origin?.userId,
};
if (
origin?.trigger === RequestTrigger.Eval &&
- metadata.evalRuntime?.toolForwarding &&
+ plan?.eval?.toolForwarding &&
!hookDispatcher.hasHook(operationId, EVAL_TOOL_FORWARDING_HOOK_ID)
) {
hookDispatcher.register(operationId, [
- createEvalToolForwardingHook(
- metadata.evalRuntime.toolForwarding,
- metadata.evalRuntime.caseId,
- ),
+ createEvalToolForwardingHook(plan.eval.toolForwarding, plan.eval.caseId),
]);
}
@@ -3883,21 +3881,21 @@ export class AgentRuntimeService {
// an early hint would end the visible loading seconds before that card
// can exist. Deferring to the terminal `visible_output_end` lets loading
// cover the export and the card land with `agent_runtime_end`.
- agentShareVisitor: metadata?.agentShareVisitor,
+ agentShareVisitor: principal?.actor?.shareVisitor,
allowEarlyFinalAnswerVisibleOutputEnd:
agent instanceof GeneralChatAgent && !stateHasEntityFileEdits(agentState),
- botContext: metadata?.botContext,
+ botContext: principal?.actor?.bot,
execSubAgent: this.delegate.execSubAgent,
execVirtualSubAgent: this.delegate.execVirtualSubAgent,
execGroupMember: this.delegate.execGroupMember,
hookDispatcher,
loadAgentState: this.coordinator.loadAgentState.bind(this.coordinator),
messageModel: this.messageModel,
- modelRuntimeConfig: metadata?.modelRuntimeConfig,
+ modelRuntimeConfig,
operationId,
serverDB: this.serverDB,
stepIndex,
- stream: metadata?.stream,
+ stream: plan?.stream,
streamManager: this.streamManager,
toolExecutionService: this.toolExecutionService,
topicId: origin?.topicId,
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index 75a59f4f0c6..8d5de20eeac 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -76,7 +76,7 @@ type SignalEvent = { [key: string]: unknown; type: string };
/**
* Whether a lifecycle event's `metadata` belongs to an Agent Share visitor
- * run. `metadata.agentShareVisitor.visitorUserId` is stamped once at operation
+ * run. `principal.actor.shareVisitor.visitorUserId` is stamped once at operation
* creation (`AgentRuntimeService.createOperation`'s `initialState.metadata`)
* and rides the state through to the terminal event β€” mirrors
* `GatewayStreamNotifier`'s share-visitor check, the sibling chokepoint that
@@ -88,8 +88,10 @@ type SignalEvent = { [key: string]: unknown; type: string };
* `AgentRuntimeService`) can reuse the exact same check instead of
* hand-rolling their own.
*/
-export const isAgentShareRun = (metadata: Record<string, unknown> | undefined | null): boolean =>
- Boolean((metadata?.agentShareVisitor as { visitorUserId?: string } | undefined)?.visitorUserId);
+export const isAgentShareRun = (
+ state:
+ { principal?: { actor?: { shareVisitor?: { visitorUserId?: string } } } } | undefined | null,
+): boolean => Boolean(state?.principal?.actor?.shareVisitor?.visitorUserId);
/**
* Normalized terminal-completion input for {@link CompletionLifecycle.completeOperation}.
@@ -503,7 +505,7 @@ export class CompletionLifecycle {
// telemetry for a run an anonymous link visitor triggered. Suppress the
// whole emission rather than merely re-scoping it: a share visitor has no
// Agent Signal identity of its own to attribute this to.
- if (isAgentShareRun(metadata)) {
+ if (isAgentShareRun(state)) {
log(
'[completion-lifecycle] skip agent signal emission for share visitor run op=%s reason=%s',
operationId,
@@ -667,7 +669,7 @@ export class CompletionLifecycle {
* shape `dispatchHooks` consumes. The SINGLE place that mirrors the runtime
* state for non-in-process paths β€” goal/deliverable become the user/assistant
* turns the gate reads, model/provider backfill the op row, hooks ride on
- * `metadata._hooks`. Replaces the per-caller hand-rolled synthetic state that
+ * `host.hooks`. Replaces the per-caller hand-rolled synthetic state that
* previously drifted (e.g. a verify field added here was missed by heteroFinish).
*/
private buildStateFromInput(input: OperationCompletionInput) {
@@ -678,10 +680,8 @@ export class CompletionLifecycle {
{ content: input.goal ?? '', role: 'user' },
{ content: input.deliverable ?? '', role: 'assistant' },
],
- metadata: {
- _hooks: input.serializedHooks,
- assistantMessageId: input.assistantMessageId,
- },
+ host: { hooks: input.serializedHooks },
+ metadata: { assistantMessageId: input.assistantMessageId },
origin: {
agentId: input.agentId,
lineage: { orchestrationRole: input.orchestrationRole },
@@ -884,7 +884,7 @@ export class CompletionLifecycle {
// so hook consumers can surface the approval request. A winning decision
// schedules a fresh continuation operation and then retires this parked
// segment; the continuation receives the serialized hooks through
- // `metadata._hooks`.
+ // `host.hooks`.
const isAsyncToolPark = reason === 'waiting_for_async_tool';
let shouldRetainHooksForRetry = false;
@@ -934,7 +934,7 @@ export class CompletionLifecycle {
if (recovered) event.lastAssistantContent = recovered;
}
- await hookDispatcher.dispatch(operationId, 'onComplete', event, metadata._hooks);
+ await hookDispatcher.dispatch(operationId, 'onComplete', event, state?.host?.hooks);
// Recall the user when a run finishes with a deliverable while they may be
// away (push / inbox). Fires on every success-like terminal β€” `done` plus
@@ -958,7 +958,7 @@ export class CompletionLifecycle {
isSuccessLikeCompletionReason(reason) &&
runOrigin.lineage?.isSubAgent !== true &&
runOrigin.lineage?.orchestrationRole !== 'member' &&
- !isAgentShareRun(metadata)
+ !isAgentShareRun(state)
) {
void this.recallUserOnCompletion(operationId, event, runOrigin).catch((error) =>
log('[%s] Completion notification failed (non-fatal): %O', operationId, error),
@@ -1029,7 +1029,7 @@ export class CompletionLifecycle {
}
if (reason === 'error') {
- await hookDispatcher.dispatch(operationId, 'onError', event, metadata._hooks);
+ await hookDispatcher.dispatch(operationId, 'onError', event, state?.host?.hooks);
const assistantMessageId = metadata?.assistantMessageId;
if (assistantMessageId && state?.error && !options?.skipErrorMessageWrite) {
@@ -1065,7 +1065,7 @@ export class CompletionLifecycle {
) {
// A queue retry may run in this same process (local callback / warm
// worker). Keep the in-memory registration until that lifecycle really
- // settles; queue mode can additionally reconstruct from metadata._hooks.
+ // settles; queue mode can additionally reconstruct from host.hooks.
shouldRetainHooksForRetry = true;
throw error;
}
diff --git a/apps/server/src/services/agentRuntime/HumanInterventionHandler.ts b/apps/server/src/services/agentRuntime/HumanInterventionHandler.ts
index c9e59bd2ace..859d9c7be00 100644
--- a/apps/server/src/services/agentRuntime/HumanInterventionHandler.ts
+++ b/apps/server/src/services/agentRuntime/HumanInterventionHandler.ts
@@ -98,7 +98,7 @@ export class HumanInterventionHandler {
toolCallId: approvedToolCall.id,
userId: state.origin?.userId,
},
- state.metadata?._hooks,
+ state.host?.hooks,
)
.catch(() => {});
@@ -182,7 +182,7 @@ export class HumanInterventionHandler {
toolCallId: rejectedToolCallId,
userId: state.origin?.userId,
},
- state.metadata?._hooks,
+ state.host?.hooks,
)
.catch(() => {});
@@ -215,7 +215,7 @@ export class HumanInterventionHandler {
toolCallId: rejectedToolCallId,
userId: state.origin?.userId,
},
- state.metadata?._hooks,
+ state.host?.hooks,
)
.catch(() => {});
diff --git a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts b/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts
index aa27f144782..d75c3a7ab7b 100644
--- a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts
+++ b/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts
@@ -174,8 +174,7 @@ export class OperationTraceRecorder {
model: partial.model,
operationId,
provider: partial.provider,
- retryDelayExpression:
- typeof metadata?.queueRetryDelay === 'string' ? metadata.queueRetryDelay : undefined,
+ retryDelayExpression: params.state?.host?.queue?.retryDelay,
startedAt: partial.startedAt ?? Date.now(),
steps: finalizedSteps,
topicId: origin.topicId,
diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
index 63149d923dd..0111f67e0d5 100644
--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
@@ -565,7 +565,8 @@ describe('CompletionLifecycle.dispatchHooks β€” error persistence', () => {
errorType: ChatErrorType.FreePlanLimit,
provider: 'lobehub',
},
- metadata: { _hooks: [], assistantMessageId: 'msg-1' },
+ metadata: { assistantMessageId: 'msg-1' },
+ host: { hooks: [] },
status: 'error',
},
'error',
@@ -599,7 +600,7 @@ describe('CompletionLifecycle.dispatchHooks β€” error persistence', () => {
await expect(
lifecycle.dispatchHooks(
'op-1',
- { metadata: { _hooks: [] }, status: 'interrupted' },
+ { host: { hooks: [] }, status: 'interrupted' },
'interrupted',
),
).rejects.toThrow('Critical webhook delivery failed: task-on-complete');
@@ -613,11 +614,7 @@ describe('CompletionLifecycle.dispatchHooks β€” error persistence', () => {
const dispatch = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
- await lifecycle.dispatchHooks(
- 'op-reclaimed',
- { metadata: { _hooks: [] }, status: 'done' },
- 'done',
- );
+ await lifecycle.dispatchHooks('op-reclaimed', { host: { hooks: [] }, status: 'done' }, 'done');
expect(dispatch).not.toHaveBeenCalled();
});
@@ -652,7 +649,7 @@ describe('CompletionLifecycle.dispatchHooks β€” verify plan race', () => {
expect(instantiateSpy).toHaveBeenCalledTimes(1);
// Completion fires while the plan instantiation is still in flight.
- const doneState = { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'done' };
+ const doneState = { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'done' };
const dispatch = lifecycle.dispatchHooks('op-1', doneState, 'done');
// The gate must stay blocked on the pending instantiation, not race past it.
@@ -687,7 +684,7 @@ describe('CompletionLifecycle.dispatchHooks β€” async-tool park', () => {
});
const parkedState = {
- metadata: { _hooks: [] },
+ host: { hooks: [] },
origin: { agentId: 'a' },
status: 'waiting_for_async_tool',
};
@@ -711,7 +708,7 @@ describe('CompletionLifecycle.dispatchHooks β€” async-tool park', () => {
const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
- const doneState = { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'done' };
+ const doneState = { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'done' };
await lifecycle.dispatchHooks('op-1', doneState, 'done');
expect(dispatchSpy).toHaveBeenCalledWith('op-1', 'onComplete', expect.anything(), []);
@@ -738,7 +735,7 @@ describe('CompletionLifecycle.dispatchHooks β€” completion notification', () =>
const buildDoneState = (origin: Record<string, unknown> = {}) => ({
createdAt: new Date(Date.now() - 90_000).toISOString(),
messages: [{ content: 'final reply', role: 'assistant' }],
- metadata: { _hooks: [] },
+ host: { hooks: [] },
origin: { agentId: 'agt_1', topicId: 'tpc_1', ...origin },
status: 'done',
});
@@ -893,7 +890,7 @@ describe('CompletionLifecycle.dispatchHooks β€” completion notification', () =>
await lifecycle.dispatchHooks(
'op-1',
- { metadata: { _hooks: [] }, origin: { agentId: 'agt_1' }, status: 'error' },
+ { host: { hooks: [] }, origin: { agentId: 'agt_1' }, status: 'error' },
'error',
);
@@ -908,7 +905,7 @@ describe('CompletionLifecycle.dispatchHooks β€” completion notification', () =>
// and leak into later dispatchHooks('done') tests in this file.
mockNotifyAgentRunCompleted.mockRejectedValueOnce(new Error('push provider down'));
- const doneState = { metadata: { _hooks: [] }, origin: { agentId: 'agt_1' }, status: 'done' };
+ const doneState = { host: { hooks: [] }, origin: { agentId: 'agt_1' }, status: 'done' };
await expect(lifecycle.dispatchHooks('op-1', doneState, 'done')).resolves.toBeUndefined();
await flushMicrotasks();
@@ -1026,7 +1023,7 @@ describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works
await lifecycle.dispatchHooks(
'op-1',
- { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
+ { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
'waiting_for_human',
);
@@ -1063,7 +1060,7 @@ describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works
await expect(
lifecycle.dispatchHooks(
'op-1',
- { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
+ { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
'waiting_for_human',
),
).rejects.toBeInstanceOf(CriticalAgentInterventionPersistenceError);
@@ -1083,7 +1080,7 @@ describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works
await expect(
lifecycle.dispatchHooks(
'op-1',
- { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
+ { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
'waiting_for_human',
),
).rejects.toMatchObject({
@@ -1112,7 +1109,7 @@ describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works
await expect(
lifecycle.dispatchHooks(
'op-1',
- { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
+ { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
'waiting_for_human',
),
).resolves.toBeUndefined();
@@ -1127,7 +1124,7 @@ describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works
await lifecycle.dispatchHooks(
'op-1',
- { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
+ { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },
'waiting_for_human',
);
@@ -1148,7 +1145,7 @@ describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
const parkedState = {
- metadata: { _hooks: [] },
+ host: { hooks: [] },
origin: { agentId: 'a' },
status: 'waiting_for_human',
};
@@ -1165,7 +1162,7 @@ describe('CompletionLifecycle.dispatchHooks β€” parks do not register file works
vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
const parkedState = {
- metadata: { _hooks: [] },
+ host: { hooks: [] },
origin: { agentId: 'a' },
status: 'waiting_for_async_tool',
};
@@ -1185,7 +1182,7 @@ describe('CompletionLifecycle.dispatchHooks β€” lastAssistantContent DB recovery
{ content: 'user prompt', id: 'msg-user', role: 'user' },
{ content: assistantContent, id: 'msg-assistant', role: 'assistant' },
],
- metadata: { _hooks: [] },
+ host: { hooks: [] },
origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },
status: 'done',
});
@@ -1240,7 +1237,7 @@ describe('CompletionLifecycle.dispatchHooks β€” lastAssistantContent DB recovery
role: 'assistantGroup',
},
],
- metadata: { _hooks: [] },
+ host: { hooks: [] },
origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },
status: 'done',
},
diff --git a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
index 8046e81bd64..952f7a3832e 100644
--- a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
@@ -326,8 +326,8 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {
createdAt: new Date().toISOString(),
lastModified: new Date().toISOString(),
messages: [{ content: 'hello', role: 'user' }],
- metadata: {
- _hooks: ['serialized-hook'],
+ host: {
+ hooks: ['serialized-hook'],
},
origin: {
agentId: 'agent-1',
@@ -346,8 +346,8 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {
events: [{ result: { content: 'done' }, type: 'llm_result' }],
newState: {
createdAt: new Date().toISOString(),
- metadata: {
- _hooks: ['serialized-hook'],
+ host: {
+ hooks: ['serialized-hook'],
},
origin: {
agentId: 'agent-1',
diff --git a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts
index a1a10c18028..4d6ebc906b4 100644
--- a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts
@@ -39,7 +39,7 @@ describe('CompletionLifecycle β€” verify gate scheduling', () => {
await lifecycle.dispatchHooks(
'op-1',
- { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'done' },
+ { host: { hooks: [] }, origin: { agentId: 'a' }, status: 'done' },
'done',
);
diff --git a/apps/server/src/services/agentRuntime/__tests__/completionWebhook.test.ts b/apps/server/src/services/agentRuntime/__tests__/completionWebhook.test.ts
index 7ab681c740d..9359fe7881e 100644
--- a/apps/server/src/services/agentRuntime/__tests__/completionWebhook.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/completionWebhook.test.ts
@@ -99,8 +99,8 @@ describe('AgentRuntimeService - Completion Hooks via createOperation', () => {
});
});
- describe('createOperation persists hooks in metadata', () => {
- it('should persist hooks in state metadata._hooks', async () => {
+ describe('createOperation persists hooks on the host envelope', () => {
+ it('should persist hooks on state.host.hooks', async () => {
const operationId = 'hook-op-1';
const hooks = [
{
@@ -128,7 +128,7 @@ describe('AgentRuntimeService - Completion Hooks via createOperation', () => {
});
const state = await stateManager.loadAgentState(operationId);
- expect(state?.metadata?._hooks).toEqual([
+ expect(state?.host?.hooks).toEqual([
expect.objectContaining({
id: 'test-completion',
type: 'onComplete',
@@ -140,7 +140,7 @@ describe('AgentRuntimeService - Completion Hooks via createOperation', () => {
]);
});
- it('should not have _hooks in metadata when no hooks provided', async () => {
+ it('should not have host.hooks when no hooks provided', async () => {
const operationId = 'hook-op-2';
await service.createOperation({
@@ -156,7 +156,7 @@ describe('AgentRuntimeService - Completion Hooks via createOperation', () => {
});
const state = await stateManager.loadAgentState(operationId);
- expect(state?.metadata?._hooks).toBeUndefined();
+ expect(state?.host?.hooks).toBeUndefined();
});
});
@@ -209,7 +209,7 @@ describe('AgentRuntimeService - Completion Hooks via createOperation', () => {
// Verify the hook config is persisted for later use
const updatedState = await stateManager.loadAgentState(operationId);
- expect(updatedState?.metadata?._hooks).toEqual([
+ expect(updatedState?.host?.hooks).toEqual([
expect.objectContaining({
id: 'test-completion',
type: 'onComplete',
@@ -237,7 +237,7 @@ describe('AgentRuntimeService - Completion Hooks via createOperation', () => {
});
const state = await stateManager.loadAgentState(operationId);
- expect(state?.metadata?._hooks).toBeUndefined();
+ expect(state?.host?.hooks).toBeUndefined();
});
it('should not throw when webhook fetch fails', async () => {
@@ -251,7 +251,7 @@ describe('AgentRuntimeService - Completion Hooks via createOperation', () => {
// Verify the hook is stored -- the hook dispatch catches errors internally
const state = await stateManager.loadAgentState(operationId);
- expect(state?.metadata?._hooks?.[0]?.webhook?.url).toBe(webhookUrl);
+ expect(state?.host?.hooks?.[0]?.webhook?.url).toBe(webhookUrl);
});
});
@@ -289,11 +289,11 @@ describe('AgentRuntimeService - Completion Hooks via createOperation', () => {
// Verify the persisted hook contains the right structure
const state = await stateManager.loadAgentState(operationId);
- const hooks = state?.metadata?._hooks;
+ const hooks = state?.host?.hooks;
expect(hooks).toBeDefined();
expect(hooks).toHaveLength(1);
- expect(hooks[0].webhook.url).toBe(webhookUrl);
- expect(hooks[0].webhook.body).toEqual(webhookBody);
+ expect(hooks?.[0]?.webhook.url).toBe(webhookUrl);
+ expect(hooks?.[0]?.webhook.body).toEqual(webhookBody);
});
});
});
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index 65a202b6d72..c06137ca821 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -322,12 +322,14 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
});
await (service as any).createAgentRuntime({
- metadata: {
- agentConfig: {},
+ agentState: {
+ metadata: {
+ agentConfig: {},
+ },
modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
- },
- origin: {
- userId: 'user-1',
+ origin: {
+ userId: 'user-1',
+ },
},
operationId: 'op-workspace',
stepIndex: 0,
@@ -348,8 +350,11 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
};
await (service as any).createAgentRuntime({
- metadata: { agentConfig: {}, modelRuntimeConfig },
- origin: { userId: 'user-1' },
+ agentState: {
+ metadata: { agentConfig: {} },
+ modelRuntimeConfig,
+ origin: { userId: 'user-1' },
+ },
operationId: 'op-model-runtime-snapshot',
stepIndex: 0,
});
@@ -367,12 +372,14 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
});
await (service as any).createAgentRuntime({
- metadata: {
- agentConfig: {},
+ agentState: {
+ metadata: {
+ agentConfig: {},
+ },
modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
- },
- origin: {
- userId: 'user-1',
+ origin: {
+ userId: 'user-1',
+ },
},
operationId: 'op-custom-agent',
stepIndex: 0,
@@ -398,12 +405,14 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
});
await (service as any).createAgentRuntime({
- metadata: {
- agentConfig: {},
+ agentState: {
+ metadata: {
+ agentConfig: {},
+ },
modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
- },
- origin: {
- userId: 'user-1',
+ origin: {
+ userId: 'user-1',
+ },
},
operationId: 'op-graph-agent',
stepIndex: 0,
@@ -422,12 +431,14 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
});
await (service as any).createAgentRuntime({
- metadata: {
- agentConfig: {},
+ agentState: {
+ metadata: {
+ agentConfig: {},
+ },
modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
- },
- origin: {
- userId: 'user-1',
+ origin: {
+ userId: 'user-1',
+ },
},
operationId: 'op-general-agent',
stepIndex: 0,
@@ -464,13 +475,15 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });
await (service as any).createAgentRuntime({
- agentState: sandboxToolCallState('/work/deck.pptx'),
- metadata: {
- agentConfig: {},
+ agentState: {
+ ...sandboxToolCallState('/work/deck.pptx'),
+ metadata: {
+ agentConfig: {},
+ },
modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
- },
- origin: {
- userId: 'user-1',
+ origin: {
+ userId: 'user-1',
+ },
},
operationId: 'op-entity-edit',
stepIndex: 3,
@@ -486,13 +499,15 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });
await (service as any).createAgentRuntime({
- agentState: sandboxToolCallState('/work/notes.md'),
- metadata: {
- agentConfig: {},
+ agentState: {
+ ...sandboxToolCallState('/work/notes.md'),
+ metadata: {
+ agentConfig: {},
+ },
modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
- },
- origin: {
- userId: 'user-1',
+ origin: {
+ userId: 'user-1',
+ },
},
operationId: 'op-plain-edit',
stepIndex: 3,
@@ -539,7 +554,7 @@ describe('AgentRuntimeService.executeStep - durable Review lifecycle retry', ()
cost: { currency: 'USD', total: 0 },
lastModified: new Date().toISOString(),
messages: [],
- metadata: { _hooks: [] },
+ host: { hooks: [] },
operationId: 'op-review-retry',
status: 'running',
stepCount: 0,
@@ -717,7 +732,7 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'
coordinator.loadAgentState = vi.fn().mockResolvedValue({
status: 'running',
stepCount: 5,
- metadata: { queueRetries: 5, queueRetryDelay: '10000' },
+ host: { queue: { retries: 5, retryDelay: '10000' } },
});
const result = await service.executeStep({ operationId: 'op-requeue', stepIndex: 5 });
@@ -1266,8 +1281,8 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
status: 'running',
stepCount: 5,
lastModified: new Date().toISOString(),
- metadata: {
- _hooks: [
+ host: {
+ hooks: [
{
id: 'test-hook',
type: 'onComplete',
@@ -1301,7 +1316,7 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
}),
).rejects.toThrow();
- // onComplete hooks must be dispatched with the full state including metadata
+ // onComplete hooks must be dispatched with the full state including the host envelope
expect(dispatchSpy).toHaveBeenCalledWith(
'op-save-fail',
'onComplete',
@@ -1309,8 +1324,8 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()
operationId: 'op-save-fail',
reason: 'error',
finalState: expect.objectContaining({
- metadata: expect.objectContaining({
- _hooks: expect.arrayContaining([
+ host: expect.objectContaining({
+ hooks: expect.arrayContaining([
expect.objectContaining({
id: 'test-hook',
webhook: { url: 'https://example.com/webhook' },
@@ -1790,7 +1805,7 @@ describe('AgentRuntimeService.executeStep - Agent Share authorization revoked mi
const agentState = {
lastModified: new Date().toISOString(),
- metadata: { agentShareVisitor: { agentId: 'agent-1', shareId: 'share-1' } },
+ principal: { actor: { shareVisitor: { agentId: 'agent-1', shareId: 'share-1' } } },
status: 'running',
stepCount: 3,
};
diff --git a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
index b9b5168695a..6e0faaf3bd8 100644
--- a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
@@ -90,8 +90,8 @@ describe('Hooks integration β€” afterStep event carries step presentation data',
createdAt: new Date().toISOString(),
lastModified: new Date().toISOString(),
messages: [{ content: 'Hello', role: 'user' }],
- metadata: {
- _hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
+ host: {
+ hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
},
origin: {
agentId: 'agent-1',
@@ -114,8 +114,8 @@ describe('Hooks integration β€” afterStep event carries step presentation data',
{ content: 'Hello', role: 'user' },
{ content: 'Let me search for that.', role: 'assistant' },
],
- metadata: {
- _hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
+ host: {
+ hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
},
origin: {
agentId: 'agent-1',
@@ -196,9 +196,11 @@ describe('Hooks integration β€” afterStep event carries step presentation data',
lastModified: new Date().toISOString(),
messages: [],
metadata: {
- _hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
_stepTracking: { lastLLMContent: 'previous content', totalToolCalls: 1 },
},
+ host: {
+ hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
+ },
origin: {
agentId: 'agent-1',
userId: 'user-1',
@@ -215,9 +217,11 @@ describe('Hooks integration β€” afterStep event carries step presentation data',
createdAt: new Date().toISOString(),
messages: [],
metadata: {
- _hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
_stepTracking: { lastLLMContent: 'previous content', totalToolCalls: 1 },
},
+ host: {
+ hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
+ },
origin: {
agentId: 'agent-1',
userId: 'user-1',
@@ -332,8 +336,8 @@ describe('Hooks integration β€” afterStep event is compatible with renderStepPro
createdAt: new Date().toISOString(),
lastModified: new Date().toISOString(),
messages: [],
- metadata: {
- _hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
+ host: {
+ hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
},
origin: {
agentId: 'agent-1',
@@ -349,8 +353,8 @@ describe('Hooks integration β€” afterStep event is compatible with renderStepPro
newState: {
createdAt: new Date().toISOString(),
messages: [{ content: 'Result', role: 'assistant' }],
- metadata: {
- _hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
+ host: {
+ hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],
},
origin: {
agentId: 'agent-1',
diff --git a/apps/server/src/services/agentRuntime/agentInterventionNotification.ts b/apps/server/src/services/agentRuntime/agentInterventionNotification.ts
index 969a7705dc5..c69c73676de 100644
--- a/apps/server/src/services/agentRuntime/agentInterventionNotification.ts
+++ b/apps/server/src/services/agentRuntime/agentInterventionNotification.ts
@@ -258,9 +258,7 @@ export const buildRuntimeInterventionNotification = async ({
canonicalToolKey: `${tool.identifier}/${tool.apiName}`,
interactionKind,
provider:
- boundedString(state?.modelRuntimeConfig?.provider) ??
- boundedString(metadata?.modelRuntimeConfig?.provider) ??
- boundedString(metadata?.provider),
+ boundedString(state?.modelRuntimeConfig?.provider) ?? boundedString(metadata?.provider),
requestRevision: revisionFor(tool),
...(security.blocked && {
risk: {
diff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
index 97615e50be7..cf4e7202b41 100644
--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
@@ -1,4 +1,5 @@
import type { ToolRunResult } from '@lobechat/agent-runtime';
+import type { SerializedAgentHook } from '@lobechat/types';
import debug from 'debug';
import urlJoin from 'url-join';
@@ -113,7 +114,7 @@ function buildWebhookPayload(
* HookDispatcher β€” central hub for registering and dispatching agent lifecycle hooks
*
* Local mode: hooks are stored in memory, handler functions called directly
- * Production mode: webhook configs persisted in AgentState.metadata._hooks,
+ * Production mode: webhook configs persisted in AgentState.host.hooks,
* delivered via HTTP POST or QStash
*/
export class HookDispatcher {
@@ -133,7 +134,11 @@ export class HookDispatcher {
operationId: string,
type: AgentHookType,
event: AnyHookEvent,
- serializedHooks?: SerializedHook[],
+ /**
+ * Hooks persisted on `state.host.hooks` (wire shape). Narrowed here to the
+ * runtime-precise {@link SerializedHook} once the type / webhook are checked.
+ */
+ serializedHooks?: SerializedAgentHook[],
): Promise<void> {
const isQueueMode = isQueueAgentRuntimeEnabled();
@@ -153,7 +158,9 @@ export class HookDispatcher {
} else {
// Production mode: deliver via webhooks
const webhookHooks =
- serializedHooks?.filter((h) => h.type === type && h.webhook) ||
+ serializedHooks?.filter(
+ (h): h is SerializedHook => h.type === type && h.webhook !== undefined,
+ ) ||
this.getSerializedHooks(operationId)?.filter((h) => h.type === type) ||
[];
@@ -275,7 +282,7 @@ export class HookDispatcher {
* Register hooks for an operation
*
* In local mode: stores hooks in memory (including handler functions)
- * In production mode: caller should persist getSerializedHooks() to state.metadata._hooks
+ * In production mode: caller should persist getSerializedHooks() to state.host.hooks
*/
register(operationId: string, hooks: AgentHook[]): void {
if (hooks.length === 0) return;
diff --git a/apps/server/src/services/agentRuntime/hooks/types.ts b/apps/server/src/services/agentRuntime/hooks/types.ts
index 7c593535a61..5d18ce991ba 100644
--- a/apps/server/src/services/agentRuntime/hooks/types.ts
+++ b/apps/server/src/services/agentRuntime/hooks/types.ts
@@ -72,7 +72,7 @@ export interface AgentHook {
// ── Serialized Hook (for Redis persistence) ──────────────
/**
- * Serialized hook config stored in AgentState.metadata._hooks (and on
+ * Serialized hook config stored in AgentState.host.hooks (and on
* `topic.metadata.runningOperation.hooks`). Only contains webhook info β€”
* handler functions can't be serialized.
*
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 4cfc47111b9..f1534e3a213 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -404,7 +404,7 @@ export interface OperationCreationParams {
agentGroup?: AgentGroupConfig;
/**
* Shared-agent visitor marker. Persisted to
- * `state.metadata.agentShareVisitor` so every later step can re-derive the
+ * `state.principal.actor.shareVisitor` so every later step can re-derive the
* share's restrictions without re-reading the share, and so
* `AgentRuntimeService.executeStep` can re-prove the run's authorization at
* each step boundary.
@@ -419,7 +419,7 @@ export interface OperationCreationParams {
*/
agentSignal?: AgentSignalOperationMarker;
/**
- * Client IP of the originating request. Spread onto `state.metadata.clientIp`
+ * Client IP of the originating request. Spread onto `state.principal.audit.clientIp`
* so downstream LLM-call metadata can carry it for auditing and spend
* attribution.
*/
@@ -459,7 +459,7 @@ export interface OperationCreationParams {
trigger?: string;
/**
* User agent of the originating request. Spread onto
- * `state.metadata.userAgent` so downstream LLM-call metadata can carry it for
+ * `state.principal.audit.userAgent` so downstream LLM-call metadata can carry it for
* auditing and spend attribution.
*/
userAgent?: string;
@@ -467,7 +467,7 @@ export interface OperationCreationParams {
autoStart?: boolean;
/**
* Sender/owner identity for bot-originated runs. Forwarded into
- * `state.metadata.botContext` so device-tool dispatch can audit who
+ * `state.principal.actor.bot` so device-tool dispatch can audit who
* triggered the call. `undefined` for first-party (web/desktop) callers.
*/
botContext?: ChatTopicBotContext;
@@ -480,7 +480,7 @@ export interface OperationCreationParams {
connectorOwnershipNote?: string;
/**
* Device-access policy decision computed once per turn by
- * `resolveDeviceAccessPolicy`. Forwarded into `state.metadata.deviceAccessPolicy`
+ * `resolveDeviceAccessPolicy`. Forwarded into `state.principal.policy.deviceAccess`
* so the dispatch site can include `reason` in the audit entry without
* re-deriving it.
*/
@@ -497,7 +497,7 @@ export interface OperationCreationParams {
evalRuntime?: EvalRuntimeContext;
/**
* Resolved execution plan for the run (see `resolveExecutionPlan`).
- * Forwarded into `state.metadata.executionPlan` so step-level layers (the
+ * Forwarded into `state.plan.execution` so step-level layers (the
* `call_llm` device-tool injection) consume the plan instead of re-deriving
* device capability from raw config.
*/
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index d6d34bb16dc..86a90bf2bbf 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -207,7 +207,7 @@ export interface ToolExecutionContext {
currentTodos?: StepContextTodoItem[];
/**
* Whether the run's execution plan is device-capable (`device` or
- * `device-unrouted`) β€” derived from `state.metadata.executionPlan` by the
+ * `device-unrouted`) β€” derived from `state.plan.execution` by the
* runtime executors. Device-only skills gate listing/activation/loading on
* this consistently, so a `device-unrouted` run can activate them before the
* model routes a device; actual command execution stays gated at the device
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
index 8143d5f7f58..10da57df05d 100644
--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts
+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
@@ -161,8 +161,14 @@ export class GeneralChatAgent implements Agent {
// Get security blacklist for resolver metadata
const securityBlacklist = state.securityBlacklist ?? DEFAULT_SECURITY_BLACKLIST;
- // Build resolver metadata: merge state.metadata with security blacklist
- const resolverMetadata = { ...state.metadata, securityBlacklist };
+ // Resolvers see one flat record: the run ledger plus the facts they audit
+ // against β€” the security blacklist and the plan's working directory (the
+ // path-scope audit fences file paths to it).
+ const resolverMetadata = {
+ ...state.metadata,
+ securityBlacklist,
+ workingDirectory: state.plan?.workingDirectory,
+ };
// Get user config (default to 'manual' mode)
const userConfig = state.userInterventionConfig || { approvalMode: 'manual' };
@@ -216,7 +222,7 @@ export class GeneralChatAgent implements Agent {
// Phase 3: Per-tool dynamic resolver
const config = this.getToolInterventionConfig(toolCalling, state);
const isDynamicConfig = this.isDynamicInterventionConfig(config);
- const dynamicPolicy = await this.resolveDynamicPolicy(config, toolArgs, state.metadata);
+ const dynamicPolicy = await this.resolveDynamicPolicy(config, toolArgs, resolverMetadata);
const staticConfig = isDynamicConfig
? undefined
: (config as HumanInterventionConfig | undefined);
diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
index b63864c37e8..2a729e86ca9 100644
--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
@@ -2541,7 +2541,7 @@ describe('GeneralChatAgent', () => {
};
const state = createMockState({
- metadata: { workingDirectory: '/workspace' },
+ plan: { workingDirectory: '/workspace' },
toolManifestMap: {
'local-system': {
identifier: 'local-system',
@@ -2603,7 +2603,7 @@ describe('GeneralChatAgent', () => {
};
const state = createMockState({
- metadata: { workingDirectory: '/workspace' },
+ plan: { workingDirectory: '/workspace' },
toolManifestMap: {
'local-system': {
identifier: 'local-system',
@@ -2670,7 +2670,7 @@ describe('GeneralChatAgent', () => {
};
const state = createMockState({
- metadata: { workingDirectory: '/workspace' },
+ plan: { workingDirectory: '/workspace' },
toolManifestMap: {
'local-system': {
identifier: 'local-system',
@@ -2734,7 +2734,7 @@ describe('GeneralChatAgent', () => {
};
const state = createMockState({
- metadata: { workingDirectory: '/workspace' },
+ plan: { workingDirectory: '/workspace' },
toolManifestMap: {
'local-system': {
identifier: 'local-system',
@@ -3597,7 +3597,7 @@ describe('GeneralChatAgent', () => {
};
const state = createMockState({
- metadata: { workingDirectory: '/workspace' },
+ plan: { workingDirectory: '/workspace' },
toolManifestMap: {
'my-tool': { identifier: 'my-tool', humanIntervention: 'never' },
},
diff --git a/packages/agent-runtime/src/executors/compressContext.ts b/packages/agent-runtime/src/executors/compressContext.ts
index a7491bc21ec..64c811c14fb 100644
--- a/packages/agent-runtime/src/executors/compressContext.ts
+++ b/packages/agent-runtime/src/executors/compressContext.ts
@@ -109,7 +109,7 @@ export const compressContext =
tokenCount: currentTokenCount,
userId,
} as AnyHookEvent,
- state.metadata?._hooks,
+ state.host?.hooks,
);
let createdGroupId: string | undefined;
@@ -276,7 +276,7 @@ export const compressContext =
summary: summaryResult.content.slice(0, 500),
userId,
} as AnyHookEvent,
- state.metadata?._hooks,
+ state.host?.hooks,
);
return {
@@ -322,7 +322,7 @@ export const compressContext =
tokenCount: currentTokenCount,
userId,
} as AnyHookEvent,
- state.metadata?._hooks,
+ state.host?.hooks,
);
events.push({ error, type: 'compression_error' });
diff --git a/packages/agent-runtime/src/executors/humanApprove.ts b/packages/agent-runtime/src/executors/humanApprove.ts
index 2cbaba30dec..ba728319eb3 100644
--- a/packages/agent-runtime/src/executors/humanApprove.ts
+++ b/packages/agent-runtime/src/executors/humanApprove.ts
@@ -50,7 +50,7 @@ export const requestHumanApprove =
stepIndex,
userId,
} as AnyHookEvent,
- serializedHooks: state.metadata?._hooks,
+ serializedHooks: state.host?.hooks,
type: 'beforeHumanIntervention',
})
.catch(() => {});
diff --git a/packages/agent-runtime/src/transport/lifecycle.ts b/packages/agent-runtime/src/transport/lifecycle.ts
index 99c4d76d27f..b41954e41dc 100644
--- a/packages/agent-runtime/src/transport/lifecycle.ts
+++ b/packages/agent-runtime/src/transport/lifecycle.ts
@@ -11,7 +11,7 @@ export interface LifecycleDispatchParams {
event: AnyHookEvent;
/**
* Per-operation webhook configs (the server keeps them on
- * `state.metadata._hooks` for production/queue mode). Opaque to the package
+ * `state.host.hooks` for production/queue mode). Opaque to the package
* and forwarded verbatim to the adapter.
*/
serializedHooks?: unknown;
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index 8191ea0cb19..1e9e54a5adc 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -5,6 +5,7 @@ import type {
BotPlatformContext,
DiscordContext,
EvalContext,
+ OperationSkillSet,
OperationToolSet,
ProjectInstructionFile,
ToolExecutor,
@@ -12,12 +13,17 @@ import type {
UserMemoryConfig,
} from '@lobechat/context-engine';
import type {
+ AgentShareVisitorContext,
AgentSignalOperationMarker,
ChatToolPayload,
+ ChatTopicBotContext,
+ EvalToolForwardingConfig,
+ ExecutionPlan,
ExpertiseContextSnapshot,
LobeAgentChatConfig,
LobeAgentConfig,
SecurityBlacklistConfig,
+ SerializedAgentHook,
UserInterventionConfig,
} from '@lobechat/types';
@@ -96,6 +102,67 @@ export interface AgentRunOrigin {
workspaceId?: string;
}
+/**
+ * Under whose authority the run acts and what it is allowed to do.
+ *
+ * Decided by the host when the operation is created and frozen from then on;
+ * each dispatch boundary only re-presents these facts (share-visitor grants,
+ * device access) instead of re-deriving them.
+ */
+export interface AgentRunPrincipal {
+ /** Who the run acts as. */
+ actor?: {
+ /** Sender / owner identity for bot-originated runs. */
+ bot?: ChatTopicBotContext;
+ /**
+ * Principal pool the routed device lives in: `personal` when a workspace
+ * run was routed to the caller's own device via a per-user `local` override.
+ */
+ deviceScope?: 'personal' | 'workspace';
+ /** Shared-agent visitor marker. Present only for a share-visitor run. */
+ shareVisitor?: AgentShareVisitorContext;
+ };
+ /** Request provenance kept for auditing and spend attribution. */
+ audit?: {
+ clientIp?: string;
+ userAgent?: string;
+ };
+ /** Decisions about what the run may do, made once per turn. */
+ policy?: {
+ /** Device-access decision; `reason` names the branch that granted or denied it. */
+ deviceAccess?: { canUseDevice: boolean; reason: string };
+ };
+}
+
+/**
+ * How the run executes: the resolved execution plan plus the controls the
+ * caller fixed for it. Frozen at creation. The model itself lives on
+ * `AgentState.modelRuntimeConfig`; the tool set on `operationToolSet`.
+ */
+export interface AgentRunPlan {
+ /** Evaluation execution controls (tool forwarding) for eval runs. */
+ eval?: { caseId?: string; toolForwarding?: EvalToolForwardingConfig };
+ /** Where (and whether) the run executes, resolved once at the entry point. */
+ execution?: ExecutionPlan;
+ /** Operation-level skill set for the skill resolver. */
+ skills?: OperationSkillSet;
+ /** Whether LLM calls stream. Defaults to true. */
+ stream?: boolean;
+ /** Working directory the run executes in. */
+ workingDirectory?: string;
+}
+
+/**
+ * What the host needs to deliver and retry the run. Written by the host,
+ * carried by the runtime without interpretation.
+ */
+export interface AgentRunHostEnvelope {
+ /** Serialized lifecycle hook configs (webhook mode), so a queue worker can rebuild the dispatcher. */
+ hooks?: SerializedAgentHook[];
+ /** Queue retry policy for step scheduling. */
+ queue?: { retries?: number; retryDelay?: string };
+}
+
/**
* Search route resolved once before the run starts. Declared here rather than
* imported so the runtime package does not depend on the model catalog;
@@ -223,6 +290,9 @@ export interface AgentState {
* and a summary prompt injected to produce a final text response.
*/
forceFinish?: boolean;
+ // --- Host envelope ---
+ /** What the host needs to deliver and retry the run. Opaque to the runtime. */
+ host?: AgentRunHostEnvelope;
// --- Interruption Handling ---
/**
* When status is 'interrupted', this stores the interruption context
@@ -250,10 +320,11 @@ export interface AgentState {
messages: any[];
/**
- * Un-converged run context. Keys that have a business home live in the
- * typed slots (`origin`, `world`, `binding`, …); anything left here is either host
- * plumbing the runtime does not interpret or context that has not been
- * placed yet. `normalizeAgentState` lifts legacy keys out on load.
+ * Run ledger the runtime and host write while the operation executes
+ * (step tracking, work anchors, intervention preparation …). Facts that are
+ * fixed at creation live in the typed slots (`origin`, `principal`, `plan`,
+ * `world`, `binding`, `host`); `normalizeAgentState` lifts legacy keys out
+ * of here on load.
*/
metadata?: Record<string, any>;
@@ -286,13 +357,13 @@ export interface AgentState {
operationId: string;
/** Operation-level tool set snapshot (immutable after creation) */
operationToolSet?: OperationToolSet;
-
// --- Origin ---
/**
* Where this run came from and where it sits in the run tree. Frozen when
* the operation is created.
*/
origin?: AgentRunOrigin;
+
pendingApprovalBatch?: {
assistantMessageId: string;
id: string;
@@ -320,8 +391,8 @@ export interface AgentState {
* Cleared once consumed.
*/
pendingAssistantMessageId?: string;
-
pendingHumanPrompt?: { metadata?: Record<string, unknown>; prompt: string };
+
pendingHumanSelect?: {
metadata?: Record<string, unknown>;
multi?: boolean;
@@ -335,6 +406,12 @@ export interface AgentState {
* for human-in-the-loop operations.
*/
pendingToolsCalling?: ChatToolPayload[];
+ // --- Plan ---
+ /** How the run executes. Frozen at creation. */
+ plan?: AgentRunPlan;
+ // --- Principal ---
+ /** Under whose authority the run acts and what it may do. Frozen at creation. */
+ principal?: AgentRunPrincipal;
/**
* Security blacklist configuration
* These rules will ALWAYS block execution and require human intervention,
diff --git a/packages/agent-runtime/src/utils/normalizeAgentState.test.ts b/packages/agent-runtime/src/utils/normalizeAgentState.test.ts
index 41813eea0ba..1c07f27c8b9 100644
--- a/packages/agent-runtime/src/utils/normalizeAgentState.test.ts
+++ b/packages/agent-runtime/src/utils/normalizeAgentState.test.ts
@@ -18,7 +18,7 @@ const baseState = (): AgentState =>
describe('normalizeAgentState', () => {
it('returns the same object when metadata carries no legacy keys', () => {
- const state = { ...baseState(), metadata: { _hooks: [], queueRetries: 2 } };
+ const state = { ...baseState(), metadata: { _stepLabel: 'step', work: { id: 'work_1' } } };
expect(normalizeAgentState(state)).toBe(state);
});
@@ -87,7 +87,7 @@ describe('normalizeAgentState', () => {
const state = {
...baseState(),
metadata: {
- _hooks: [],
+ _stepLabel: 'step',
agentId: 'agent-1',
agentInterventionContinuation: {
resolutionRequestId: 'r1',
@@ -132,7 +132,68 @@ describe('normalizeAgentState', () => {
// `null` / `undefined` legacy values are absent, not carried as null.
expect('groupId' in normalized.origin!).toBe(false);
expect('threadId' in normalized.origin!).toBe(false);
- expect(normalized.metadata).toEqual({ _hooks: [] });
+ expect(normalized.metadata).toEqual({ _stepLabel: 'step' });
+ });
+
+ it('lifts principal, plan and host keys and folds the model config into its top-level slot', () => {
+ const state = {
+ ...baseState(),
+ metadata: {
+ _hooks: [{ id: 'h1', type: 'webhook', webhook: { url: 'https://x' } }],
+ activeDeviceScope: 'workspace',
+ agentShareVisitor: { shareId: 'share-1', visitorUserId: 'visitor-1' },
+ botContext: { applicationId: 'app-1', isOwner: true, platform: 'discord' },
+ clientIp: '10.0.0.1',
+ deviceAccessPolicy: { canUseDevice: false, reason: 'external-bot' },
+ evalRuntime: { caseId: 'case-1' },
+ executionPlan: { kind: 'sandbox', target: 'sandbox' },
+ modelRuntimeConfig: { model: 'gpt-4', provider: 'openai' },
+ operationSkillSet: { enabledSkillIds: [], skills: [] },
+ queueRetries: 3,
+ queueRetryDelay: '10s',
+ stream: false,
+ userAgent: 'lh-cli',
+ workingDirectory: '/repo',
+ },
+ };
+
+ const normalized = normalizeAgentState(state);
+
+ expect(normalized.principal).toEqual({
+ actor: {
+ bot: { applicationId: 'app-1', isOwner: true, platform: 'discord' },
+ deviceScope: 'workspace',
+ shareVisitor: { shareId: 'share-1', visitorUserId: 'visitor-1' },
+ },
+ audit: { clientIp: '10.0.0.1', userAgent: 'lh-cli' },
+ policy: { deviceAccess: { canUseDevice: false, reason: 'external-bot' } },
+ });
+ expect(normalized.plan).toEqual({
+ eval: { caseId: 'case-1' },
+ execution: { kind: 'sandbox', target: 'sandbox' },
+ skills: { enabledSkillIds: [], skills: [] },
+ stream: false,
+ workingDirectory: '/repo',
+ });
+ expect(normalized.host).toEqual({
+ hooks: [{ id: 'h1', type: 'webhook', webhook: { url: 'https://x' } }],
+ queue: { retries: 3, retryDelay: '10s' },
+ });
+ expect(normalized.modelRuntimeConfig).toEqual({ model: 'gpt-4', provider: 'openai' });
+ expect(normalized.metadata).toEqual({});
+ });
+
+ it('keeps the top-level model config over the legacy metadata copy', () => {
+ const state = {
+ ...baseState(),
+ metadata: { modelRuntimeConfig: { model: 'legacy', provider: 'openai' } },
+ modelRuntimeConfig: { model: 'pinned', provider: 'openai' },
+ };
+
+ expect(normalizeAgentState(state).modelRuntimeConfig).toEqual({
+ model: 'pinned',
+ provider: 'openai',
+ });
});
it('merges lifted origin keys into an existing origin without overriding it', () => {
diff --git a/packages/agent-runtime/src/utils/normalizeAgentState.ts b/packages/agent-runtime/src/utils/normalizeAgentState.ts
index 73eac0223de..b882e9d8866 100644
--- a/packages/agent-runtime/src/utils/normalizeAgentState.ts
+++ b/packages/agent-runtime/src/utils/normalizeAgentState.ts
@@ -27,6 +27,24 @@ const LEGACY_KEY_PATHS: Record<string, readonly string[]> = {
isSubAgent: ['origin', 'lineage', 'isSubAgent'],
orchestrationRole: ['origin', 'lineage', 'orchestrationRole'],
subAgentProgress: ['origin', 'lineage', 'progressAnchor'],
+ // --- principal ---
+ activeDeviceScope: ['principal', 'actor', 'deviceScope'],
+ agentShareVisitor: ['principal', 'actor', 'shareVisitor'],
+ botContext: ['principal', 'actor', 'bot'],
+ clientIp: ['principal', 'audit', 'clientIp'],
+ deviceAccessPolicy: ['principal', 'policy', 'deviceAccess'],
+ userAgent: ['principal', 'audit', 'userAgent'],
+ // --- plan (the model config folds into the top-level slot it duplicated) ---
+ evalRuntime: ['plan', 'eval'],
+ executionPlan: ['plan', 'execution'],
+ modelRuntimeConfig: ['modelRuntimeConfig'],
+ operationSkillSet: ['plan', 'skills'],
+ stream: ['plan', 'stream'],
+ workingDirectory: ['plan', 'workingDirectory'],
+ // --- host ---
+ _hooks: ['host', 'hooks'],
+ queueRetries: ['host', 'queue', 'retries'],
+ queueRetryDelay: ['host', 'queue', 'retryDelay'],
// --- world ---
agentConfig: ['world', 'agent'],
agentGroup: ['world', 'group'],
@@ -68,8 +86,9 @@ const setIfAbsent = (root: Record<string, unknown>, path: readonly string[], val
};
/**
- * Lift legacy `metadata.*` run context into the typed `origin` / `world` /
- * `binding` slots so every reader can rely on the slots alone.
+ * Lift legacy `metadata.*` run context into the typed slots (`origin`,
+ * `principal`, `plan`, `world`, `binding`, `host`) so every reader can rely on
+ * the slots alone.
*
* Runs at the persistence boundary (state load) for blobs written before the
* slots existed. Slot values already present win over legacy keys, and the
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index 60403a671bc..6641b381fae 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -840,6 +840,45 @@ export const buildHeteroExecArgs = (
*/
export type DeviceExecutionTarget = 'auto' | 'device' | 'local' | 'none' | 'sandbox';
+export type ExecutionPlanUnroutedReason =
+ /** `auto` mode with more than one device online β€” the model must pick one */
+ | 'ambiguous-online-devices'
+ /** an explicitly bound device exists but is offline β€” never silently fall back */
+ | 'bound-device-offline'
+ /**
+ * device-capable target (`auto` / `local` / `device`) but no device selected β€”
+ * nothing bound/requested, and not the `auto` single-online-device case
+ */
+ | 'no-bound-device'
+ /** `auto` mode but no device online at all */
+ | 'no-online-device';
+
+/**
+ * Where (and whether) a run executes, resolved ONCE at the entry point.
+ * Downstream layers consume the plan instead of re-deriving the answer from
+ * `executionTarget` / `boundDeviceId` / online state themselves.
+ *
+ * `target` is the EFFECTIVE execution target (platform defaults and coercions
+ * applied; degraded to `none` when device access is denied) β€” consumers must
+ * read it instead of re-resolving `agencyConfig.executionTarget`.
+ */
+export type ExecutionPlan = { target: DeviceExecutionTarget } &
+ /** route execution / device tools to this device (the local machine is a registered device) */
+ (
+ | { deviceId: string; kind: 'device' }
+ /**
+ * Device-targeted but no routable device right now. The run proceeds without
+ * an active device; the remote-device proxy may let the model activate one
+ * mid-run (native agents), or the caller may treat this as a hard error
+ * (hetero dispatch).
+ */
+ | { kind: 'device-unrouted'; reason: ExecutionPlanUnroutedReason }
+ /** plain chat β€” no execution environment, no run tools, no device ever */
+ | { kind: 'none' }
+ /** ephemeral cloud sandbox */
+ | { kind: 'sandbox' }
+ );
+
/**
* Whether a workspace member may override the agent's shared execution target.
*
diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.ts
index d2ef4b3c1c8..d5911467729 100644
--- a/src/helpers/executionTarget.ts
+++ b/src/helpers/executionTarget.ts
@@ -2,6 +2,7 @@ import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import type {
AgentDeviceOverride,
DeviceExecutionTarget,
+ ExecutionPlan,
LobeAgentAgencyConfig,
LobeAgentChatConfig,
RuntimeEnvMode,
@@ -307,44 +308,7 @@ export const resolveRuntimeMode = (
}),
);
-export type ExecutionPlanUnroutedReason =
- /** `auto` mode with more than one device online β€” the model must pick one */
- | 'ambiguous-online-devices'
- /** an explicitly bound device exists but is offline β€” never silently fall back */
- | 'bound-device-offline'
- /**
- * device-capable target (`auto` / `local` / `device`) but no device selected β€”
- * nothing bound/requested, and not the `auto` single-online-device case
- */
- | 'no-bound-device'
- /** `auto` mode but no device online at all */
- | 'no-online-device';
-
-/**
- * Where (and whether) a run executes, resolved ONCE at the entry point.
- * Downstream layers consume the plan instead of re-deriving the answer from
- * `executionTarget` / `boundDeviceId` / online state themselves.
- *
- * `target` is the EFFECTIVE execution target (platform defaults and coercions
- * applied; degraded to `none` when device access is denied) β€” consumers must
- * read it instead of re-resolving `agencyConfig.executionTarget`.
- */
-export type ExecutionPlan = { target: DeviceExecutionTarget } &
- /** route execution / device tools to this device (the local machine is a registered device) */
- (
- | { deviceId: string; kind: 'device' }
- /**
- * Device-targeted but no routable device right now. The run proceeds without
- * an active device; the remote-device proxy may let the model activate one
- * mid-run (native agents), or the caller may treat this as a hard error
- * (hetero dispatch).
- */
- | { kind: 'device-unrouted'; reason: ExecutionPlanUnroutedReason }
- /** plain chat β€” no execution environment, no run tools, no device ever */
- | { kind: 'none' }
- /** ephemeral cloud sandbox */
- | { kind: 'sandbox' }
- );
+export type { ExecutionPlan, ExecutionPlanUnroutedReason } from '@lobechat/types';
export type ExecutionManifestEnvironment = ExecutionPlan['kind'] | 'local';