Skip to content

Session context policy: let a plugin narrow what one agent session loads (BB plugins, skills, MCP, CLI plugins, instructions) — working prototype #4233

Description

@VKirill

The workflow

I run one bb with ~40 plugins, a few hundred skills, a dozen MCP servers and several CLI plugins, and use it for very different work: bb development, an agency of hidden worker threads (reviewer, executor, copywriter), SEO, client projects. Everything that is installed enters every agent session:

  • every BB plugin's instructions, dynamic tools, skills and provider env;
  • every provider-native skill, MCP server and CLI plugin (~/.claude.json, ~/.codex/config.toml, ~/.claude/plugins, ~/.agents/skills, …);
  • the project's CLAUDE.md / AGENTS.md chain and <dataDir>/AGENTS.md.

What I want is what Multica does per agent: 100 skills installed, three assigned to this agent/project. The same for MCP servers and plugins. The rules should be settable per project and per directory (section), and a hidden worker thread should be launchable bare, with only what its role needs.

This issue supersedes my two earlier requests, which describe halves of the same thing:

I have now built it as a working prototype on a fork and run it on my own server. This issue is the full description, so you can decide whether to adopt it (as experimental_* APIs) and in what shape.

What happens today

On bb 0.43.3 (desktop-v0.43.3, e865697f5):

  • bb.agents.configure() lets a plugin select its own tools and skills. A plugin cannot scope another plugin out; static contributeInstructions providers get only { threadId, projectId }.
  • bb plugin disable is app-wide.
  • Provider bridges start the CLI with the user's full native config. There is no per-session way to drop a native skill, MCP server or CLI plugin. Giving each session its own HOME / CLAUDE_CONFIG_DIR / CODEX_HOME breaks login and session resume.
  • Core stages one shared skills root per environment, so two threads in the same environment cannot see different BB skills.
  • A plugin that should be absent from a place still renders its composer UI there and still runs its message.dispatch hook.

What you would expect

One plugin-facing extension point: a session policy. A plugin answers, per thread, "what may this session load?" Core enforces the BB side, and each provider bridge enforces the CLI side with that CLI's own per-process switches. No separate home directories are used, so login and resume keep working.

The prototype: https://github.com/VKirill/bb/tree/vk/experimental. The full diff against desktop-v0.43.3 is here. There are 12 commits. Every change is marked VK EXPERIMENTAL, new names use a vk prefix, and the upstream files touched are listed in VK_PATCHES.md. A plugin author's guide (in Russian) is in VK_FUNCTIONS.md. The consumer is bb-plugin-project-folders, whose «Session context» tab edits rules per bb / project / section with inheritance. The vk prefix is only there to keep my patches apart from upstream when rebasing; upstream names would drop it.

Below is the integration guide: what each piece does, where it goes, and the code.


1. The policy shape — packages/domain

New file packages/domain/src/vk-session-policy.ts, exported as @bb/domain/vk-session-policy (package.json exports + export * in index.ts).

export const vkPolicyFilterSchema = z.object({
  mode: z.enum(["allow", "deny"]),
  names: z.array(z.string().trim().min(1).max(200)).max(500),
});

export const vkSessionPolicySchema = z.object({
  bbPlugins: vkPolicyFilterSchema.optional(),     // BB plugin ids
  skills: vkPolicyFilterSchema.optional(),        // skill names as invoked: "ru-text", "lane-stack:ru-text"
  mcpServers: vkPolicyFilterSchema.optional(),    // provider-native MCP server names
  nativePlugins: vkPolicyFilterSchema.optional(), // Claude "name@marketplace", Codex plugin ids
  userInstructions: z.boolean().optional(),       // <dataDir>/AGENTS.md
  projectInstructions: z.boolean().optional(),    // workspace .bb/AGENTS.md + the CLI's CLAUDE.md/AGENTS.md chain
  claudeAiSync: z.boolean().optional(),           // Claude Code skills/plugins synced from claude.ai
});

Semantics:

  • Every field is optional; a missing field means "load what bb loads today", so {} is a no-op. The policy only narrows and never adds anything.
  • Names match exactly, and a trailing * matches a prefix (lane-stack:*).
  • An item with several spellings (ru-text / plugin:ru-text) passes allow if any spelling is listed and is dropped by deny if any spelling is listed. This is vkPolicyAllows(filter, ...names).

