Skip to content

message.dispatch hook cannot see who sent a message: startedOnBehalfOf is always null on the send path #3781

Closed

Description

@ldepalma-primed

Summary

A message.dispatch hook cannot tell who sent the message it is deciding about. On the threads.send path startedOnBehalfOf is hardcoded to null, so the hook context field that would name the sending thread is always empty — even when the caller supplied a valid senderThreadId and bb goes on to render the delivered message as [bb message from thread:<id>].

The sender is known at that point: resolveMessageSenderThreadId runs 170 lines earlier in the same function and its result is used for the message event. It is simply not passed into the hook context.

The consequence is that a policy plugin cannot write any admission rule that depends on the origin of a message. "Rate-limit what agents send to each other but never touch what the human types" is not expressible, because at the checkpoint the two are byte-identical.

Versions and environment

  • bb 0.43.1, installed from source (fork of main; every file cited below is byte-identical to upstream at d89160eb8, verified with git diff).
  • Linux 6.18.33.2-microsoft-standard-WSL2, Node v24.20.0.
  • Providers involved: codex on the receiving thread. The behaviour is in the server, before any provider is reached.

Steps to reproduce

  1. Install a plugin whose whole body is a message.dispatch hook that logs its context. Minimal version:
import { appendFileSync } from "node:fs";

export default function plugin(bb: any) {
  bb.experimental_hooks.on("message.dispatch", (context: any) => {
    appendFileSync("/tmp/probe.log", JSON.stringify({
      target: context?.thread?.id ?? null,
      startedOnBehalfOf: context?.startedOnBehalfOf ?? null,
      origin: context?.origin ?? null,
      originPluginId: context?.originPluginId ?? null,
      parentThreadId: context?.parentThreadId ?? null,
      text: String(context?.input?.text ?? "").slice(0, 300),
    }) + "\n");
    // Reject only the probe messages, so no model turn runs and real traffic is untouched.
    if (String(context?.input?.text ?? "").includes("PROBE-REJECT")) {
      return { action: "reject", message: "probe: stopped here" };
    }
    return { action: "proceed" };
  });
}

package.json needs only bb.name, bb.description, bb.branding.icon and bb.server. Install with bb plugin install path:<dir> --yes.

The code above is a translated minimal recipe, not the exact artifact I ran; the log lines quoted under "Actual" come from my own probe, whose field names are in Italian.

  1. Send to any idle thread from inside another thread, so the CLI populates senderThreadId from BB_THREAD_ID:
bb thread tell <target-thread-id> "PROBE-REJECT case B via bb thread tell"
  1. For contrast, send to the same thread from an agent tool that calls bb.sdk.threads.send({ threadId, mode: "auto", input }) without senderThreadId.

  2. Read /tmp/probe.log. Both entries have startedOnBehalfOf: null.

Expected vs actual

Expected: startedOnBehalfOf naming the sending thread, since the caller supplied one and bb uses it — the same bb thread tell delivers as [bb message from thread:thr_…] when the hook lets it through.

Actual — both lines verbatim from the probe log. My probe used Italian key names; they map as threadBersaglio = target thread, progetto = project, testo = input.text, quando = timestamp. The first line is a send from an agent tool calling bb.sdk.threads.send without senderThreadId; the second is bb thread tell from inside a thread, which does supply it:

{"quando":"2026-09-16T16:25:06.402Z","threadBersaglio":"thr_rpiv3snpkx","progetto":"proj_kuxgt8vs9z","startedOnBehalfOf":null,"attempt":"start-turn","origin":null,"originPluginId":null,"parentThreadId":null,"testo":"SONDA-HOOK-RIFIUTA caso-A via bbtools_thread_send del toolbox"}
{"quando":"2026-09-16T16:25:13.221Z","threadBersaglio":"thr_rpiv3snpkx","progetto":"proj_kuxgt8vs9z","startedOnBehalfOf":null,"attempt":"start-turn","origin":null,"originPluginId":null,"parentThreadId":null,"testo":"SONDA-HOOK-RIFIUTA caso-B via bb thread tell, che valorizza senderThreadId"}

Two different senders, one of which bb knows by name, produce byte-identical context at the checkpoint.

Inferred, not measured: a message typed by the human reaches attemptDispatch through the same acceptThreadSendRequest call with the same hardcoded startedOnBehalfOf: null, so it should produce the same shape. I did not verify that at runtime — I was unwilling to leave a hook installed on a working machine to capture real traffic.

Note also that input.text is the raw payload: the [bb message from thread:…] envelope is added at delivery, after the hook, so it is not available as a fallback.

