Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/lib/messaging/applier/host-state-applier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

import type { SandboxMessagingPlan } from "../manifest";
import { parseSandboxMessagingPlan } from "../plan-validation";
import * as registry from "../../state/registry";
import { MessagingSetupApplier } from "./setup-applier";
import type { MessagingSetupEnvOptions } from "./types";
Expand Down Expand Up @@ -42,9 +43,10 @@ export class MessagingHostStateApplier {
if (plan.sandboxName !== sandboxName) return false;
const entry = registry.getSandbox(sandboxName);
if (!entry) return false;
const existingPlan = parseSandboxMessagingPlan(entry.messaging?.plan);
const nextPlan =
options.mode === "merge" && entry.messaging?.plan
? mergeSandboxMessagingPlans(entry.messaging.plan, plan)
options.mode === "merge" && existingPlan
? mergeSandboxMessagingPlans(existingPlan, plan)
: clonePlan(plan);
return registry.updateSandbox(sandboxName, {
messaging: {
Expand Down
19 changes: 8 additions & 11 deletions src/lib/messaging/compiler/workflow-planner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// SPDX-License-Identifier: Apache-2.0

import { MessagingHookRegistry } from "../hooks";
import { hydrateDerivedSandboxMessagingPlanFields } from "../persistence";
import { parseSandboxMessagingPlan } from "../plan-validation";
import type {
ChannelManifestRegistry,
MessagingAgentId,
Expand Down Expand Up @@ -177,7 +179,7 @@ export class MessagingWorkflowPlanner {
sandboxEntry: MessagingWorkflowPlannerSandboxEntry | null | undefined,
channelIds: readonly MessagingChannelId[],
): MessagingCompilerCredentialAvailability | undefined {
const plan = sandboxEntry?.messaging?.plan;
const plan = parseSandboxMessagingPlan(sandboxEntry?.messaging?.plan);
if (!plan) return undefined;

const availability: Record<string, boolean> = {};
Expand Down Expand Up @@ -247,16 +249,11 @@ function onlyConfiguredChannels(
function readSandboxEntryPlan(
context: Pick<MessagingWorkflowPlannerSandboxContext, "agent" | "sandboxEntry" | "sandboxName">,
): SandboxMessagingPlan | null {
const plan = context.sandboxEntry?.messaging?.plan;
if (
!plan ||
plan.schemaVersion !== 1 ||
plan.sandboxName !== context.sandboxName ||
plan.agent !== context.agent
) {
return null;
}
return clonePlan(plan);
const plan = parseSandboxMessagingPlan(context.sandboxEntry?.messaging?.plan, {
sandboxName: context.sandboxName,
agent: context.agent,
});
return plan ? hydrateDerivedSandboxMessagingPlanFields(plan) : null;
}

function disabledChannelsFromSandboxEntry(
Expand Down
1 change: 1 addition & 0 deletions src/lib/messaging/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ export * from "./compiler";
export * from "./hooks";
export * from "./applier";
export * from "./manifest";
export * from "./persistence";
export * from "./utils";
195 changes: 195 additions & 0 deletions src/lib/messaging/persistence.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import {
createBuiltInChannelManifestRegistry,
createBuiltInRenderTemplateResolver,
} from "./channels";
import {
collectTemplateReferencesInLines,
collectTemplateReferencesInValue,
isTruthyRenderTemplate,
resolveCredentialTemplatesInLines,
resolveCredentialTemplatesInValue,
resolveRenderTemplatesInLines,
resolveRenderTemplatesInValue,
} from "./compiler/engines/template";
import type {
ChannelHookSpec,
ChannelManifest,
MessagingAgentId,
MessagingChannelId,
SandboxMessagingAgentRenderPlan,
SandboxMessagingChannelPlan,
SandboxMessagingEnvLinesRenderPlan,
SandboxMessagingHookReferencePlan,
SandboxMessagingJsonRenderPlan,
SandboxMessagingPlan,
} from "./manifest";

export type PersistedSandboxMessagingChannelPlan = Omit<SandboxMessagingChannelPlan, "hooks"> & {
readonly hooks?: readonly SandboxMessagingHookReferencePlan[];
};

export type PersistedSandboxMessagingPlan = Omit<
SandboxMessagingPlan,
"channels" | "agentRender"
> & {
readonly channels: readonly PersistedSandboxMessagingChannelPlan[];
readonly agentRender?: readonly SandboxMessagingAgentRenderPlan[];
};

export function compactSandboxMessagingPlanForPersistence(
plan: SandboxMessagingPlan,
): PersistedSandboxMessagingPlan {
const { agentRender: _agentRender, channels, ...rest } = clonePlan(plan);
return {
...rest,
channels: channels.map(({ hooks: _hooks, ...channel }) => channel),
};
}

export function hydrateDerivedSandboxMessagingPlanFields(
plan: SandboxMessagingPlan,
): SandboxMessagingPlan {
const manifestRegistry = createBuiltInChannelManifestRegistry();
const channels = plan.channels.map((channel) => {
if (channel.hooks.length > 0) return channel;
return {
...channel,
hooks: channelHooksFromManifest(
plan.agent,
channel.channelId,
manifestRegistry.get(channel.channelId),
),
};
});
const hydratedPlan = { ...plan, channels };
return {
...hydratedPlan,
agentRender:
hydratedPlan.agentRender.length > 0
? hydratedPlan.agentRender
: agentRenderFromManifests(hydratedPlan, manifestRegistry),
};
}

function channelHooksFromManifest(
agent: MessagingAgentId,
channelId: MessagingChannelId,
manifest: ChannelManifest | undefined,
): SandboxMessagingHookReferencePlan[] {
if (!manifest) return [];
return manifest.hooks
.filter((hook) => isHookForAgent(hook, agent))
.map((hook) => cloneHookReference(channelId, hook));
}

function agentRenderFromManifests(
plan: SandboxMessagingPlan,
manifestRegistry: ReturnType<typeof createBuiltInChannelManifestRegistry>,
): SandboxMessagingAgentRenderPlan[] {
const render: SandboxMessagingAgentRenderPlan[] = [];
const referenceResolver = createBuiltInRenderTemplateResolver();
for (const channel of plan.channels) {
const manifest = manifestRegistry.get(channel.channelId);
if (!manifest) continue;
const context = {
inputs: channel.inputs,
env: process.env,
referenceResolver,
};

for (const [index, entry] of manifest.render.entries()) {
if (entry.agent !== plan.agent) continue;
if (!isTruthyRenderTemplate(entry.when, context)) continue;
const renderId = entry.id ?? `${manifest.id}-render-${index}`;
const hookId = renderId;
const handler = "common.staticOutputs";

if (entry.kind === "json-fragment") {
const credentialResolved = resolveCredentialTemplatesInValue(
entry.fragment.value,
manifest.credentials,
);
const value = resolveRenderTemplatesInValue(credentialResolved, context);
if (value === undefined) continue;
render.push({
channelId: manifest.id,
renderId,
hookId,
handler,
kind: "json-fragment",
agent: entry.agent,
target: entry.target,
path: entry.fragment.path,
value,
templateRefs: collectTemplateReferencesInValue(value),
} satisfies SandboxMessagingJsonRenderPlan);
continue;
}

const credentialResolved = resolveCredentialTemplatesInLines(
entry.lines,
manifest.credentials,
);
const lines = resolveRenderTemplatesInLines(credentialResolved, context);
if (lines.length === 0) continue;
assertSingleLineEnvRenderLines(manifest.id, renderId, lines);
render.push({
channelId: manifest.id,
renderId,
hookId,
handler,
kind: "env-lines",
agent: entry.agent,
target: entry.target,
lines,
templateRefs: collectTemplateReferencesInLines(lines),
} satisfies SandboxMessagingEnvLinesRenderPlan);
}
}
return render;
}

function cloneHookReference(
channelId: MessagingChannelId,
hook: ChannelHookSpec,
): SandboxMessagingHookReferencePlan {
return {
channelId,
id: hook.id,
phase: hook.phase,
handler: hook.handler,
agents: hook.agents ? [...hook.agents] : undefined,
inputs: hook.inputs ? [...hook.inputs] : undefined,
outputs: hook.outputs?.map((output) => ({ ...output })),
onFailure: hook.onFailure,
};
}

function isHookForAgent(hook: ChannelHookSpec, agent: MessagingAgentId): boolean {
return !hook.agents || hook.agents.includes(agent);
}

function assertSingleLineEnvRenderLines(
channelId: string,
renderId: string,
lines: readonly string[],
): void {
for (const line of lines) {
if (/[\r\n]/.test(line)) {
throw new Error(
"Messaging env render '" +
renderId +
"' for " +
channelId +
" must not contain line breaks.",
);
}
}
}

function clonePlan(plan: SandboxMessagingPlan): SandboxMessagingPlan {
return JSON.parse(JSON.stringify(plan)) as SandboxMessagingPlan;
}
13 changes: 13 additions & 0 deletions src/lib/messaging/plan-validation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
getMessagingChannelConfigFromPlan,
parseSandboxMessagingPlan,
} from "./plan-validation";
import { compactSandboxMessagingPlanForPersistence } from "./persistence";

function makePlan(overrides: Partial<SandboxMessagingPlan> = {}): SandboxMessagingPlan {
return {
Expand Down Expand Up @@ -64,6 +65,18 @@ describe("parseSandboxMessagingPlan", () => {
expect(parsed).not.toBe(source);
});

it("accepts compact persisted plans without render or channel hooks", () => {
const source = makePlan();
const compact = compactSandboxMessagingPlanForPersistence(source);
const parsed = parseSandboxMessagingPlan(compact);

expect(parsed).toEqual({
...source,
agentRender: [],
channels: source.channels.map((channel) => ({ ...channel, hooks: [] })),
});
});

it("rejects mismatched selectors, duplicate channels, and unsupported channels", () => {
expect(parseSandboxMessagingPlan(makePlan(), { sandboxName: "other" })).toBeNull();
expect(parseSandboxMessagingPlan(makePlan(), { agent: "hermes" })).toBeNull();
Expand Down
29 changes: 27 additions & 2 deletions src/lib/messaging/plan-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function parseSandboxMessagingPlan(
!Array.isArray(value.disabledChannels) ||
!Array.isArray(value.credentialBindings) ||
!isObject(value.networkPolicy) ||
!Array.isArray(value.agentRender) ||
(Object.hasOwn(value, "agentRender") && !Array.isArray(value.agentRender)) ||
!Array.isArray(value.buildSteps) ||
!Array.isArray(value.stateUpdates) ||
!Array.isArray(value.healthChecks)
Expand All @@ -45,6 +45,7 @@ export function parseSandboxMessagingPlan(
if (typeof channel.active !== "boolean") return null;
if (typeof channel.disabled !== "boolean") return null;
if (!Array.isArray(channel.inputs)) return null;
if (Object.hasOwn(channel, "hooks") && !Array.isArray(channel.hooks)) return null;
if (supported && !supported.has(channel.channelId)) return null;
if (
value.channels.findIndex(
Expand All @@ -56,7 +57,9 @@ export function parseSandboxMessagingPlan(
}
if (!value.disabledChannels.every((channelId) => typeof channelId === "string")) return null;

return cloneSandboxMessagingPlan(value as unknown as SandboxMessagingPlan);
return cloneSandboxMessagingPlan(
normalizePersistedSandboxMessagingPlanShape(value as unknown as MaybeCompactMessagingPlan),
);
}

export function cloneSandboxMessagingPlan(plan: SandboxMessagingPlan): SandboxMessagingPlan {
Expand Down Expand Up @@ -100,6 +103,28 @@ export function getMessagingChannelConfigFromPlan(
return Object.keys(config).length > 0 ? config : null;
}

type MaybeCompactMessagingChannelPlan = Omit<SandboxMessagingPlan["channels"][number], "hooks"> & {
readonly hooks?: SandboxMessagingPlan["channels"][number]["hooks"];
};

type MaybeCompactMessagingPlan = Omit<SandboxMessagingPlan, "agentRender" | "channels"> & {
readonly agentRender?: SandboxMessagingPlan["agentRender"];
readonly channels: readonly MaybeCompactMessagingChannelPlan[];
};

function normalizePersistedSandboxMessagingPlanShape(
plan: MaybeCompactMessagingPlan,
): SandboxMessagingPlan {
return {
...plan,
agentRender: Array.isArray(plan.agentRender) ? [...plan.agentRender] : [],
channels: plan.channels.map((channel) => ({
...channel,
hooks: Array.isArray(channel.hooks) ? [...channel.hooks] : [],
})),
};
}

function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
2 changes: 1 addition & 1 deletion src/lib/onboard/messaging-channel-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ export function writePlanToEnv(plan: SandboxMessagingPlan): void {
}

export function getRegistrySandboxMessagingPlan(sandboxName: string): SandboxMessagingPlan | null {
return registry.getSandbox(sandboxName)?.messaging?.plan ?? null;
return registry.getHydratedMessagingPlanFromEntry(registry.getSandbox(sandboxName));
}

function resolveMessagingSetupSandboxName(options: SetupSelectedMessagingChannelsOptions): string {
Expand Down
Loading
Loading