The same file defines the runtime half that travels to a bridge:

export const VK_SESSION_POLICY_PROVIDER_OPTION = "vkSessionPolicy";

export const vkRuntimeSessionPolicySchema = z.object({
  version: z.literal(1),
  bbSkillsDenied: z.array(z.string()).optional(), // exact BB skill names, resolved by core
  skills: vkPolicyFilterSchema.optional(),        // native skills
  mcpServers: vkPolicyFilterSchema.optional(),
  nativePlugins: vkPolicyFilterSchema.optional(),
  projectInstructions: z.literal(false).optional(),
  claudeAiSync: z.literal(false).optional(),
});

export function readVkRuntimeSessionPolicy(providerOptions: unknown): VkRuntimeSessionPolicy | null;

It also defines VkContextContribution { pluginId, instructions, configure, tools[], skills[] } (section 3).

2. Plugin API: bb.agents.experimental_vkSessionPolicy(resolver)

SDK contract, packages/plugin-sdk/src/backend-contract.ts: optional members on PluginAgents plus type re-exports.

experimental_vkSessionPolicy?(
  resolver: (context: PluginAgentConfigurationContext)
    => VkSessionPolicy | null | Promise<VkSessionPolicy | null>,
): void;
experimental_vkContextContributions?(): VkContextContribution[];

Registration, apps/server/src/services/plugins/plugin-api.ts: store the resolver on the handle, next to agentConfigurationProvider. There is one resolver per factory execution; a second registration throws.

let vkSessionPolicyResolver: PluginVkSessionPolicyResolver | null = null;
const agents: PluginAgents = {
  experimental_vkSessionPolicy(resolver) {
    assertLive();
    if (vkSessionPolicyResolver !== null) throw new Error("session policy resolver is already registered");
    if (typeof resolver !== "function") throw new Error("experimental_vkSessionPolicy requires a resolver function");
    vkSessionPolicyResolver = resolver;
  },
  experimental_vkContextContributions() { assertLive(); return listPluginVkContextContributions(); },
  // ...configure, contributeInstructions, …
};
// handle: get vkSessionPolicyResolver() { return vkSessionPolicyResolver; }

Resolution, apps/server/src/services/plugins/plugin-service.ts resolveVkSessionPolicy:

  • Runs in the same context as configure, including the resolver's own thread metadata. This lets a plugin recognise the threads it spawned and their role.
  • Goes through invokeWrapped + raceTimeout(2 s) and validates with vkSessionPolicySchema.
  • The first non-null answer in plugin id order wins.
  • A throw, an invalid shape or a timeout is logged and treated as null, so the session opens as today (fails open).
async resolveVkSessionPolicy({ context }) {
  const resolvers = [...loaded.entries()].sort(([a], [b]) => a.localeCompare(b))
    .flatMap(([pluginId, p]) => p.handle.vkSessionPolicyResolver ? [{ pluginId, resolver: p.handle.vkSessionPolicyResolver }] : []);
  const metadataByPluginId = /* listThreadPluginMetadataRows(db, context.thread.id, resolver ids), as configure does */;
  for (const { pluginId, resolver } of resolvers) {
    const outcome = await invokeWrapped(pluginId, "vk session policy", async () =>
      raceTimeout(Promise.resolve(resolver({ ...context, pluginMetadata: deepFreezePluginMetadata(metadataByPluginId.get(pluginId) ?? {}) }))
        .then((v) => v == null ? null : vkSessionPolicySchema.parse(v)), 2_000, "timed out after 2000ms"));
    if (outcome.ok && outcome.value !== null) return { pluginId, policy: outcome.value };
  }
  return null;
}

It is exposed through plugin-agent-contributions.ts as resolvePluginVkSessionPolicy / listPluginVkContextContributions, the same indirection resolvePluginAgentConfiguration uses.

Design question for you: "first non-null wins" is simple but does not compose. A directory plugin (project-folders) and an agency plugin cannot both narrow the same thread. Combining answers (intersect allow, union deny, false wins for booleans) is a small change in this loop, and it fits the #3843 guardrail "results from several hooks are combined". I would prefer that upstream.

