@warlock.js/core 4.5.0 → 4.6.0
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 +27 -0
- package/esm/ai/src/agent/agent.mjs +126 -7
- package/esm/ai/src/agent/agent.mjs.map +1 -1
- package/esm/ai/src/agent/signature.mjs +57 -0
- package/esm/ai/src/agent/signature.mjs.map +1 -0
- package/esm/ai/src/agent/snapshot.mjs +101 -0
- package/esm/ai/src/agent/snapshot.mjs.map +1 -0
- package/esm/ai/src/ai.mjs +37 -1
- package/esm/ai/src/ai.mjs.map +1 -1
- package/esm/ai/src/errors/agent-drift-error.mjs +31 -0
- package/esm/ai/src/errors/agent-drift-error.mjs.map +1 -0
- package/esm/ai/src/errors/index.mjs +2 -0
- package/esm/ai/src/errors/planner-drift-error.mjs +33 -0
- package/esm/ai/src/errors/planner-drift-error.mjs.map +1 -0
- package/esm/ai/src/image/image-cost.mjs +55 -0
- package/esm/ai/src/image/image-cost.mjs.map +1 -0
- package/esm/ai/src/image/image.mjs +112 -0
- package/esm/ai/src/image/image.mjs.map +1 -0
- package/esm/ai/src/image/index.mjs +4 -0
- package/esm/ai/src/index.mjs +20 -0
- package/esm/ai/src/planner/planner-run.mjs +161 -6
- package/esm/ai/src/planner/planner-run.mjs.map +1 -1
- package/esm/ai/src/planner/planner.mjs +25 -1
- package/esm/ai/src/planner/planner.mjs.map +1 -1
- package/esm/ai/src/planner/snapshot.mjs +95 -0
- package/esm/ai/src/planner/snapshot.mjs.map +1 -0
- package/esm/ai/src/rag/hybrid/bm25.mjs +51 -0
- package/esm/ai/src/rag/hybrid/bm25.mjs.map +1 -0
- package/esm/ai/src/rag/hybrid/hybrid-rank.mjs +29 -0
- package/esm/ai/src/rag/hybrid/hybrid-rank.mjs.map +1 -0
- package/esm/ai/src/rag/hybrid/rrf.mjs +30 -0
- package/esm/ai/src/rag/hybrid/rrf.mjs.map +1 -0
- package/esm/ai/src/rag/index.mjs +11 -0
- package/esm/ai/src/rag/loaders/errors.mjs +25 -0
- package/esm/ai/src/rag/loaders/errors.mjs.map +1 -0
- package/esm/ai/src/rag/loaders/index.mjs +7 -0
- package/esm/ai/src/rag/loaders/load-html.mjs +138 -0
- package/esm/ai/src/rag/loaders/load-html.mjs.map +1 -0
- package/esm/ai/src/rag/loaders/load-pdf.mjs +150 -0
- package/esm/ai/src/rag/loaders/load-pdf.mjs.map +1 -0
- package/esm/ai/src/rag/loaders/load-text.mjs +60 -0
- package/esm/ai/src/rag/loaders/load-text.mjs.map +1 -0
- package/esm/ai/src/rag/loaders/load-web.mjs +89 -0
- package/esm/ai/src/rag/loaders/load-web.mjs.map +1 -0
- package/esm/ai/src/rag/store/pg-vector-store.mjs +328 -0
- package/esm/ai/src/rag/store/pg-vector-store.mjs.map +1 -0
- package/esm/ai/src/rag/transforms/multi-query.mjs +41 -0
- package/esm/ai/src/rag/transforms/multi-query.mjs.map +1 -0
- package/esm/ai/src/speech/index.mjs +3 -0
- package/esm/ai/src/speech/speech.mjs +122 -0
- package/esm/ai/src/speech/speech.mjs.map +1 -0
- package/esm/ai/src/supervisor/entries.mjs +2 -2
- package/esm/ai/src/supervisor/entries.mjs.map +1 -1
- package/esm/ai/src/transcribe/audio-input.mjs +84 -0
- package/esm/ai/src/transcribe/audio-input.mjs.map +1 -0
- package/esm/ai/src/transcribe/index.mjs +4 -0
- package/esm/ai/src/transcribe/transcribe.mjs +127 -0
- package/esm/ai/src/transcribe/transcribe.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/cli/commands/doctor/checks/config.check.mjs +42 -0
- package/esm/cli/commands/doctor/checks/config.check.mjs.map +1 -0
- package/esm/cli/commands/doctor/checks/connectors.check.mjs +28 -0
- package/esm/cli/commands/doctor/checks/connectors.check.mjs.map +1 -0
- package/esm/cli/commands/doctor/checks/health.check.mjs +35 -0
- package/esm/cli/commands/doctor/checks/health.check.mjs.map +1 -0
- package/esm/cli/commands/doctor/checks/index.mjs +25 -0
- package/esm/cli/commands/doctor/checks/index.mjs.map +1 -0
- package/esm/cli/commands/doctor/checks/optional-peers.check.mjs +90 -0
- package/esm/cli/commands/doctor/checks/optional-peers.check.mjs.map +1 -0
- package/esm/cli/commands/doctor/checks/release-hygiene.check.mjs +69 -0
- package/esm/cli/commands/doctor/checks/release-hygiene.check.mjs.map +1 -0
- package/esm/cli/commands/doctor/checks/routes.check.mjs +30 -0
- package/esm/cli/commands/doctor/checks/routes.check.mjs.map +1 -0
- package/esm/cli/commands/doctor/doctor-command.action.mjs +28 -0
- package/esm/cli/commands/doctor/doctor-command.action.mjs.map +1 -0
- package/esm/cli/commands/doctor/format-report.mjs +44 -0
- package/esm/cli/commands/doctor/format-report.mjs.map +1 -0
- package/esm/cli/commands/doctor/run-checks.mjs +50 -0
- package/esm/cli/commands/doctor/run-checks.mjs.map +1 -0
- package/esm/cli/commands/doctor.command.mjs +29 -0
- package/esm/cli/commands/doctor.command.mjs.map +1 -0
- package/esm/cli/commands/generate/templates/stubs.mjs +6 -8
- package/esm/cli/commands/generate/templates/stubs.mjs.map +1 -1
- package/esm/cli/commands/routes/format-routes-table.mjs +129 -0
- package/esm/cli/commands/routes/format-routes-table.mjs.map +1 -0
- package/esm/cli/commands/routes/route-row.mjs +92 -0
- package/esm/cli/commands/routes/route-row.mjs.map +1 -0
- package/esm/cli/commands/routes/routes-command.action.mjs +43 -0
- package/esm/cli/commands/routes/routes-command.action.mjs.map +1 -0
- package/esm/cli/commands/routes.command.mjs +51 -0
- package/esm/cli/commands/routes.command.mjs.map +1 -0
- package/esm/cli/commands/seed.command.mjs +5 -0
- package/esm/cli/commands/seed.command.mjs.map +1 -1
- package/esm/cli/framework-cli-commands.mjs +4 -0
- package/esm/cli/framework-cli-commands.mjs.map +1 -1
- package/esm/config/config-getter.mjs +5 -5
- package/esm/config/config-getter.mjs.map +1 -1
- package/esm/config/config-loader.mjs +2 -2
- package/esm/config/config-loader.mjs.map +1 -1
- package/esm/connectors/access-connector.mjs +2 -2
- package/esm/connectors/access-connector.mjs.map +1 -1
- package/esm/connectors/ai-connector.mjs +2 -2
- package/esm/connectors/ai-connector.mjs.map +1 -1
- package/esm/connectors/cache-connector.mjs +2 -2
- package/esm/connectors/cache-connector.mjs.map +1 -1
- package/esm/connectors/database-connector.mjs +2 -2
- package/esm/connectors/database-connector.mjs.map +1 -1
- package/esm/connectors/herald-connector.mjs +2 -2
- package/esm/connectors/herald-connector.mjs.map +1 -1
- package/esm/connectors/http-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.mjs +9 -7
- package/esm/connectors/http-connector.mjs.map +1 -1
- package/esm/connectors/logger-connector.mjs +2 -2
- package/esm/connectors/logger-connector.mjs.map +1 -1
- package/esm/connectors/mail-connector.mjs +2 -2
- package/esm/connectors/mail-connector.mjs.map +1 -1
- package/esm/connectors/notifications-connector.mjs +2 -2
- package/esm/connectors/notifications-connector.mjs.map +1 -1
- package/esm/connectors/socket-connector.mjs +3 -3
- package/esm/connectors/socket-connector.mjs.map +1 -1
- package/esm/database/index.d.mts +2 -1
- package/esm/database/index.mjs +1 -0
- package/esm/database/seed-command-action.mjs +44 -4
- package/esm/database/seed-command-action.mjs.map +1 -1
- package/esm/database/seeds/seed-records-table-migration.mjs +36 -0
- package/esm/database/seeds/seed-records-table-migration.mjs.map +1 -0
- package/esm/database/seeds/seeder.d.mts +22 -5
- package/esm/database/seeds/seeder.d.mts.map +1 -1
- package/esm/database/seeds/seeder.errors.d.mts +22 -0
- package/esm/database/seeds/seeder.errors.d.mts.map +1 -0
- package/esm/database/seeds/seeder.errors.mjs +29 -0
- package/esm/database/seeds/seeder.errors.mjs.map +1 -0
- package/esm/database/seeds/seeder.mjs.map +1 -1
- package/esm/database/seeds/seeders.manager.mjs +90 -11
- package/esm/database/seeds/seeders.manager.mjs.map +1 -1
- package/esm/database/seeds/types.d.mts +117 -1
- package/esm/database/seeds/types.d.mts.map +1 -1
- package/esm/database/seeds/utils.mjs +6 -1
- package/esm/database/seeds/utils.mjs.map +1 -1
- package/esm/dev-server/module-loader.d.mts +12 -0
- package/esm/dev-server/module-loader.d.mts.map +1 -1
- package/esm/dev-server/module-loader.mjs +30 -2
- package/esm/dev-server/module-loader.mjs.map +1 -1
- package/esm/http/config.mjs +2 -2
- package/esm/http/config.mjs.map +1 -1
- package/esm/http/createHttpApplication.mjs +2 -2
- package/esm/http/createHttpApplication.mjs.map +1 -1
- package/esm/http/health.d.mts +14 -0
- package/esm/http/health.d.mts.map +1 -1
- package/esm/http/health.mjs +16 -0
- package/esm/http/health.mjs.map +1 -1
- package/esm/http/middleware/idempotency.middleware.mjs +5 -5
- package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
- package/esm/http/middleware/inject-request-context.mjs +2 -2
- package/esm/http/middleware/inject-request-context.mjs.map +1 -1
- package/esm/http/middleware/maintenance.middleware.mjs +4 -4
- package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
- package/esm/http/plugins.mjs +9 -9
- package/esm/http/plugins.mjs.map +1 -1
- package/esm/http/response.mjs +5 -5
- package/esm/http/response.mjs.map +1 -1
- package/esm/http/server.mjs +4 -4
- package/esm/http/server.mjs.map +1 -1
- package/esm/index.d.mts +4 -3
- package/esm/index.mjs +2 -1
- package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts +28 -1
- package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-query-builder.mjs +39 -0
- package/esm/repositories/adapters/cascade/cascade-query-builder.mjs.map +1 -1
- package/esm/repositories/contracts/index.d.mts +1 -1
- package/esm/repositories/contracts/query-builder.contract.d.mts +87 -1
- package/esm/repositories/contracts/query-builder.contract.d.mts.map +1 -1
- package/esm/repositories/index.d.mts +1 -1
- package/esm/repositories/repository.manager.d.mts +99 -1
- package/esm/repositories/repository.manager.d.mts.map +1 -1
- package/esm/repositories/repository.manager.mjs +128 -0
- package/esm/repositories/repository.manager.mjs.map +1 -1
- package/esm/router/router.d.mts +9 -0
- package/esm/router/router.d.mts.map +1 -1
- package/esm/router/router.mjs +21 -1
- package/esm/router/router.mjs.map +1 -1
- package/esm/utils/paths.mjs +2 -2
- package/esm/utils/paths.mjs.map +1 -1
- package/esm/validation/validateAll.mjs +2 -2
- package/esm/validation/validateAll.mjs.map +1 -1
- package/llms-full.txt +427 -45
- package/llms.txt +4 -2
- package/package.json +9 -9
- package/skills/README.md +65 -0
- package/skills/health-checks/SKILL.md +13 -0
- package/skills/use-repository/SKILL.md +38 -1
- package/skills/warlock-doctor/SKILL.md +135 -0
- package/skills/warlock-routes/SKILL.md +91 -0
- package/skills/write-seeder/SKILL.md +143 -45
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snapshot.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/agent/snapshot.ts"],"sourcesContent":["import { resolveDefaultSnapshotStore } from \"../config\";\nimport type {\n AgentResumeOptions,\n} from \"../contracts/agent/agent-options.type\";\nimport type {\n AgentSnapshot,\n AgentSnapshotStatus,\n} from \"../contracts/agent/agent-snapshot.type\";\nimport type { SnapshotStore } from \"../contracts/orchestrator/snapshot-store.contract\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport type { LLMTrip } from \"../contracts/result/llm-trip.type\";\nimport type { ToolCall } from \"../contracts/result/tool-call.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport { AgentDriftError, AgentExecutionError } from \"../errors\";\n\n/**\n * The agent's `durable` config, narrowed to the fields the snapshot\n * helpers read. Kept minimal so this module doesn't depend on the full\n * resolved-config shape.\n */\nexport type AgentDurableConfig = {\n store?: SnapshotStore<AgentSnapshot>;\n deleteOnComplete?: boolean;\n};\n\n/**\n * Resolve the effective {@link SnapshotStore}: the agent's own\n * `durable.store` wins; absent that, fall back to the global default\n * set via `ai.config({ defaultSnapshotStore })`.\n *\n * The global default is typed for the supervisor snapshot shape, but\n * every store impl keys purely by `runId` and round-trips whatever\n * envelope it is handed — so it serves an `AgentSnapshot` just as well.\n * The cast re-tags the shape at this single boundary (Option B); the\n * agent only ever hands it an `AgentSnapshot`.\n */\nfunction resolveSnapshotStore(\n durable: AgentDurableConfig | undefined,\n): SnapshotStore<AgentSnapshot> | undefined {\n return (\n durable?.store ??\n (resolveDefaultSnapshotStore() as SnapshotStore<AgentSnapshot> | undefined)\n );\n}\n\nexport type PersistAgentParams = {\n durable: AgentDurableConfig | undefined;\n runId: string;\n agentName: string;\n signature: string;\n version?: string;\n input: string;\n systemPrompt?: string;\n responseSchema?: Record<string, unknown>;\n promptName?: string;\n promptVersion?: string;\n messages: Message[];\n trips: LLMTrip[];\n toolCalls: ToolCall[];\n usage: Usage;\n status: AgentSnapshotStatus;\n startedAt: string;\n};\n\nexport type PersistOutcome = { ok: true } | { ok: false; error: unknown };\n\n/**\n * Write the current run state to the resolved snapshot store. No-op\n * (returns `{ ok: true }`) when neither `durable.store` nor the global\n * `defaultSnapshotStore` is configured — the common non-durable path.\n * Failures are returned as `{ ok: false }` rather than thrown so the\n * engine can surface them via logs without aborting the run — a failed\n * checkpoint loses resume-ability from that point but never breaks an\n * otherwise-healthy run.\n */\nexport async function persistAgentSnapshot(\n params: PersistAgentParams,\n): Promise<PersistOutcome> {\n const store = resolveSnapshotStore(params.durable);\n\n if (!store) {\n return { ok: true };\n }\n\n const snapshot: AgentSnapshot = {\n runId: params.runId,\n agentName: params.agentName,\n signature: params.signature,\n version: params.version,\n input: params.input,\n systemPrompt: params.systemPrompt,\n responseSchema: params.responseSchema,\n promptName: params.promptName,\n promptVersion: params.promptVersion,\n messages: params.messages,\n trips: params.trips,\n toolCalls: params.toolCalls,\n usage: params.usage,\n status: params.status,\n startedAt: params.startedAt,\n savedAt: new Date().toISOString(),\n };\n\n try {\n await store.save(snapshot);\n\n return { ok: true };\n } catch (error) {\n return { ok: false, error };\n }\n}\n\n/**\n * Delete a persisted snapshot — used after a successful run when\n * `durable.deleteOnComplete` is set. Never throws: a failed delete is\n * surfaced as `{ ok: false }` and the engine logs it. No-op (ok) when no\n * store is configured.\n */\nexport async function deleteAgentSnapshot(params: {\n durable: AgentDurableConfig | undefined;\n runId: string;\n}): Promise<PersistOutcome> {\n const store = resolveSnapshotStore(params.durable);\n\n if (!store) {\n return { ok: true };\n }\n\n try {\n await store.delete(params.runId);\n\n return { ok: true };\n } catch (error) {\n return { ok: false, error };\n }\n}\n\n/**\n * Load a persisted snapshot for `resume()` and run the drift check.\n * Throws `AgentExecutionError` when no store is configured or when the\n * run is missing; throws `AgentDriftError` when the stored signature\n * doesn't match the current definition (unless `force` is set).\n */\nexport async function loadAgentSnapshotForResume(params: {\n durable: AgentDurableConfig | undefined;\n agentName: string;\n signature: string;\n runId: string;\n options?: AgentResumeOptions<unknown>;\n}): Promise<AgentSnapshot> {\n const store = resolveSnapshotStore(params.durable);\n\n if (!store) {\n throw new AgentExecutionError(\n `agent \"${params.agentName}\" has no durable store configured — set \\`durable: { store }\\` on the config or call \\`ai.config({ defaultSnapshotStore })\\` at boot before calling resume()`,\n { context: { runId: params.runId } },\n );\n }\n\n const snapshot = (await store.load(params.runId)) ?? null;\n\n if (!snapshot) {\n throw new AgentExecutionError(\n `agent \"${params.agentName}\": no snapshot for runId \"${params.runId}\"`,\n { context: { runId: params.runId } },\n );\n }\n\n if (!params.options?.force && snapshot.signature !== params.signature) {\n throw new AgentDriftError(\n `agent \"${params.agentName}\" signature drift on resume`,\n {\n savedSignature: snapshot.signature,\n currentSignature: params.signature,\n runId: params.runId,\n },\n );\n }\n\n return snapshot;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoCA,SAAS,qBACP,SAC0C;CAC1C,OACE,SAAS,SACR,4BAA4B;AAEjC;;;;;;;;;;AAgCA,eAAsB,qBACpB,QACyB;CACzB,MAAM,QAAQ,qBAAqB,OAAO,OAAO;CAEjD,IAAI,CAAC,OACH,OAAO,EAAE,IAAI,KAAK;CAGpB,MAAM,WAA0B;EAC9B,OAAO,OAAO;EACd,WAAW,OAAO;EAClB,WAAW,OAAO;EAClB,SAAS,OAAO;EAChB,OAAO,OAAO;EACd,cAAc,OAAO;EACrB,gBAAgB,OAAO;EACvB,YAAY,OAAO;EACnB,eAAe,OAAO;EACtB,UAAU,OAAO;EACjB,OAAO,OAAO;EACd,WAAW,OAAO;EAClB,OAAO,OAAO;EACd,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB,0BAAS,IAAI,KAAK,EAAC,CAAC,YAAY;CAClC;CAEA,IAAI;EACF,MAAM,MAAM,KAAK,QAAQ;EAEzB,OAAO,EAAE,IAAI,KAAK;CACpB,SAAS,OAAO;EACd,OAAO;GAAE,IAAI;GAAO;EAAM;CAC5B;AACF;;;;;;;AAQA,eAAsB,oBAAoB,QAGd;CAC1B,MAAM,QAAQ,qBAAqB,OAAO,OAAO;CAEjD,IAAI,CAAC,OACH,OAAO,EAAE,IAAI,KAAK;CAGpB,IAAI;EACF,MAAM,MAAM,OAAO,OAAO,KAAK;EAE/B,OAAO,EAAE,IAAI,KAAK;CACpB,SAAS,OAAO;EACd,OAAO;GAAE,IAAI;GAAO;EAAM;CAC5B;AACF;;;;;;;AAQA,eAAsB,2BAA2B,QAMtB;CACzB,MAAM,QAAQ,qBAAqB,OAAO,OAAO;CAEjD,IAAI,CAAC,OACH,MAAM,IAAI,oBACR,UAAU,OAAO,UAAU,+JAC3B,EAAE,SAAS,EAAE,OAAO,OAAO,MAAM,EAAE,CACrC;CAGF,MAAM,WAAY,MAAM,MAAM,KAAK,OAAO,KAAK,KAAM;CAErD,IAAI,CAAC,UACH,MAAM,IAAI,oBACR,UAAU,OAAO,UAAU,4BAA4B,OAAO,MAAM,IACpE,EAAE,SAAS,EAAE,OAAO,OAAO,MAAM,EAAE,CACrC;CAGF,IAAI,CAAC,OAAO,SAAS,SAAS,SAAS,cAAc,OAAO,WAC1D,MAAM,IAAI,gBACR,UAAU,OAAO,UAAU,8BAC3B;EACE,gBAAgB,SAAS;EACzB,kBAAkB,OAAO;EACzB,OAAO,OAAO;CAChB,CACF;CAGF,OAAO;AACT"}
|
package/esm/ai/src/ai.mjs
CHANGED
|
@@ -21,6 +21,13 @@ import { redis } from "./checkpoint/redis.mjs";
|
|
|
21
21
|
import { dataset } from "./eval/dataset.mjs";
|
|
22
22
|
import { evalScorers } from "./eval/index.mjs";
|
|
23
23
|
import { human } from "./human/register.mjs";
|
|
24
|
+
import { image } from "./image/image.mjs";
|
|
25
|
+
import "./image/index.mjs";
|
|
26
|
+
import { speech } from "./speech/speech.mjs";
|
|
27
|
+
import "./speech/index.mjs";
|
|
28
|
+
import { audioFromBuffer, audioFromFile, audioMediaTypeForFilename } from "./transcribe/audio-input.mjs";
|
|
29
|
+
import { transcribe } from "./transcribe/transcribe.mjs";
|
|
30
|
+
import "./transcribe/index.mjs";
|
|
24
31
|
import { guardrail as guardrail$1 } from "./guard/guardrail.mjs";
|
|
25
32
|
import { mockRouter } from "./mock/mock-router.mjs";
|
|
26
33
|
import "./mock/index.mjs";
|
|
@@ -35,9 +42,20 @@ import { instruction } from "./system-prompt/instruction.mjs";
|
|
|
35
42
|
import { persona } from "./system-prompt/persona.mjs";
|
|
36
43
|
import { systemPrompt } from "./system-prompt/system-prompt.mjs";
|
|
37
44
|
import { defaultPromptsManager } from "./prompts/prompts-manager.mjs";
|
|
45
|
+
import { chunk } from "./rag/chunk/chunk.mjs";
|
|
46
|
+
import { cacheVectorStore } from "./rag/store/cache-vector-store.mjs";
|
|
38
47
|
import { rag } from "./rag/rag.mjs";
|
|
48
|
+
import { pgVectorStore, vectorLiteral } from "./rag/store/pg-vector-store.mjs";
|
|
49
|
+
import { loadText } from "./rag/loaders/load-text.mjs";
|
|
50
|
+
import { loadHtml } from "./rag/loaders/load-html.mjs";
|
|
51
|
+
import { loadWeb } from "./rag/loaders/load-web.mjs";
|
|
52
|
+
import { loadPdf } from "./rag/loaders/load-pdf.mjs";
|
|
39
53
|
import { keywordReranker } from "./rag/rerank/keyword-reranker.mjs";
|
|
40
54
|
import { llmReranker } from "./rag/rerank/llm-reranker.mjs";
|
|
55
|
+
import { reciprocalRankFusion } from "./rag/hybrid/rrf.mjs";
|
|
56
|
+
import { bm25Rank } from "./rag/hybrid/bm25.mjs";
|
|
57
|
+
import { hybridRank } from "./rag/hybrid/hybrid-rank.mjs";
|
|
58
|
+
import { multiQuery } from "./rag/transforms/multi-query.mjs";
|
|
41
59
|
import "./rag/index.mjs";
|
|
42
60
|
import { prompt } from "./prompt/prompt.mjs";
|
|
43
61
|
import "./prompt/index.mjs";
|
|
@@ -113,7 +131,19 @@ const ai = {
|
|
|
113
131
|
planner,
|
|
114
132
|
rag: Object.assign(rag, {
|
|
115
133
|
keywordReranker,
|
|
116
|
-
llmReranker
|
|
134
|
+
llmReranker,
|
|
135
|
+
chunk,
|
|
136
|
+
cacheVectorStore,
|
|
137
|
+
pgVectorStore,
|
|
138
|
+
vectorLiteral,
|
|
139
|
+
loadText,
|
|
140
|
+
loadHtml,
|
|
141
|
+
loadWeb,
|
|
142
|
+
loadPdf,
|
|
143
|
+
bm25Rank,
|
|
144
|
+
reciprocalRankFusion,
|
|
145
|
+
hybridRank,
|
|
146
|
+
multiQuery
|
|
117
147
|
}),
|
|
118
148
|
spawnSubAgent,
|
|
119
149
|
router,
|
|
@@ -121,6 +151,12 @@ const ai = {
|
|
|
121
151
|
batch,
|
|
122
152
|
streamObject,
|
|
123
153
|
serve,
|
|
154
|
+
image,
|
|
155
|
+
speech,
|
|
156
|
+
transcribe,
|
|
157
|
+
audioFromFile,
|
|
158
|
+
audioFromBuffer,
|
|
159
|
+
audioMediaTypeForFilename,
|
|
124
160
|
fallbackModel,
|
|
125
161
|
eval: evalScorers,
|
|
126
162
|
dataset,
|
package/esm/ai/src/ai.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai.mjs","names":["checkpointMemory","checkpointPg","checkpointRedis","snapshotMemory","snapshotPg","snapshotRedis","guardrailSuite"],"sources":["../../../../../../../../@warlock.js/ai/src/ai.ts"],"sourcesContent":["import { agent } from \"./agent/agent\";\nimport { batch } from \"./batch\";\nimport { streamObject } from \"./object-stream\";\nimport { serve } from \"./serve\";\nimport {\n checkpointMemory,\n checkpointPg,\n checkpointRedis,\n} from \"./checkpoint\";\nimport { setAIConfig } from \"./config\";\nimport { dataset, evalScorers } from \"./eval\";\nimport { humanApproval } from \"./human/human-approval\";\nimport { human } from \"./human/register\";\nimport { resume } from \"./human/resume\";\nimport {\n interruptMemory,\n interruptPg,\n interruptRedis,\n} from \"./human/stores\";\nimport { guardrail as guardrailSuite } from \"./guard/guardrail\";\nimport { budget, readBudgetFallbackSignal } from \"./middleware/builtins/budget\";\nimport { memory } from \"./memory\";\nimport { guardrail } from \"./middleware/builtins/guardrail\";\nimport { semanticCache } from \"./middleware/builtins/semantic-cache\";\nimport { composeMiddleware, forTool } from \"./middleware/helpers\";\nimport { mockRouter } from \"./mock\";\nimport { fallbackModel } from \"./model\";\nimport { orchestrator } from \"./orchestrator\";\nimport { planner } from \"./planner\";\nimport { defaultPromptsManager } from \"./prompts/prompts-manager\";\nimport { rag } from \"./rag\";\nimport { keywordReranker } from \"./rag/rerank/keyword-reranker\";\nimport { llmReranker } from \"./rag/rerank/llm-reranker\";\nimport { spawnSubAgent } from \"./agent/spawn-sub-agent\";\nimport { skills } from \"./skills\";\nimport { prompt } from \"./prompt\";\nimport { vcr } from \"./vcr\";\nimport { snapshotMemory, snapshotPg, snapshotRedis } from \"./snapshot\";\nimport { fanOut, router } from \"./supervisor\";\nimport { supervisor } from \"./supervisor/supervisor\";\nimport { team } from \"./team/team\";\nimport { instruction } from \"./system-prompt/instruction\";\nimport { persona } from \"./system-prompt/persona\";\nimport { systemPrompt } from \"./system-prompt/system-prompt\";\nimport { tool } from \"./tool/tool\";\nimport { step } from \"./workflow/step\";\nimport { workflow } from \"./workflow/workflow\";\n\n/**\n * The shape of the top-level `ai` namespace. Declared as an `interface` (not an\n * inferred `const` type) so satellite packages can attach their verb via\n * `declare module \"@warlock.js/ai\" { interface Ai { … } }` — e.g. `ai.workspace`,\n * `ai.tools`, `ai.mcp`, `ai.human`. The runtime object below is asserted to this\n * type; a satellite assigns its member on import.\n */\nexport interface Ai {\n config: typeof setAIConfig;\n tool: typeof tool;\n agent: typeof agent;\n systemPrompt: typeof systemPrompt;\n persona: typeof persona;\n instruction: typeof instruction;\n workflow: typeof workflow;\n step: typeof step;\n supervisor: typeof supervisor;\n team: typeof team;\n orchestrator: typeof orchestrator;\n memory: typeof memory;\n skills: typeof skills;\n planner: typeof planner;\n rag: typeof rag & {\n keywordReranker: typeof keywordReranker;\n llmReranker: typeof llmReranker;\n };\n spawnSubAgent: typeof spawnSubAgent;\n router: typeof router;\n fanOut: typeof fanOut;\n batch: typeof batch;\n /** Structured-output streaming — partial-object snapshots + a strict final parse (A1). */\n streamObject: typeof streamObject;\n /** Serve an executable as an SSE HTTP endpoint — production serving primitive (A3). */\n serve: typeof serve;\n fallbackModel: typeof fallbackModel;\n eval: typeof evalScorers;\n dataset: typeof dataset;\n prompt: typeof prompt;\n /**\n * Process-wide registry of named, versioned `systemPrompt(...)` builders,\n * keyed by `name@version`. A `systemPrompt(input, { name })` (or any\n * `.meta({ name })` rename) auto-registers here; `ai.prompts.get(name)` /\n * `.resolve(name)` reads them back, and `systemPrompt().merge(name)` folds a\n * registered prompt into a new one.\n */\n prompts: ReturnType<typeof defaultPromptsManager>;\n vcr: typeof vcr;\n mockRouter: typeof mockRouter;\n middleware: {\n budget: typeof budget;\n guardrail: typeof guardrail;\n semanticCache: typeof semanticCache;\n compose: typeof composeMiddleware;\n forTool: typeof forTool;\n readBudgetFallbackSignal: typeof readBudgetFallbackSignal;\n };\n checkpoint: {\n memory: typeof checkpointMemory;\n pg: typeof checkpointPg;\n redis: typeof checkpointRedis;\n };\n snapshot: {\n memory: typeof snapshotMemory;\n pg: typeof snapshotPg;\n redis: typeof snapshotRedis;\n };\n /**\n * Human-in-the-loop tool approval (interrupt / resume).\n *\n * - `human.approval(options)` — the `tool.before` approval-gate middleware.\n * - `human.resume(id, decision, options)` — out-of-process durable resume.\n * - `human.interrupt.{memory,pg,redis}()` — durable {@link InterruptStore}\n * factories (memory ships real; pg/redis are lazy optional peers).\n */\n human: {\n approval: typeof humanApproval;\n resume: typeof resume;\n interrupt: {\n memory: typeof interruptMemory;\n pg: typeof interruptPg;\n redis: typeof interruptRedis;\n };\n };\n /**\n * Content-intelligence guardrail. `ai.guardrail(options)` builds a composed\n * input / output / tool middleware; `ai.guardrail.{pii,topic,injection,moderation}`\n * are the built-in detector factories.\n */\n guardrail: typeof guardrailSuite;\n}\n\n/**\n * Top-level `ai` namespace — holds built-in factories and user-registered SDK adapters.\n *\n * Factories:\n * - `ai.tool(...)` — wrap an async function with a schema-validated input.\n * - `ai.agent(...)` — build an executable agent from model + tools + prompt.\n * - `ai.systemPrompt(...)` — compose a layered persona + instructions prompt.\n * - `ai.persona(text)` — reusable persona block (can be passed to `systemPrompt`).\n * - `ai.instruction(text)` — reusable instruction block (can be passed to `systemPrompt`).\n * - `ai.orchestrator(...)` — session-state manager wrapped around a supervisor (durable session, drift detection, resume, commands).\n * - `ai.memory(...)` — build an agent-memory store with WORKING (in-run scratch) and SEMANTIC (cache-driver `.similar()` recall) tiers.\n * - `ai.skills(...)` — build a runtime skills library (always-injected metadata catalog + on-demand loadSkill tool).\n * - `ai.planner(...)` — build an executable that generates an ordered plan over registered capabilities, then runs it step-by-step.\n * - `ai.spawnSubAgent(spec)` — thin wrapper that builds a fresh one-shot `agent()` with an optional per-task `budget` and runs the task once. A general primitive (not planner-specific).\n * - `ai.router(...)` — build a supervisor-compatible routing agent from named intents.\n * - `ai.fanOut(unit, count)` — spread one agent/workflow into N intent entries for voting / self-consistency.\n * - `ai.batch(executable, items, opts?)` — run any executable over a dataset with bounded concurrency + per-item retry.\n * - `ai.fallbackModel(models, opts?)` — wrap an ordered model list that fails over to the next on transient provider errors.\n * - `ai.eval.{exact,contains,predicate,judge}(...)` — built-in scorer factories for `agent.eval(...)`.\n * - `ai.mockRouter(decisions, opts?)` — deterministic supervisor `route` callback for tests.\n * - `ai.checkpoint.{memory,pg,redis}()` — durable orchestrator session checkpoint stores.\n * - `ai.snapshot.{memory,pg,redis}()` — supervisor-run snapshot stores for `iterate: true` resume.\n * - `ai.human.approval(...)` / `ai.human.resume(...)` / `ai.human.interrupt.{memory,pg,redis}()` — human-in-the-loop tool approval (interrupt / resume).\n * - `ai.guardrail(options)` + `ai.guardrail.{pii,topic,injection,moderation}(...)` — content-intelligence guardrails (moderation / PII / injection / topic).\n * - `ai.openai.model(...)` / `ai.anthropic.model(...)` / ... once the adapter SDK is registered.\n *\n * @example\n * const alex = ai.persona(\"You are Alex, a TypeScript expert.\");\n * const replyIn = ai.instruction(\"Respond in {{language|English}}.\");\n *\n * const prompt = ai.systemPrompt().persona(alex).instruction(replyIn);\n *\n * const myAgent = ai.agent({\n * model: ai.openai.model({ name: \"gpt-4o\" }),\n * systemPrompt: prompt,\n * tools: [myTool],\n * });\n *\n * const result = await myAgent.execute(\"What is the weather in Cairo?\", {\n * placeholders: { language: \"Arabic\" },\n * });\n */\nexport const ai = {\n config: setAIConfig,\n tool,\n agent,\n systemPrompt,\n persona,\n instruction,\n workflow,\n step,\n supervisor,\n team,\n orchestrator,\n memory,\n skills,\n planner,\n rag: Object.assign(rag, { keywordReranker, llmReranker }),\n spawnSubAgent,\n router,\n fanOut,\n batch,\n streamObject,\n serve,\n fallbackModel,\n eval: evalScorers,\n dataset,\n prompt,\n prompts: defaultPromptsManager(),\n vcr,\n mockRouter,\n middleware: {\n budget,\n guardrail,\n semanticCache,\n compose: composeMiddleware,\n forTool,\n readBudgetFallbackSignal,\n },\n checkpoint: {\n memory: checkpointMemory,\n pg: checkpointPg,\n redis: checkpointRedis,\n },\n snapshot: {\n memory: snapshotMemory,\n pg: snapshotPg,\n redis: snapshotRedis,\n },\n human,\n guardrail: guardrailSuite,\n // Asserted (not `: Ai`) so a consumer build that augments `Ai` with a\n // satellite verb (e.g. `workspace`) doesn't flag this literal as missing it.\n} as Ai;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqLA,MAAa,KAAK;CAChB,QAAQ;CACR;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,KAAK,OAAO,OAAO,KAAK;EAAE;EAAiB;CAAY,CAAC;CACxD;CACA;CACA;CACA;CACA;CACA;CACA;CACA,MAAM;CACN;CACA;CACA,SAAS,sBAAsB;CAC/B;CACA;CACA,YAAY;EACV;EACA;EACA;EACA,SAAS;EACT;EACA;CACF;CACA,YAAY;EACV,QAAQA;EACJC;EACGC;CACT;CACA,UAAU;EACR,QAAQC;EACR,IAAIC;EACJ,OAAOC;CACT;CACA;CACA,WAAWC;AAGb"}
|
|
1
|
+
{"version":3,"file":"ai.mjs","names":["checkpointMemory","checkpointPg","checkpointRedis","snapshotMemory","snapshotPg","snapshotRedis","guardrailSuite"],"sources":["../../../../../../../../@warlock.js/ai/src/ai.ts"],"sourcesContent":["import { agent } from \"./agent/agent\";\nimport { batch } from \"./batch\";\nimport { streamObject } from \"./object-stream\";\nimport { serve } from \"./serve\";\nimport {\n checkpointMemory,\n checkpointPg,\n checkpointRedis,\n} from \"./checkpoint\";\nimport { setAIConfig } from \"./config\";\nimport { dataset, evalScorers } from \"./eval\";\nimport { humanApproval } from \"./human/human-approval\";\nimport { human } from \"./human/register\";\nimport { image } from \"./image\";\nimport { speech } from \"./speech\";\nimport {\n audioFromBuffer,\n audioFromFile,\n audioMediaTypeForFilename,\n transcribe,\n} from \"./transcribe\";\nimport { resume } from \"./human/resume\";\nimport {\n interruptMemory,\n interruptPg,\n interruptRedis,\n} from \"./human/stores\";\nimport { guardrail as guardrailSuite } from \"./guard/guardrail\";\nimport { budget, readBudgetFallbackSignal } from \"./middleware/builtins/budget\";\nimport { memory } from \"./memory\";\nimport { guardrail } from \"./middleware/builtins/guardrail\";\nimport { semanticCache } from \"./middleware/builtins/semantic-cache\";\nimport { composeMiddleware, forTool } from \"./middleware/helpers\";\nimport { mockRouter } from \"./mock\";\nimport { fallbackModel } from \"./model\";\nimport { orchestrator } from \"./orchestrator\";\nimport { planner } from \"./planner\";\nimport { defaultPromptsManager } from \"./prompts/prompts-manager\";\nimport {\n bm25Rank,\n cacheVectorStore,\n chunk,\n hybridRank,\n keywordReranker,\n llmReranker,\n loadHtml,\n loadPdf,\n loadText,\n loadWeb,\n multiQuery,\n pgVectorStore,\n rag,\n reciprocalRankFusion,\n vectorLiteral,\n} from \"./rag\";\nimport { spawnSubAgent } from \"./agent/spawn-sub-agent\";\nimport { skills } from \"./skills\";\nimport { prompt } from \"./prompt\";\nimport { vcr } from \"./vcr\";\nimport { snapshotMemory, snapshotPg, snapshotRedis } from \"./snapshot\";\nimport { fanOut, router } from \"./supervisor\";\nimport { supervisor } from \"./supervisor/supervisor\";\nimport { team } from \"./team/team\";\nimport { instruction } from \"./system-prompt/instruction\";\nimport { persona } from \"./system-prompt/persona\";\nimport { systemPrompt } from \"./system-prompt/system-prompt\";\nimport { tool } from \"./tool/tool\";\nimport { step } from \"./workflow/step\";\nimport { workflow } from \"./workflow/workflow\";\n\n/**\n * The shape of the top-level `ai` namespace. Declared as an `interface` (not an\n * inferred `const` type) so satellite packages can attach their verb via\n * `declare module \"@warlock.js/ai\" { interface Ai { … } }` — e.g. `ai.workspace`,\n * `ai.tools`, `ai.mcp`, `ai.human`. The runtime object below is asserted to this\n * type; a satellite assigns its member on import.\n */\nexport interface Ai {\n config: typeof setAIConfig;\n tool: typeof tool;\n agent: typeof agent;\n systemPrompt: typeof systemPrompt;\n persona: typeof persona;\n instruction: typeof instruction;\n workflow: typeof workflow;\n step: typeof step;\n supervisor: typeof supervisor;\n team: typeof team;\n orchestrator: typeof orchestrator;\n memory: typeof memory;\n skills: typeof skills;\n planner: typeof planner;\n rag: typeof rag & {\n keywordReranker: typeof keywordReranker;\n llmReranker: typeof llmReranker;\n chunk: typeof chunk;\n cacheVectorStore: typeof cacheVectorStore;\n pgVectorStore: typeof pgVectorStore;\n vectorLiteral: typeof vectorLiteral;\n loadText: typeof loadText;\n loadHtml: typeof loadHtml;\n loadWeb: typeof loadWeb;\n loadPdf: typeof loadPdf;\n bm25Rank: typeof bm25Rank;\n reciprocalRankFusion: typeof reciprocalRankFusion;\n hybridRank: typeof hybridRank;\n multiQuery: typeof multiQuery;\n };\n spawnSubAgent: typeof spawnSubAgent;\n router: typeof router;\n fanOut: typeof fanOut;\n batch: typeof batch;\n /** Structured-output streaming — partial-object snapshots + a strict final parse (A1). */\n streamObject: typeof streamObject;\n /** Serve an executable as an SSE HTTP endpoint — production serving primitive (A3). */\n serve: typeof serve;\n /**\n * Generate images from a text prompt — the image-output verb of the\n * output-modality track (Theme I). Wraps an `ImageModelContract` (from\n * `openai.image(...)` / `google.image(...)`) in the uniform\n * never-throws `{ data, error, usage, report }` envelope with cost-truth\n * and observability.\n */\n image: typeof image;\n /** Text-to-speech (TTS) — the audio-output verb of the modality track (Theme I). */\n speech: typeof speech;\n /** Speech-to-text (STT / transcription) — the audio-input verb of the modality track (Theme I). */\n transcribe: typeof transcribe;\n /** Read an audio file from disk → `AudioInput` for `ai.transcribe` (non-AI file plumbing). */\n audioFromFile: typeof audioFromFile;\n /** Package raw audio bytes → `AudioInput` for `ai.transcribe`. */\n audioFromBuffer: typeof audioFromBuffer;\n /** Resolve the audio media type from a filename's extension. */\n audioMediaTypeForFilename: typeof audioMediaTypeForFilename;\n fallbackModel: typeof fallbackModel;\n eval: typeof evalScorers;\n dataset: typeof dataset;\n prompt: typeof prompt;\n /**\n * Process-wide registry of named, versioned `systemPrompt(...)` builders,\n * keyed by `name@version`. A `systemPrompt(input, { name })` (or any\n * `.meta({ name })` rename) auto-registers here; `ai.prompts.get(name)` /\n * `.resolve(name)` reads them back, and `systemPrompt().merge(name)` folds a\n * registered prompt into a new one.\n */\n prompts: ReturnType<typeof defaultPromptsManager>;\n vcr: typeof vcr;\n mockRouter: typeof mockRouter;\n middleware: {\n budget: typeof budget;\n guardrail: typeof guardrail;\n semanticCache: typeof semanticCache;\n compose: typeof composeMiddleware;\n forTool: typeof forTool;\n readBudgetFallbackSignal: typeof readBudgetFallbackSignal;\n };\n checkpoint: {\n memory: typeof checkpointMemory;\n pg: typeof checkpointPg;\n redis: typeof checkpointRedis;\n };\n snapshot: {\n memory: typeof snapshotMemory;\n pg: typeof snapshotPg;\n redis: typeof snapshotRedis;\n };\n /**\n * Human-in-the-loop tool approval (interrupt / resume).\n *\n * - `human.approval(options)` — the `tool.before` approval-gate middleware.\n * - `human.resume(id, decision, options)` — out-of-process durable resume.\n * - `human.interrupt.{memory,pg,redis}()` — durable {@link InterruptStore}\n * factories (memory ships real; pg/redis are lazy optional peers).\n */\n human: {\n approval: typeof humanApproval;\n resume: typeof resume;\n interrupt: {\n memory: typeof interruptMemory;\n pg: typeof interruptPg;\n redis: typeof interruptRedis;\n };\n };\n /**\n * Content-intelligence guardrail. `ai.guardrail(options)` builds a composed\n * input / output / tool middleware; `ai.guardrail.{pii,topic,injection,moderation}`\n * are the built-in detector factories.\n */\n guardrail: typeof guardrailSuite;\n}\n\n/**\n * Top-level `ai` namespace — holds built-in factories and user-registered SDK adapters.\n *\n * Factories:\n * - `ai.tool(...)` — wrap an async function with a schema-validated input.\n * - `ai.agent(...)` — build an executable agent from model + tools + prompt.\n * - `ai.systemPrompt(...)` — compose a layered persona + instructions prompt.\n * - `ai.persona(text)` — reusable persona block (can be passed to `systemPrompt`).\n * - `ai.instruction(text)` — reusable instruction block (can be passed to `systemPrompt`).\n * - `ai.orchestrator(...)` — session-state manager wrapped around a supervisor (durable session, drift detection, resume, commands).\n * - `ai.memory(...)` — build an agent-memory store with WORKING (in-run scratch) and SEMANTIC (cache-driver `.similar()` recall) tiers.\n * - `ai.skills(...)` — build a runtime skills library (always-injected metadata catalog + on-demand loadSkill tool).\n * - `ai.planner(...)` — build an executable that generates an ordered plan over registered capabilities, then runs it step-by-step.\n * - `ai.spawnSubAgent(spec)` — thin wrapper that builds a fresh one-shot `agent()` with an optional per-task `budget` and runs the task once. A general primitive (not planner-specific).\n * - `ai.router(...)` — build a supervisor-compatible routing agent from named intents.\n * - `ai.fanOut(unit, count)` — spread one agent/workflow into N intent entries for voting / self-consistency.\n * - `ai.batch(executable, items, opts?)` — run any executable over a dataset with bounded concurrency + per-item retry.\n * - `ai.fallbackModel(models, opts?)` — wrap an ordered model list that fails over to the next on transient provider errors.\n * - `ai.eval.{exact,contains,predicate,judge}(...)` — built-in scorer factories for `agent.eval(...)`.\n * - `ai.mockRouter(decisions, opts?)` — deterministic supervisor `route` callback for tests.\n * - `ai.checkpoint.{memory,pg,redis}()` — durable orchestrator session checkpoint stores.\n * - `ai.snapshot.{memory,pg,redis}()` — supervisor-run snapshot stores for `iterate: true` resume.\n * - `ai.human.approval(...)` / `ai.human.resume(...)` / `ai.human.interrupt.{memory,pg,redis}()` — human-in-the-loop tool approval (interrupt / resume).\n * - `ai.guardrail(options)` + `ai.guardrail.{pii,topic,injection,moderation}(...)` — content-intelligence guardrails (moderation / PII / injection / topic).\n * - `ai.openai.model(...)` / `ai.anthropic.model(...)` / ... once the adapter SDK is registered.\n *\n * @example\n * const alex = ai.persona(\"You are Alex, a TypeScript expert.\");\n * const replyIn = ai.instruction(\"Respond in {{language|English}}.\");\n *\n * const prompt = ai.systemPrompt().persona(alex).instruction(replyIn);\n *\n * const myAgent = ai.agent({\n * model: ai.openai.model({ name: \"gpt-4o\" }),\n * systemPrompt: prompt,\n * tools: [myTool],\n * });\n *\n * const result = await myAgent.execute(\"What is the weather in Cairo?\", {\n * placeholders: { language: \"Arabic\" },\n * });\n */\nexport const ai = {\n config: setAIConfig,\n tool,\n agent,\n systemPrompt,\n persona,\n instruction,\n workflow,\n step,\n supervisor,\n team,\n orchestrator,\n memory,\n skills,\n planner,\n rag: Object.assign(rag, {\n keywordReranker,\n llmReranker,\n chunk,\n cacheVectorStore,\n pgVectorStore,\n vectorLiteral,\n loadText,\n loadHtml,\n loadWeb,\n loadPdf,\n bm25Rank,\n reciprocalRankFusion,\n hybridRank,\n multiQuery,\n }),\n spawnSubAgent,\n router,\n fanOut,\n batch,\n streamObject,\n serve,\n image,\n speech,\n transcribe,\n audioFromFile,\n audioFromBuffer,\n audioMediaTypeForFilename,\n fallbackModel,\n eval: evalScorers,\n dataset,\n prompt,\n prompts: defaultPromptsManager(),\n vcr,\n mockRouter,\n middleware: {\n budget,\n guardrail,\n semanticCache,\n compose: composeMiddleware,\n forTool,\n readBudgetFallbackSignal,\n },\n checkpoint: {\n memory: checkpointMemory,\n pg: checkpointPg,\n redis: checkpointRedis,\n },\n snapshot: {\n memory: snapshotMemory,\n pg: snapshotPg,\n redis: snapshotRedis,\n },\n human,\n guardrail: guardrailSuite,\n // Asserted (not `: Ai`) so a consumer build that augments `Ai` with a\n // satellite verb (e.g. `workspace`) doesn't flag this literal as missing it.\n} as Ai;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyOA,MAAa,KAAK;CAChB,QAAQ;CACR;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,KAAK,OAAO,OAAO,KAAK;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CACD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,MAAM;CACN;CACA;CACA,SAAS,sBAAsB;CAC/B;CACA;CACA,YAAY;EACV;EACA;EACA;EACA,SAAS;EACT;EACA;CACF;CACA,YAAY;EACV,QAAQA;EACJC;EACGC;CACT;CACA,UAAU;EACR,QAAQC;EACR,IAAIC;EACJ,OAAOC;CACT;CACA;CACA,WAAWC;AAGb"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { AgentExecutionError } from "./agent-execution-error.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../@warlock.js/ai/src/errors/agent-drift-error.ts
|
|
4
|
+
/**
|
|
5
|
+
* `agent.resume(runId)` loaded a durable snapshot whose structural
|
|
6
|
+
* fingerprint does not match the current agent definition (model +
|
|
7
|
+
* provider + sorted tool names + maxTrips + output presence + version).
|
|
8
|
+
* The resume is refused — no trip runs — and the user decides how to
|
|
9
|
+
* recover: discard the snapshot, migrate manually, or call
|
|
10
|
+
* `resume(runId, { force: true })` to bypass the check.
|
|
11
|
+
*
|
|
12
|
+
* Mirrors `SupervisorDriftError` / `WorkflowDriftError` — same rationale,
|
|
13
|
+
* different primitive. Thrown (not returned on `result.error`) because a
|
|
14
|
+
* drifted resume never produces a valid run.
|
|
15
|
+
*/
|
|
16
|
+
var AgentDriftError = class extends AgentExecutionError {
|
|
17
|
+
static {
|
|
18
|
+
this.defaultCategory = "drift";
|
|
19
|
+
}
|
|
20
|
+
constructor(message, options) {
|
|
21
|
+
super(message, options, "AGENT_DRIFT");
|
|
22
|
+
this.name = "AgentDriftError";
|
|
23
|
+
this.savedSignature = options.savedSignature;
|
|
24
|
+
this.currentSignature = options.currentSignature;
|
|
25
|
+
this.runId = options.runId;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
//#endregion
|
|
30
|
+
export { AgentDriftError };
|
|
31
|
+
//# sourceMappingURL=agent-drift-error.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-drift-error.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/errors/agent-drift-error.ts"],"sourcesContent":["import type { AIErrorOptions } from \"./ai-error\";\nimport { AgentExecutionError } from \"./agent-execution-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\nexport type AgentDriftErrorOptions = AIErrorOptions & {\n /** Signature recorded on the snapshot being resumed. */\n savedSignature: string;\n /** Signature computed from the current agent definition. */\n currentSignature: string;\n runId: string;\n};\n\n/**\n * `agent.resume(runId)` loaded a durable snapshot whose structural\n * fingerprint does not match the current agent definition (model +\n * provider + sorted tool names + maxTrips + output presence + version).\n * The resume is refused — no trip runs — and the user decides how to\n * recover: discard the snapshot, migrate manually, or call\n * `resume(runId, { force: true })` to bypass the check.\n *\n * Mirrors `SupervisorDriftError` / `WorkflowDriftError` — same rationale,\n * different primitive. Thrown (not returned on `result.error`) because a\n * drifted resume never produces a valid run.\n */\nexport class AgentDriftError extends AgentExecutionError {\n public static readonly defaultCategory: ErrorCategory = \"drift\";\n\n public readonly savedSignature: string;\n public readonly currentSignature: string;\n public readonly runId: string;\n\n public constructor(message: string, options: AgentDriftErrorOptions) {\n super(message, options, \"AGENT_DRIFT\");\n this.name = \"AgentDriftError\";\n this.savedSignature = options.savedSignature;\n this.currentSignature = options.currentSignature;\n this.runId = options.runId;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwBA,IAAa,kBAAb,cAAqC,oBAAoB;;yBACC;;CAMxD,AAAO,YAAY,SAAiB,SAAiC;EACnE,MAAM,SAAS,SAAS,aAAa;EACrC,KAAK,OAAO;EACZ,KAAK,iBAAiB,QAAQ;EAC9B,KAAK,mBAAmB,QAAQ;EAChC,KAAK,QAAQ,QAAQ;CACvB;AACF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { AIError } from "./ai-error.mjs";
|
|
2
2
|
import { AgentExecutionError } from "./agent-execution-error.mjs";
|
|
3
3
|
import { AgentCancelledError } from "./agent-cancelled-error.mjs";
|
|
4
|
+
import { AgentDriftError } from "./agent-drift-error.mjs";
|
|
4
5
|
import { AgentMaxTripsError } from "./agent-max-trips-error.mjs";
|
|
5
6
|
import { BudgetExceededError } from "./budget-exceeded-error.mjs";
|
|
6
7
|
import { ProviderError } from "./provider-error.mjs";
|
|
@@ -19,6 +20,7 @@ import { OrchestratorDriftError } from "./orchestrator-drift-error.mjs";
|
|
|
19
20
|
import { OutboundPolicyError } from "./outbound-policy-error.mjs";
|
|
20
21
|
import { PlannerFailedError } from "./planner-failed-error.mjs";
|
|
21
22
|
import { PlannerCancelledError } from "./planner-cancelled-error.mjs";
|
|
23
|
+
import { PlannerDriftError } from "./planner-drift-error.mjs";
|
|
22
24
|
import { PlannerPlanInvalidError } from "./planner-plan-invalid-error.mjs";
|
|
23
25
|
import "./provider-auth-error.mjs";
|
|
24
26
|
import "./provider-rate-limit-error.mjs";
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { PlannerFailedError } from "./planner-failed-error.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../@warlock.js/ai/src/errors/planner-drift-error.ts
|
|
4
|
+
/**
|
|
5
|
+
* `planner.resume(runId)` loaded a durable snapshot whose structural
|
|
6
|
+
* fingerprint does not match the current planner definition (name +
|
|
7
|
+
* ordered capability names). The resume is refused — no node runs — and
|
|
8
|
+
* the user decides how to recover: discard the snapshot, migrate
|
|
9
|
+
* manually, or call `resume(runId, { force: true })` to bypass the check.
|
|
10
|
+
*
|
|
11
|
+
* A mid-run re-plan is NOT drift — the plan changed, not the definition;
|
|
12
|
+
* the persisted `replanCount` honors the replan budget across a resume.
|
|
13
|
+
*
|
|
14
|
+
* Mirrors `SupervisorDriftError` / `WorkflowDriftError` — same rationale,
|
|
15
|
+
* different primitive. Thrown (not returned on `result.error`) because a
|
|
16
|
+
* drifted resume never produces a valid run.
|
|
17
|
+
*/
|
|
18
|
+
var PlannerDriftError = class extends PlannerFailedError {
|
|
19
|
+
static {
|
|
20
|
+
this.defaultCategory = "drift";
|
|
21
|
+
}
|
|
22
|
+
constructor(message, options) {
|
|
23
|
+
super(message, options, "PLANNER_DRIFT");
|
|
24
|
+
this.name = "PlannerDriftError";
|
|
25
|
+
this.savedSignature = options.savedSignature;
|
|
26
|
+
this.currentSignature = options.currentSignature;
|
|
27
|
+
this.runId = options.runId;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
//#endregion
|
|
32
|
+
export { PlannerDriftError };
|
|
33
|
+
//# sourceMappingURL=planner-drift-error.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"planner-drift-error.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/errors/planner-drift-error.ts"],"sourcesContent":["import type { AIErrorOptions } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\nimport { PlannerFailedError } from \"./planner-failed-error\";\n\nexport type PlannerDriftErrorOptions = AIErrorOptions & {\n /** Signature recorded on the snapshot being resumed. */\n savedSignature: string;\n /** Signature computed from the current planner definition. */\n currentSignature: string;\n runId: string;\n};\n\n/**\n * `planner.resume(runId)` loaded a durable snapshot whose structural\n * fingerprint does not match the current planner definition (name +\n * ordered capability names). The resume is refused — no node runs — and\n * the user decides how to recover: discard the snapshot, migrate\n * manually, or call `resume(runId, { force: true })` to bypass the check.\n *\n * A mid-run re-plan is NOT drift — the plan changed, not the definition;\n * the persisted `replanCount` honors the replan budget across a resume.\n *\n * Mirrors `SupervisorDriftError` / `WorkflowDriftError` — same rationale,\n * different primitive. Thrown (not returned on `result.error`) because a\n * drifted resume never produces a valid run.\n */\nexport class PlannerDriftError extends PlannerFailedError {\n public static readonly defaultCategory: ErrorCategory = \"drift\";\n\n public readonly savedSignature: string;\n public readonly currentSignature: string;\n public readonly runId: string;\n\n public constructor(message: string, options: PlannerDriftErrorOptions) {\n super(message, options, \"PLANNER_DRIFT\");\n this.name = \"PlannerDriftError\";\n this.savedSignature = options.savedSignature;\n this.currentSignature = options.currentSignature;\n this.runId = options.runId;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,IAAa,oBAAb,cAAuC,mBAAmB;;yBACA;;CAMxD,AAAO,YAAY,SAAiB,SAAmC;EACrE,MAAM,SAAS,SAAS,eAAe;EACvC,KAAK,OAAO;EACZ,KAAK,iBAAiB,QAAQ;EAC9B,KAAK,mBAAmB,QAAQ;EAChC,KAAK,QAAQ,QAAQ;CACvB;AACF"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { computeCost } from "../utils/compute-cost.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../@warlock.js/ai/src/image/image-cost.ts
|
|
4
|
+
/**
|
|
5
|
+
* Price one image-generation `Usage` against an
|
|
6
|
+
* {@link ImageModelPricing}, returning a `ModelPricing`-shaped USD
|
|
7
|
+
* breakdown so image spend folds into the exact same `Usage.cost`
|
|
8
|
+
* rollup the text path uses (`accumulateCost` / `mergeUsage`). There is
|
|
9
|
+
* no separate image-cost field anywhere downstream — only this one
|
|
10
|
+
* function, which knows the two metering models:
|
|
11
|
+
*
|
|
12
|
+
* - **Per-image** (DALL·E, Imagen): `perImageBySize[size]` (when the
|
|
13
|
+
* request `size` matches a tier) else flat `perImage`, times the
|
|
14
|
+
* number of images returned, attributed to `cost.output` (the image
|
|
15
|
+
* IS the output). Token channels stay 0.
|
|
16
|
+
* - **Token** (gpt-image-1): delegates to the standard
|
|
17
|
+
* {@link computeCost} against the prompt/image token `Usage`.
|
|
18
|
+
*
|
|
19
|
+
* Per-image wins when both shapes are configured (a provider is one or
|
|
20
|
+
* the other). Returns `undefined` when no usable pricing is present —
|
|
21
|
+
* the framework treats that as "cost unknown", never a false zero.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* computeImageCost({ input: 0, output: 0, total: 0 }, 2, "1024x1024", { perImage: 0.04 });
|
|
25
|
+
* // → { input: 0, output: 0.08 }
|
|
26
|
+
*/
|
|
27
|
+
function computeImageCost(usage, imageCount, size, pricing) {
|
|
28
|
+
if (!pricing) return;
|
|
29
|
+
if (pricing.perImage !== void 0 || pricing.perImageBySize !== void 0) {
|
|
30
|
+
const perImage = resolvePerImageRate(size, pricing);
|
|
31
|
+
if (perImage === void 0) return;
|
|
32
|
+
return {
|
|
33
|
+
input: 0,
|
|
34
|
+
output: perImage * imageCount
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
if (pricing.input !== void 0 && pricing.output !== void 0) return computeCost(usage, {
|
|
38
|
+
input: pricing.input,
|
|
39
|
+
output: pricing.output
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Resolve the USD-per-image rate: a `perImageBySize` tier matching the
|
|
44
|
+
* requested `size` wins, otherwise the flat `perImage`. Returns
|
|
45
|
+
* `undefined` only when neither is set (the caller already gated on
|
|
46
|
+
* per-image metering being configured at all).
|
|
47
|
+
*/
|
|
48
|
+
function resolvePerImageRate(size, pricing) {
|
|
49
|
+
if (size !== void 0 && pricing.perImageBySize?.[size] !== void 0) return pricing.perImageBySize[size];
|
|
50
|
+
return pricing.perImage;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
//#endregion
|
|
54
|
+
export { computeImageCost };
|
|
55
|
+
//# sourceMappingURL=image-cost.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image-cost.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/image/image-cost.ts"],"sourcesContent":["import type { ImageModelPricing } from \"../contracts/image-model.contract\";\nimport type { ModelPricing } from \"../contracts/result/model-pricing.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport { computeCost } from \"../utils/compute-cost\";\n\n/**\n * Price one image-generation `Usage` against an\n * {@link ImageModelPricing}, returning a `ModelPricing`-shaped USD\n * breakdown so image spend folds into the exact same `Usage.cost`\n * rollup the text path uses (`accumulateCost` / `mergeUsage`). There is\n * no separate image-cost field anywhere downstream — only this one\n * function, which knows the two metering models:\n *\n * - **Per-image** (DALL·E, Imagen): `perImageBySize[size]` (when the\n * request `size` matches a tier) else flat `perImage`, times the\n * number of images returned, attributed to `cost.output` (the image\n * IS the output). Token channels stay 0.\n * - **Token** (gpt-image-1): delegates to the standard\n * {@link computeCost} against the prompt/image token `Usage`.\n *\n * Per-image wins when both shapes are configured (a provider is one or\n * the other). Returns `undefined` when no usable pricing is present —\n * the framework treats that as \"cost unknown\", never a false zero.\n *\n * @example\n * computeImageCost({ input: 0, output: 0, total: 0 }, 2, \"1024x1024\", { perImage: 0.04 });\n * // → { input: 0, output: 0.08 }\n */\nexport function computeImageCost(\n usage: Usage,\n imageCount: number,\n size: string | undefined,\n pricing: ImageModelPricing | undefined,\n): ModelPricing | undefined {\n if (!pricing) {\n return undefined;\n }\n\n const perImageMetered = pricing.perImage !== undefined || pricing.perImageBySize !== undefined;\n\n if (perImageMetered) {\n const perImage = resolvePerImageRate(size, pricing);\n\n if (perImage === undefined) {\n return undefined;\n }\n\n return { input: 0, output: perImage * imageCount };\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/**\n * Resolve the USD-per-image rate: a `perImageBySize` tier matching the\n * requested `size` wins, otherwise the flat `perImage`. Returns\n * `undefined` only when neither is set (the caller already gated on\n * per-image metering being configured at all).\n */\nfunction resolvePerImageRate(\n size: string | undefined,\n pricing: ImageModelPricing,\n): number | undefined {\n if (size !== undefined && pricing.perImageBySize?.[size] !== undefined) {\n return pricing.perImageBySize[size];\n }\n\n return pricing.perImage;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,iBACd,OACA,YACA,MACA,SAC0B;CAC1B,IAAI,CAAC,SACH;CAKF,IAFwB,QAAQ,aAAa,UAAa,QAAQ,mBAAmB,QAEhE;EACnB,MAAM,WAAW,oBAAoB,MAAM,OAAO;EAElD,IAAI,aAAa,QACf;EAGF,OAAO;GAAE,OAAO;GAAG,QAAQ,WAAW;EAAW;CACnD;CAEA,IAAI,QAAQ,UAAU,UAAa,QAAQ,WAAW,QACpD,OAAO,YAAY,OAAO;EAAE,OAAO,QAAQ;EAAO,QAAQ,QAAQ;CAAO,CAAC;AAI9E;;;;;;;AAQA,SAAS,oBACP,MACA,SACoB;CACpB,IAAI,SAAS,UAAa,QAAQ,iBAAiB,UAAU,QAC3D,OAAO,QAAQ,eAAe;CAGhC,OAAO,QAAQ;AACjB"}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { AIError } from "../errors/ai-error.mjs";
|
|
2
|
+
import { ProviderError } from "../errors/provider-error.mjs";
|
|
3
|
+
import { generateRunId } from "../utils/generate-run-id.mjs";
|
|
4
|
+
import { stampReportLineage } from "../utils/stamp-report-lineage.mjs";
|
|
5
|
+
import { notifyObservers } from "../observe/resolve-observers.mjs";
|
|
6
|
+
import { computeImageCost } from "./image-cost.mjs";
|
|
7
|
+
|
|
8
|
+
//#region ../@warlock.js/ai/src/image/image.ts
|
|
9
|
+
/**
|
|
10
|
+
* Generate one or more images from a text prompt — the image-output
|
|
11
|
+
* counterpart to `ai.agent`, and the first verb of the output-modality
|
|
12
|
+
* track (Theme I). Wraps an {@link ImageModelContract} (from
|
|
13
|
+
* `openai.image(...)` / `google.image(...)`) in the framework's uniform
|
|
14
|
+
* result contract:
|
|
15
|
+
*
|
|
16
|
+
* - **Never throws.** Provider failures (auth, rate-limit,
|
|
17
|
+
* content-filter, invalid request) surface as a typed `AIError` on
|
|
18
|
+
* `result.error`; `result.data` is then `undefined`.
|
|
19
|
+
* - **Cost-truth.** When the model carries pricing, `result.usage.cost`
|
|
20
|
+
* is filled in — per-token for gpt-image-1, per-image for
|
|
21
|
+
* DALL·E / Imagen — folding into the same `Usage.cost` rollup as text.
|
|
22
|
+
* - **Observable.** The completed {@link ImageReport} routes to any
|
|
23
|
+
* registered `Observer` (panoptic, OTel, …) via the shared `observe`
|
|
24
|
+
* seam, exactly like an agent run.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* const openai = new OpenAISDK({ apiKey });
|
|
28
|
+
* const { data, error, usage } = await ai.image({
|
|
29
|
+
* model: openai.image({ name: "gpt-image-1" }),
|
|
30
|
+
* prompt: "an isometric office desk, soft studio lighting",
|
|
31
|
+
* size: "1024x1024",
|
|
32
|
+
* });
|
|
33
|
+
*
|
|
34
|
+
* if (error) console.warn(error.code);
|
|
35
|
+
* else for (const img of data.images) save(img); // { type: "base64" | "url", ... }
|
|
36
|
+
*/
|
|
37
|
+
async function image(params) {
|
|
38
|
+
const { model, prompt } = params;
|
|
39
|
+
const runId = generateRunId("image");
|
|
40
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
41
|
+
const startPerf = performance.now();
|
|
42
|
+
const usage = {
|
|
43
|
+
input: 0,
|
|
44
|
+
output: 0,
|
|
45
|
+
total: 0
|
|
46
|
+
};
|
|
47
|
+
let data;
|
|
48
|
+
let error;
|
|
49
|
+
let status = "completed";
|
|
50
|
+
let imageCount = 0;
|
|
51
|
+
try {
|
|
52
|
+
const response = await model.generate(prompt, {
|
|
53
|
+
count: params.count,
|
|
54
|
+
size: params.size,
|
|
55
|
+
quality: params.quality,
|
|
56
|
+
aspectRatio: params.aspectRatio,
|
|
57
|
+
negativePrompt: params.negativePrompt,
|
|
58
|
+
format: params.format,
|
|
59
|
+
signal: params.signal,
|
|
60
|
+
...params.options
|
|
61
|
+
});
|
|
62
|
+
Object.assign(usage, response.usage);
|
|
63
|
+
if (usage.cost === void 0) {
|
|
64
|
+
const cost = computeImageCost(usage, response.images.length, params.size, model.pricing);
|
|
65
|
+
if (cost !== void 0) usage.cost = cost;
|
|
66
|
+
}
|
|
67
|
+
data = { images: response.images };
|
|
68
|
+
imageCount = response.images.length;
|
|
69
|
+
} catch (thrown) {
|
|
70
|
+
error = thrown instanceof AIError ? thrown : new ProviderError(toMessage(thrown), { cause: thrown });
|
|
71
|
+
status = params.signal?.aborted ? "cancelled" : "failed";
|
|
72
|
+
}
|
|
73
|
+
const report = {
|
|
74
|
+
runId,
|
|
75
|
+
rootRunId: runId,
|
|
76
|
+
name: params.name ?? "image",
|
|
77
|
+
type: "image",
|
|
78
|
+
status,
|
|
79
|
+
error,
|
|
80
|
+
startedAt,
|
|
81
|
+
endedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
82
|
+
duration: performance.now() - startPerf,
|
|
83
|
+
usage,
|
|
84
|
+
children: [],
|
|
85
|
+
model: {
|
|
86
|
+
name: model.name,
|
|
87
|
+
provider: model.provider
|
|
88
|
+
},
|
|
89
|
+
imageCount,
|
|
90
|
+
reportSchemaVersion: 1
|
|
91
|
+
};
|
|
92
|
+
stampReportLineage(report, {
|
|
93
|
+
rootRunId: runId,
|
|
94
|
+
sessionId: params.sessionId
|
|
95
|
+
});
|
|
96
|
+
await notifyObservers(params.observe, report);
|
|
97
|
+
return {
|
|
98
|
+
type: "image",
|
|
99
|
+
data,
|
|
100
|
+
error,
|
|
101
|
+
usage,
|
|
102
|
+
report
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/** Best-effort message for a non-`AIError` thrown value. */
|
|
106
|
+
function toMessage(thrown) {
|
|
107
|
+
return thrown instanceof Error ? thrown.message : String(thrown);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
//#endregion
|
|
111
|
+
export { image };
|
|
112
|
+
//# sourceMappingURL=image.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image.mjs","names":[],"sources":["../../../../../../../../../@warlock.js/ai/src/image/image.ts"],"sourcesContent":["import type {\n GeneratedImage,\n ImageModelContract,\n} from \"../contracts/image-model.contract\";\nimport 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 { Usage } from \"../contracts/result/usage.type\";\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 { generateRunId } from \"../utils/generate-run-id\";\nimport { stampReportLineage } from \"../utils/stamp-report-lineage\";\nimport { computeImageCost } from \"./image-cost\";\n\n/**\n * Parameters for {@link image}. `model` comes from an adapter's\n * `image()` factory (`openai.image({ name })` / `google.image({ name })`);\n * the rest are provider-neutral generation knobs plus the standard\n * observability seam every verb shares.\n */\nexport type ImageParams = {\n /** The image model to generate from (`sdk.image({ name })`). */\n model: ImageModelContract;\n /** Text description of the image(s) to generate. */\n prompt: string;\n /** How many images to generate. Adapters clamp to the provider max. */\n count?: number;\n /** Requested pixel size as `\"WxH\"` (e.g. `\"1024x1024\"`). */\n size?: string;\n /** Quality tier (e.g. `\"standard\"` / `\"hd\"`). */\n quality?: string;\n /** Aspect ratio (e.g. `\"1:1\"`, `\"16:9\"`) — ratio-based providers (Imagen). */\n aspectRatio?: string;\n /** Concepts to steer away from (Imagen `negativePrompt`). */\n negativePrompt?: string;\n /** Output container hint (`\"png\"` / `\"jpeg\"` / `\"webp\"`). */\n format?: string;\n /** Cancellation handle, wired into the provider request where supported. */\n signal?: AbortSignal;\n /**\n * Observability routing for this call — same `observe` seam as\n * agents / workflows. `true` routes to the globally registered\n * observers; an `Observer` object routes flow-locally; `false` opts\n * out; omitted follows the global observe-all flag.\n */\n observe?: FlowObserveOption;\n /** Groups this call into a session for flat cost/trace queries. */\n sessionId?: string;\n /** Report node name (defaults to `\"image\"`). */\n name?: string;\n /** Provider-specific options forwarded verbatim to the adapter. */\n options?: Record<string, unknown>;\n};\n\n/** Success payload of an {@link image} run. */\nexport type ImageData = {\n /** The generated images, normalized to the discriminated shape. */\n images: GeneratedImage[];\n};\n\n/**\n * The report node an {@link image} run produces — a {@link BaseReport}\n * (`type: \"image\"`) plus which model ran and how many images came back,\n * so panoptic and any flat-row consumer attribute the cost/latency\n * without special-casing.\n */\nexport type ImageReport = BaseReport & {\n type: \"image\";\n /** Identity of the image model this run used. */\n model: { name: string; provider: string };\n /** Number of images returned (0 on failure). */\n imageCount: number;\n};\n\n/**\n * Result envelope of {@link image} — the same uniform\n * `{ data, error, usage, report }` every executable returns, narrowed\n * with the `\"image\"` discriminant.\n */\nexport type ImageResult = ExecuteResult<ImageData> & {\n type: \"image\";\n report: ImageReport;\n};\n\n/**\n * Generate one or more images from a text prompt — the image-output\n * counterpart to `ai.agent`, and the first verb of the output-modality\n * track (Theme I). Wraps an {@link ImageModelContract} (from\n * `openai.image(...)` / `google.image(...)`) in the framework's uniform\n * result contract:\n *\n * - **Never throws.** Provider failures (auth, rate-limit,\n * content-filter, invalid request) surface as a typed `AIError` on\n * `result.error`; `result.data` is then `undefined`.\n * - **Cost-truth.** When the model carries pricing, `result.usage.cost`\n * is filled in — per-token for gpt-image-1, per-image for\n * DALL·E / Imagen — folding into the same `Usage.cost` rollup as text.\n * - **Observable.** The completed {@link ImageReport} routes to any\n * registered `Observer` (panoptic, OTel, …) via the shared `observe`\n * seam, exactly like an agent run.\n *\n * @example\n * const openai = new OpenAISDK({ apiKey });\n * const { data, error, usage } = await ai.image({\n * model: openai.image({ name: \"gpt-image-1\" }),\n * prompt: \"an isometric office desk, soft studio lighting\",\n * size: \"1024x1024\",\n * });\n *\n * if (error) console.warn(error.code);\n * else for (const img of data.images) save(img); // { type: \"base64\" | \"url\", ... }\n */\nexport async function image(params: ImageParams): Promise<ImageResult> {\n const { model, prompt } = params;\n\n const runId = generateRunId(\"image\");\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: ImageData | undefined;\n let error: AIError | undefined;\n let status: ImageReport[\"status\"] = \"completed\";\n let imageCount = 0;\n\n try {\n const response = await model.generate(prompt, {\n count: params.count,\n size: params.size,\n quality: params.quality,\n aspectRatio: params.aspectRatio,\n negativePrompt: params.negativePrompt,\n format: params.format,\n signal: params.signal,\n ...params.options,\n });\n\n // Preserve every usage channel the adapter reported (cached /\n // reasoning / cache-write, and any adapter-supplied `cost`), mirroring\n // how the agent path routes provider usage. Then honor a pre-priced\n // response or compute image cost — `usage.cost ??= …` precedence, same\n // as the agent path.\n Object.assign(usage, response.usage);\n\n if (usage.cost === undefined) {\n const cost = computeImageCost(usage, response.images.length, params.size, model.pricing);\n if (cost !== undefined) {\n usage.cost = cost;\n }\n }\n\n data = { images: response.images };\n imageCount = response.images.length;\n } catch (thrown) {\n error = thrown instanceof AIError ? thrown : new ProviderError(toMessage(thrown), { cause: thrown });\n // A caller-aborted run is \"cancelled\", not \"failed\" — keep the typed\n // cause but distinguish the terminal status for dashboards/retry policy.\n status = params.signal?.aborted ? \"cancelled\" : \"failed\";\n }\n\n const report: ImageReport = {\n runId,\n rootRunId: runId,\n name: params.name ?? \"image\",\n type: \"image\",\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 imageCount,\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: \"image\", data, error, usage, report };\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkHA,eAAsB,MAAM,QAA2C;CACrE,MAAM,EAAE,OAAO,WAAW;CAE1B,MAAM,QAAQ,cAAc,OAAO;CACnC,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,SAAgC;CACpC,IAAI,aAAa;CAEjB,IAAI;EACF,MAAM,WAAW,MAAM,MAAM,SAAS,QAAQ;GAC5C,OAAO,OAAO;GACd,MAAM,OAAO;GACb,SAAS,OAAO;GAChB,aAAa,OAAO;GACpB,gBAAgB,OAAO;GACvB,QAAQ,OAAO;GACf,QAAQ,OAAO;GACf,GAAG,OAAO;EACZ,CAAC;EAOD,OAAO,OAAO,OAAO,SAAS,KAAK;EAEnC,IAAI,MAAM,SAAS,QAAW;GAC5B,MAAM,OAAO,iBAAiB,OAAO,SAAS,OAAO,QAAQ,OAAO,MAAM,MAAM,OAAO;GACvF,IAAI,SAAS,QACX,MAAM,OAAO;EAEjB;EAEA,OAAO,EAAE,QAAQ,SAAS,OAAO;EACjC,aAAa,SAAS,OAAO;CAC/B,SAAS,QAAQ;EACf,QAAQ,kBAAkB,UAAU,SAAS,IAAI,cAAc,UAAU,MAAM,GAAG,EAAE,OAAO,OAAO,CAAC;EAGnG,SAAS,OAAO,QAAQ,UAAU,cAAc;CAClD;CAEA,MAAM,SAAsB;EAC1B;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;EACX,OAAO;GAAE,MAAM,MAAM;GAAM,UAAU,MAAM;EAAS;EACpD;EACA;CACF;CAEA,mBAAmB,QAAQ;EAAE,WAAW;EAAO,WAAW,OAAO;CAAU,CAAC;CAE5E,MAAM,gBAAgB,OAAO,SAAS,MAAM;CAE5C,OAAO;EAAE,MAAM;EAAS;EAAM;EAAO;EAAO;CAAO;AACrD;;AAGA,SAAS,UAAU,QAAyB;CAC1C,OAAO,kBAAkB,QAAQ,OAAO,UAAU,OAAO,MAAM;AACjE"}
|
package/esm/ai/src/index.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { AIError } from "./errors/ai-error.mjs";
|
|
2
2
|
import { AgentExecutionError } from "./errors/agent-execution-error.mjs";
|
|
3
3
|
import { AgentCancelledError } from "./errors/agent-cancelled-error.mjs";
|
|
4
|
+
import { AgentDriftError } from "./errors/agent-drift-error.mjs";
|
|
4
5
|
import { AgentMaxTripsError } from "./errors/agent-max-trips-error.mjs";
|
|
5
6
|
import { BudgetExceededError } from "./errors/budget-exceeded-error.mjs";
|
|
6
7
|
import { ProviderError } from "./errors/provider-error.mjs";
|
|
@@ -16,6 +17,7 @@ import { OrchestratorDriftError } from "./errors/orchestrator-drift-error.mjs";
|
|
|
16
17
|
import { OutboundPolicyError } from "./errors/outbound-policy-error.mjs";
|
|
17
18
|
import { PlannerFailedError } from "./errors/planner-failed-error.mjs";
|
|
18
19
|
import { PlannerCancelledError } from "./errors/planner-cancelled-error.mjs";
|
|
20
|
+
import { PlannerDriftError } from "./errors/planner-drift-error.mjs";
|
|
19
21
|
import { PlannerPlanInvalidError } from "./errors/planner-plan-invalid-error.mjs";
|
|
20
22
|
import { RoutingError } from "./errors/routing-error.mjs";
|
|
21
23
|
import { SchemaValidationError } from "./errors/schema-validation-error.mjs";
|
|
@@ -95,6 +97,14 @@ import { memory as memory$2 } from "./human/stores/memory.mjs";
|
|
|
95
97
|
import { pg as pg$1 } from "./human/stores/pg.mjs";
|
|
96
98
|
import { redis as redis$1 } from "./human/stores/redis.mjs";
|
|
97
99
|
import "./human/stores/index.mjs";
|
|
100
|
+
import { computeImageCost } from "./image/image-cost.mjs";
|
|
101
|
+
import { image } from "./image/image.mjs";
|
|
102
|
+
import "./image/index.mjs";
|
|
103
|
+
import { speech } from "./speech/speech.mjs";
|
|
104
|
+
import "./speech/index.mjs";
|
|
105
|
+
import { audioFromBuffer, audioFromFile, audioMediaTypeForFilename } from "./transcribe/audio-input.mjs";
|
|
106
|
+
import { transcribe } from "./transcribe/transcribe.mjs";
|
|
107
|
+
import "./transcribe/index.mjs";
|
|
98
108
|
import { injection } from "./guard/detectors/injection.mjs";
|
|
99
109
|
import { pii } from "./guard/detectors/pii.mjs";
|
|
100
110
|
import { topic } from "./guard/detectors/topic.mjs";
|
|
@@ -141,8 +151,18 @@ import { defaultPromptsManager, promptKey, prompts } from "./prompts/prompts-man
|
|
|
141
151
|
import { chunk } from "./rag/chunk/chunk.mjs";
|
|
142
152
|
import { cacheVectorStore } from "./rag/store/cache-vector-store.mjs";
|
|
143
153
|
import { rag } from "./rag/rag.mjs";
|
|
154
|
+
import { pgVectorStore, vectorLiteral } from "./rag/store/pg-vector-store.mjs";
|
|
155
|
+
import { loadText } from "./rag/loaders/load-text.mjs";
|
|
156
|
+
import { loadHtml } from "./rag/loaders/load-html.mjs";
|
|
157
|
+
import { loadWeb } from "./rag/loaders/load-web.mjs";
|
|
158
|
+
import { PDF_PARSE_INSTALL_INSTRUCTIONS } from "./rag/loaders/errors.mjs";
|
|
159
|
+
import { loadPdf } from "./rag/loaders/load-pdf.mjs";
|
|
144
160
|
import { keywordReranker } from "./rag/rerank/keyword-reranker.mjs";
|
|
145
161
|
import { llmReranker } from "./rag/rerank/llm-reranker.mjs";
|
|
162
|
+
import { reciprocalRankFusion } from "./rag/hybrid/rrf.mjs";
|
|
163
|
+
import { bm25Rank } from "./rag/hybrid/bm25.mjs";
|
|
164
|
+
import { hybridRank } from "./rag/hybrid/hybrid-rank.mjs";
|
|
165
|
+
import { multiQuery } from "./rag/transforms/multi-query.mjs";
|
|
146
166
|
import "./rag/index.mjs";
|
|
147
167
|
import { PromptNotFoundError, PromptValidationError } from "./prompt/errors.mjs";
|
|
148
168
|
import { prompt } from "./prompt/prompt.mjs";
|