{"version":3,"file":"decide.mjs","names":[],"sources":["../../../../../../../ai/src/supervisor/decide.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport { END, type EndSentinel } from \"../contracts/end.type\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { IterationSnapshot } from \"../contracts/supervisor/iteration-snapshot.type\";\nimport type { Next } from \"../contracts/supervisor/next.type\";\nimport type { RouteContext } from \"../contracts/supervisor/route-context.type\";\nimport type { RouterEntry } from \"../contracts/supervisor/router-entry.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport { AIError, SupervisorFailedError, SupervisorRoutingError } from \"../errors\";\nimport type { ResolvedIntentEntry } from \"./entries\";\nimport { buildRouterContextMessage } from \"./router-prompt\";\n\n/**\n * Outcome of one dispatch decision — what the iteration loop needs to\n * act on. `kind: \"end\"` signals termination; `kind: \"dispatch\"` carries\n * the resolved intents (always an array; single-agent dispatch has\n * length 1). `source` records which path made the call so the\n * iteration snapshot can surface it to debuggers.\n */\nexport type DispatchDecision =\n  | {\n      kind: \"end\";\n      source: \"route\" | \"router\" | \"initialAgent\" | \"classifier\";\n      raw: Next;\n      reasoning?: string;\n      durationMs: number;\n      usage?: { input: number; output: number; total: number };\n      /** Full router-agent report when this decision came from a router. */\n      routerReport?: BaseReport;\n    }\n  | {\n      kind: \"dispatch\";\n      intents: string[];\n      source: \"route\" | \"router\" | \"initialAgent\" | \"classifier\";\n      raw: Next;\n      reasoning?: string;\n      durationMs: number;\n      usage?: { input: number; output: number; total: number };\n      /** Full router-agent report when this decision came from a router. */\n      routerReport?: BaseReport;\n    };\n\nexport type DecideParams = {\n  config: SupervisorConfig<unknown>;\n  entries: Map<string, ResolvedIntentEntry>;\n  iteration: number;\n  maxIterations: number;\n  iterations: IterationSnapshot[];\n  input: SupervisorInput;\n  /**\n   * Per-execute state accumulator at the start of this iteration.\n   * Threaded into `RouteContext` for the route callback and\n   * rendered into the router prompt so routing decisions can be\n   * state-aware (Q14).\n   */\n  state: Record<string, unknown>;\n  /**\n   * Frozen request-scoped bag from the `execute({ context })` call —\n   * surfaced on `RouteContext.context` for both `route` callbacks\n   * and `RouterEntry.placeholders` / `RouterEntry.input` resolvers.\n   */\n  context: Readonly<Record<string, unknown>>;\n  /**\n   * Frozen prior-conversation history from `execute({ history })` —\n   * surfaced on `RouteContext.history` and forwarded to the router\n   * agent as `agent.execute(input, { history })` so router decisions\n   * are conversation-aware.\n   */\n  history: ReadonlyArray<Message>;\n  /**\n   * Resolved natural-language objective from `SupervisorConfig.goal`\n   * (materialized to plain text at supervisor construction). Surfaced\n   * on `RouteContext.goal` for `route` / `RouterEntry` resolvers, and\n   * injected into the router agent's per-turn user message via\n   * `buildRouterContextMessage`. `undefined` when no goal was set.\n   */\n  goal: string | undefined;\n  evaluateFeedback?: RouteContext[\"evaluateFeedback\"];\n  /**\n   * Forensic record of the iter-0 classifier (Phase 7). Threaded into\n   * `RouteContext.classifier` so route callbacks and router-agent\n   * input composers can read the classification trail without\n   * re-parsing state.\n   */\n  classifier?: RouteContext[\"classifier\"];\n  signal?: AbortSignal;\n  /**\n   * Override for the very first iteration — when `initialAgent` is\n   * set, the first turn skips `route`/`router` and dispatches the\n   * named intent directly. `runIteration` passes `true` only on turn\n   * 0 when the config has `initialAgent`.\n   */\n  useInitialAgent?: boolean;\n};\n\n/**\n * Unified dispatch decision entry — calls either the `route` callback\n * or the `router` agent based on the supervisor's configured mode and\n * normalizes the result into a `DispatchDecision`. Runtime validates\n * every routing value against the configured agent keys; unknown keys\n * surface as `SupervisorRoutingError`.\n */\nexport async function decide(params: DecideParams): Promise<DispatchDecision> {\n  if (params.useInitialAgent && params.config.initialAgent) {\n    const intent = params.config.initialAgent;\n    validateKey(intent, params.entries);\n\n    return {\n      kind: \"dispatch\",\n      intents: [intent],\n      source: \"initialAgent\",\n      raw: intent,\n      durationMs: 0,\n    };\n  }\n\n  if (params.config.route) {\n    return decideViaCallback(params);\n  }\n\n  if (params.config.router) {\n    return decideViaRouter(params);\n  }\n\n  throw new SupervisorFailedError(\n    `ai.supervisor(\"${params.config.name}\"): neither \\`route\\` nor \\`router\\` is configured — factory validation should have prevented this`,\n    { context: { authoring: true } },\n  );\n}\n\nasync function decideViaCallback(params: DecideParams): Promise<DispatchDecision> {\n  const started = performance.now();\n  const ctx: RouteContext = {\n    iteration: params.iteration,\n    input: params.input,\n    state: params.state,\n    iterations: params.iterations,\n    feedback:\n      typeof params.evaluateFeedback?.feedback === \"string\"\n        ? params.evaluateFeedback.feedback\n        : undefined,\n    evaluateFeedback: params.evaluateFeedback,\n    context: params.context,\n    history: params.history,\n    goal: params.goal,\n    classifier: params.classifier,\n  };\n\n  let raw: Next;\n\n  try {\n    raw = await params.config.route!(ctx);\n  } catch (thrown) {\n    throw wrapRouteError(params.config.name, thrown);\n  }\n\n  const durationMs = performance.now() - started;\n\n  return normalize(raw, params.entries, \"route\", durationMs, resolveMaxFanOut(params.config));\n}\n\nasync function decideViaRouter(params: DecideParams): Promise<DispatchDecision> {\n  const { agent, placeholders, inputOverride, historySlicer } = resolveRouterEntry(\n    params.config.router!,\n  );\n  const started = performance.now();\n\n  const routeCtx: RouteContext = {\n    iteration: params.iteration,\n    input: params.input,\n    state: params.state,\n    iterations: params.iterations,\n    feedback:\n      typeof params.evaluateFeedback?.feedback === \"string\"\n        ? params.evaluateFeedback.feedback\n        : undefined,\n    evaluateFeedback: params.evaluateFeedback,\n    context: params.context,\n    history: params.history,\n    goal: params.goal,\n  };\n\n  const userMessage =\n    inputOverride?.(routeCtx) ??\n    buildRouterContextMessage({\n      entries: params.entries,\n      iteration: params.iteration,\n      maxIterations: params.maxIterations,\n      iterations: params.iterations,\n      input: params.input,\n      state: params.state,\n      feedback: routeCtx.feedback,\n      supervisorPrompt: resolveSupervisorPromptText(params.config),\n      goal: params.goal,\n    });\n\n  const resolvedPlaceholders = placeholders?.(routeCtx);\n\n  // Inject the canonical router output schema so the supervisor gets\n  // a predictable `{ next, reasoning? }` shape regardless of what the\n  // user scripted on the router agent. Lets the router stay a plain\n  // agent — no supervisor-specific config needed at construction.\n  const routerHistory = resolveRouterHistory(\n    historySlicer,\n    routeCtx,\n    params.history,\n    params.config.historyWindow?.router,\n  );\n\n  const routerResult = await agent.execute(userMessage, {\n    signal: params.signal,\n    output: ROUTER_OUTPUT_SCHEMA as unknown as StandardSchemaV1<{\n      next: Next;\n      reasoning?: string;\n    }>,\n    ...(resolvedPlaceholders ? { placeholders: resolvedPlaceholders } : {}),\n    ...(routerHistory.length > 0 ? { history: routerHistory } : {}),\n  });\n\n  const durationMs = performance.now() - started;\n\n  if (routerResult.error) {\n    throw routerResult.error instanceof AIError\n      ? routerResult.error\n      : new SupervisorFailedError(`router agent failed`, {\n          cause: routerResult.error,\n        });\n  }\n\n  const data = routerResult.data;\n\n  if (!data || typeof data !== \"object\") {\n    throw new SupervisorRoutingError(\n      `router agent returned no structured \\`next\\` — did its output schema include { next, reasoning? }?`,\n      { returned: data, availableKeys: [...params.entries.keys()] },\n    );\n  }\n\n  const rawNext = (data as { next?: unknown }).next;\n  const reasoning = (data as { reasoning?: unknown }).reasoning;\n\n  if (rawNext === undefined) {\n    throw new SupervisorRoutingError(`router agent output missing \\`next\\` field`, {\n      returned: data,\n      availableKeys: [...params.entries.keys()],\n    });\n  }\n\n  const decision = normalize(\n    rawNext as Next,\n    params.entries,\n    \"router\",\n    durationMs,\n    resolveMaxFanOut(params.config),\n  );\n\n  return {\n    ...decision,\n    reasoning: typeof reasoning === \"string\" ? reasoning : undefined,\n    usage: routerResult.usage,\n    routerReport: routerResult.report,\n  };\n}\n\n/**\n * Normalize the `router` config field — accepts either a bare\n * `AgentContract` (shorthand) or a full `RouterEntry` — into a\n * uniform `{ agent, placeholders?, inputOverride? }` triple. Centralized\n * so the dispatch path doesn't branch on shape.\n */\nfunction resolveRouterEntry(router: AgentContract<unknown> | RouterEntry): {\n  agent: AgentContract<unknown>;\n  placeholders?: RouterEntry[\"placeholders\"];\n  inputOverride?: RouterEntry[\"input\"];\n  historySlicer?: RouterEntry[\"history\"];\n} {\n  if (typeof (router as { execute?: unknown }).execute === \"function\") {\n    return { agent: router as AgentContract<unknown> };\n  }\n\n  const entry = router as RouterEntry;\n\n  return {\n    agent: entry.agent,\n    placeholders: entry.placeholders,\n    inputOverride: entry.input,\n    historySlicer: entry.history,\n  };\n}\n\n/**\n * Resolve the supervisor's own `systemPrompt` (string or contract)\n * into plain text. Returns `undefined` when the supervisor didn't\n * configure one. The resolved text is surfaced in the per-turn\n * router user message so the router sees team/domain context without\n * disturbing the router agent's own factory-level system prompt —\n * functionally equivalent to prepending, without requiring an API\n * expansion on `AgentContract` to read the router's system prompt.\n */\nfunction resolveSupervisorPromptText(config: SupervisorConfig<unknown>): string | undefined {\n  if (!config.systemPrompt) {\n    return undefined;\n  }\n\n  return typeof config.systemPrompt === \"string\"\n    ? config.systemPrompt\n    : config.systemPrompt.resolve();\n}\n\n/**\n * Convert the raw routing value (callback return OR router agent\n * `next` field) into a canonical `DispatchDecision`, validating every\n * named intent against the supervisor's `intents` map.\n */\nfunction normalize(\n  raw: Next,\n  entries: Map<string, ResolvedIntentEntry>,\n  source: \"route\" | \"router\",\n  durationMs: number,\n  maxFanOut: number,\n): DispatchDecision {\n  if (isEnd(raw)) {\n    return { kind: \"end\", source, raw, durationMs };\n  }\n\n  if (typeof raw === \"string\") {\n    validateKey(raw, entries);\n\n    return {\n      kind: \"dispatch\",\n      intents: [raw],\n      source,\n      raw,\n      durationMs,\n    };\n  }\n\n  if (Array.isArray(raw)) {\n    if (raw.length === 0) {\n      throw new SupervisorRoutingError(\n        `router returned an empty array — must be a non-empty list of agent intents`,\n        { returned: raw, availableKeys: [...entries.keys()] },\n      );\n    }\n\n    for (const intent of raw) {\n      if (typeof intent !== \"string\") {\n        throw new SupervisorRoutingError(`router returned a non-string inside its fan-out array`, {\n          returned: raw,\n          availableKeys: [...entries.keys()],\n        });\n      }\n\n      validateKey(intent, entries);\n    }\n\n    return {\n      kind: \"dispatch\",\n      intents: capFanOut(raw as string[], entries, maxFanOut),\n      source,\n      raw,\n      durationMs,\n    };\n  }\n\n  throw new SupervisorRoutingError(\n    `router returned an unsupported value — expected a string, string[], or END`,\n    { returned: raw, availableKeys: [...entries.keys()] },\n  );\n}\n\n/**\n * Default fan-out WIDTH ceiling — how many intents one dispatch\n * decision may run in parallel. `maxIterations` bounds depth; this\n * bounds width, so total work per run is bounded by the product\n * instead of by iterations alone.\n */\nexport const DEFAULT_MAX_FAN_OUT = 10;\n\n/**\n * Resolve the configured width ceiling. Factory validation\n * (`supervisor.ts`) rejects non-integer / `< 1` values at authoring\n * time, so this only has to apply the default.\n */\nexport function resolveMaxFanOut(config: Pick<SupervisorConfig<never>, \"maxFanOut\">): number {\n  return config.maxFanOut ?? DEFAULT_MAX_FAN_OUT;\n}\n\n/**\n * Dedupe + width-cap a fan-out intent list before it reaches\n * `Promise.all(...dispatchOne)`.\n *\n * Duplicates are collapsed silently: running the same intent twice in\n * one decision is pure wasted spend (branch results are indexed by\n * intent downstream, so the extras can't change the outcome), and a\n * router that repeats itself is sloppy rather than hostile.\n *\n * Exceeding the cap *after* dedupe THROWS rather than truncating.\n * Truncation would silently hand an attacker-chosen subset of the\n * decision to the executor and hide the anomaly from the operator;\n * every other routing violation in this file (unknown key, empty\n * array, non-string element) already fails loudly as\n * `SupervisorRoutingError`, so a width violation surfaces in the same\n * place, with the same code, carrying the offending array.\n *\n * Threat model: the router's prompt embeds supervisor `state` and\n * prior branch outputs, both of which can carry attacker-controlled\n * text from tool results. Without a width bound, one injected\n * \"always return this 200-element `next` array\" turns a single\n * iteration into 200 real agent/workflow executions — no unknown\n * intent name required, so the existing allowlist check never fires.\n */\nexport function capFanOut(\n  intents: string[],\n  entries: Map<string, ResolvedIntentEntry>,\n  maxFanOut: number,\n): string[] {\n  const unique = [...new Set(intents)];\n\n  if (unique.length > maxFanOut) {\n    throw new SupervisorRoutingError(\n      `routing decision fanned out to ${unique.length} intents — exceeds maxFanOut=${maxFanOut}. Raise \\`maxFanOut\\` if this width is intended.`,\n      { returned: intents, availableKeys: [...entries.keys()] },\n    );\n  }\n\n  return unique;\n}\n\nfunction validateKey(intent: string, entries: Map<string, ResolvedIntentEntry>): void {\n  if (!entries.has(intent)) {\n    throw new SupervisorRoutingError(`router returned unknown agent key \"${intent}\"`, {\n      returned: intent,\n      availableKeys: [...entries.keys()],\n    });\n  }\n}\n\nfunction isEnd(value: unknown): value is EndSentinel {\n  return value === END;\n}\n\n/**\n * Resolve the history slice forwarded to the router agent. Mirrors\n * `SupervisorExecution.resolveHistoryFor(\"router\", ...)` — duplicated\n * here so the standalone `decide()` function stays callable without\n * threading the execution instance through. Precedence is identical:\n * entry slicer > `historyWindow.router` > full history.\n */\nfunction resolveRouterHistory(\n  slicer: RouterEntry[\"history\"] | undefined,\n  routeCtx: RouteContext,\n  full: ReadonlyArray<Message>,\n  window: number | undefined,\n): Message[] {\n  if (slicer) {\n    const sliced = slicer(routeCtx);\n    return sliced ? [...sliced] : [];\n  }\n\n  if (window === undefined || window < 0) {\n    return [...full];\n  }\n\n  if (window === 0) {\n    return [];\n  }\n\n  return full.slice(-window);\n}\n\n/**\n * JSON Schema form of the canonical router output shape. Surfaced via\n * the Standard JSON Schema V1 extension path (`[\"~standard\"].jsonSchema.input`)\n * so `extractJsonSchema()` can pull it for native structured-output\n * enforcement on capable providers (OpenAI strict json_schema mode,\n * Anthropic tool-use shape, etc.). Without this, the model is told to\n * emit JSON only via soft system-prompt instruction — fragile, and\n * skipped entirely when the model advertises `structuredOutput: true`.\n *\n * `next` is intentionally `string` (not a union with arrays) because\n * OpenAI strict mode rejects polymorphic root types — fan-out via\n * `string[]` is still validated at the framework layer; the model\n * just emits a single intent name (or the END sentinel) and the\n * supervisor's own normalizer handles the rest.\n */\nconst ROUTER_OUTPUT_JSON_SCHEMA = {\n  type: \"object\",\n  properties: {\n    next: {\n      type: \"string\",\n      description: \"Name of the agent to dispatch next, or the END sentinel to terminate the run.\",\n    },\n    reasoning: {\n      type: \"string\",\n      description: \"One-sentence justification for the routing choice.\",\n    },\n  },\n  required: [\"next\", \"reasoning\"],\n  additionalProperties: false,\n};\n\n/**\n * Canonical Standard Schema the supervisor injects when calling the\n * router agent. Pragmatic — accepts any `next` shape the router can\n * plausibly emit (`string`, `string[]`, or the `END` literal) plus an\n * optional `reasoning` field. Rejects anything else so a broken\n * router output surfaces cleanly via the agent's own validation path.\n *\n * Exposes `[\"~standard\"].jsonSchema.input()` (Standard JSON Schema V1)\n * so capable providers enforce the shape natively rather than relying\n * on prompt-side coaching.\n */\nconst ROUTER_OUTPUT_SCHEMA: StandardSchemaV1<{\n  next: Next;\n  reasoning?: string;\n}> = {\n  \"~standard\": {\n    version: 1,\n    vendor: \"warlock-supervisor\",\n    jsonSchema: {\n      input: () => ROUTER_OUTPUT_JSON_SCHEMA,\n    },\n    validate(value: unknown): StandardSchemaV1.Result<{ next: Next; reasoning?: string }> {\n      if (!value || typeof value !== \"object\") {\n        return { issues: [{ message: \"router output must be an object\" }] };\n      }\n\n      const record = value as { next?: unknown; reasoning?: unknown };\n      const rawNext = record.next;\n\n      const nextIsValid =\n        typeof rawNext === \"string\" ||\n        (Array.isArray(rawNext) && rawNext.every((element) => typeof element === \"string\"));\n\n      if (!nextIsValid) {\n        return {\n          issues: [\n            {\n              message: \"router output `next` must be a string, string[], or the END sentinel\",\n            },\n          ],\n        };\n      }\n\n      const reasoning = typeof record.reasoning === \"string\" ? record.reasoning : undefined;\n\n      return {\n        value: { next: rawNext as Next, reasoning },\n      };\n    },\n  } as StandardSchemaV1<{ next: Next; reasoning?: string }>[\"~standard\"] & {\n    jsonSchema: { input: () => Record<string, unknown> };\n  },\n};\n\nfunction wrapRouteError(supervisorName: string, thrown: unknown): AIError {\n  if (thrown instanceof AIError) {\n    return thrown;\n  }\n\n  const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n  return new SupervisorFailedError(\n    `\\`route\\` callback threw in supervisor \"${supervisorName}\": ${message}`,\n    { cause: thrown },\n  );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAyGA,eAAsB,OAAO,QAAiD;CAC5E,IAAI,OAAO,mBAAmB,OAAO,OAAO,cAAc;EACxD,MAAM,SAAS,OAAO,OAAO;EAC7B,YAAY,QAAQ,OAAO,OAAO;EAElC,OAAO;GACL,MAAM;GACN,SAAS,CAAC,MAAM;GAChB,QAAQ;GACR,KAAK;GACL,YAAY;EACd;CACF;CAEA,IAAI,OAAO,OAAO,OAChB,OAAO,kBAAkB,MAAM;CAGjC,IAAI,OAAO,OAAO,QAChB,OAAO,gBAAgB,MAAM;CAG/B,MAAM,IAAI,sBACR,kBAAkB,OAAO,OAAO,KAAK,qGACrC,EAAE,SAAS,EAAE,WAAW,KAAK,EAAE,CACjC;AACF;AAEA,eAAe,kBAAkB,QAAiD;CAChF,MAAM,UAAU,YAAY,IAAI;CAChC,MAAM,MAAoB;EACxB,WAAW,OAAO;EAClB,OAAO,OAAO;EACd,OAAO,OAAO;EACd,YAAY,OAAO;EACnB,UACE,OAAO,OAAO,kBAAkB,aAAa,WACzC,OAAO,iBAAiB,WACxB;EACN,kBAAkB,OAAO;EACzB,SAAS,OAAO;EAChB,SAAS,OAAO;EAChB,MAAM,OAAO;EACb,YAAY,OAAO;CACrB;CAEA,IAAI;CAEJ,IAAI;EACF,MAAM,MAAM,OAAO,OAAO,MAAO,GAAG;CACtC,SAAS,QAAQ;EACf,MAAM,eAAe,OAAO,OAAO,MAAM,MAAM;CACjD;CAEA,MAAM,aAAa,YAAY,IAAI,IAAI;CAEvC,OAAO,UAAU,KAAK,OAAO,SAAS,SAAS,YAAY,iBAAiB,OAAO,MAAM,CAAC;AAC5F;AAEA,eAAe,gBAAgB,QAAiD;CAC9E,MAAM,EAAE,OAAO,cAAc,eAAe,kBAAkB,mBA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