3. bb.agents.experimental_vkContextContributions()

In plugin-service.ts listVkContextContributions, for every loaded plugin:

  • instructions: whether instructionProvider is set;
  • configure: whether agentConfigurationProvider is set;
  • tools: the tool names from collectAgentTools();
  • skills: the skill folders under its skillsRootPaths.

A policy editor uses this to label each plugin in the list: "adds instructions · 5 tools · 3 skills", or "UI only". Without it a user cannot tell which plugins actually shape the session.

4. Core enforces the BB side — thread-runtime-config.ts

New file apps/server/src/services/threads/vk-session-policy.ts holds the helpers vkPluginAllowed, vkEnvPluginId, vkUserInstructionsAllowed, vkProjectInstructionsAllowed and buildVkRuntimeSessionPolicy.

In resolveThreadRuntimeCommandConfig, the configure context object is hoisted into agentContext and reused, so both calls see the same context:

const conditionalConfiguration = await resolvePluginAgentConfiguration({ context: agentContext, skillIdsByPlugin });
const vkResolved = await resolvePluginVkSessionPolicy({ context: agentContext });
const vkPolicy = vkResolved?.policy ?? null;

The policy is then applied at each existing contribution point. Built-in contributions have pluginId === null and always stay:

// provider env
(await resolvePluginProviderEnv(...)).filter((e) => vkPluginAllowed(vkPolicy, vkEnvPluginId(e)))
// dynamic tools (+ their tool-scoped instructions)
resolveDynamicTools(conditionalConfiguration.tools).filter((c) => vkPluginAllowed(vkPolicy, c.pluginId))
// static instructions
for (const c of listPluginInstructionContributions()) { if (!vkPluginAllowed(vkPolicy, c.pluginId)) continue; … }
// configure() dynamic instructions
for (const c of conditionalConfiguration.dynamicInstructions) { if (!vkPluginAllowed(vkPolicy, c.pluginId)) continue; … }
// <dataDir>/AGENTS.md and workspace .bb/AGENTS.md
if (dataDirAgentInstructions && vkUserInstructionsAllowed(vkPolicy)) …
if (workspaceAgentInstructions && vkProjectInstructionsAllowed(vkPolicy)) …

BB skills. The environment's shared skill catalog is not changed. Changing it would thrash the runtime whenever two threads with different policies share an environment. Instead, core resolves the catalog to exact names and sends them to the bridge:

const skillCatalog = resolveSkillCatalog(deps, { … });
const injectedSkillSources = skillCatalog.map((e) => e.runtimeSource);   // unchanged
const vkSessionPolicy = buildVkRuntimeSessionPolicy(vkPolicy, skillCatalog);
// bbSkillsDenied = catalog entries whose plugin fails bbPlugins or whose name fails skills

ResolvedThreadRuntimeCommandConfig gains vkSessionPolicy: VkRuntimeSessionPolicy | null. An info log line "VK session policy applied" records the thread, the plugin that supplied the policy and the count of denied skills.

5. Transport to the bridge — thread-commands.ts

In thread-commands.ts toRuntimeExecutionOptions, the policy is merged into the provider options for both thread.start and turn.submit:

const providerOptions = args.vkSessionPolicy
  ? { ...derivedProviderOptions, [VK_SESSION_POLICY_PROVIDER_OPTION]: args.vkSessionPolicy }
  : derivedProviderOptions;

Carrying it as an opaque provider option keeps the host-daemon untouched. Bridges ship to machines as artifacts, so no daemon protocol change is needed. A bridge that doesn't know the key ignores it.

Bridges get the helpers from @get-bb/plugin-sdk/provider-bridge: readVkRuntimeSessionPolicy, vkPolicyAllows, vkRuntimeSessionPolicySchema and vkFilterSkillRoot.

6. Shared bridge helper: a filtered twin of a skills root

New file packages/provider-bridge-protocol/src/bridge-kit/vk-skill-roots.ts, exported from bridge-kit/index.ts.