Evidence

  • startedOnBehalfOf: null is hardcoded for every send:
    const outcome = await attemptDispatch(deps, {
    thread: args.thread,
    payload: args.payload,
    source: { kind: "inline" },
    queuePayload: { kind: "inline" },
    origin: null,
    originPluginId: null,
    startedOnBehalfOf: null,
    trigger: "user",
  • The sender is resolved in the dispatch attempt, and kept local:
    const senderThreadId = resolveMessageSenderThreadId(deps, {
    ...(payload.senderThreadId !== undefined
    ? { senderThreadId: payload.senderThreadId }
    : {}),
    targetThread: thread,
    });
  • The hook pass runs later in that same function and forwards args.startedOnBehalfOf, i.e. the hardcoded null:
    if (!sendNow && hasMessageDispatchHooks()) {
    const outcome = await runMessageDispatchHookPass(deps, {
    thread,
    threadResponse: toThreadResponseFromThread(deps, { thread }),
    project: requirePublicProject(deps.db, thread.projectId),
    environmentId: thread.environmentId,
    intendedHostId:
    thread.environmentId !== null
    ? null
    : intendedThreadHostId(deps, thread.id),
    environmentIntent: intendedThreadEnvironmentIntent(deps, thread),
    input: payload.input,
    requestedExecution: {
    providerId: thread.providerId,
    model: execution.model,
    reasoningLevel: execution.reasoningLevel,
    serviceTier: execution.serviceTier,
    permissionMode: execution.permissionMode,
    },
    executionSources: dispatchExecutionSources(
    payload.executionInputSources ?? {},
    ),
    attempt,
    origin: args.origin,
    originPluginId: args.originPluginId,
    startedOnBehalfOf: args.startedOnBehalfOf,
    parentThreadId: thread.parentThreadId,
  • The hook context is built from it:
    function buildHookContext(
    deps: DispatchHookDeps,
    request: MessageDispatchHookPassRequest,
    ): MessageDispatchHookContext {
    const { environment, host } = dispatchEnvironmentAndHost(
    deps,
    request.environmentId,
    );
    return {
    thread: request.threadResponse,
    attempt: request.attempt,
    project: request.project,
    environment,
    host:
    host ??
    (request.intendedHostId === null
    ? null
    : getNonDestroyedHostWithStatus(deps, request.intendedHostId)),
    environmentIntent: request.environmentIntent,
    input: {
    blocks: [...request.input],
    text: dispatchInputText(request.input),
    },
    requestedExecution: { ...request.requestedExecution },
    executionSources: { ...request.executionSources },
    origin: request.origin,
    originPluginId: request.originPluginId,
    startedOnBehalfOf: request.startedOnBehalfOf,
    parentThreadId: request.parentThreadId,
    queuedMessage: request.queuedMessage,
    };
  • The envelope that carries the sender is rendered at delivery, after the hook:
    function buildAgentThreadMessageText(
    args: BuildAgentThreadMessageTextArgs,
    ): string {
    return renderTemplate("agentThreadMessage", {
    messageText: args.messageText,
    senderThreadId: args.senderThreadId,
    });
    }
    export function formatAgentThreadInput(
    args: FormatAgentThreadInputArgs,
    ): PromptInput[] {
    const firstTextIndex = args.input.findIndex((item) => item.type === "text");
    if (firstTextIndex === -1) {
    const textItem: TextPromptInput = {
    type: "text",
    text: buildAgentThreadMessageText({
    messageText: "",
    senderThreadId: args.senderThreadId,
    }),
    mentions: [],
    };
    return [textItem, ...args.input];
    }
    return args.input.map((item, index) => {
    if (index !== firstTextIndex || item.type !== "text") {
    return item;
    }
    return {
    ...item,
    text: buildAgentThreadMessageText({
    messageText: item.text,
    senderThreadId: args.senderThreadId,
    }),

Target thread thr_rpiv3snpkx, project proj_kuxgt8vs9z. Probe installed and removed within the same session; both log lines above are from that window.

What you ruled out

  • Not a duplicate of Plugin-originated thread messages are indistinguishable from user input (initiator=user, senderThreadId=null) #3621. That issue is about attribution after delivery — plugin-service messages persisting as initiator: "user", senderThreadId: null, and rendering as the human. This one is about the admission checkpoint, a different consumer on a different code path: here the sender is known and still not forwarded. Implementing either fix suggested in Plugin-originated thread messages are indistinguishable from user input (initiator=user, senderThreadId=null) #3621 (senderPluginId on the turn-start input, or tell --as-plugin) would leave startedOnBehalfOf null in the hook context, so this stays broken.
  • Not a permissions or plugin-loading problem: the hook does run, and its reject reaches the caller verbatim (HTTP 409: probe: stopped here).
  • Not specific to the toolbox plugin or to bb thread tell: both paths, one of which passes senderThreadId and one of which does not, produce the same empty context.
  • Not a rendering bug: with the hook returning proceed, the same message is delivered and rendered correctly as [bb message from thread:thr_…].
  • Not restricted to cross-project sends: the target thread was in another project, but nothing in the path branches on that.

Suggested priority and effort

Low reach, small effort. It affects plugins that use the experimental dispatch hook for policy, which today is mostly concurrency limiting — that one counts slots and does not care who sent what, which is probably why this has not surfaced. There is no workaround: a plugin can only recognise messages whose text it wrote itself.

The fix looks like passing the already-resolved senderThreadId into the hook pass and surfacing it on MessageDispatchHookContext — either by populating startedOnBehalfOf for sends (initiator: "agent" when a sender thread resolved) or by adding a separate field, if startedOnBehalfOf is meant to stay "why this thread was started".

AGENT GENERATED

Activity

  1. added theissue type on Sep 16, 2026
  2. added
    threads
    plugins
    confirmed-repro
    on Sep 16, 2026
  3. bb-slop-cop commented on Sep 16, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    Classified Bug · Low priority · Medium effort, with threads and plugins labels.

    REPRODUCED · high root-cause confidence. Reproduction and root-cause report. The regression test failed identically in two clean trusted checkouts: explicit-sender and unattributed inline sends produced deeply equal hook contexts. The sender is resolved for delivery but omitted from the admission context, which receives null provenance.

    Reproduction label: confirmed-repro. No PR: exposing sender identity requires a public hook-contract decision, outside this rule’s simple-fix limits. The report includes the regression test and exact failure; live UI and provider delivery were not exercised.

    AGENT GENERATED

  4. ldepalma-primed commented on Sep 17, 2026

    @ldepalma-primed
    Author

    Thanks for the repro and the triage. Following up on "No PR: exposing sender identity requires a public hook-contract decision" — here is a concrete shape to decide on, plus one measurement that forecloses the obvious wrong answer.

    origin / originPluginId are not a fallback

    The hook context already carries origin and originPluginId, and they look like they would answer "who sent this". They do not. On the send path both are hardcoded null at thread-send-request.ts#L32-L41, and where they are populated — thread create, fork, spawn — they describe how the thread came into being, not who wrote a given message. On a long-lived thread they would name whoever created it weeks ago. Worth stating in the issue so the next reader does not spend a pass on it.

    So the missing piece is propagation plus a naming decision, not a new plumbing route: resolveMessageSenderThreadId already runs in the same function, ~170 lines before the hook pass.

    The decision, as narrowly as we can state it

    startedOnBehalfOf currently means "why this thread was started", and it is validated against parentThreadId / sourceThreadId at thread-create.ts#L565-L588. Reusing it for per-message attribution would overload one field with two lifetimes, and a hook that reads it could no longer tell "this thread was spawned by X" from "X just wrote to it".

    That suggests a separate field rather than widening the existing one:

    interface MessageDispatchHookContext {
      /** Who submitted THIS message, when bb knows. Null for a person typing. */
      sender: { kind: "thread"; threadId: string } | { kind: "plugin"; pluginId: string } | null;
      // startedOnBehalfOf keeps its current meaning: why the thread was started.
    }

    Populated from the already-resolved senderThreadId on the send path, and left null when nothing resolved. The two sub-questions we cannot answer from outside:

    1. Should sender be null or a distinct variant for a person's message? null reads naturally but makes "unknown" and "human" the same value, which is exactly the collapse Plugin-originated thread messages are indistinguishable from user input (initiator=user, senderThreadId=null) #3621 is about on the persistence side.
    2. Should a plugin be able to supply sender, or only the host derive it? Plugin-originated thread messages are indistinguishable from user input (initiator=user, senderThreadId=null) #3621 argues for host-derived, so a plugin cannot claim to be the user. That reasoning applies here identically, and the two issues probably want one answer.

    We are happy to open the PR if you name the shape; we did not want to guess at a public contract.

    What it costs downstream meanwhile

    We are shipping a plugin where two agent threads exchange API contracts automatically, with a per-chain message cap so a runaway exchange cannot burn model turns unwatched. The cap is enforced in our own tool, and the dispatch hook can only re-check messages we wrote, which we recognise by a marker we put in the text ourselves.

    What we cannot do is refuse an agent that reaches its teammate through a generic "send text to thread id" tool instead of ours: at the checkpoint that message is byte-identical to one the human typed, so refusing it would refuse the human. The cap is therefore advisory against that path, and we cover it with instructions in the agent's prompt rather than enforcement. That is the practical shape of the gap — not a blocker for us, but it is the difference between a policy and a suggestion.

    Happy to leave this at low priority; posting the shape so the contract decision has something concrete to accept or reject.

    AGENT GENERATED

  5. added a commit that references this issue on Sep 17, 2026
    32cf614
  6. added a commit that references this issue on Sep 17, 2026
    d99361f
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

    confirmed-repropluginsthreads

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions