@warlock.js/ai 4.5.0 → 4.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/cjs/index.cjs +20 -1
- package/cjs/{src-DFibP2FQ.cjs → src-Bmajk4Qg.cjs} +1 -1
- package/cjs/{src-C02yzsLs.cjs → src-OZyDYHxm.cjs} +2789 -691
- package/cjs/src-OZyDYHxm.cjs.map +1 -0
- package/esm/agent/agent-config.type.d.mts +29 -0
- package/esm/agent/agent-config.type.d.mts.map +1 -1
- package/esm/agent/agent.d.mts.map +1 -1
- package/esm/agent/agent.mjs +126 -7
- package/esm/agent/agent.mjs.map +1 -1
- package/esm/agent/signature.mjs +57 -0
- package/esm/agent/signature.mjs.map +1 -0
- package/esm/agent/snapshot.mjs +101 -0
- package/esm/agent/snapshot.mjs.map +1 -0
- package/esm/ai-openai/src/image.mjs +5 -0
- package/esm/ai-openai/src/index.mjs +3 -0
- package/esm/ai-openai/src/sdk.mjs +3 -0
- package/esm/ai-openai/src/speech.mjs +5 -0
- package/esm/ai-openai/src/transcription.mjs +6 -0
- package/esm/ai-openai/src/utils/index.mjs +1 -0
- package/esm/ai-openai/src/utils/to-openai-messages.mjs +3 -0
- package/esm/ai.d.mts +45 -0
- package/esm/ai.d.mts.map +1 -1
- package/esm/ai.mjs +37 -1
- package/esm/ai.mjs.map +1 -1
- package/esm/contracts/agent/agent-options.type.d.mts +22 -2
- package/esm/contracts/agent/agent-options.type.d.mts.map +1 -1
- package/esm/contracts/agent/agent-snapshot.type.d.mts +90 -0
- package/esm/contracts/agent/agent-snapshot.type.d.mts.map +1 -0
- package/esm/contracts/agent/agent.contract.d.mts +29 -1
- package/esm/contracts/agent/agent.contract.d.mts.map +1 -1
- package/esm/contracts/agent/index.d.mts +2 -1
- package/esm/contracts/image-model.contract.d.mts +156 -0
- package/esm/contracts/image-model.contract.d.mts.map +1 -0
- package/esm/contracts/index.d.mts +8 -3
- package/esm/contracts/planner/index.d.mts +3 -2
- package/esm/contracts/planner/planner-config.type.d.mts +30 -0
- package/esm/contracts/planner/planner-config.type.d.mts.map +1 -1
- package/esm/contracts/planner/planner-execute-options.type.d.mts +13 -1
- package/esm/contracts/planner/planner-execute-options.type.d.mts.map +1 -1
- package/esm/contracts/planner/planner-snapshot.type.d.mts +77 -0
- package/esm/contracts/planner/planner-snapshot.type.d.mts.map +1 -0
- package/esm/contracts/planner/planner.contract.d.mts +21 -1
- package/esm/contracts/planner/planner.contract.d.mts.map +1 -1
- package/esm/contracts/result/base-report.type.d.mts +1 -1
- package/esm/contracts/result/base-report.type.d.mts.map +1 -1
- package/esm/contracts/result/base-report.type.mjs.map +1 -1
- package/esm/contracts/sdk-adapter.contract.d.mts +37 -0
- package/esm/contracts/sdk-adapter.contract.d.mts.map +1 -1
- package/esm/contracts/speech-model.contract.d.mts +97 -0
- package/esm/contracts/speech-model.contract.d.mts.map +1 -0
- package/esm/contracts/transcription-model.contract.d.mts +101 -0
- package/esm/contracts/transcription-model.contract.d.mts.map +1 -0
- package/esm/errors/agent-drift-error.d.mts +32 -0
- package/esm/errors/agent-drift-error.d.mts.map +1 -0
- package/esm/errors/agent-drift-error.mjs +31 -0
- package/esm/errors/agent-drift-error.mjs.map +1 -0
- package/esm/errors/error-code.type.d.mts +1 -1
- package/esm/errors/index.d.mts +2 -0
- package/esm/errors/index.mjs +2 -0
- package/esm/errors/planner-drift-error.d.mts +34 -0
- package/esm/errors/planner-drift-error.d.mts.map +1 -0
- package/esm/errors/planner-drift-error.mjs +33 -0
- package/esm/errors/planner-drift-error.mjs.map +1 -0
- package/esm/image/image-cost.d.mts +32 -0
- package/esm/image/image-cost.d.mts.map +1 -0
- package/esm/image/image-cost.mjs +55 -0
- package/esm/image/image-cost.mjs.map +1 -0
- package/esm/image/image.d.mts +92 -0
- package/esm/image/image.d.mts.map +1 -0
- package/esm/image/image.mjs +113 -0
- package/esm/image/image.mjs.map +1 -0
- package/esm/image/index.mjs +4 -0
- package/esm/index.d.mts +26 -4
- package/esm/index.mjs +20 -1
- package/esm/mock/index.d.mts +3 -0
- package/esm/mock/index.mjs +3 -0
- package/esm/mock/mock-config.type.d.mts +22 -0
- package/esm/mock/mock-config.type.d.mts.map +1 -1
- package/esm/mock/mock-image-model.d.mts +41 -0
- package/esm/mock/mock-image-model.d.mts.map +1 -0
- package/esm/mock/mock-image-model.mjs +52 -0
- package/esm/mock/mock-image-model.mjs.map +1 -0
- package/esm/mock/mock-sdk.d.mts +7 -1
- package/esm/mock/mock-sdk.d.mts.map +1 -1
- package/esm/mock/mock-sdk.mjs +27 -0
- package/esm/mock/mock-sdk.mjs.map +1 -1
- package/esm/mock/mock-speech-model.d.mts +31 -0
- package/esm/mock/mock-speech-model.d.mts.map +1 -0
- package/esm/mock/mock-speech-model.mjs +39 -0
- package/esm/mock/mock-speech-model.mjs.map +1 -0
- package/esm/mock/mock-transcription-model.d.mts +32 -0
- package/esm/mock/mock-transcription-model.d.mts.map +1 -0
- package/esm/mock/mock-transcription-model.mjs +36 -0
- package/esm/mock/mock-transcription-model.mjs.map +1 -0
- package/esm/planner/planner-run.d.mts +8 -0
- package/esm/planner/planner-run.d.mts.map +1 -1
- package/esm/planner/planner-run.mjs +161 -6
- package/esm/planner/planner-run.mjs.map +1 -1
- package/esm/planner/planner.d.mts.map +1 -1
- package/esm/planner/planner.mjs +25 -1
- package/esm/planner/planner.mjs.map +1 -1
- package/esm/planner/snapshot.mjs +95 -0
- package/esm/planner/snapshot.mjs.map +1 -0
- package/esm/rag/index.d.mts +7 -0
- package/esm/rag/index.mjs +7 -0
- package/esm/rag/loaders/errors.d.mts +19 -0
- package/esm/rag/loaders/errors.d.mts.map +1 -0
- package/esm/rag/loaders/errors.mjs +25 -0
- package/esm/rag/loaders/errors.mjs.map +1 -0
- package/esm/rag/loaders/index.mjs +7 -0
- package/esm/rag/loaders/load-html.d.mts +26 -0
- package/esm/rag/loaders/load-html.d.mts.map +1 -0
- package/esm/rag/loaders/load-html.mjs +138 -0
- package/esm/rag/loaders/load-html.mjs.map +1 -0
- package/esm/rag/loaders/load-pdf.d.mts +38 -0
- package/esm/rag/loaders/load-pdf.d.mts.map +1 -0
- package/esm/rag/loaders/load-pdf.mjs +150 -0
- package/esm/rag/loaders/load-pdf.mjs.map +1 -0
- package/esm/rag/loaders/load-text.d.mts +47 -0
- package/esm/rag/loaders/load-text.d.mts.map +1 -0
- package/esm/rag/loaders/load-text.mjs +60 -0
- package/esm/rag/loaders/load-text.mjs.map +1 -0
- package/esm/rag/loaders/load-web.d.mts +42 -0
- package/esm/rag/loaders/load-web.d.mts.map +1 -0
- package/esm/rag/loaders/load-web.mjs +89 -0
- package/esm/rag/loaders/load-web.mjs.map +1 -0
- package/esm/rag/loaders/loader.type.d.mts +89 -0
- package/esm/rag/loaders/loader.type.d.mts.map +1 -0
- package/esm/rag/store/pg-vector-store.d.mts +139 -0
- package/esm/rag/store/pg-vector-store.d.mts.map +1 -0
- package/esm/rag/store/pg-vector-store.mjs +328 -0
- package/esm/rag/store/pg-vector-store.mjs.map +1 -0
- package/esm/speech/index.mjs +3 -0
- package/esm/speech/speech.d.mts +65 -0
- package/esm/speech/speech.d.mts.map +1 -0
- package/esm/speech/speech.mjs +123 -0
- package/esm/speech/speech.mjs.map +1 -0
- package/esm/supervisor/entries.mjs +2 -2
- package/esm/supervisor/entries.mjs.map +1 -1
- package/esm/transcribe/audio-input.d.mts +47 -0
- package/esm/transcribe/audio-input.d.mts.map +1 -0
- package/esm/transcribe/audio-input.mjs +84 -0
- package/esm/transcribe/audio-input.mjs.map +1 -0
- package/esm/transcribe/index.mjs +4 -0
- package/esm/transcribe/transcribe.d.mts +64 -0
- package/esm/transcribe/transcribe.d.mts.map +1 -0
- package/esm/transcribe/transcribe.mjs +128 -0
- package/esm/transcribe/transcribe.mjs.map +1 -0
- package/llms-full.txt +753 -0
- package/llms.txt +5 -0
- package/package.json +3 -3
- package/skills/README.md +4 -0
- package/skills/durable-agent-runs/SKILL.md +135 -0
- package/skills/generate-images/SKILL.md +138 -0
- package/skills/generate-speech/SKILL.md +139 -0
- package/skills/rag-loaders-and-stores/SKILL.md +164 -0
- package/skills/transcribe-audio/SKILL.md +157 -0
- package/cjs/src-C02yzsLs.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entries.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/supervisor/entries.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 type { EndSentinel } from \"../contracts/end.type\";\nimport type { AgentResult } from \"../contracts/result/agent-result.type\";\nimport type { WorkflowResult } from \"../contracts/result/workflow-result.type\";\nimport type { DispatchContext } from \"../contracts/supervisor/dispatch-context.type\";\nimport type {\n DispatchRawResult,\n IntentCallback,\n IntentEntry,\n IntentRunEntry,\n SupervisorIntentValue,\n} from \"../contracts/supervisor/intent-entry.type\";\nimport type { RouteContext } from \"../contracts/supervisor/route-context.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { WorkflowInstance } from \"../contracts/workflow/workflow.contract\";\nimport { SupervisorFailedError } from \"../errors\";\n\n/**\n * Normalized internal representation of one entry in a supervisor's\n * `intents` map — resolved at factory time from one of the accepted\n * value forms (bare agent / workflow / callback / object entry).\n *\n * Carrying the explicit `type` discriminator keeps downstream code\n * (execution, signature, router-prompt) from having to re-detect\n * shape on every dispatch. The discriminated union below replaces\n * the flat-shape used in Phase 3 so callbacks can carry their own\n * function reference + dispatch-context-shaped resolvers.\n *\n * Discriminator renamed `kind` → `type` (Q12) for codebase-wide\n * consistency — every other discriminated result/report shape uses\n * `type`.\n */\nexport type ResolvedIntentEntry =\n | ResolvedAgentEntry\n | ResolvedWorkflowEntry\n | ResolvedCallbackEntry;\n\n/**\n * Successor directive function type — the resolver-time projection of\n * `IntentEntry.next` / `IntentRunEntry.next`. Single source of truth\n * across the three resolved variants.\n */\nexport type IntentNext = (ctx: DispatchContext) => string | string[] | EndSentinel | undefined;\n\n/**\n * Resolver-time projection of `IntentEntry.history` /\n * `RouterEntry.history` / `AckEntry.history`. Custom slicer that\n * REPLACES the default `historyWindow.<role>` slice.\n */\nexport type EntryHistorySlicer = (ctx: RouteContext) => Message[] | ReadonlyArray<Message>;\n\nexport type ResolvedAgentEntry = {\n intent: string;\n type: \"agent\";\n unit: AgentContract<unknown>;\n description: string;\n input?: (ctx: RouteContext) => string;\n /**\n * Per-dispatch placeholder values for the agent's systemPrompt\n * template. Forwarded as `agent.execute(input, { placeholders })`.\n * Phase 3.4 (Stage 4b) — replaces the dropped `composeAgentInput`\n * mechanism for threading state into agents.\n */\n placeholders?: (ctx: DispatchContext) => Record<string, unknown>;\n /**\n * Schema declaring this intent's slice of supervisor state. Agent\n * output is strip-merged against it; only validated keys appear on\n * `IterationSnapshot.result[intent].output` AND merge into\n * supervisor `state`.\n */\n output?: StandardSchemaV1<unknown>;\n /**\n * Successor directive (Stage 4d / Q24). When present, runs after\n * this branch's slice merges into state to choose the next dispatch\n * (or terminate) without invoking the router.\n */\n next?: IntentNext;\n /**\n * Custom history slicer — replaces the default\n * `historyWindow.agents` slice when supplied. See `IntentEntry.history`.\n */\n history?: EntryHistorySlicer;\n /**\n * Phase 5 / decisions §34. `\"stream\"` runs the agent without\n * structured-output coercion and writes the assembled prose into\n * `state[streamTo]`; `\"structured\"` is the default. Resolved at\n * factory time — `undefined` here is treated as `\"structured\"`.\n */\n mode?: \"structured\" | \"stream\";\n /** State key the assembled stream-mode prose writes into. Set iff `mode === \"stream\"`. */\n streamTo?: string;\n};\n\nexport type ResolvedWorkflowEntry = {\n intent: string;\n type: \"workflow\";\n unit: WorkflowInstance<unknown, unknown>;\n description: string;\n input?: (ctx: RouteContext) => string;\n placeholders?: (ctx: DispatchContext) => Record<string, unknown>;\n output?: StandardSchemaV1<unknown>;\n next?: IntentNext;\n history?: EntryHistorySlicer;\n};\n\nexport type ResolvedCallbackEntry = {\n intent: string;\n type: \"callback\";\n /**\n * The callback that actually runs at dispatch time. Always present\n * regardless of whether the user passed bare-function shorthand or\n * the `{ run, ... }` entry form.\n */\n callback: IntentCallback;\n /**\n * Description is required only when the supervisor uses a router.\n * Callback intents under a router are validated separately\n * (see {@link assertRouterDescriptions}); under deterministic\n * `route` mode this field is `undefined`.\n */\n description?: string;\n /**\n * Per-intent input resolver. Receives the upcoming\n * `DispatchContext` and returns the value forwarded as\n * `ctx.input` to the callback.\n */\n input?: (ctx: DispatchContext) => unknown;\n placeholders?: (ctx: DispatchContext) => Record<string, unknown>;\n /**\n * Schema declaring this callback's slice of state. Without it, the\n * full return value shallow-merges; with it, return is strip-merged\n * to declared keys before merging.\n */\n output?: StandardSchemaV1<unknown>;\n next?: IntentNext;\n};\n\n/**\n * Validate and normalize the `intents` map into resolved entries.\n * Runs at factory time — throws `SupervisorFailedError` on the first\n * malformed entry so author-time bugs surface immediately rather\n * than mid-run.\n *\n * Validation rules:\n * - Every value must be an agent, a workflow, a callback function,\n * or an object entry with `agent` / `workflow` / `run`.\n * - Object entries with more than one of `{ agent, workflow, run }`\n * throw with code `SUPERVISOR_INTENT_MIXED_DISPATCH`.\n * - Agent / workflow / agent-shaped entries must resolve to a\n * non-empty description from the underlying unit or the entry's\n * `description` override. Bare callback shorthand has no\n * description source — that's enforced separately by\n * {@link assertRouterDescriptions} when a router is configured.\n */\nexport function resolveIntentEntries(\n rawIntents: Record<string, SupervisorIntentValue>,\n supervisorName: string,\n): Map<string, ResolvedIntentEntry> {\n const entries = Object.entries(rawIntents);\n\n if (entries.length === 0) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): \\`intents\\` must contain at least one entry`,\n { context: { authoring: true } },\n );\n }\n\n const resolved = new Map<string, ResolvedIntentEntry>();\n\n for (const [intent, value] of entries) {\n if (!intent || typeof intent !== \"string\") {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): every \\`intents\\` key must be a non-empty string`,\n { context: { authoring: true } },\n );\n }\n\n resolved.set(intent, resolveOne(intent, value, supervisorName));\n }\n\n return resolved;\n}\n\n/**\n * Construction-time guard: when the supervisor is configured with a\n * `router`, every intent must resolve to a non-empty description so\n * the router LLM has a signal for picking it. Bare callback\n * shorthand and `IntentRunEntry` without `description` fail this\n * check; agents and workflows whose underlying primitive lacks a\n * description fail too — same uniform error message.\n *\n * Deterministic `route` callers skip this check entirely.\n */\nexport function assertRouterDescriptions(\n config: SupervisorConfig<unknown>,\n entries: Map<string, ResolvedIntentEntry>,\n): void {\n if (!config.router) {\n return;\n }\n\n for (const [intent, entry] of entries) {\n const description = entry.type === \"callback\" ? entry.description : entry.description;\n\n if (description && description.trim().length > 0) {\n continue;\n }\n\n const fix =\n entry.type === \"callback\"\n ? \"upgrade the bare callback to `{ run, description }`\"\n : \"set `description` on the agent/workflow or via the `IntentEntry` `description` override\";\n\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): intents[\"${intent}\"] needs a description because a \\`router\\` is configured — ${fix}`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_DESCRIPTION_REQUIRED\",\n );\n }\n}\n\nfunction resolveOne(\n intent: string,\n value: SupervisorIntentValue,\n supervisorName: string,\n): ResolvedIntentEntry {\n // (c) Bare callback shorthand — typeof function. Highest priority\n // so a user passing `(ctx) => …` never accidentally matches the\n // object-shape branches below.\n if (typeof value === \"function\") {\n return {\n intent,\n type: \"callback\",\n callback: value as IntentCallback,\n description: undefined,\n };\n }\n\n if (!value || typeof value !== \"object\") {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] is not an agent, workflow, callback, or entry object`,\n { context: { authoring: true, intent } },\n );\n }\n\n // Detect mixed-dispatch entries up front. Two of `{ agent, workflow,\n // run }` together is dev confusion, not a feature.\n assertSingleDispatchField(intent, value, supervisorName);\n\n // (d.run) Run-entry — `{ run, description?, input?, output? }`.\n if (\"run\" in value && typeof (value as IntentRunEntry).run === \"function\") {\n const entry = value as IntentRunEntry;\n\n return {\n intent,\n type: \"callback\",\n callback: entry.run,\n description: entry.description,\n input: entry.input,\n placeholders: entry.placeholders,\n output: entry.output,\n next: entry.next,\n };\n }\n\n // (d.agent / a / b) Agent-entry or bare unit. The existing\n // `IntentEntry` shape uses `agent: AgentContract | WorkflowInstance`\n // for both agent and workflow object entries; the resolver still\n // dispatches the underlying unit kind correctly.\n const entryForm = asAgentEntryForm(value);\n const unit = entryForm\n ? entryForm.agent\n : (value as AgentContract<unknown> | WorkflowInstance<unknown, unknown>);\n\n if (!isDispatchableUnit(unit)) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] must be an AgentContract, WorkflowInstance, callback, or entry object`,\n { context: { authoring: true, intent } },\n );\n }\n\n const detectedType = detectType(unit);\n const description = resolveAgentLikeDescription(intent, entryForm, unit, supervisorName);\n\n if (detectedType === \"workflow\") {\n if (entryForm?.mode === \"stream\") {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] sets \\`mode: \"stream\"\\` on a workflow entry — stream mode is agent-only in v1. Wrap the workflow in an agent or remove the \\`mode\\` field.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_STREAM_ON_WORKFLOW\",\n );\n }\n\n return {\n intent,\n type: \"workflow\",\n unit: unit as WorkflowInstance<unknown, unknown>,\n description,\n input: entryForm?.input,\n placeholders: entryForm?.placeholders,\n output: entryForm?.output,\n next: entryForm?.next,\n history: entryForm?.history,\n };\n }\n\n assertStreamModeShape(intent, entryForm, supervisorName);\n\n return {\n intent,\n type: \"agent\",\n unit: unit as AgentContract<unknown>,\n description,\n input: entryForm?.input,\n placeholders: entryForm?.placeholders,\n output: entryForm?.output,\n next: entryForm?.next,\n history: entryForm?.history,\n mode: entryForm?.mode,\n streamTo: entryForm?.streamTo,\n };\n}\n\n/**\n * Phase 5 / decisions §34 — enforce the two stream-mode invariants at\n * construction time:\n *\n * 1. `mode: \"stream\"` and per-intent `output` are mutually exclusive.\n * Stream agents declare their state contribution via `streamTo`,\n * not via a schema; allowing both would silently pick one and\n * surprise the author.\n * 2. `streamTo` is required when `mode === \"stream\"`. A stream agent\n * that doesn't write somewhere is a black box — fail loud at the\n * factory rather than at run-time when state validation surfaces a\n * missing key.\n */\nfunction assertStreamModeShape(\n intent: string,\n entryForm: IntentEntry | undefined,\n supervisorName: string,\n): void {\n if (!entryForm || entryForm.mode !== \"stream\") {\n return;\n }\n\n if (entryForm.output) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] sets both \\`mode: \"stream\"\\` and \\`output\\` — stream mode declares its slice via \\`streamTo\\`, not a schema. Drop one.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_STREAM_AND_OUTPUT\",\n );\n }\n\n if (typeof entryForm.streamTo !== \"string\" || entryForm.streamTo.trim().length === 0) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] sets \\`mode: \"stream\"\\` without a non-empty \\`streamTo\\` — a stream agent must name the state key its assembled prose writes into.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_STREAM_TO_REQUIRED\",\n );\n }\n}\n\n/**\n * Reject entries that mix dispatch fields. `{ agent, run }` is a\n * common copy-paste bug; we surface it at construction with a clear\n * message rather than silently picking one based on resolution\n * order.\n */\nfunction assertSingleDispatchField(intent: string, value: object, supervisorName: string): void {\n const dispatchKeys = ([\"run\", \"agent\", \"workflow\"] as const).filter((key) => key in value);\n\n if (dispatchKeys.length > 1) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] has multiple dispatch fields (${dispatchKeys\n .map((key) => `\\`${key}\\``)\n .join(\n \", \",\n )}) — pick one. Two dispatch fields on the same entry is dev confusion, not a feature.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_MIXED_DISPATCH\",\n );\n }\n}\n\n/**\n * Coerce a `SupervisorIntentValue` into the agent-flavored\n * `IntentEntry` form when the caller passed the object form. Returns\n * `undefined` for bare shorthand. The shape check keys on the\n * presence of an `agent` property because both `AgentContract` and\n * `WorkflowInstance` have their own identifying fields\n * (`isAnonymous` for agents, `signature` for workflows) but neither\n * carries a top-level `agent`.\n */\nfunction asAgentEntryForm(value: object): IntentEntry | undefined {\n if (!(\"agent\" in value)) {\n return undefined;\n }\n\n const candidate = (value as { agent: unknown }).agent;\n\n if (!candidate || typeof candidate !== \"object\") {\n return undefined;\n }\n\n return value as IntentEntry;\n}\n\nfunction isDispatchableUnit(\n value: unknown,\n): value is AgentContract<unknown> | WorkflowInstance<unknown, unknown> {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n\n const candidate = value as { name?: unknown; execute?: unknown };\n\n return typeof candidate.name === \"string\" && typeof candidate.execute === \"function\";\n}\n\nfunction detectType(\n unit: AgentContract<unknown> | WorkflowInstance<unknown, unknown>,\n): \"agent\" | \"workflow\" {\n // Workflows expose a structural `signature` field; agents don't.\n if (typeof (unit as WorkflowInstance<unknown, unknown>).signature === \"string\") {\n return \"workflow\";\n }\n\n return \"agent\";\n}\n\nfunction resolveAgentLikeDescription(\n intent: string,\n entryForm: IntentEntry | undefined,\n unit: AgentContract<unknown> | WorkflowInstance<unknown, unknown>,\n supervisorName: string,\n): string {\n const entryOverride = entryForm?.description;\n\n if (entryOverride && entryOverride.trim().length > 0) {\n return entryOverride;\n }\n\n const unitDescription = (unit as { description?: unknown }).description;\n\n if (typeof unitDescription === \"string\" && unitDescription.trim().length > 0) {\n return unitDescription;\n }\n\n // Empty string sentinel — caller (assertRouterDescriptions) decides\n // whether a missing description is fatal. Under deterministic\n // `route` mode it isn't.\n return \"\";\n}\n\n/**\n * Type guard helper for downstream modules. Narrows a raw\n * `AgentResult | WorkflowResult` based on the resolved entry's kind,\n * so transformers and emitters can pull the right fields without\n * re-checking shape.\n */\nexport function isAgentResult(raw: DispatchRawResult): raw is AgentResult<unknown> {\n return raw.type === \"agent\";\n}\n\nexport function isWorkflowResult(raw: DispatchRawResult): raw is WorkflowResult<unknown> {\n return raw.type === \"workflow\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4JA,SAAgB,qBACd,YACA,gBACkC;CAClC,MAAM,UAAU,OAAO,QAAQ,UAAU;CAEzC,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,sBACR,kBAAkB,eAAe,kDACjC,EAAE,SAAS,EAAE,WAAW,KAAK,EAAE,CACjC;CAGF,MAAM,2BAAW,IAAI,IAAiC;CAEtD,KAAK,MAAM,CAAC,QAAQ,UAAU,SAAS;EACrC,IAAI,CAAC,UAAU,OAAO,WAAW,UAC/B,MAAM,IAAI,sBACR,kBAAkB,eAAe,uDACjC,EAAE,SAAS,EAAE,WAAW,KAAK,EAAE,CACjC;EAGF,SAAS,IAAI,QAAQ,WAAW,QAAQ,OAAO,cAAc,CAAC;CAChE;CAEA,OAAO;AACT;;;;;;;;;;;AAYA,SAAgB,yBACd,QACA,SACM;CACN,IAAI,CAAC,OAAO,QACV;CAGF,KAAK,MAAM,CAAC,QAAQ,UAAU,SAAS;EACrC,MAAM,cAAc,MAAM,SAAS,aAAa,MAAM,cAAc,MAAM;EAE1E,IAAI,eAAe,YAAY,KAAK,CAAC,CAAC,SAAS,GAC7C;EAGF,MAAM,MACJ,MAAM,SAAS,aACX,wDACA;EAEN,MAAM,IAAI,sBACR,kBAAkB,OAAO,KAAK,eAAe,OAAO,8DAA8D,OAClH,EAAE,SAAS;GAAE,WAAW;GAAM;EAAO,EAAE,GACvC,wCACF;CACF;AACF;AAEA,SAAS,WACP,QACA,OACA,gBACqB;CAIrB,IAAI,OAAO,UAAU,YACnB,OAAO;EACL;EACA,MAAM;EACN,UAAU;EACV,aAAa;CACf;CAGF,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B,MAAM,IAAI,sBACR,kBAAkB,eA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gBAAgB,KAAK,CAAC,CAAC,SAAS,GACzE,OAAO;CAMT,OAAO;AACT;;;;;;;AAQA,SAAgB,cAAc,KAAqD;CACjF,OAAO,IAAI,SAAS;AACtB;AAEA,SAAgB,iBAAiB,KAAwD;CACvF,OAAO,IAAI,SAAS;AACtB"}
|
|
1
|
+
{"version":3,"file":"entries.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/supervisor/entries.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 type { EndSentinel } from \"../contracts/end.type\";\nimport type { AgentResult } from \"../contracts/result/agent-result.type\";\nimport type { WorkflowResult } from \"../contracts/result/workflow-result.type\";\nimport type { DispatchContext } from \"../contracts/supervisor/dispatch-context.type\";\nimport type {\n DispatchRawResult,\n IntentCallback,\n IntentEntry,\n IntentRunEntry,\n SupervisorIntentValue,\n} from \"../contracts/supervisor/intent-entry.type\";\nimport type { RouteContext } from \"../contracts/supervisor/route-context.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { WorkflowInstance } from \"../contracts/workflow/workflow.contract\";\nimport { SupervisorFailedError } from \"../errors\";\n\n/**\n * Normalized internal representation of one entry in a supervisor's\n * `intents` map — resolved at factory time from one of the accepted\n * value forms (bare agent / workflow / callback / object entry).\n *\n * Carrying the explicit `type` discriminator keeps downstream code\n * (execution, signature, router-prompt) from having to re-detect\n * shape on every dispatch. The discriminated union below replaces\n * the flat-shape used in Phase 3 so callbacks can carry their own\n * function reference + dispatch-context-shaped resolvers.\n *\n * Discriminator renamed `kind` → `type` (Q12) for codebase-wide\n * consistency — every other discriminated result/report shape uses\n * `type`.\n */\nexport type ResolvedIntentEntry =\n | ResolvedAgentEntry\n | ResolvedWorkflowEntry\n | ResolvedCallbackEntry;\n\n/**\n * Successor directive function type — the resolver-time projection of\n * `IntentEntry.next` / `IntentRunEntry.next`. Single source of truth\n * across the three resolved variants.\n */\nexport type IntentNext = (ctx: DispatchContext) => string | string[] | EndSentinel | undefined;\n\n/**\n * Resolver-time projection of `IntentEntry.history` /\n * `RouterEntry.history` / `AckEntry.history`. Custom slicer that\n * REPLACES the default `historyWindow.<role>` slice.\n */\nexport type EntryHistorySlicer = (ctx: RouteContext) => Message[] | ReadonlyArray<Message>;\n\nexport type ResolvedAgentEntry = {\n intent: string;\n type: \"agent\";\n unit: AgentContract<unknown>;\n description: string;\n input?: (ctx: RouteContext) => string;\n /**\n * Per-dispatch placeholder values for the agent's systemPrompt\n * template. Forwarded as `agent.execute(input, { placeholders })`.\n * Phase 3.4 (Stage 4b) — replaces the dropped `composeAgentInput`\n * mechanism for threading state into agents.\n */\n placeholders?: (ctx: DispatchContext) => Record<string, unknown>;\n /**\n * Schema declaring this intent's slice of supervisor state. Agent\n * output is strip-merged against it; only validated keys appear on\n * `IterationSnapshot.result[intent].output` AND merge into\n * supervisor `state`.\n */\n output?: StandardSchemaV1<unknown>;\n /**\n * Successor directive (Stage 4d / Q24). When present, runs after\n * this branch's slice merges into state to choose the next dispatch\n * (or terminate) without invoking the router.\n */\n next?: IntentNext;\n /**\n * Custom history slicer — replaces the default\n * `historyWindow.agents` slice when supplied. See `IntentEntry.history`.\n */\n history?: EntryHistorySlicer;\n /**\n * Phase 5 / decisions §34. `\"stream\"` runs the agent without\n * structured-output coercion and writes the assembled prose into\n * `state[streamTo]`; `\"structured\"` is the default. Resolved at\n * factory time — `undefined` here is treated as `\"structured\"`.\n */\n mode?: \"structured\" | \"stream\";\n /** State key the assembled stream-mode prose writes into. Set iff `mode === \"stream\"`. */\n streamTo?: string;\n};\n\nexport type ResolvedWorkflowEntry = {\n intent: string;\n type: \"workflow\";\n unit: WorkflowInstance<unknown, unknown>;\n description: string;\n input?: (ctx: RouteContext) => string;\n placeholders?: (ctx: DispatchContext) => Record<string, unknown>;\n output?: StandardSchemaV1<unknown>;\n next?: IntentNext;\n history?: EntryHistorySlicer;\n};\n\nexport type ResolvedCallbackEntry = {\n intent: string;\n type: \"callback\";\n /**\n * The callback that actually runs at dispatch time. Always present\n * regardless of whether the user passed bare-function shorthand or\n * the `{ run, ... }` entry form.\n */\n callback: IntentCallback;\n /**\n * Description is required only when the supervisor uses a router.\n * Callback intents under a router are validated separately\n * (see {@link assertRouterDescriptions}); under deterministic\n * `route` mode this field is `undefined`.\n */\n description?: string;\n /**\n * Per-intent input resolver. Receives the upcoming\n * `DispatchContext` and returns the value forwarded as\n * `ctx.input` to the callback.\n */\n input?: (ctx: DispatchContext) => unknown;\n placeholders?: (ctx: DispatchContext) => Record<string, unknown>;\n /**\n * Schema declaring this callback's slice of state. Without it, the\n * full return value shallow-merges; with it, return is strip-merged\n * to declared keys before merging.\n */\n output?: StandardSchemaV1<unknown>;\n next?: IntentNext;\n};\n\n/**\n * Validate and normalize the `intents` map into resolved entries.\n * Runs at factory time — throws `SupervisorFailedError` on the first\n * malformed entry so author-time bugs surface immediately rather\n * than mid-run.\n *\n * Validation rules:\n * - Every value must be an agent, a workflow, a callback function,\n * or an object entry with `agent` / `workflow` / `run`.\n * - Object entries with more than one of `{ agent, workflow, run }`\n * throw with code `SUPERVISOR_INTENT_MIXED_DISPATCH`.\n * - Agent / workflow / agent-shaped entries must resolve to a\n * non-empty description from the underlying unit or the entry's\n * `description` override. Bare callback shorthand has no\n * description source — that's enforced separately by\n * {@link assertRouterDescriptions} when a router is configured.\n */\nexport function resolveIntentEntries(\n rawIntents: Record<string, SupervisorIntentValue>,\n supervisorName: string,\n): Map<string, ResolvedIntentEntry> {\n const entries = Object.entries(rawIntents);\n\n if (entries.length === 0) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): \\`intents\\` must contain at least one entry`,\n { context: { authoring: true } },\n );\n }\n\n const resolved = new Map<string, ResolvedIntentEntry>();\n\n for (const [intent, value] of entries) {\n if (!intent || typeof intent !== \"string\") {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): every \\`intents\\` key must be a non-empty string`,\n { context: { authoring: true } },\n );\n }\n\n resolved.set(intent, resolveOne(intent, value, supervisorName));\n }\n\n return resolved;\n}\n\n/**\n * Construction-time guard: when the supervisor is configured with a\n * `router`, every intent must resolve to a non-empty description so\n * the router LLM has a signal for picking it. Bare callback\n * shorthand and `IntentRunEntry` without `description` fail this\n * check; agents and workflows whose underlying primitive lacks a\n * description fail too — same uniform error message.\n *\n * Deterministic `route` callers skip this check entirely.\n */\nexport function assertRouterDescriptions(\n config: SupervisorConfig<unknown>,\n entries: Map<string, ResolvedIntentEntry>,\n): void {\n if (!config.router) {\n return;\n }\n\n for (const [intent, entry] of entries) {\n const description = entry.type === \"callback\" ? entry.description : entry.description;\n\n if (description && description.trim().length > 0) {\n continue;\n }\n\n const fix =\n entry.type === \"callback\"\n ? \"upgrade the bare callback to `{ run, description }`\"\n : \"set `description` on the agent/workflow or via the `IntentEntry` `description` override\";\n\n throw new SupervisorFailedError(\n `ai.supervisor(\"${config.name}\"): intents[\"${intent}\"] needs a description because a \\`router\\` is configured — ${fix}`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_DESCRIPTION_REQUIRED\",\n );\n }\n}\n\nfunction resolveOne(\n intent: string,\n value: SupervisorIntentValue,\n supervisorName: string,\n): ResolvedIntentEntry {\n // (c) Bare callback shorthand — typeof function. Highest priority\n // so a user passing `(ctx) => …` never accidentally matches the\n // object-shape branches below.\n if (typeof value === \"function\") {\n return {\n intent,\n type: \"callback\",\n callback: value as IntentCallback,\n description: undefined,\n };\n }\n\n if (!value || typeof value !== \"object\") {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] is not an agent, workflow, callback, or entry object`,\n { context: { authoring: true, intent } },\n );\n }\n\n // Detect mixed-dispatch entries up front. Two of `{ agent, workflow,\n // run }` together is dev confusion, not a feature.\n assertSingleDispatchField(intent, value, supervisorName);\n\n // (d.run) Run-entry — `{ run, description?, input?, output? }`.\n if (\"run\" in value && typeof (value as IntentRunEntry).run === \"function\") {\n const entry = value as IntentRunEntry;\n\n return {\n intent,\n type: \"callback\",\n callback: entry.run,\n description: entry.description,\n input: entry.input,\n placeholders: entry.placeholders,\n output: entry.output,\n next: entry.next,\n };\n }\n\n // (d.agent / a / b) Agent-entry or bare unit. The existing\n // `IntentEntry` shape uses `agent: AgentContract | WorkflowInstance`\n // for both agent and workflow object entries; the resolver still\n // dispatches the underlying unit kind correctly.\n const entryForm = asAgentEntryForm(value);\n const unit = entryForm\n ? entryForm.agent\n : (value as AgentContract<unknown> | WorkflowInstance<unknown, unknown>);\n\n if (!isDispatchableUnit(unit)) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] must be an AgentContract, WorkflowInstance, callback, or entry object`,\n { context: { authoring: true, intent } },\n );\n }\n\n const detectedType = detectType(unit);\n const description = resolveAgentLikeDescription(intent, entryForm, unit, supervisorName);\n\n if (detectedType === \"workflow\") {\n if (entryForm?.mode === \"stream\") {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] sets \\`mode: \"stream\"\\` on a workflow entry — stream mode is agent-only in v1. Wrap the workflow in an agent or remove the \\`mode\\` field.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_STREAM_ON_WORKFLOW\",\n );\n }\n\n return {\n intent,\n type: \"workflow\",\n unit: unit as WorkflowInstance<unknown, unknown>,\n description,\n input: entryForm?.input,\n placeholders: entryForm?.placeholders,\n output: entryForm?.output,\n next: entryForm?.next,\n history: entryForm?.history,\n };\n }\n\n assertStreamModeShape(intent, entryForm, supervisorName);\n\n return {\n intent,\n type: \"agent\",\n unit: unit as AgentContract<unknown>,\n description,\n input: entryForm?.input,\n placeholders: entryForm?.placeholders,\n output: entryForm?.output,\n next: entryForm?.next,\n history: entryForm?.history,\n mode: entryForm?.mode,\n streamTo: entryForm?.streamTo,\n };\n}\n\n/**\n * Phase 5 / decisions §34 — enforce the two stream-mode invariants at\n * construction time:\n *\n * 1. `mode: \"stream\"` and per-intent `output` are mutually exclusive.\n * Stream agents declare their state contribution via `streamTo`,\n * not via a schema; allowing both would silently pick one and\n * surprise the author.\n * 2. `streamTo` is required when `mode === \"stream\"`. A stream agent\n * that doesn't write somewhere is a black box — fail loud at the\n * factory rather than at run-time when state validation surfaces a\n * missing key.\n */\nfunction assertStreamModeShape(\n intent: string,\n entryForm: IntentEntry | undefined,\n supervisorName: string,\n): void {\n if (!entryForm || entryForm.mode !== \"stream\") {\n return;\n }\n\n if (entryForm.output) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] sets both \\`mode: \"stream\"\\` and \\`output\\` — stream mode declares its slice via \\`streamTo\\`, not a schema. Drop one.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_STREAM_AND_OUTPUT\",\n );\n }\n\n if (typeof entryForm.streamTo !== \"string\" || entryForm.streamTo.trim().length === 0) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] sets \\`mode: \"stream\"\\` without a non-empty \\`streamTo\\` — a stream agent must name the state key its assembled prose writes into.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_STREAM_TO_REQUIRED\",\n );\n }\n}\n\n/**\n * Reject entries that mix dispatch fields. `{ agent, run }` is a\n * common copy-paste bug; we surface it at construction with a clear\n * message rather than silently picking one based on resolution\n * order.\n */\nfunction assertSingleDispatchField(intent: string, value: object, supervisorName: string): void {\n const dispatchKeys = ([\"run\", \"agent\", \"workflow\"] as const).filter((key) => key in value);\n\n if (dispatchKeys.length > 1) {\n throw new SupervisorFailedError(\n `ai.supervisor(\"${supervisorName}\"): intents[\"${intent}\"] has multiple dispatch fields (${dispatchKeys\n .map((key) => `\\`${key}\\``)\n .join(\n \", \",\n )}) — pick one. Two dispatch fields on the same entry is dev confusion, not a feature.`,\n { context: { authoring: true, intent } },\n \"SUPERVISOR_INTENT_MIXED_DISPATCH\",\n );\n }\n}\n\n/**\n * Coerce a `SupervisorIntentValue` into the agent-flavored\n * `IntentEntry` form when the caller passed the object form. Returns\n * `undefined` for bare shorthand. The shape check keys on the\n * presence of an `agent` property because both `AgentContract` and\n * `WorkflowInstance` have their own identifying fields\n * (`isAnonymous` for agents, `signature` for workflows) but neither\n * carries a top-level `agent`.\n */\nfunction asAgentEntryForm(value: object): IntentEntry | undefined {\n if (!(\"agent\" in value)) {\n return undefined;\n }\n\n const candidate = (value as { agent: unknown }).agent;\n\n if (!candidate || typeof candidate !== \"object\") {\n return undefined;\n }\n\n return value as IntentEntry;\n}\n\nfunction isDispatchableUnit(\n value: unknown,\n): value is AgentContract<unknown> | WorkflowInstance<unknown, unknown> {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n\n const candidate = value as { name?: unknown; execute?: unknown };\n\n return typeof candidate.name === \"string\" && typeof candidate.execute === \"function\";\n}\n\nfunction detectType(\n unit: AgentContract<unknown> | WorkflowInstance<unknown, unknown>,\n): \"agent\" | \"workflow\" {\n // Both agents and workflows now expose a structural `signature` (the\n // drift fingerprint durable resume added to the agent), so `signature`\n // no longer distinguishes them. Agents expose a token-`stream()` method;\n // workflows do not (workflow streaming is step-level, not a `.stream`\n // API) — use that as the positive agent marker.\n if (typeof (unit as AgentContract<unknown>).stream === \"function\") {\n return \"agent\";\n }\n\n return \"workflow\";\n}\n\nfunction resolveAgentLikeDescription(\n intent: string,\n entryForm: IntentEntry | undefined,\n unit: AgentContract<unknown> | WorkflowInstance<unknown, unknown>,\n supervisorName: string,\n): string {\n const entryOverride = entryForm?.description;\n\n if (entryOverride && entryOverride.trim().length > 0) {\n return entryOverride;\n }\n\n const unitDescription = (unit as { description?: unknown }).description;\n\n if (typeof unitDescription === \"string\" && unitDescription.trim().length > 0) {\n return unitDescription;\n }\n\n // Empty string sentinel — caller (assertRouterDescriptions) decides\n // whether a missing description is fatal. Under deterministic\n // `route` mode it isn't.\n return \"\";\n}\n\n/**\n * Type guard helper for downstream modules. Narrows a raw\n * `AgentResult | WorkflowResult` based on the resolved entry's kind,\n * so transformers and emitters can pull the right fields without\n * re-checking shape.\n */\nexport function isAgentResult(raw: DispatchRawResult): raw is AgentResult<unknown> {\n return raw.type === \"agent\";\n}\n\nexport function isWorkflowResult(raw: DispatchRawResult): raw is WorkflowResult<unknown> {\n return raw.type === \"workflow\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4JA,SAAgB,qBACd,YACA,gBACkC;CAClC,MAAM,UAAU,OAAO,QAAQ,UAAU;CAEzC,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,sBACR,kBAAkB,eAAe,kDACjC,EAAE,SAAS,EAAE,WAAW,KAAK,EAAE,CACjC;CAGF,MAAM,2BAAW,IAAI,IAAiC;CAEtD,KAAK,MAAM,CAAC,QAAQ,UAAU,SAAS;EACrC,IAAI,CAAC,UAAU,OAAO,WAAW,UAC/B,MAAM,IAAI,sBACR,kBAAkB,eAAe,uDACjC,EAAE,SAAS,EAAE,WAAW,KAAK,EAAE,CACjC;EAGF,SAAS,IAAI,QAAQ,WAAW,QAAQ,OAAO,cAAc,CAAC;CAChE;CAEA,OAAO;AACT;;;;;;;;;;;AAYA,SAAgB,yBACd,QACA,SACM;CACN,IAAI,CAAC,OAAO,QACV;CAGF,KAAK,MAAM,CAAC,QAAQ,UAAU,SAAS;EACrC,MAAM,cAAc,MAAM,SAAS,aAAa,MAAM,cAAc,MAAM;EAE1E,IAAI,eAAe,YAAY,KAAK,CAAC,CAAC,SAAS,GAC7C;EAGF,MAAM,MACJ,MAAM,SAAS,aACX,wDACA;EAEN,MAAM,IAAI,sBACR,kBAAkB,OAAO,KAAK,eAAe,OAAO,8DAA8D,OAClH,EAAE,SAAS;GAAE,WAAW;GAAM;EAAO,EAAE,GACvC,wCACF;CACF;AACF;AAEA,SAAS,WACP,QACA,OACA,gBACqB;CAIrB,IAAI,OAAO,UAAU,YACnB,OAAO;EACL;EACA,M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cAAc,KAAK,CAAC,CAAC,SAAS,GACjD,OAAO;CAGT,MAAM,kBAAmB,KAAmC;CAE5D,IAAI,OAAO,oBAAoB,YAAY,gBAAgB,KAAK,CAAC,CAAC,SAAS,GACzE,OAAO;CAMT,OAAO;AACT;;;;;;;AAQA,SAAgB,cAAc,KAAqD;CACjF,OAAO,IAAI,SAAS;AACtB;AAEA,SAAgB,iBAAiB,KAAwD;CACvF,OAAO,IAAI,SAAS;AACtB"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { AudioInput } from "../contracts/transcription-model.contract.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../@warlock.js/ai/src/transcribe/audio-input.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Resolve the audio media type from a filename's extension, or
|
|
6
|
+
* `undefined` when the extension is unknown. Case-insensitive.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* audioMediaTypeForFilename("voice-note.opus"); // "audio/ogg"
|
|
10
|
+
*/
|
|
11
|
+
declare function audioMediaTypeForFilename(filename: string): string | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* Package raw audio bytes as an {@link AudioInput} for `ai.transcribe()`.
|
|
14
|
+
* Pure plumbing — no AI, no I/O. Use when you already hold the bytes
|
|
15
|
+
* (an upload buffer, a downloaded blob).
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* const audio = audioFromBuffer(uploadBuffer, "audio/ogg", "note.ogg");
|
|
19
|
+
* const { data } = await ai.transcribe({ model: openai.transcribe({ name: "whisper-1" }), audio });
|
|
20
|
+
*/
|
|
21
|
+
declare function audioFromBuffer(data: Uint8Array, mediaType: string, filename?: string): AudioInput;
|
|
22
|
+
/**
|
|
23
|
+
* Read an audio file from disk and package it as an {@link AudioInput}
|
|
24
|
+
* for `ai.transcribe()` — the one-line bridge from a file on disk
|
|
25
|
+
* (WhatsApp `.ogg`/`.opus`, a meeting `.m4a`, a `.wav`) to the
|
|
26
|
+
* transcription verb. **Pure utility — no AI here**; the actual text
|
|
27
|
+
* extraction is the AI step (`ai.transcribe`).
|
|
28
|
+
*
|
|
29
|
+
* The media type is inferred from the file extension (override via
|
|
30
|
+
* `options.mediaType` for extensionless or mislabeled files).
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* // WhatsApp voice note → text, end to end:
|
|
34
|
+
* const audio = await audioFromFile("./voice-note.ogg");
|
|
35
|
+
* const { data, error } = await ai.transcribe({
|
|
36
|
+
* model: openai.transcribe({ name: "whisper-1" }),
|
|
37
|
+
* audio,
|
|
38
|
+
* language: "en",
|
|
39
|
+
* });
|
|
40
|
+
* if (!error) console.log(data.text);
|
|
41
|
+
*/
|
|
42
|
+
declare function audioFromFile(filePath: string, options?: {
|
|
43
|
+
mediaType?: string;
|
|
44
|
+
}): Promise<AudioInput>;
|
|
45
|
+
//#endregion
|
|
46
|
+
export { audioFromBuffer, audioFromFile, audioMediaTypeForFilename };
|
|
47
|
+
//# sourceMappingURL=audio-input.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"audio-input.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/transcribe/audio-input.ts"],"mappings":";;;;;AAgCA;;;;AAA0D;iBAA1C,yBAAA,CAA0B,QAAgB;;;;;;;;;;iBAa1C,eAAA,CACd,IAAA,EAAM,UAAA,EACN,SAAA,UACA,QAAA,YACC,UAAU;AA4Bb;;;;;;;;;;AAGqB;;;;;;;;;;AAHrB,iBAAsB,aAAA,CACpB,QAAA,UACA,OAAA;EAAY,SAAA;AAAA,IACX,OAAO,CAAC,UAAA"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { basename, extname } from "node:path";
|
|
3
|
+
|
|
4
|
+
//#region ../@warlock.js/ai/src/transcribe/audio-input.ts
|
|
5
|
+
/**
|
|
6
|
+
* File-extension → IANA audio media type map covering the formats the
|
|
7
|
+
* common STT providers accept — including the **WhatsApp voice-note**
|
|
8
|
+
* formats (`.ogg` / `.opus`, Opus-in-Ogg on Android; `.m4a` on iOS).
|
|
9
|
+
*/
|
|
10
|
+
const AUDIO_MEDIA_TYPES = {
|
|
11
|
+
".mp3": "audio/mpeg",
|
|
12
|
+
".mpeg": "audio/mpeg",
|
|
13
|
+
".mpga": "audio/mpeg",
|
|
14
|
+
".m4a": "audio/mp4",
|
|
15
|
+
".mp4": "audio/mp4",
|
|
16
|
+
".wav": "audio/wav",
|
|
17
|
+
".webm": "audio/webm",
|
|
18
|
+
".weba": "audio/webm",
|
|
19
|
+
".ogg": "audio/ogg",
|
|
20
|
+
".oga": "audio/ogg",
|
|
21
|
+
".opus": "audio/ogg",
|
|
22
|
+
".flac": "audio/flac",
|
|
23
|
+
".aac": "audio/aac"
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Resolve the audio media type from a filename's extension, or
|
|
27
|
+
* `undefined` when the extension is unknown. Case-insensitive.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* audioMediaTypeForFilename("voice-note.opus"); // "audio/ogg"
|
|
31
|
+
*/
|
|
32
|
+
function audioMediaTypeForFilename(filename) {
|
|
33
|
+
return AUDIO_MEDIA_TYPES[extname(filename).toLowerCase()];
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Package raw audio bytes as an {@link AudioInput} for `ai.transcribe()`.
|
|
37
|
+
* Pure plumbing — no AI, no I/O. Use when you already hold the bytes
|
|
38
|
+
* (an upload buffer, a downloaded blob).
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* const audio = audioFromBuffer(uploadBuffer, "audio/ogg", "note.ogg");
|
|
42
|
+
* const { data } = await ai.transcribe({ model: openai.transcribe({ name: "whisper-1" }), audio });
|
|
43
|
+
*/
|
|
44
|
+
function audioFromBuffer(data, mediaType, filename) {
|
|
45
|
+
return {
|
|
46
|
+
base64: Buffer.from(data).toString("base64"),
|
|
47
|
+
mediaType,
|
|
48
|
+
...filename ? { filename } : {}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Read an audio file from disk and package it as an {@link AudioInput}
|
|
53
|
+
* for `ai.transcribe()` — the one-line bridge from a file on disk
|
|
54
|
+
* (WhatsApp `.ogg`/`.opus`, a meeting `.m4a`, a `.wav`) to the
|
|
55
|
+
* transcription verb. **Pure utility — no AI here**; the actual text
|
|
56
|
+
* extraction is the AI step (`ai.transcribe`).
|
|
57
|
+
*
|
|
58
|
+
* The media type is inferred from the file extension (override via
|
|
59
|
+
* `options.mediaType` for extensionless or mislabeled files).
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* // WhatsApp voice note → text, end to end:
|
|
63
|
+
* const audio = await audioFromFile("./voice-note.ogg");
|
|
64
|
+
* const { data, error } = await ai.transcribe({
|
|
65
|
+
* model: openai.transcribe({ name: "whisper-1" }),
|
|
66
|
+
* audio,
|
|
67
|
+
* language: "en",
|
|
68
|
+
* });
|
|
69
|
+
* if (!error) console.log(data.text);
|
|
70
|
+
*/
|
|
71
|
+
async function audioFromFile(filePath, options) {
|
|
72
|
+
const buffer = await readFile(filePath);
|
|
73
|
+
const filename = basename(filePath);
|
|
74
|
+
const mediaType = options?.mediaType ?? audioMediaTypeForFilename(filename) ?? "audio/mpeg";
|
|
75
|
+
return {
|
|
76
|
+
base64: buffer.toString("base64"),
|
|
77
|
+
mediaType,
|
|
78
|
+
filename
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
//#endregion
|
|
83
|
+
export { audioFromBuffer, audioFromFile, audioMediaTypeForFilename };
|
|
84
|
+
//# sourceMappingURL=audio-input.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"audio-input.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/transcribe/audio-input.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { basename, extname } from \"node:path\";\nimport type { AudioInput } from \"../contracts/transcription-model.contract\";\n\n/**\n * File-extension → IANA audio media type map covering the formats the\n * common STT providers accept — including the **WhatsApp voice-note**\n * formats (`.ogg` / `.opus`, Opus-in-Ogg on Android; `.m4a` on iOS).\n */\nconst AUDIO_MEDIA_TYPES: Record<string, string> = {\n \".mp3\": \"audio/mpeg\",\n \".mpeg\": \"audio/mpeg\",\n \".mpga\": \"audio/mpeg\",\n \".m4a\": \"audio/mp4\",\n \".mp4\": \"audio/mp4\",\n \".wav\": \"audio/wav\",\n \".webm\": \"audio/webm\",\n \".weba\": \"audio/webm\",\n \".ogg\": \"audio/ogg\",\n \".oga\": \"audio/ogg\",\n \".opus\": \"audio/ogg\",\n \".flac\": \"audio/flac\",\n \".aac\": \"audio/aac\",\n};\n\n/**\n * Resolve the audio media type from a filename's extension, or\n * `undefined` when the extension is unknown. Case-insensitive.\n *\n * @example\n * audioMediaTypeForFilename(\"voice-note.opus\"); // \"audio/ogg\"\n */\nexport function audioMediaTypeForFilename(filename: string): string | undefined {\n return AUDIO_MEDIA_TYPES[extname(filename).toLowerCase()];\n}\n\n/**\n * Package raw audio bytes as an {@link AudioInput} for `ai.transcribe()`.\n * Pure plumbing — no AI, no I/O. Use when you already hold the bytes\n * (an upload buffer, a downloaded blob).\n *\n * @example\n * const audio = audioFromBuffer(uploadBuffer, \"audio/ogg\", \"note.ogg\");\n * const { data } = await ai.transcribe({ model: openai.transcribe({ name: \"whisper-1\" }), audio });\n */\nexport function audioFromBuffer(\n data: Uint8Array,\n mediaType: string,\n filename?: string,\n): AudioInput {\n return {\n base64: Buffer.from(data).toString(\"base64\"),\n mediaType,\n ...(filename ? { filename } : {}),\n };\n}\n\n/**\n * Read an audio file from disk and package it as an {@link AudioInput}\n * for `ai.transcribe()` — the one-line bridge from a file on disk\n * (WhatsApp `.ogg`/`.opus`, a meeting `.m4a`, a `.wav`) to the\n * transcription verb. **Pure utility — no AI here**; the actual text\n * extraction is the AI step (`ai.transcribe`).\n *\n * The media type is inferred from the file extension (override via\n * `options.mediaType` for extensionless or mislabeled files).\n *\n * @example\n * // WhatsApp voice note → text, end to end:\n * const audio = await audioFromFile(\"./voice-note.ogg\");\n * const { data, error } = await ai.transcribe({\n * model: openai.transcribe({ name: \"whisper-1\" }),\n * audio,\n * language: \"en\",\n * });\n * if (!error) console.log(data.text);\n */\nexport async function audioFromFile(\n filePath: string,\n options?: { mediaType?: string },\n): Promise<AudioInput> {\n const buffer = await readFile(filePath);\n const filename = basename(filePath);\n const mediaType = options?.mediaType ?? audioMediaTypeForFilename(filename) ?? \"audio/mpeg\";\n\n return { base64: buffer.toString(\"base64\"), mediaType, filename };\n}\n"],"mappings":";;;;;;;;;AASA,MAAM,oBAA4C;CAChD,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;AACV;;;;;;;;AASA,SAAgB,0BAA0B,UAAsC;CAC9E,OAAO,kBAAkB,QAAQ,QAAQ,CAAC,CAAC,YAAY;AACzD;;;;;;;;;;AAWA,SAAgB,gBACd,MACA,WACA,UACY;CACZ,OAAO;EACL,QAAQ,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,QAAQ;EAC3C;EACA,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;CACjC;AACF;;;;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,cACpB,UACA,SACqB;CACrB,MAAM,SAAS,MAAM,SAAS,QAAQ;CACtC,MAAM,WAAW,SAAS,QAAQ;CAClC,MAAM,YAAY,SAAS,aAAa,0BAA0B,QAAQ,KAAK;CAE/E,OAAO;EAAE,QAAQ,OAAO,SAAS,QAAQ;EAAG;EAAW;CAAS;AAClE"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { BaseReport } from "../contracts/result/base-report.type.mjs";
|
|
2
|
+
import { ExecuteResult } from "../contracts/result/execute-result.type.mjs";
|
|
3
|
+
import { FlowObserveOption } from "../observe/resolve-observers.mjs";
|
|
4
|
+
import { AudioInput, TranscriptionModelContract, TranscriptionSegment } from "../contracts/transcription-model.contract.mjs";
|
|
5
|
+
|
|
6
|
+
//#region ../@warlock.js/ai/src/transcribe/transcribe.d.ts
|
|
7
|
+
/** Parameters for {@link transcribe}. `model` comes from `sdk.transcribe({ name })`. */
|
|
8
|
+
type TranscribeParams = {
|
|
9
|
+
/** The STT model to transcribe with. */model: TranscriptionModelContract; /** The audio to transcribe (inlined base64 bytes + media type). */
|
|
10
|
+
audio: AudioInput; /** BCP-47 language hint. */
|
|
11
|
+
language?: string; /** Optional priming prompt (spelling/style hints). */
|
|
12
|
+
prompt?: string; /** Provider response-format override (e.g. `"verbose_json"`). */
|
|
13
|
+
format?: string; /** Cancellation handle. */
|
|
14
|
+
signal?: AbortSignal; /** Observability routing — same `observe` seam as agents. */
|
|
15
|
+
observe?: FlowObserveOption; /** Groups this call into a session for flat cost/trace queries. */
|
|
16
|
+
sessionId?: string; /** Report node name (defaults to `"transcription"`). */
|
|
17
|
+
name?: string; /** Provider-specific options forwarded verbatim to the adapter. */
|
|
18
|
+
options?: Record<string, unknown>;
|
|
19
|
+
};
|
|
20
|
+
/** Success payload of a {@link transcribe} run. */
|
|
21
|
+
type TranscriptionData = {
|
|
22
|
+
/** The full transcript text. */text: string; /** Timestamped segments when the provider returned them. */
|
|
23
|
+
segments?: TranscriptionSegment[];
|
|
24
|
+
};
|
|
25
|
+
/** The report node a {@link transcribe} run produces (`type: "transcription"`). */
|
|
26
|
+
type TranscriptionReport = BaseReport & {
|
|
27
|
+
type: "transcription"; /** Identity of the STT model this run used. */
|
|
28
|
+
model: {
|
|
29
|
+
name: string;
|
|
30
|
+
provider: string;
|
|
31
|
+
}; /** Input audio duration in seconds, when the provider reported it. */
|
|
32
|
+
durationSeconds?: number;
|
|
33
|
+
};
|
|
34
|
+
/** Result envelope of {@link transcribe} — the uniform `{ data, error, usage, report }`. */
|
|
35
|
+
type TranscriptionResult = ExecuteResult<TranscriptionData> & {
|
|
36
|
+
type: "transcription";
|
|
37
|
+
report: TranscriptionReport;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Transcribe audio to text — the speech-to-text verb of the
|
|
41
|
+
* output-modality track (Theme I), inverse of `ai.speech()`. Wraps a
|
|
42
|
+
* {@link TranscriptionModelContract} (from `openai.transcribe(...)`) in
|
|
43
|
+
* the uniform result contract:
|
|
44
|
+
*
|
|
45
|
+
* - **Never throws.** Provider failures surface as a typed `AIError` on
|
|
46
|
+
* `result.error`.
|
|
47
|
+
* - **Cost-truth.** `result.usage.cost` is filled per-minute
|
|
48
|
+
* (`whisper-1`) or per-token (`gpt-4o-transcribe`).
|
|
49
|
+
* - **Observable.** The completed {@link TranscriptionReport} routes to
|
|
50
|
+
* any registered `Observer` via the `observe` seam.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* const openai = new OpenAISDK({ apiKey });
|
|
54
|
+
* const { data, error } = await ai.transcribe({
|
|
55
|
+
* model: openai.transcribe({ name: "whisper-1" }),
|
|
56
|
+
* audio: { base64, mediaType: "audio/mpeg", filename: "voicemail.mp3" },
|
|
57
|
+
* language: "en",
|
|
58
|
+
* });
|
|
59
|
+
* if (!error) console.log(data.text);
|
|
60
|
+
*/
|
|
61
|
+
declare function transcribe(params: TranscribeParams): Promise<TranscriptionResult>;
|
|
62
|
+
//#endregion
|
|
63
|
+
export { TranscribeParams, TranscriptionData, TranscriptionReport, TranscriptionResult, transcribe };
|
|
64
|
+
//# sourceMappingURL=transcribe.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transcribe.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/transcribe/transcribe.ts"],"mappings":";;;;;;;KAoBY,gBAAA;EAAA,wCAEV,KAAA,EAAO,0BAAA;EAEP,KAAA,EAAO,UAAA,EAAA;EAEP,QAAA,WAQU;EANV,MAAA,WAYgB;EAVhB,MAAA,WARA;EAUA,MAAA,GAAS,WAAA,EART;EAUA,OAAA,GAAU,iBAAA,EARV;EAUA,SAAA,WANA;EAQA,IAAA,WANS;EAQT,OAAA,GAAU,MAAA;AAAA;;KAIA,iBAAA;EAJV,gCAMA,IAAA,UANgB;EAQhB,QAAA,GAAW,oBAAoB;AAAA;;KAIrB,mBAAA,GAAsB,UAAU;EAC1C,IAAA,mBAPA;EASA,KAAA;IAAS,IAAA;IAAc,QAAA;EAAA,GAHb;EAKV,eAAA;AAAA;;KAIU,mBAAA,GAAsB,aAAA,CAAc,iBAAA;EAC9C,IAAA;EACA,MAAA,EAAQ,mBAAA;AAAA;;;;AANO;AAIjB;;;;;;;;;;;;;;AAE6B;AAyB7B;;;iBAAsB,UAAA,CAAW,MAAA,EAAQ,gBAAA,GAAmB,OAAA,CAAQ,mBAAA"}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { AIError } from "../errors/ai-error.mjs";
|
|
2
|
+
import { ProviderError } from "../errors/provider-error.mjs";
|
|
3
|
+
import { computeCost } from "../utils/compute-cost.mjs";
|
|
4
|
+
import { generateRunId } from "../utils/generate-run-id.mjs";
|
|
5
|
+
import { REPORT_SCHEMA_VERSION } from "../contracts/result/base-report.type.mjs";
|
|
6
|
+
import { stampReportLineage } from "../utils/stamp-report-lineage.mjs";
|
|
7
|
+
import { notifyObservers } from "../observe/resolve-observers.mjs";
|
|
8
|
+
|
|
9
|
+
//#region ../@warlock.js/ai/src/transcribe/transcribe.ts
|
|
10
|
+
/**
|
|
11
|
+
* Transcribe audio to text — the speech-to-text verb of the
|
|
12
|
+
* output-modality track (Theme I), inverse of `ai.speech()`. Wraps a
|
|
13
|
+
* {@link TranscriptionModelContract} (from `openai.transcribe(...)`) in
|
|
14
|
+
* the uniform result contract:
|
|
15
|
+
*
|
|
16
|
+
* - **Never throws.** Provider failures surface as a typed `AIError` on
|
|
17
|
+
* `result.error`.
|
|
18
|
+
* - **Cost-truth.** `result.usage.cost` is filled per-minute
|
|
19
|
+
* (`whisper-1`) or per-token (`gpt-4o-transcribe`).
|
|
20
|
+
* - **Observable.** The completed {@link TranscriptionReport} routes to
|
|
21
|
+
* any registered `Observer` via the `observe` seam.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* const openai = new OpenAISDK({ apiKey });
|
|
25
|
+
* const { data, error } = await ai.transcribe({
|
|
26
|
+
* model: openai.transcribe({ name: "whisper-1" }),
|
|
27
|
+
* audio: { base64, mediaType: "audio/mpeg", filename: "voicemail.mp3" },
|
|
28
|
+
* language: "en",
|
|
29
|
+
* });
|
|
30
|
+
* if (!error) console.log(data.text);
|
|
31
|
+
*/
|
|
32
|
+
async function transcribe(params) {
|
|
33
|
+
const { model, audio } = params;
|
|
34
|
+
const runId = generateRunId("transcription");
|
|
35
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
36
|
+
const startPerf = performance.now();
|
|
37
|
+
const usage = {
|
|
38
|
+
input: 0,
|
|
39
|
+
output: 0,
|
|
40
|
+
total: 0
|
|
41
|
+
};
|
|
42
|
+
let data;
|
|
43
|
+
let error;
|
|
44
|
+
let status = "completed";
|
|
45
|
+
let durationSeconds;
|
|
46
|
+
try {
|
|
47
|
+
const response = await model.transcribe(audio, {
|
|
48
|
+
language: params.language,
|
|
49
|
+
prompt: params.prompt,
|
|
50
|
+
format: params.format,
|
|
51
|
+
signal: params.signal,
|
|
52
|
+
...params.options
|
|
53
|
+
});
|
|
54
|
+
Object.assign(usage, response.usage);
|
|
55
|
+
durationSeconds = response.durationSeconds;
|
|
56
|
+
if (usage.cost === void 0) {
|
|
57
|
+
const cost = computeTranscriptionCost(usage, durationSeconds, model.pricing);
|
|
58
|
+
if (cost !== void 0) usage.cost = cost;
|
|
59
|
+
}
|
|
60
|
+
data = {
|
|
61
|
+
text: response.text,
|
|
62
|
+
...response.segments ? { segments: response.segments } : {}
|
|
63
|
+
};
|
|
64
|
+
} catch (thrown) {
|
|
65
|
+
error = thrown instanceof AIError ? thrown : new ProviderError(toMessage(thrown), { cause: thrown });
|
|
66
|
+
status = params.signal?.aborted ? "cancelled" : "failed";
|
|
67
|
+
}
|
|
68
|
+
const report = {
|
|
69
|
+
runId,
|
|
70
|
+
rootRunId: runId,
|
|
71
|
+
name: params.name ?? "transcription",
|
|
72
|
+
type: "transcription",
|
|
73
|
+
status,
|
|
74
|
+
error,
|
|
75
|
+
startedAt,
|
|
76
|
+
endedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
77
|
+
duration: performance.now() - startPerf,
|
|
78
|
+
usage,
|
|
79
|
+
children: [],
|
|
80
|
+
model: {
|
|
81
|
+
name: model.name,
|
|
82
|
+
provider: model.provider
|
|
83
|
+
},
|
|
84
|
+
...durationSeconds !== void 0 ? { durationSeconds } : {},
|
|
85
|
+
reportSchemaVersion: 1
|
|
86
|
+
};
|
|
87
|
+
stampReportLineage(report, {
|
|
88
|
+
rootRunId: runId,
|
|
89
|
+
sessionId: params.sessionId
|
|
90
|
+
});
|
|
91
|
+
await notifyObservers(params.observe, report);
|
|
92
|
+
return {
|
|
93
|
+
type: "transcription",
|
|
94
|
+
data,
|
|
95
|
+
error,
|
|
96
|
+
usage,
|
|
97
|
+
report
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Price an STT run: `perMinute × (durationSeconds / 60)` (per-minute
|
|
102
|
+
* metering, attributed to `cost.input`) wins when configured, otherwise
|
|
103
|
+
* the standard token math. Returns `undefined` when no usable pricing
|
|
104
|
+
* is present (e.g. per-minute pricing but the provider didn't report a
|
|
105
|
+
* duration).
|
|
106
|
+
*/
|
|
107
|
+
function computeTranscriptionCost(usage, durationSeconds, pricing) {
|
|
108
|
+
if (!pricing) return;
|
|
109
|
+
if (pricing.perMinute !== void 0) {
|
|
110
|
+
if (durationSeconds === void 0) return;
|
|
111
|
+
return {
|
|
112
|
+
input: durationSeconds / 60 * pricing.perMinute,
|
|
113
|
+
output: 0
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
if (pricing.input !== void 0 && pricing.output !== void 0) return computeCost(usage, {
|
|
117
|
+
input: pricing.input,
|
|
118
|
+
output: pricing.output
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
/** Best-effort message for a non-`AIError` thrown value. */
|
|
122
|
+
function toMessage(thrown) {
|
|
123
|
+
return thrown instanceof Error ? thrown.message : String(thrown);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
//#endregion
|
|
127
|
+
export { transcribe };
|
|
128
|
+
//# sourceMappingURL=transcribe.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transcribe.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/transcribe/transcribe.ts"],"sourcesContent":["import type { BaseReport } from \"../contracts/result/base-report.type\";\nimport { REPORT_SCHEMA_VERSION } from \"../contracts/result/base-report.type\";\nimport type { ExecuteResult } from \"../contracts/result/execute-result.type\";\nimport type { ModelPricing } from \"../contracts/result/model-pricing.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport type {\n AudioInput,\n TranscriptionModelContract,\n TranscriptionModelPricing,\n TranscriptionSegment,\n} from \"../contracts/transcription-model.contract\";\nimport { AIError } from \"../errors/ai-error\";\nimport { ProviderError } from \"../errors/provider-error\";\nimport type { FlowObserveOption } from \"../observe/resolve-observers\";\nimport { notifyObservers } from \"../observe/resolve-observers\";\nimport { computeCost } from \"../utils/compute-cost\";\nimport { generateRunId } from \"../utils/generate-run-id\";\nimport { stampReportLineage } from \"../utils/stamp-report-lineage\";\n\n/** Parameters for {@link transcribe}. `model` comes from `sdk.transcribe({ name })`. */\nexport type TranscribeParams = {\n /** The STT model to transcribe with. */\n model: TranscriptionModelContract;\n /** The audio to transcribe (inlined base64 bytes + media type). */\n audio: AudioInput;\n /** BCP-47 language hint. */\n language?: string;\n /** Optional priming prompt (spelling/style hints). */\n prompt?: string;\n /** Provider response-format override (e.g. `\"verbose_json\"`). */\n format?: string;\n /** Cancellation handle. */\n signal?: AbortSignal;\n /** Observability routing — same `observe` seam as agents. */\n observe?: FlowObserveOption;\n /** Groups this call into a session for flat cost/trace queries. */\n sessionId?: string;\n /** Report node name (defaults to `\"transcription\"`). */\n name?: string;\n /** Provider-specific options forwarded verbatim to the adapter. */\n options?: Record<string, unknown>;\n};\n\n/** Success payload of a {@link transcribe} run. */\nexport type TranscriptionData = {\n /** The full transcript text. */\n text: string;\n /** Timestamped segments when the provider returned them. */\n segments?: TranscriptionSegment[];\n};\n\n/** The report node a {@link transcribe} run produces (`type: \"transcription\"`). */\nexport type TranscriptionReport = BaseReport & {\n type: \"transcription\";\n /** Identity of the STT model this run used. */\n model: { name: string; provider: string };\n /** Input audio duration in seconds, when the provider reported it. */\n durationSeconds?: number;\n};\n\n/** Result envelope of {@link transcribe} — the uniform `{ data, error, usage, report }`. */\nexport type TranscriptionResult = ExecuteResult<TranscriptionData> & {\n type: \"transcription\";\n report: TranscriptionReport;\n};\n\n/**\n * Transcribe audio to text — the speech-to-text verb of the\n * output-modality track (Theme I), inverse of `ai.speech()`. Wraps a\n * {@link TranscriptionModelContract} (from `openai.transcribe(...)`) in\n * the uniform result contract:\n *\n * - **Never throws.** Provider failures surface as a typed `AIError` on\n * `result.error`.\n * - **Cost-truth.** `result.usage.cost` is filled per-minute\n * (`whisper-1`) or per-token (`gpt-4o-transcribe`).\n * - **Observable.** The completed {@link TranscriptionReport} routes to\n * any registered `Observer` via the `observe` seam.\n *\n * @example\n * const openai = new OpenAISDK({ apiKey });\n * const { data, error } = await ai.transcribe({\n * model: openai.transcribe({ name: \"whisper-1\" }),\n * audio: { base64, mediaType: \"audio/mpeg\", filename: \"voicemail.mp3\" },\n * language: \"en\",\n * });\n * if (!error) console.log(data.text);\n */\nexport async function transcribe(params: TranscribeParams): Promise<TranscriptionResult> {\n const { model, audio } = params;\n\n const runId = generateRunId(\"transcription\");\n const startedAt = new Date().toISOString();\n const startPerf = performance.now();\n\n const usage: Usage = { input: 0, output: 0, total: 0 };\n let data: TranscriptionData | undefined;\n let error: AIError | undefined;\n let status: TranscriptionReport[\"status\"] = \"completed\";\n let durationSeconds: number | undefined;\n\n try {\n const response = await model.transcribe(audio, {\n language: params.language,\n prompt: params.prompt,\n format: params.format,\n signal: params.signal,\n ...params.options,\n });\n\n Object.assign(usage, response.usage);\n durationSeconds = response.durationSeconds;\n\n if (usage.cost === undefined) {\n const cost = computeTranscriptionCost(usage, durationSeconds, model.pricing);\n if (cost !== undefined) {\n usage.cost = cost;\n }\n }\n\n data = { text: response.text, ...(response.segments ? { segments: response.segments } : {}) };\n } catch (thrown) {\n error =\n thrown instanceof AIError ? thrown : new ProviderError(toMessage(thrown), { cause: thrown });\n status = params.signal?.aborted ? \"cancelled\" : \"failed\";\n }\n\n const report: TranscriptionReport = {\n runId,\n rootRunId: runId,\n name: params.name ?? \"transcription\",\n type: \"transcription\",\n status,\n error,\n startedAt,\n endedAt: new Date().toISOString(),\n duration: performance.now() - startPerf,\n usage,\n children: [],\n model: { name: model.name, provider: model.provider },\n ...(durationSeconds !== undefined ? { durationSeconds } : {}),\n reportSchemaVersion: REPORT_SCHEMA_VERSION,\n };\n\n stampReportLineage(report, { rootRunId: runId, sessionId: params.sessionId });\n\n await notifyObservers(params.observe, report);\n\n return { type: \"transcription\", data, error, usage, report };\n}\n\n/**\n * Price an STT run: `perMinute × (durationSeconds / 60)` (per-minute\n * metering, attributed to `cost.input`) wins when configured, otherwise\n * the standard token math. Returns `undefined` when no usable pricing\n * is present (e.g. per-minute pricing but the provider didn't report a\n * duration).\n */\nfunction computeTranscriptionCost(\n usage: Usage,\n durationSeconds: number | undefined,\n pricing: TranscriptionModelPricing | undefined,\n): ModelPricing | undefined {\n if (!pricing) {\n return undefined;\n }\n\n if (pricing.perMinute !== undefined) {\n if (durationSeconds === undefined) {\n return undefined;\n }\n return { input: (durationSeconds / 60) * pricing.perMinute, output: 0 };\n }\n\n if (pricing.input !== undefined && pricing.output !== undefined) {\n return computeCost(usage, { input: pricing.input, output: pricing.output });\n }\n\n return undefined;\n}\n\n/** Best-effort message for a non-`AIError` thrown value. */\nfunction toMessage(thrown: unknown): string {\n return thrown instanceof Error ? thrown.message : String(thrown);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwFA,eAAsB,WAAW,QAAwD;CACvF,MAAM,EAAE,OAAO,UAAU;CAEzB,MAAM,QAAQ,cAAc,eAAe;CAC3C,MAAM,6BAAY,IAAI,KAAK,EAAC,CAAC,YAAY;CACzC,MAAM,YAAY,YAAY,IAAI;CAElC,MAAM,QAAe;EAAE,OAAO;EAAG,QAAQ;EAAG,OAAO;CAAE;CACrD,IAAI;CACJ,IAAI;CACJ,IAAI,SAAwC;CAC5C,IAAI;CAEJ,IAAI;EACF,MAAM,WAAW,MAAM,MAAM,WAAW,OAAO;GAC7C,UAAU,OAAO;GACjB,QAAQ,OAAO;GACf,QAAQ,OAAO;GACf,QAAQ,OAAO;GACf,GAAG,OAAO;EACZ,CAAC;EAED,OAAO,OAAO,OAAO,SAAS,KAAK;EACnC,kBAAkB,SAAS;EAE3B,IAAI,MAAM,SAAS,QAAW;GAC5B,MAAM,OAAO,yBAAyB,OAAO,iBAAiB,MAAM,OAAO;GAC3E,IAAI,SAAS,QACX,MAAM,OAAO;EAEjB;EAEA,OAAO;GAAE,MAAM,SAAS;GAAM,GAAI,SAAS,WAAW,EAAE,UAAU,SAAS,SAAS,IAAI,CAAC;EAAG;CAC9F,SAAS,QAAQ;EACf,QACE,kBAAkB,UAAU,SAAS,IAAI,cAAc,UAAU,MAAM,GAAG,EAAE,OAAO,OAAO,CAAC;EAC7F,SAAS,OAAO,QAAQ,UAAU,cAAc;CAClD;CAEA,MAAM,SAA8B;EAClC;EACA,WAAW;EACX,MAAM,OAAO,QAAQ;EACrB,MAAM;EACN;EACA;EACA;EACA,0BAAS,IAAI,KAAK,EAAC,CAAC,YAAY;EAChC,UAAU,YAAY,IAAI,IAAI;EAC9B;EACA,UAAU,CAAC;EAC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