The shared root is replaced, per session, by a directory of symlinks to every skill except the denied ones. The twin is content-addressed by (root, denied names), so threads with the same policy share it. It is built in a staging dir and moved into place with an atomic rename, so concurrent builds are safe.

export function vkFilterSkillRoot(args: { cacheDir: string; deniedNames: ReadonlySet<string>; rootPath: string }): string

7. Per-CLI enforcement (no separate HOME)

CLI BB skills Native skills MCP servers CLI plugins Project instructions
Claude Code filtered twin in the skill plugin dir SDK skills allow list; deny → skillOverrides: off + disallowedTools: Skill(name) strictMcpConfig + configs copied from ~/.claude.json (user/local), <cwd>/.mcp.json, enabled Claude plugins' .mcp.json (with ${CLAUDE_PLUGIN_ROOT} and ${VAR:-default} expanded); deny → deniedMcpServers flag layer enabledPlugins: { id: false } flag layer claudeMdExcludes (folder, parents, subfolders; the user's ~/.claude stays)
Codex filtered twins in skills/extraRoots/set -c skills.config=[{path|name, enabled=false}]: recursive discovery, names from SKILL.md frontmatter -c mcp_servers.<n>.enabled=false -c plugins.<id>.enabled=false -c project_doc_max_bytes=0
OpenCode (ACP) filtered skill list OPENCODE_CONFIG_CONTENT → permission.skill OPENCODE_CONFIG_CONTENT → mcp.<n>.enabled=false — OPENCODE_DISABLE_PROJECT_CONFIG=1
Cursor (ACP) filtered skill list — (no switch in Cursor) a per-policy CURSOR_DATA_DIR overlay (~/.cursor/bb-vk-overlays/<hash>) with its own mcp-disabled.json; the real project data folder is symlinked, and acp-sessions stay in the config dir, so resume works — — (no switch)

claudeAiSync: false → Claude flag layer syncClaudeAiSkills: false, syncClaudeAiPlugins: false.

bb-bridge (bb's own MCP server, which carries plugin tools) is always kept.

Claude Code — plugins/provider-claude-code

  • New file src/bridge/vk-session-policy.ts. buildClaudeVkSessionOptions({ bbSkillNames, cwd, policy }) reads the native inventory and returns { disallowedTools, flagSettings, mcpServers, skills, strictMcpConfig }. The inventory covers MCP by scope, plugin MCP, enabled plugins, and personal/project/plugin skills.
  • commands.ts: vkSessionPolicy: vkRuntimeSessionPolicySchema.optional() in claudeThreadStartParamsSchema.
  • session-params.ts: vkSessionPolicy: readVkRuntimeSessionPolicy(args.options.providerOptions), passed into the internal session params.
  • session-options.ts buildSessionOptions: merges vk.flagSettings under buildFlagSettings(params), appends vk.disallowedTools, and sets mcpServers, vkStrictMcpConfig, vkSkills and vkFlagSettings.
  • sdk-session.ts: passes strictMcpConfig / skills to query(). In applyFlagSettings it keeps vkFlagSettings underneath, because the flag layer is replaced wholesale on a model/effort change.
  • bridge.ts:
    • skills/configure also keeps the raw roots;
    • vkSkillRootsFor(providerOptions) builds filtered twins when bbSkillsDenied is non-empty;
    • attachThreadSession merges bb-bridge into sessionOptions.mcpServers instead of replacing them;
    • toSessionConstructionConfig includes the policy, so a policy change rebuilds the session.

Codex — plugins/provider-codex

  • New file src/bridge/vk-session-policy.ts, with buildCodexVkLaunchArgs({ cwd, policy }) → ["-c", "…", …].
  • bridge.ts:
    • spawnChildConnection takes vkLaunchArgs and appends them to this child's args only;
    • each session stores vkBbSkillsDenied, and vkSessionSkillExtraRoots() swaps extra roots for filtered twins in initializeChild and handleSkillsConfigure;
    • constructionSignature includes the policy, so a change rebuilds the child.
  • Pitfalls found live:
    • an -c mcp_servers.X.enabled=false for a server that is not in config.toml makes codex app-server fail with Error: bootstrap, so only servers listed there are disabled;
    • Codex splits override keys on . without honouring TOML quotes, so ids containing . are skipped;
    • plugin skill names differ from folder names, so names come from SKILL.md frontmatter.

ACP (OpenCode, Cursor) — packages/provider-bridge-acp

  • New file src/vk-session-policy.ts: vkFilterAcpSkillRoots, buildAcpVkEnv (OpenCode) and buildCursorVkEnv.
  • bridge/bridge.ts:
    • vkSessionEnv() computes the env from the dialect. When the registration omits the dialect, it resolves it from the launch command.
    • The env is used both at session start and in turn/start's env comparison. Otherwise the first turn rebuilds the session without the policy env; this bug was found live.
  • cursor-mcp-approval.ts: exports cursorProjectSlug / cursorDataDirectory for the overlay.

8. An excluded plugin is absent from the place, not only from the session

When a place's policy drops a plugin, that plugin's composer UI and its dispatch hook should also disappear there. Otherwise the UI offers a mode (for example Agency's "delegate" toggle) whose instructions and tools the session no longer has.

  • Server, new file vk-excluded-plugins.ts. resolveVkExcludedPluginIds(db, place) builds the configure context from a thread, or from project + host + environment/path before a thread exists, then resolves the policy. The plugin that supplied the policy is never excluded.
  • Route, routes/plugins.ts: GET /api/v1/plugins/vk-excluded-plugins?threadId=… or ?projectId=…&hostId=…&environmentId=…&path=… → { ok: true, pluginIds: [...] }, behind localAuthProblem.
  • Dispatch, dispatch-hooks.ts runMessageDispatchHookPass: resolves the excluded set before the evaluation lock, skips those plugins' hooks, and drops their experimental_submission.
  • App, new hook hooks/queries/vk-excluded-plugins-queries.ts. It uses a small cache over useSyncExternalStore with 15 s freshness. It deliberately avoids react-query, because composer slots also render in trees without a QueryClientProvider. A 404 on a stock server means nothing is excluded.
  • composer-slot-hooks.ts useResolvedComposerSlot: filters registrations by the excluded set. The place comes from vkPlaceOf(host): an explicit host.vkPlace, else the thread / side-chat / new-thread scope.
  • plugin-composer-host.tsx: optional vkPlace?: VkComposerPlace on PluginComposerHost.
  • NewThreadComposer.tsx: vkPlace = { projectId, hostId, environmentId, path }. The path comes from the submission's provider inputs or, while the seed stands, from environmentSeed.providerInputs, because providers without an inputs form (project checkout) drop the seed's inputs from the submission.

9. Tests

In the fork:

  • packages/domain/test/vk-session-policy.test.ts: filter semantics and runtime parsing.
  • apps/server/test/services/plugins/plugin-vk-session-policy.test.ts: first valid answer in id order, invalid answers skipped, null when no plugin registers, double registration rejected, thread metadata passed to the resolver, context contributions.
  • apps/server/test/threads/vk-session-policy.test.ts:
    • denied plugins' tools, instructions and env are dropped, as are user and project instructions;
    • BB skills are resolved to exact denied names while injectedSkillSources stays unchanged;
    • with no policy nothing changes;
    • excluded plugin ids per thread and per project, never the policy owner.
  • Bridge tests: provider-claude-code/src/bridge/vk-session-policy.test.ts, provider-codex/src/bridge/vk-session-policy.test.ts and provider-bridge-acp/src/vk-session-policy.test.ts.
  • apps/app/src/components/plugin/vk-composer-exclusion.test.tsx.
  • plugin-agent-tools.test.ts: bb.agents key list updated. The bb-guide API index docs list the new exports.

10. Live verification

The prototype has run on my server since 2026-09-24 (runtime 0.43.3-vk.*, hub on Linux, hosts on macOS). Each group was checked in real threads by asking the agent what it has and by inspecting the CLI's actual arguments, env and config, not only with unit tests:

  • Claude Code, Codex, OpenCode: native skills, MCP servers and CLI plugins narrowed in allow and deny modes.
  • Cursor: BB side and MCP servers via the overlay; resume keeps working.
  • BB plugins in allow mode (only env-catalog): other plugins' tools and instructions are gone, and 27 plugin skills are removed.
  • Claude plugin MCP servers (by full plugin:<p>:<server> name).
  • Provider env: an excluded plugin's contributeProviderEnv no longer reaches the CLI.
  • projectInstructions: false and claudeAiSync: false.
  • Composer: with agency excluded in a section, its toggle is gone in that section's new-thread composer and in its threads, and still present elsewhere.

Context and alternatives

  • Separate HOME / CLAUDE_CONFIG_DIR / CODEX_HOME per session (Multica does a per-task CODEX_HOME with auth.json symlinked). It breaks login and resume in bb's model, where sessions are long-lived. Per-process switches achieve the same narrowing without that.
  • Each plugin self-gates in configure(). This only works for plugins you control, and not for provider-native config.
  • A thread-create allowlist. Fixed at creation, and it doesn't cover threads started from the normal composer.
  • Known limits:
    • Cursor has no switch for its own skills or project rules;
    • bb-bridge always stays;
    • a policy change applies when the provider session is next constructed (the bridges include it in the construction signature, so the next turn rebuilds);
    • first-non-null does not compose (see the design question in section 2).

I'm happy to turn this into PRs split by layer if you want it: domain + plugin API + core first, then one PR per bridge, then composer/dispatch exclusion. I'd adjust names and the composition rule to your preference.

AGENT GENERATED

Activity

  1. added
    plugins
    providers
    on Sep 26, 2026
  2. bb-slop-cop commented on Sep 26, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    Classification: Feature · Priority Medium · Effort High · Labels plugins, providers.

    No pull request: this feature needs product and architecture decisions across the plugin API and provider bridges.

  3. barhaughogda commented on Sep 26, 2026

    @barhaughogda

    Another use case for this, from a team-of-agents plugin (teammates as BB conversations: a chief of staff, developers, a reviewer, a marketer...).

    We'd like access to be locked per teammate (per agent session), not only guided by instructions:

    • A marketer session can post to the company's social accounts (an MCP server or a browser profile with its logins); the developer and reviewer sessions must not see that server or those logins at all.
    • A reviewer should get read-only tools, and no deploy or publish tools.

    Today bb.agents.configure() lets us choose only our own plugin's tools and skills for a session. That covers role skills, and we ship a small reviewed kit per role that way. But we can't take another plugin, a user MCP server or a native CLI plugin out of one session and leave it in another.

    What we'd need is roughly your proposal: a per-session policy from configure() (or a sibling hook) that can allow or deny other BB plugins, MCP servers and native skills by name, applied when the provider session starts and kept on resume. If it can only allow-list, that's fine for us.

  4. VKirill commented on Sep 26, 2026

    @VKirill
    Author

    @barhaughogda thanks, that's exactly the case I built this for.

    I've implemented it on a fork and run it daily on my own bb server (Claude Code, Codex, OpenCode, Cursor):

    • Fork: https://github.com/VKirill/bb/tree/vk/experimental — the README covers what it adds, how to install it next to an official bb, how to rebase it onto new upstream tags and how to roll back.
    • API: bb.agents.experimental_vkSessionPolicy(resolver). The resolver gets the same context as configure() and returns allow/deny filters for other BB plugins, skills (BB and native), provider MCP servers and CLI plugins, plus switches for project/user instructions. It's resolved on thread.start and turn.submit, so it applies again on resume. A plugin the policy leaves out also loses its composer UI and dispatch hooks at that place.

    Your "team of agents" case maps onto it directly. I'm building an Agency plugin that does the same thing (departments, employees such as a marketer, developers and a reviewer, jobs and acceptance). It's still in development: https://github.com/VKirill/bb-plugin-agency. Each employee's allowed skills, MCP servers and plugins are frozen in the launch snapshot and applied through that policy. So the marketer's session gets the social MCP server, the reviewer's doesn't, and a reused reviewer thread keeps its original policy when it resumes.

    Two limits you'd run into: policies from different plugins aren't merged (the first non-null answer in plugin id order wins, so answer only for your own threads), and Cursor can't filter native skills. Details are in the fork README and VK_FUNCTIONS.md.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    pluginsproviders

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions