orchajs 0.16.0 → 0.18.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/README.md +9 -3
- package/dist/amarsia/metadata.js +30 -16
- package/dist/amarsia/metadata.js.map +1 -1
- package/dist/cli.js +4 -4
- package/dist/cli.js.map +1 -1
- package/dist/compiler/build-project.js +2 -2
- package/dist/env.d.ts.map +1 -1
- package/dist/env.js +5 -2
- package/dist/env.js.map +1 -1
- package/dist/playground/public/app.js +9 -9
- package/dist/playground/public/app.js.map +4 -4
- package/dist/playground/server.d.ts.map +1 -1
- package/dist/playground/server.js +9 -4
- package/dist/playground/server.js.map +1 -1
- package/dist/project-loader.js +1 -1
- package/dist/providers/google-gemini.d.ts +67 -4
- package/dist/providers/google-gemini.d.ts.map +1 -1
- package/dist/providers/google-gemini.js +13 -2
- package/dist/providers/google-gemini.js.map +1 -1
- package/dist/providers/google-genai.d.ts.map +1 -1
- package/dist/providers/google-genai.js +2 -2
- package/dist/providers/google-genai.js.map +1 -1
- package/dist/providers/index.js +11 -1
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/vertex-ai.d.ts.map +1 -1
- package/dist/providers/vertex-ai.js +2 -2
- package/dist/providers/vertex-ai.js.map +1 -1
- package/dist/runtime/actions/context.js +25 -1
- package/dist/runtime/actions/context.js.map +1 -1
- package/dist-cjs/amarsia/metadata.js +37 -25
- package/dist-cjs/amarsia/metadata.js.map +2 -2
- package/dist-cjs/amarsia/sync.js +1 -1
- package/dist-cjs/cli-agents-template.js +1 -1
- package/dist-cjs/compiler/build-project.js +24 -24
- package/dist-cjs/compiler/build-project.js.map +2 -2
- package/dist-cjs/compiler/compile.js +31 -31
- package/dist-cjs/compiler/compile.js.map +2 -2
- package/dist-cjs/env.js +10 -7
- package/dist-cjs/env.js.map +2 -2
- package/dist-cjs/errors.js +1 -1
- package/dist-cjs/file-content.js +6 -6
- package/dist-cjs/file-content.js.map +2 -2
- package/dist-cjs/index.js +1 -1
- package/dist-cjs/integrations/esbuild.js +4 -4
- package/dist-cjs/integrations/esbuild.js.map +2 -2
- package/dist-cjs/orcha.js +4 -4
- package/dist-cjs/orcha.js.map +2 -2
- package/dist-cjs/playground/server.js +34 -30
- package/dist-cjs/playground/server.js.map +2 -2
- package/dist-cjs/playground/source.js +11 -11
- package/dist-cjs/playground/source.js.map +2 -2
- package/dist-cjs/project-loader.js +11 -11
- package/dist-cjs/project-loader.js.map +2 -2
- package/dist-cjs/providers/anthropic.js +1 -1
- package/dist-cjs/providers/bedrock.js +8 -8
- package/dist-cjs/providers/bedrock.js.map +2 -2
- package/dist-cjs/providers/catalog.js +1 -1
- package/dist-cjs/providers/deepseek.js +1 -1
- package/dist-cjs/providers/dispatcher.js +1 -1
- package/dist-cjs/providers/google-gemini.js +13 -3
- package/dist-cjs/providers/google-gemini.js.map +2 -2
- package/dist-cjs/providers/google-genai.js +2 -2
- package/dist-cjs/providers/google-genai.js.map +2 -2
- package/dist-cjs/providers/index.js +11 -1
- package/dist-cjs/providers/index.js.map +2 -2
- package/dist-cjs/providers/openai.js +1 -1
- package/dist-cjs/providers/sse.js +1 -1
- package/dist-cjs/providers/types.js +1 -1
- package/dist-cjs/providers/vertex-ai.js +6 -2
- package/dist-cjs/providers/vertex-ai.js.map +2 -2
- package/dist-cjs/runtime/actions/context.js +26 -2
- package/dist-cjs/runtime/actions/context.js.map +2 -2
- package/dist-cjs/runtime/actions/execute.js +1 -1
- package/dist-cjs/runtime/actions/native.js +3 -3
- package/dist-cjs/runtime/actions/native.js.map +2 -2
- package/dist-cjs/runtime/actions/sandbox.js +1 -1
- package/dist-cjs/runtime/agent.js +3 -3
- package/dist-cjs/runtime/agent.js.map +2 -2
- package/dist-cjs/runtime/context.js +1 -1
- package/dist-cjs/runtime/create-orcha.js +3 -3
- package/dist-cjs/runtime/create-orcha.js.map +2 -2
- package/dist-cjs/runtime/execution.js +1 -1
- package/dist-cjs/runtime/session-events.js +1 -1
- package/dist-cjs/runtime/structured-output.js +1 -1
- package/dist-cjs/storage/browser-indexeddb.js +1 -1
- package/dist-cjs/storage/create-store.js +1 -1
- package/dist-cjs/storage/edge-store.js +1 -1
- package/dist-cjs/storage/migrate.js +1 -1
- package/dist-cjs/storage/node-jsonl.js +10 -10
- package/dist-cjs/storage/node-jsonl.js.map +2 -2
- package/dist-cjs/storage/node-sqlite.js +7 -7
- package/dist-cjs/storage/node-sqlite.js.map +2 -2
- package/dist-cjs/storage/react-native-jsonl.js +1 -1
- package/dist-cjs/testing.js +17 -17
- package/dist-cjs/testing.js.map +2 -2
- package/dist-cjs/types/google-genai-sdk.d.js +3 -0
- package/dist-cjs/types/google-genai-sdk.d.js.map +7 -0
- package/dist-cjs/types.js +1 -1
- package/package.json +14 -9
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/playground/source.ts"],
|
|
4
|
-
"sourcesContent": ["import { readFile, readdir } from \"
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAkC;AAClC,
|
|
4
|
+
"sourcesContent": ["import { readFile, readdir } from \"fs/promises\";\nimport { resolve } from \"path\";\nimport { getOrchaRuntimeContext } from \"../runtime/context.js\";\nimport type { OrchaClient } from \"../runtime/create-orcha.js\";\nimport type {\n AgentRegistration,\n CompiledAgentManifest,\n} from \"../types.js\";\n\nexport interface PlaygroundSourceItem {\n key: string;\n name: string;\n description?: string;\n enabled: boolean;\n configuration: Record<string, unknown>;\n rawConfiguration: string;\n instructions?: string;\n source?: string;\n}\n\nexport interface PlaygroundAgentSource {\n key: string;\n name: string;\n description?: string;\n provider: string;\n model: string;\n actionCount: number;\n skillCount: number;\n evaluationCount: number;\n subagentCount: number;\n configuration: Record<string, unknown>;\n rawConfiguration: string;\n instructions: string;\n actions: PlaygroundSourceItem[];\n skills: PlaygroundSourceItem[];\n evaluations: PlaygroundSourceItem[];\n subagents: Array<{\n key: string;\n name: string;\n description?: string;\n }>;\n}\n\nexport async function readPlaygroundAgentSource(\n orcha: OrchaClient,\n agentKey: string,\n): Promise<PlaygroundAgentSource> {\n const context = getOrchaRuntimeContext(orcha);\n const manifest = context.bundle.agents[agentKey];\n const registration = context.registrations[agentKey];\n if (!manifest || !registration) {\n throw new Error(`Unknown agent \"${agentKey}\".`);\n }\n const directory = registeredAgentDirectory(\n context.projectRoot,\n registration,\n );\n const rawConfiguration = await readRequired(\n resolve(directory, \"index.json\"),\n );\n const configuration = parseObject(rawConfiguration, `${agentKey}/index.json`);\n const instructions = await readRequired(\n resolve(directory, \"instructions.md\"),\n );\n\n return {\n key: agentKey,\n name: manifest.name,\n description: manifest.description,\n provider: manifest.provider,\n model: manifest.model,\n actionCount: Object.keys(manifest.actions).length,\n skillCount: Object.keys(manifest.skills).length,\n evaluationCount: Object.keys(manifest.evaluations).length,\n subagentCount: Object.keys(manifest.subagents).length,\n configuration,\n rawConfiguration,\n instructions,\n actions: await readCollectionItems(\n directory,\n \"actions\",\n manifest.actions,\n true,\n ),\n skills: await readCollectionItems(\n directory,\n \"skills\",\n manifest.skills,\n false,\n ),\n evaluations: await readCollectionItems(\n directory,\n \"evaluations\",\n manifest.evaluations,\n false,\n ),\n subagents: Object.entries(manifest.subagents).map(([key, child]) => ({\n key,\n name: child.name,\n description: child.description,\n })),\n };\n}\n\nfunction registeredAgentDirectory(\n projectRoot: string,\n registration: AgentRegistration,\n): string {\n const registeredPath =\n typeof registration === \"string\" ? registration : registration.path;\n return resolve(projectRoot, \"orcha\", registeredPath);\n}\n\nasync function readCollectionItems(\n agentDirectory: string,\n collection: \"actions\" | \"skills\" | \"evaluations\",\n manifests:\n | CompiledAgentManifest[\"actions\"]\n | CompiledAgentManifest[\"skills\"]\n | CompiledAgentManifest[\"evaluations\"],\n includeSource: boolean,\n): Promise<PlaygroundSourceItem[]> {\n const root = resolve(agentDirectory, collection);\n let entries;\n try {\n entries = await readdir(root, { withFileTypes: true });\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return [];\n }\n throw error;\n }\n const byDirectory = new Map(\n Object.entries(manifests).map(([key, manifest]) => [\n manifest.directoryName,\n { key, manifest },\n ]),\n );\n return Promise.all(\n entries\n .filter((entry) => entry.isDirectory() && !entry.name.startsWith(\".\"))\n .sort((left, right) => left.name.localeCompare(right.name))\n .map(async (entry) => {\n const directory = resolve(root, entry.name);\n const rawConfiguration = await readRequired(\n resolve(directory, \"index.json\"),\n );\n const configuration = parseObject(\n rawConfiguration,\n `${collection}/${entry.name}/index.json`,\n );\n const compiled = byDirectory.get(entry.name);\n const instructions = includeSource\n ? undefined\n : await readOptional(resolve(directory, \"instructions.md\"));\n const source = includeSource\n ? await readOptional(resolve(directory, \"index.js\"))\n : undefined;\n return {\n key: compiled?.key ?? entry.name,\n name:\n typeof configuration.name === \"string\"\n ? configuration.name\n : entry.name,\n description:\n typeof configuration.description === \"string\"\n ? configuration.description\n : undefined,\n enabled: configuration.enabled !== false,\n configuration,\n rawConfiguration,\n ...(instructions !== undefined ? { instructions } : {}),\n ...(source !== undefined ? { source } : {}),\n };\n }),\n );\n}\n\nasync function readRequired(path: string): Promise<string> {\n return readFile(path, \"utf8\");\n}\n\nasync function readOptional(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return undefined;\n }\n throw error;\n }\n}\n\nfunction parseObject(\n source: string,\n label: string,\n): Record<string, unknown> {\n const value: unknown = JSON.parse(source);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${label} must contain a JSON object.`);\n }\n return value as Record<string, unknown>;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAkC;AAClC,kBA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U,CAAC,IACjD;AACJ,aAAO;AAAA,QACL,KAAK,UAAU,OAAO,MAAM;AAAA,QAC5B,MACE,OAAO,cAAc,SAAS,WAC1B,cAAc,OACd,MAAM;AAAA,QACZ,aACE,OAAO,cAAc,gBAAgB,WACjC,cAAc,cACd;AAAA,QACN,SAAS,cAAc,YAAY;AAAA,QACnC;AAAA,QACA;AAAA,QACA,GAAI,iBAAiB,SAAY,EAAE,aAAa,IAAI,CAAC;AAAA,QACrD,GAAI,WAAW,SAAY,EAAE,OAAO,IAAI,CAAC;AAAA,MAC3C;AAAA,IACF,CAAC;AAAA,EACL;AACF;AAEA,eAAe,aAAa,MAA+B;AACzD,aAAO,0BAAS,MAAM,MAAM;AAC9B;AAEA,eAAe,aAAa,MAA2C;AACrE,MAAI;AACF,WAAO,UAAM,0BAAS,MAAM,MAAM;AAAA,EACpC,SAAS,OAAO;AACd,QACE,iBAAiB,SACjB,UAAU,SACT,MAAgC,SAAS,UAC1C;AACA,aAAO;AAAA,IACT;AACA,UAAM;AAAA,EACR;AACF;AAEA,SAAS,YACP,QACA,OACyB;AACzB,QAAM,QAAiB,KAAK,MAAM,MAAM;AACxC,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG;AAC/D,UAAM,IAAI,MAAM,GAAG,KAAK,8BAA8B;AAAA,EACxD;AACA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict"; const __orchaImportMetaUrl = require("
|
|
1
|
+
"use strict"; const __orchaImportMetaUrl = require("url").pathToFileURL(__filename).href;
|
|
2
2
|
"use strict";
|
|
3
3
|
var __defProp = Object.defineProperty;
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -22,21 +22,21 @@ __export(project_loader_exports, {
|
|
|
22
22
|
loadProject: () => loadProject
|
|
23
23
|
});
|
|
24
24
|
module.exports = __toCommonJS(project_loader_exports);
|
|
25
|
-
var
|
|
26
|
-
var import_promises = require("
|
|
27
|
-
var
|
|
28
|
-
var
|
|
25
|
+
var import_fs = require("fs");
|
|
26
|
+
var import_promises = require("fs/promises");
|
|
27
|
+
var import_path = require("path");
|
|
28
|
+
var import_url = require("url");
|
|
29
29
|
var import_esbuild = require("esbuild");
|
|
30
30
|
var import_env = require("./env.js");
|
|
31
31
|
var import_orcha = require("./orcha.js");
|
|
32
32
|
async function loadProject(projectRoot) {
|
|
33
33
|
(0, import_env.loadProjectEnvironment)(projectRoot);
|
|
34
|
-
const registryPath = (0,
|
|
35
|
-
if (!(0,
|
|
34
|
+
const registryPath = (0, import_path.resolve)(projectRoot, "orcha/index.ts");
|
|
35
|
+
if (!(0, import_fs.existsSync)(registryPath)) {
|
|
36
36
|
throw new Error('Missing "orcha/index.ts". Run "orcha init" first.');
|
|
37
37
|
}
|
|
38
|
-
const temporaryDirectory = (0,
|
|
39
|
-
const bundlePath = (0,
|
|
38
|
+
const temporaryDirectory = (0, import_path.resolve)(projectRoot, ".orcha/.cli");
|
|
39
|
+
const bundlePath = (0, import_path.resolve)(
|
|
40
40
|
temporaryDirectory,
|
|
41
41
|
`registry-${process.pid}-${Date.now()}.mjs`
|
|
42
42
|
);
|
|
@@ -49,7 +49,7 @@ async function loadProject(projectRoot) {
|
|
|
49
49
|
bundle: true,
|
|
50
50
|
format: "esm",
|
|
51
51
|
platform: "node",
|
|
52
|
-
target: "
|
|
52
|
+
target: "node18",
|
|
53
53
|
packages: "external",
|
|
54
54
|
logLevel: "silent"
|
|
55
55
|
});
|
|
@@ -58,7 +58,7 @@ async function loadProject(projectRoot) {
|
|
|
58
58
|
process.env.ORCHA_PROJECT_ROOT = projectRoot;
|
|
59
59
|
process.env.ORCHA_COMPILING = "1";
|
|
60
60
|
try {
|
|
61
|
-
await import(`${(0,
|
|
61
|
+
await import(`${(0, import_url.pathToFileURL)(bundlePath).href}?time=${Date.now()}`);
|
|
62
62
|
} finally {
|
|
63
63
|
restoreEnvironment("ORCHA_PROJECT_ROOT", previousRoot);
|
|
64
64
|
restoreEnvironment("ORCHA_COMPILING", previousCompiling);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/project-loader.ts"],
|
|
4
|
-
"sourcesContent": ["import { existsSync } from \"
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["import { existsSync } from \"fs\";\nimport { mkdir, rm } from \"fs/promises\";\nimport { resolve } from \"path\";\nimport { pathToFileURL } from \"url\";\nimport { build as bundleEntry } from \"esbuild\";\nimport { loadProjectEnvironment } from \"./env.js\";\nimport { orcha } from \"./orcha.js\";\n\nexport async function loadProject(projectRoot: string): Promise<void> {\n loadProjectEnvironment(projectRoot);\n const registryPath = resolve(projectRoot, \"orcha/index.ts\");\n if (!existsSync(registryPath)) {\n throw new Error('Missing \"orcha/index.ts\". Run \"orcha init\" first.');\n }\n const temporaryDirectory = resolve(projectRoot, \".orcha/.cli\");\n const bundlePath = resolve(\n temporaryDirectory,\n `registry-${process.pid}-${Date.now()}.mjs`,\n );\n await mkdir(temporaryDirectory, { recursive: true });\n try {\n const previousBundle = orcha.isInitialized()\n ? orcha.getCompiledBundle()\n : undefined;\n await bundleEntry({\n entryPoints: [registryPath],\n outfile: bundlePath,\n bundle: true,\n format: \"esm\",\n platform: \"node\",\n target: \"node18\",\n packages: \"external\",\n logLevel: \"silent\",\n });\n const previousRoot = process.env.ORCHA_PROJECT_ROOT;\n const previousCompiling = process.env.ORCHA_COMPILING;\n process.env.ORCHA_PROJECT_ROOT = projectRoot;\n process.env.ORCHA_COMPILING = \"1\";\n try {\n await import(\n `${pathToFileURL(bundlePath).href}?time=${Date.now()}`\n );\n } finally {\n restoreEnvironment(\"ORCHA_PROJECT_ROOT\", previousRoot);\n restoreEnvironment(\"ORCHA_COMPILING\", previousCompiling);\n }\n if (\n !orcha.isInitialized() ||\n orcha.getCompiledBundle() === previousBundle\n ) {\n throw new Error(\n '\"orcha/index.ts\" must call orcha.init({ providers, agents }).',\n );\n }\n } finally {\n await rm(bundlePath, { force: true });\n }\n}\n\nfunction restoreEnvironment(\n name: string,\n value: string | undefined,\n): void {\n if (value === undefined) {\n delete process.env[name];\n } else {\n process.env[name] = value;\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAA2B;AAC3B,sBAA0B;AAC1B,kBAAwB;AACxB,iBAA8B;AAC9B,qBAAqC;AACrC,iBAAuC;AACvC,mBAAsB;AAEtB,eAAsB,YAAY,aAAoC;AACpE,yCAAuB,WAAW;AAClC,QAAM,mBAAe,qBAAQ,aAAa,gBAAgB;AAC1D,MAAI,KAAC,sBAAW,YAAY,GAAG;AAC7B,UAAM,IAAI,MAAM,mDAAmD;AAAA,EACrE;AACA,QAAM,yBAAqB,qBAAQ,aAAa,aAAa;AAC7D,QAAM,iBAAa;AAAA,IACjB;AAAA,IACA,YAAY,QAAQ,GAAG,IAAI,KAAK,IAAI,CAAC;AAAA,EACvC;AACA,YAAM,uBAAM,oBAAoB,EAAE,WAAW,KAAK,CAAC;AACnD,MAAI;AACF,UAAM,iBAAiB,mBAAM,cAAc,IACvC,mBAAM,kBAAkB,IACxB;AACJ,cAAM,eAAAA,OAAY;AAAA,MAChB,aAAa,CAAC,YAAY;AAAA,MAC1B,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,UAAU;AAAA,MACV,UAAU;AAAA,IACZ,CAAC;AACD,UAAM,eAAe,QAAQ,IAAI;AACjC,UAAM,oBAAoB,QAAQ,IAAI;AACtC,YAAQ,IAAI,qBAAqB;AACjC,YAAQ,IAAI,kBAAkB;AAC9B,QAAI;AACF,YAAM,OACJ,OAAG,0BAAc,UAAU,EAAE,IAAI,SAAS,KAAK,IAAI,CAAC;AAAA,IAExD,UAAE;AACA,yBAAmB,sBAAsB,YAAY;AACrD,yBAAmB,mBAAmB,iBAAiB;AAAA,IACzD;AACA,QACE,CAAC,mBAAM,cAAc,KACrB,mBAAM,kBAAkB,MAAM,gBAC9B;AACA,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAAA,EACF,UAAE;AACA,cAAM,oBAAG,YAAY,EAAE,OAAO,KAAK,CAAC;AAAA,EACtC;AACF;AAEA,SAAS,mBACP,MACA,OACM;AACN,MAAI,UAAU,QAAW;AACvB,WAAO,QAAQ,IAAI,IAAI;AAAA,EACzB,OAAO;AACL,YAAQ,IAAI,IAAI,IAAI;AAAA,EACtB;AACF;",
|
|
6
6
|
"names": ["bundleEntry"]
|
|
7
7
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict"; const __orchaImportMetaUrl = require("
|
|
1
|
+
"use strict"; const __orchaImportMetaUrl = require("url").pathToFileURL(__filename).href;
|
|
2
2
|
"use strict";
|
|
3
3
|
var __defProp = Object.defineProperty;
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict"; const __orchaImportMetaUrl = require("
|
|
1
|
+
"use strict"; const __orchaImportMetaUrl = require("url").pathToFileURL(__filename).href;
|
|
2
2
|
"use strict";
|
|
3
3
|
var __defProp = Object.defineProperty;
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -24,8 +24,8 @@ __export(bedrock_exports, {
|
|
|
24
24
|
});
|
|
25
25
|
module.exports = __toCommonJS(bedrock_exports);
|
|
26
26
|
var import_client_bedrock_runtime = require("@aws-sdk/client-bedrock-runtime");
|
|
27
|
-
var
|
|
28
|
-
var
|
|
27
|
+
var import_crypto = require("crypto");
|
|
28
|
+
var import_path = require("path");
|
|
29
29
|
var import_errors = require("../errors.js");
|
|
30
30
|
var import_file_content = require("../file-content.js");
|
|
31
31
|
var import_structured_output = require("../runtime/structured-output.js");
|
|
@@ -207,7 +207,7 @@ function toBedrockBinaryBlock(bytes, mimeType, fileName) {
|
|
|
207
207
|
);
|
|
208
208
|
}
|
|
209
209
|
function documentFormat(fileName, mimeType) {
|
|
210
|
-
const extension = (0,
|
|
210
|
+
const extension = (0, import_path.extname)(fileName).slice(1).toLowerCase();
|
|
211
211
|
if (["csv", "doc", "docx", "html", "md", "pdf", "txt", "xls", "xlsx"].includes(
|
|
212
212
|
extension
|
|
213
213
|
)) {
|
|
@@ -225,14 +225,14 @@ function documentFormat(fileName, mimeType) {
|
|
|
225
225
|
return void 0;
|
|
226
226
|
}
|
|
227
227
|
function safeBedrockDocumentName(fileName) {
|
|
228
|
-
const name = (0,
|
|
228
|
+
const name = (0, import_path.basename)(fileName, (0, import_path.extname)(fileName)).replace(/[^A-Za-z0-9()[\] -]/g, " ").replace(/\s+/g, " ").trim();
|
|
229
229
|
return name || "document";
|
|
230
230
|
}
|
|
231
231
|
function fileNameFromUri(uri) {
|
|
232
232
|
try {
|
|
233
|
-
return (0,
|
|
233
|
+
return (0, import_path.basename)(new URL(uri).pathname) || "document";
|
|
234
234
|
} catch {
|
|
235
|
-
return (0,
|
|
235
|
+
return (0, import_path.basename)(uri) || "document";
|
|
236
236
|
}
|
|
237
237
|
}
|
|
238
238
|
function imageFormat(mimeType) {
|
|
@@ -434,7 +434,7 @@ function invalidToolInputError(options) {
|
|
|
434
434
|
const previewLimit = 1e3;
|
|
435
435
|
const receivedStart = options.input.length > previewLimit ? `${options.input.slice(0, previewLimit)}\u2026` : options.input;
|
|
436
436
|
const receivedEnd = options.input.length > previewLimit ? `\u2026${options.input.slice(-previewLimit)}` : options.input;
|
|
437
|
-
const receivedSha256 = (0,
|
|
437
|
+
const receivedSha256 = (0, import_crypto.createHash)("sha256").update(options.input).digest("hex");
|
|
438
438
|
const requestReference = options.requestId ? ` Bedrock request ID: ${options.requestId}.` : "";
|
|
439
439
|
return new import_errors.OrchaError(
|
|
440
440
|
"provider_error",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/providers/bedrock.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n BedrockRuntimeClient,\n ConverseStreamCommand,\n type ContentBlock,\n type ConverseStreamCommandInput,\n type ConverseStreamOutput,\n type DocumentFormat,\n type Message,\n type TokenUsage,\n} from \"@aws-sdk/client-bedrock-runtime\";\nimport { createHash } from \"node:crypto\";\nimport { basename, extname } from \"node:path\";\nimport { OrchaError } from \"../errors.js\";\nimport { readLocalFileContent } from \"../file-content.js\";\nimport { parseStructuredOutput } from \"../runtime/structured-output.js\";\nimport type {\n BedrockProviderConfiguration,\n MessageContent,\n ProviderConfiguration,\n} from \"../types.js\";\nimport type {\n ProviderAdapter,\n ProviderAssistantBlock,\n ProviderMessage,\n ProviderRequest,\n ProviderResponse,\n ProviderStopReason,\n ProviderToolCall,\n} from \"./types.js\";\n\ninterface PartialTextBlock {\n type: \"text\";\n text: string;\n}\n\ninterface PartialReasoningBlock {\n type: \"reasoning\";\n text: string;\n signature?: string;\n redactedContent?: Uint8Array;\n}\n\ninterface PartialToolCall {\n type: \"tool_call\";\n callId: string;\n name: string;\n input: string;\n}\n\ntype PartialBlock =\n | PartialTextBlock\n | PartialReasoningBlock\n | PartialToolCall;\n\ntype BedrockDocument =\n | null\n | boolean\n | number\n | string\n | BedrockDocument[]\n | { [key: string]: BedrockDocument };\n\ninterface CollectedBedrockResponse {\n requestId?: string;\n blocks: ProviderAssistantBlock[];\n stopReason?: string;\n usage?: TokenUsage;\n}\n\nexport interface BedrockContentClient {\n send(\n command: ConverseStreamCommand,\n options?: { abortSignal?: AbortSignal },\n ): Promise<{\n stream?: AsyncIterable<ConverseStreamOutput>;\n $metadata: { requestId?: string };\n }>;\n}\n\nexport const bedrockProvider: ProviderAdapter = {\n name: \"bedrock\",\n generate: generateBedrock,\n};\n\nasync function generateBedrock(\n configuration: ProviderConfiguration,\n request: ProviderRequest,\n): Promise<ProviderResponse> {\n const bedrockConfiguration = validateConfiguration(configuration);\n if (request.outputType === \"image\" || request.outputType === \"audio\") {\n throw new OrchaError(\n \"unsupported_provider_capability\",\n `Amazon Bedrock Converse does not support \"${request.outputType}\" as a direct agent output.`,\n );\n }\n\n const client = new BedrockRuntimeClient({\n region: bedrockConfiguration.region,\n ...(bedrockConfiguration.baseUrl\n ? { endpoint: bedrockConfiguration.baseUrl }\n : {}),\n ...(bedrockConfiguration.credentials\n ? { credentials: bedrockConfiguration.credentials }\n : {}),\n });\n return generateBedrockContent(client, request);\n}\n\nexport async function generateBedrockContent(\n client: BedrockContentClient,\n request: ProviderRequest,\n): Promise<ProviderResponse> {\n const input: ConverseStreamCommandInput = {\n modelId: request.model,\n system: [{ text: systemPrompt(request) }],\n messages: await toBedrockMessages(request.messages),\n ...(request.maxTokens\n ? { inferenceConfig: { maxTokens: request.maxTokens } }\n : {}),\n };\n\n if (request.tools.length > 0) {\n input.toolConfig = {\n tools: request.tools.map((tool) => ({\n toolSpec: {\n name: tool.name,\n description: tool.description,\n inputSchema: {\n json: toBedrockDocument(tool.parameters),\n },\n },\n })),\n };\n }\n if (request.reasoningLevel && isAnthropicModel(request.model)) {\n input.additionalModelRequestFields = {\n thinking: { type: \"adaptive\" },\n output_config: { effort: request.reasoningLevel },\n };\n }\n\n const response = await client.send(\n new ConverseStreamCommand(input),\n { abortSignal: request.signal },\n );\n if (!response.stream) {\n throw new Error(\"Amazon Bedrock returned no response stream.\");\n }\n\n const collected = await collectBedrockStream(\n response.stream,\n request,\n response.$metadata.requestId,\n request.publishOutput,\n );\n return toProviderResponse(request, collected);\n}\n\nfunction validateConfiguration(\n configuration: ProviderConfiguration,\n): BedrockProviderConfiguration {\n if (\n !(\"region\" in configuration) ||\n typeof configuration.region !== \"string\" ||\n !configuration.region.trim()\n ) {\n throw new Error(\n 'Missing AWS region in orcha.init({ providers: { bedrock: { region: \"...\" } } }).',\n );\n }\n if (\n configuration.credentials &&\n (!configuration.credentials.accessKeyId.trim() ||\n !configuration.credentials.secretAccessKey.trim())\n ) {\n throw new Error(\n \"Bedrock credentials require accessKeyId and secretAccessKey.\",\n );\n }\n return configuration;\n}\n\nfunction systemPrompt(request: ProviderRequest): string {\n if (request.outputType !== \"json\") {\n return request.systemPrompt;\n }\n return `${request.systemPrompt}\\n\\nReturn only valid JSON matching this JSON Schema:\\n${JSON.stringify(request.outputSchema ?? {})}`;\n}\n\nasync function toBedrockMessages(\n messages: ProviderMessage[],\n): Promise<Message[]> {\n const output: Message[] = [];\n for (const message of messages) {\n if (message.role === \"user\") {\n output.push({\n role: \"user\",\n content:\n typeof message.content === \"string\"\n ? [{ text: message.content }]\n : await Promise.all(\n message.content.map(toBedrockUserBlock),\n ),\n });\n continue;\n }\n if (message.role === \"tool\") {\n output.push({\n role: \"user\",\n content: message.results.map((result) => ({\n toolResult: {\n toolUseId: result.callId,\n content: [\n { json: toBedrockDocument(result.output) },\n ],\n ...(result.isError ? { status: \"error\" as const } : {}),\n },\n })),\n });\n continue;\n }\n\n output.push({\n role: \"assistant\",\n content: message.content.map((block) =>\n toBedrockAssistantBlock(\n block,\n message.provider === \"bedrock\",\n ),\n ),\n });\n }\n return output;\n}\n\nasync function toBedrockUserBlock(\n block: MessageContent,\n): Promise<ContentBlock> {\n if (block.type === \"text\") {\n return { text: block.text };\n }\n if (block.type === \"file\") {\n const file = await readLocalFileContent(block);\n return toBedrockBinaryBlock(\n file.bytes,\n block.mimeType,\n file.fileName,\n );\n }\n if (\n block.type === \"image\" ||\n block.type === \"url\"\n ) {\n const response = await fetch(block.fileUri);\n if (!response.ok) {\n throw new Error(\n `Could not load Bedrock file input: HTTP ${response.status}.`,\n );\n }\n return toBedrockBinaryBlock(\n new Uint8Array(await response.arrayBuffer()),\n block.mimeType,\n fileNameFromUri(block.fileUri),\n );\n }\n throw new OrchaError(\n \"unsupported_content_type\",\n `Amazon Bedrock does not support Orcha content type \"${block.type}\" with MIME type \"${block.mimeType}\".`,\n );\n}\n\nfunction toBedrockBinaryBlock(\n bytes: Uint8Array,\n mimeType: string,\n fileName: string,\n): ContentBlock {\n if (mimeType.startsWith(\"image/\")) {\n return {\n image: {\n format: imageFormat(mimeType),\n source: {\n bytes,\n },\n },\n };\n }\n const format = documentFormat(fileName, mimeType);\n if (format) {\n return {\n document: {\n format,\n name: safeBedrockDocumentName(fileName),\n source: { bytes },\n },\n };\n }\n throw new OrchaError(\n \"unsupported_content_type\",\n `Amazon Bedrock does not support file MIME type \"${mimeType}\".`,\n );\n}\n\nfunction documentFormat(\n fileName: string,\n mimeType: string,\n): DocumentFormat | undefined {\n const extension = extname(fileName).slice(1).toLowerCase();\n if (\n [\"csv\", \"doc\", \"docx\", \"html\", \"md\", \"pdf\", \"txt\", \"xls\", \"xlsx\"].includes(\n extension,\n )\n ) {\n return extension as DocumentFormat;\n }\n if (mimeType === \"application/pdf\") return \"pdf\";\n if (mimeType === \"application/msword\") return \"doc\";\n if (\n mimeType ===\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\n ) return \"docx\";\n if (mimeType === \"application/vnd.ms-excel\") return \"xls\";\n if (\n mimeType ===\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"\n ) return \"xlsx\";\n if (mimeType === \"text/csv\") return \"csv\";\n if (mimeType === \"text/html\") return \"html\";\n if (mimeType === \"text/markdown\") return \"md\";\n if (mimeType === \"text/plain\") return \"txt\";\n return undefined;\n}\n\nfunction safeBedrockDocumentName(fileName: string): string {\n const name = basename(fileName, extname(fileName))\n .replace(/[^A-Za-z0-9()[\\] -]/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n return name || \"document\";\n}\n\nfunction fileNameFromUri(uri: string): string {\n try {\n return basename(new URL(uri).pathname) || \"document\";\n } catch {\n return basename(uri) || \"document\";\n }\n}\n\nfunction imageFormat(\n mimeType: string,\n): \"png\" | \"jpeg\" | \"gif\" | \"webp\" {\n const subtype = mimeType.toLowerCase().split(\";\")[0]?.split(\"/\")[1];\n if (\n subtype === \"png\" ||\n subtype === \"jpeg\" ||\n subtype === \"gif\" ||\n subtype === \"webp\"\n ) {\n return subtype;\n }\n if (subtype === \"jpg\") {\n return \"jpeg\";\n }\n throw new OrchaError(\n \"unsupported_content_type\",\n `Amazon Bedrock does not support image MIME type \"${mimeType}\".`,\n );\n}\n\nfunction toBedrockAssistantBlock(\n block: ProviderAssistantBlock,\n replayBedrockState: boolean,\n): ContentBlock {\n if (block.type === \"text\") {\n return { text: block.text };\n }\n if (block.type === \"tool_call\") {\n return {\n toolUse: {\n toolUseId: block.callId,\n name: block.name,\n input: toBedrockDocument(block.arguments),\n },\n };\n }\n if (!replayBedrockState) {\n return { text: block.text };\n }\n if (!block.text && block.replay?.opaqueData) {\n return {\n reasoningContent: {\n redactedContent: Uint8Array.from(\n Buffer.from(block.replay.opaqueData, \"base64\"),\n ),\n },\n };\n }\n return {\n reasoningContent: {\n reasoningText: {\n text: block.text,\n ...(block.replay?.opaqueData\n ? { signature: block.replay.opaqueData }\n : {}),\n },\n },\n };\n}\n\nasync function collectBedrockStream(\n stream: AsyncIterable<ConverseStreamOutput>,\n request: ProviderRequest,\n requestId?: string,\n publishOutput?: (output: string) => void,\n): Promise<CollectedBedrockResponse> {\n const blocks = new Map<number, PartialBlock>();\n let stopReason: string | undefined;\n let usage: TokenUsage | undefined;\n let cumulativeText = \"\";\n\n for await (const event of stream) {\n throwStreamError(event);\n\n const start = event.contentBlockStart;\n if (start?.start?.toolUse) {\n blocks.set(start.contentBlockIndex ?? blocks.size, {\n type: \"tool_call\",\n callId: start.start.toolUse.toolUseId ?? \"\",\n name: start.start.toolUse.name ?? \"\",\n input: \"\",\n });\n }\n\n const deltaEvent = event.contentBlockDelta;\n const delta = deltaEvent?.delta;\n const index = deltaEvent?.contentBlockIndex ?? blocks.size;\n if (delta?.text !== undefined) {\n const block = getPartialTextBlock(blocks, index);\n block.text += delta.text;\n cumulativeText += delta.text;\n publishOutput?.(cumulativeText);\n }\n if (delta?.toolUse?.input !== undefined) {\n const block = blocks.get(index);\n if (!block || block.type !== \"tool_call\") {\n throw new Error(\n `Amazon Bedrock streamed tool input before tool start at block ${index}.`,\n );\n }\n block.input += delta.toolUse.input;\n }\n if (delta?.reasoningContent) {\n const block = getPartialReasoningBlock(blocks, index);\n if (delta.reasoningContent.text !== undefined) {\n block.text += delta.reasoningContent.text;\n }\n if (delta.reasoningContent.signature !== undefined) {\n block.signature = delta.reasoningContent.signature;\n }\n if (delta.reasoningContent.redactedContent !== undefined) {\n block.redactedContent =\n delta.reasoningContent.redactedContent;\n }\n }\n if (event.messageStop?.stopReason) {\n stopReason = event.messageStop.stopReason;\n }\n if (event.metadata?.usage) {\n usage = event.metadata.usage;\n }\n }\n\n return {\n requestId,\n blocks: [...blocks.entries()]\n .sort(([left], [right]) => left - right)\n .map(([, block]) => normalizeBlock(block, request, requestId)),\n stopReason,\n usage,\n };\n}\n\nfunction getPartialTextBlock(\n blocks: Map<number, PartialBlock>,\n index: number,\n): PartialTextBlock {\n const existing = blocks.get(index);\n if (existing?.type === \"text\") {\n return existing;\n }\n const block: PartialTextBlock = { type: \"text\", text: \"\" };\n blocks.set(index, block);\n return block;\n}\n\nfunction getPartialReasoningBlock(\n blocks: Map<number, PartialBlock>,\n index: number,\n): PartialReasoningBlock {\n const existing = blocks.get(index);\n if (existing?.type === \"reasoning\") {\n return existing;\n }\n const block: PartialReasoningBlock = {\n type: \"reasoning\",\n text: \"\",\n };\n blocks.set(index, block);\n return block;\n}\n\nfunction normalizeBlock(\n block: PartialBlock,\n request: ProviderRequest,\n requestId?: string,\n): ProviderAssistantBlock {\n if (block.type === \"text\") {\n return block;\n }\n if (block.type === \"tool_call\") {\n return {\n type: \"tool_call\",\n callId: block.callId,\n name: block.name,\n arguments: parseToolInput(\n block.input,\n block.name,\n request,\n requestId,\n ),\n };\n }\n if (block.redactedContent) {\n return {\n type: \"reasoning\",\n text: \"\",\n replay: {\n opaqueData: Buffer.from(\n block.redactedContent,\n ).toString(\"base64\"),\n },\n };\n }\n return {\n type: \"reasoning\",\n text: block.text,\n ...(block.signature\n ? { replay: { opaqueData: block.signature } }\n : {}),\n };\n}\n\nfunction parseToolInput(\n input: string,\n name: string,\n request: ProviderRequest,\n requestId?: string,\n): Record<string, unknown> {\n if (!input) {\n return {};\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(input);\n } catch (error) {\n throw invalidToolInputError({\n input,\n name,\n request,\n requestId,\n reason: error instanceof Error ? error.message : \"Invalid JSON.\",\n });\n }\n if (isRecord(parsed)) {\n return parsed;\n }\n throw invalidToolInputError({\n input,\n name,\n request,\n requestId,\n reason: \"The decoded value was not a JSON object.\",\n });\n}\n\nfunction invalidToolInputError(options: {\n input: string;\n name: string;\n request: ProviderRequest;\n requestId?: string;\n reason: string;\n}): OrchaError {\n const tool = options.request.tools.find(\n (candidate) => candidate.name === options.name,\n );\n const expectedSchema = tool?.parameters ?? {\n type: \"object\",\n };\n const previewLimit = 1_000;\n const receivedStart =\n options.input.length > previewLimit\n ? `${options.input.slice(0, previewLimit)}\u2026`\n : options.input;\n const receivedEnd =\n options.input.length > previewLimit\n ? `\u2026${options.input.slice(-previewLimit)}`\n : options.input;\n const receivedSha256 = createHash(\"sha256\")\n .update(options.input)\n .digest(\"hex\");\n const requestReference = options.requestId\n ? ` Bedrock request ID: ${options.requestId}.`\n : \"\";\n return new OrchaError(\n \"provider_error\",\n [\n `Amazon Bedrock model \"${options.request.model}\" generated invalid arguments for tool \"${options.name}\".`,\n `Expected a JSON object matching ${JSON.stringify(expectedSchema)}.`,\n `Received ${options.input.length} characters. Start: ${JSON.stringify(receivedStart)}. End: ${JSON.stringify(receivedEnd)}.`,\n `JSON decoding failed: ${options.reason}`,\n \"These arguments were generated by the model after Orcha sent the tool definition; they were not accepted application input.\",\n \"Retry the run. If the received payload appears to be valid JSON, report a possible Orcha stream-decoding issue at https://github.com/Amarsia/orcha/issues.\",\n requestReference,\n ].join(\" \"),\n {\n retryable: true,\n details: {\n provider: \"bedrock\",\n model: options.request.model,\n tool: options.name,\n sentToolDefinition: tool\n ? {\n toolSpec: {\n name: tool.name,\n description: tool.description,\n inputSchema: {\n json: toBedrockDocument(tool.parameters),\n },\n },\n }\n : {\n toolSpec: {\n name: options.name,\n inputSchema: {\n json: toBedrockDocument(expectedSchema),\n },\n },\n },\n expectedSchema,\n receivedLength: options.input.length,\n receivedStart,\n receivedEnd,\n receivedSha256,\n decodeError: options.reason,\n ...(options.requestId ? { requestId: options.requestId } : {}),\n issueUrl: \"https://github.com/Amarsia/orcha/issues\",\n },\n },\n );\n}\n\nfunction toProviderResponse(\n request: ProviderRequest,\n response: CollectedBedrockResponse,\n): ProviderResponse {\n const textOutput = response.blocks\n .filter(\n (block): block is PartialTextBlock =>\n block.type === \"text\",\n )\n .map((block) => block.text)\n .join(\"\");\n const toolCalls = response.blocks.filter(\n (block): block is ProviderToolCall =>\n block.type === \"tool_call\",\n );\n const stopReason = normalizeStopReason(response.stopReason);\n return {\n output:\n request.outputType === \"json\" &&\n toolCalls.length === 0 &&\n stopReason !== \"max_tokens\"\n ? parseStructuredOutput(\n textOutput,\n request.outputSchema ?? {},\n )\n : textOutput,\n responseId: response.requestId,\n stopReason,\n content: response.blocks,\n toolCalls,\n usage: {\n inputTokens: response.usage?.inputTokens ?? 0,\n outputTokens: response.usage?.outputTokens ?? 0,\n reasoningTokens: null,\n cacheReadTokens:\n response.usage?.cacheReadInputTokens ?? 0,\n cacheWriteTokens:\n response.usage?.cacheWriteInputTokens ?? 0,\n },\n };\n}\n\nfunction normalizeStopReason(\n reason: string | undefined,\n): ProviderStopReason | undefined {\n if (!reason) {\n return undefined;\n }\n if (reason === \"end_turn\" || reason === \"stop_sequence\") {\n return \"end_turn\";\n }\n if (reason === \"tool_use\") {\n return \"tool_call\";\n }\n if (\n reason === \"max_tokens\" ||\n reason === \"model_context_window_exceeded\"\n ) {\n return \"max_tokens\";\n }\n if (\n reason === \"content_filtered\" ||\n reason === \"guardrail_intervened\"\n ) {\n return \"content_filter\";\n }\n return \"unknown\";\n}\n\nfunction throwStreamError(event: ConverseStreamOutput): void {\n const error =\n event.internalServerException ??\n event.modelStreamErrorException ??\n event.validationException ??\n event.throttlingException ??\n event.serviceUnavailableException;\n if (error) {\n throw new Error(\n error.message ?? \"Amazon Bedrock streaming request failed.\",\n );\n }\n}\n\nfunction isAnthropicModel(model: string): boolean {\n const normalized = model.toLowerCase();\n return (\n normalized.includes(\"anthropic.\") ||\n normalized.includes(\"claude\")\n );\n}\n\nfunction toBedrockDocument(value: unknown): BedrockDocument {\n if (value === undefined || value === null) {\n return null;\n }\n if (\n typeof value === \"string\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new Error(\n \"Amazon Bedrock document values must contain finite numbers.\",\n );\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(toBedrockDocument);\n }\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => [\n key,\n toBedrockDocument(item),\n ]),\n );\n }\n throw new Error(\n `Amazon Bedrock cannot serialize a ${typeof value} document value.`,\n );\n}\n\nfunction isRecord(\n value: unknown,\n): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value)\n );\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oCASO;AACP,yBAA2B;AAC3B,uBAAkC;AAClC,oBAA2B;AAC3B,0BAAqC;AACrC,+BAAsC;AAiE/B,MAAM,kBAAmC;AAAA,EAC9C,MAAM;AAAA,EACN,UAAU;AACZ;AAEA,eAAe,gBACb,eACA,SAC2B;AAC3B,QAAM,uBAAuB,sBAAsB,aAAa;AAChE,MAAI,QAAQ,eAAe,WAAW,QAAQ,eAAe,SAAS;AACpE,UAAM,IAAI;AAAA,MACR;AAAA,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AAE,IAAI,CAAC,CAAC,KAAK,IAAI,MAAM;AAAA,QACzC;AAAA,QACA,kBAAkB,IAAI;AAAA,MACxB,CAAC;AAAA,IACH;AAAA,EACF;AACA,QAAM,IAAI;AAAA,IACR,qCAAqC,OAAO,KAAK;AAAA,EACnD;AACF;AAEA,SAAS,SACP,OACkC;AAClC,SACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,KAAK;AAExB;",
|
|
4
|
+
"sourcesContent": ["import {\n BedrockRuntimeClient,\n ConverseStreamCommand,\n type ContentBlock,\n type ConverseStreamCommandInput,\n type ConverseStreamOutput,\n type DocumentFormat,\n type Message,\n type TokenUsage,\n} from \"@aws-sdk/client-bedrock-runtime\";\nimport { createHash } from \"crypto\";\nimport { basename, extname } from \"path\";\nimport { OrchaError } from \"../errors.js\";\nimport { readLocalFileContent } from \"../file-content.js\";\nimport { parseStructuredOutput } from \"../runtime/structured-output.js\";\nimport type {\n BedrockProviderConfiguration,\n MessageContent,\n ProviderConfiguration,\n} from \"../types.js\";\nimport type {\n ProviderAdapter,\n ProviderAssistantBlock,\n ProviderMessage,\n ProviderRequest,\n ProviderResponse,\n ProviderStopReason,\n ProviderToolCall,\n} from \"./types.js\";\n\ninterface PartialTextBlock {\n type: \"text\";\n text: string;\n}\n\ninterface PartialReasoningBlock {\n type: \"reasoning\";\n text: string;\n signature?: string;\n redactedContent?: Uint8Array;\n}\n\ninterface PartialToolCall {\n type: \"tool_call\";\n callId: string;\n name: string;\n input: string;\n}\n\ntype PartialBlock =\n | PartialTextBlock\n | PartialReasoningBlock\n | PartialToolCall;\n\ntype BedrockDocument =\n | null\n | boolean\n | number\n | string\n | BedrockDocument[]\n | { [key: string]: BedrockDocument };\n\ninterface CollectedBedrockResponse {\n requestId?: string;\n blocks: ProviderAssistantBlock[];\n stopReason?: string;\n usage?: TokenUsage;\n}\n\nexport interface BedrockContentClient {\n send(\n command: ConverseStreamCommand,\n options?: { abortSignal?: AbortSignal },\n ): Promise<{\n stream?: AsyncIterable<ConverseStreamOutput>;\n $metadata: { requestId?: string };\n }>;\n}\n\nexport const bedrockProvider: ProviderAdapter = {\n name: \"bedrock\",\n generate: generateBedrock,\n};\n\nasync function generateBedrock(\n configuration: ProviderConfiguration,\n request: ProviderRequest,\n): Promise<ProviderResponse> {\n const bedrockConfiguration = validateConfiguration(configuration);\n if (request.outputType === \"image\" || request.outputType === \"audio\") {\n throw new OrchaError(\n \"unsupported_provider_capability\",\n `Amazon Bedrock Converse does not support \"${request.outputType}\" as a direct agent output.`,\n );\n }\n\n const client = new BedrockRuntimeClient({\n region: bedrockConfiguration.region,\n ...(bedrockConfiguration.baseUrl\n ? { endpoint: bedrockConfiguration.baseUrl }\n : {}),\n ...(bedrockConfiguration.credentials\n ? { credentials: bedrockConfiguration.credentials }\n : {}),\n });\n return generateBedrockContent(client, request);\n}\n\nexport async function generateBedrockContent(\n client: BedrockContentClient,\n request: ProviderRequest,\n): Promise<ProviderResponse> {\n const input: ConverseStreamCommandInput = {\n modelId: request.model,\n system: [{ text: systemPrompt(request) }],\n messages: await toBedrockMessages(request.messages),\n ...(request.maxTokens\n ? { inferenceConfig: { maxTokens: request.maxTokens } }\n : {}),\n };\n\n if (request.tools.length > 0) {\n input.toolConfig = {\n tools: request.tools.map((tool) => ({\n toolSpec: {\n name: tool.name,\n description: tool.description,\n inputSchema: {\n json: toBedrockDocument(tool.parameters),\n },\n },\n })),\n };\n }\n if (request.reasoningLevel && isAnthropicModel(request.model)) {\n input.additionalModelRequestFields = {\n thinking: { type: \"adaptive\" },\n output_config: { effort: request.reasoningLevel },\n };\n }\n\n const response = await client.send(\n new ConverseStreamCommand(input),\n { abortSignal: request.signal },\n );\n if (!response.stream) {\n throw new Error(\"Amazon Bedrock returned no response stream.\");\n }\n\n const collected = await collectBedrockStream(\n response.stream,\n request,\n response.$metadata.requestId,\n request.publishOutput,\n );\n return toProviderResponse(request, collected);\n}\n\nfunction validateConfiguration(\n configuration: ProviderConfiguration,\n): BedrockProviderConfiguration {\n if (\n !(\"region\" in configuration) ||\n typeof configuration.region !== \"string\" ||\n !configuration.region.trim()\n ) {\n throw new Error(\n 'Missing AWS region in orcha.init({ providers: { bedrock: { region: \"...\" } } }).',\n );\n }\n if (\n configuration.credentials &&\n (!configuration.credentials.accessKeyId.trim() ||\n !configuration.credentials.secretAccessKey.trim())\n ) {\n throw new Error(\n \"Bedrock credentials require accessKeyId and secretAccessKey.\",\n );\n }\n return configuration;\n}\n\nfunction systemPrompt(request: ProviderRequest): string {\n if (request.outputType !== \"json\") {\n return request.systemPrompt;\n }\n return `${request.systemPrompt}\\n\\nReturn only valid JSON matching this JSON Schema:\\n${JSON.stringify(request.outputSchema ?? {})}`;\n}\n\nasync function toBedrockMessages(\n messages: ProviderMessage[],\n): Promise<Message[]> {\n const output: Message[] = [];\n for (const message of messages) {\n if (message.role === \"user\") {\n output.push({\n role: \"user\",\n content:\n typeof message.content === \"string\"\n ? [{ text: message.content }]\n : await Promise.all(\n message.content.map(toBedrockUserBlock),\n ),\n });\n continue;\n }\n if (message.role === \"tool\") {\n output.push({\n role: \"user\",\n content: message.results.map((result) => ({\n toolResult: {\n toolUseId: result.callId,\n content: [\n { json: toBedrockDocument(result.output) },\n ],\n ...(result.isError ? { status: \"error\" as const } : {}),\n },\n })),\n });\n continue;\n }\n\n output.push({\n role: \"assistant\",\n content: message.content.map((block) =>\n toBedrockAssistantBlock(\n block,\n message.provider === \"bedrock\",\n ),\n ),\n });\n }\n return output;\n}\n\nasync function toBedrockUserBlock(\n block: MessageContent,\n): Promise<ContentBlock> {\n if (block.type === \"text\") {\n return { text: block.text };\n }\n if (block.type === \"file\") {\n const file = await readLocalFileContent(block);\n return toBedrockBinaryBlock(\n file.bytes,\n block.mimeType,\n file.fileName,\n );\n }\n if (\n block.type === \"image\" ||\n block.type === \"url\"\n ) {\n const response = await fetch(block.fileUri);\n if (!response.ok) {\n throw new Error(\n `Could not load Bedrock file input: HTTP ${response.status}.`,\n );\n }\n return toBedrockBinaryBlock(\n new Uint8Array(await response.arrayBuffer()),\n block.mimeType,\n fileNameFromUri(block.fileUri),\n );\n }\n throw new OrchaError(\n \"unsupported_content_type\",\n `Amazon Bedrock does not support Orcha content type \"${block.type}\" with MIME type \"${block.mimeType}\".`,\n );\n}\n\nfunction toBedrockBinaryBlock(\n bytes: Uint8Array,\n mimeType: string,\n fileName: string,\n): ContentBlock {\n if (mimeType.startsWith(\"image/\")) {\n return {\n image: {\n format: imageFormat(mimeType),\n source: {\n bytes,\n },\n },\n };\n }\n const format = documentFormat(fileName, mimeType);\n if (format) {\n return {\n document: {\n format,\n name: safeBedrockDocumentName(fileName),\n source: { bytes },\n },\n };\n }\n throw new OrchaError(\n \"unsupported_content_type\",\n `Amazon Bedrock does not support file MIME type \"${mimeType}\".`,\n );\n}\n\nfunction documentFormat(\n fileName: string,\n mimeType: string,\n): DocumentFormat | undefined {\n const extension = extname(fileName).slice(1).toLowerCase();\n if (\n [\"csv\", \"doc\", \"docx\", \"html\", \"md\", \"pdf\", \"txt\", \"xls\", \"xlsx\"].includes(\n extension,\n )\n ) {\n return extension as DocumentFormat;\n }\n if (mimeType === \"application/pdf\") return \"pdf\";\n if (mimeType === \"application/msword\") return \"doc\";\n if (\n mimeType ===\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\n ) return \"docx\";\n if (mimeType === \"application/vnd.ms-excel\") return \"xls\";\n if (\n mimeType ===\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"\n ) return \"xlsx\";\n if (mimeType === \"text/csv\") return \"csv\";\n if (mimeType === \"text/html\") return \"html\";\n if (mimeType === \"text/markdown\") return \"md\";\n if (mimeType === \"text/plain\") return \"txt\";\n return undefined;\n}\n\nfunction safeBedrockDocumentName(fileName: string): string {\n const name = basename(fileName, extname(fileName))\n .replace(/[^A-Za-z0-9()[\\] -]/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n return name || \"document\";\n}\n\nfunction fileNameFromUri(uri: string): string {\n try {\n return basename(new URL(uri).pathname) || \"document\";\n } catch {\n return basename(uri) || \"document\";\n }\n}\n\nfunction imageFormat(\n mimeType: string,\n): \"png\" | \"jpeg\" | \"gif\" | \"webp\" {\n const subtype = mimeType.toLowerCase().split(\";\")[0]?.split(\"/\")[1];\n if (\n subtype === \"png\" ||\n subtype === \"jpeg\" ||\n subtype === \"gif\" ||\n subtype === \"webp\"\n ) {\n return subtype;\n }\n if (subtype === \"jpg\") {\n return \"jpeg\";\n }\n throw new OrchaError(\n \"unsupported_content_type\",\n `Amazon Bedrock does not support image MIME type \"${mimeType}\".`,\n );\n}\n\nfunction toBedrockAssistantBlock(\n block: ProviderAssistantBlock,\n replayBedrockState: boolean,\n): ContentBlock {\n if (block.type === \"text\") {\n return { text: block.text };\n }\n if (block.type === \"tool_call\") {\n return {\n toolUse: {\n toolUseId: block.callId,\n name: block.name,\n input: toBedrockDocument(block.arguments),\n },\n };\n }\n if (!replayBedrockState) {\n return { text: block.text };\n }\n if (!block.text && block.replay?.opaqueData) {\n return {\n reasoningContent: {\n redactedContent: Uint8Array.from(\n Buffer.from(block.replay.opaqueData, \"base64\"),\n ),\n },\n };\n }\n return {\n reasoningContent: {\n reasoningText: {\n text: block.text,\n ...(block.replay?.opaqueData\n ? { signature: block.replay.opaqueData }\n : {}),\n },\n },\n };\n}\n\nasync function collectBedrockStream(\n stream: AsyncIterable<ConverseStreamOutput>,\n request: ProviderRequest,\n requestId?: string,\n publishOutput?: (output: string) => void,\n): Promise<CollectedBedrockResponse> {\n const blocks = new Map<number, PartialBlock>();\n let stopReason: string | undefined;\n let usage: TokenUsage | undefined;\n let cumulativeText = \"\";\n\n for await (const event of stream) {\n throwStreamError(event);\n\n const start = event.contentBlockStart;\n if (start?.start?.toolUse) {\n blocks.set(start.contentBlockIndex ?? blocks.size, {\n type: \"tool_call\",\n callId: start.start.toolUse.toolUseId ?? \"\",\n name: start.start.toolUse.name ?? \"\",\n input: \"\",\n });\n }\n\n const deltaEvent = event.contentBlockDelta;\n const delta = deltaEvent?.delta;\n const index = deltaEvent?.contentBlockIndex ?? blocks.size;\n if (delta?.text !== undefined) {\n const block = getPartialTextBlock(blocks, index);\n block.text += delta.text;\n cumulativeText += delta.text;\n publishOutput?.(cumulativeText);\n }\n if (delta?.toolUse?.input !== undefined) {\n const block = blocks.get(index);\n if (!block || block.type !== \"tool_call\") {\n throw new Error(\n `Amazon Bedrock streamed tool input before tool start at block ${index}.`,\n );\n }\n block.input += delta.toolUse.input;\n }\n if (delta?.reasoningContent) {\n const block = getPartialReasoningBlock(blocks, index);\n if (delta.reasoningContent.text !== undefined) {\n block.text += delta.reasoningContent.text;\n }\n if (delta.reasoningContent.signature !== undefined) {\n block.signature = delta.reasoningContent.signature;\n }\n if (delta.reasoningContent.redactedContent !== undefined) {\n block.redactedContent =\n delta.reasoningContent.redactedContent;\n }\n }\n if (event.messageStop?.stopReason) {\n stopReason = event.messageStop.stopReason;\n }\n if (event.metadata?.usage) {\n usage = event.metadata.usage;\n }\n }\n\n return {\n requestId,\n blocks: [...blocks.entries()]\n .sort(([left], [right]) => left - right)\n .map(([, block]) => normalizeBlock(block, request, requestId)),\n stopReason,\n usage,\n };\n}\n\nfunction getPartialTextBlock(\n blocks: Map<number, PartialBlock>,\n index: number,\n): PartialTextBlock {\n const existing = blocks.get(index);\n if (existing?.type === \"text\") {\n return existing;\n }\n const block: PartialTextBlock = { type: \"text\", text: \"\" };\n blocks.set(index, block);\n return block;\n}\n\nfunction getPartialReasoningBlock(\n blocks: Map<number, PartialBlock>,\n index: number,\n): PartialReasoningBlock {\n const existing = blocks.get(index);\n if (existing?.type === \"reasoning\") {\n return existing;\n }\n const block: PartialReasoningBlock = {\n type: \"reasoning\",\n text: \"\",\n };\n blocks.set(index, block);\n return block;\n}\n\nfunction normalizeBlock(\n block: PartialBlock,\n request: ProviderRequest,\n requestId?: string,\n): ProviderAssistantBlock {\n if (block.type === \"text\") {\n return block;\n }\n if (block.type === \"tool_call\") {\n return {\n type: \"tool_call\",\n callId: block.callId,\n name: block.name,\n arguments: parseToolInput(\n block.input,\n block.name,\n request,\n requestId,\n ),\n };\n }\n if (block.redactedContent) {\n return {\n type: \"reasoning\",\n text: \"\",\n replay: {\n opaqueData: Buffer.from(\n block.redactedContent,\n ).toString(\"base64\"),\n },\n };\n }\n return {\n type: \"reasoning\",\n text: block.text,\n ...(block.signature\n ? { replay: { opaqueData: block.signature } }\n : {}),\n };\n}\n\nfunction parseToolInput(\n input: string,\n name: string,\n request: ProviderRequest,\n requestId?: string,\n): Record<string, unknown> {\n if (!input) {\n return {};\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(input);\n } catch (error) {\n throw invalidToolInputError({\n input,\n name,\n request,\n requestId,\n reason: error instanceof Error ? error.message : \"Invalid JSON.\",\n });\n }\n if (isRecord(parsed)) {\n return parsed;\n }\n throw invalidToolInputError({\n input,\n name,\n request,\n requestId,\n reason: \"The decoded value was not a JSON object.\",\n });\n}\n\nfunction invalidToolInputError(options: {\n input: string;\n name: string;\n request: ProviderRequest;\n requestId?: string;\n reason: string;\n}): OrchaError {\n const tool = options.request.tools.find(\n (candidate) => candidate.name === options.name,\n );\n const expectedSchema = tool?.parameters ?? {\n type: \"object\",\n };\n const previewLimit = 1_000;\n const receivedStart =\n options.input.length > previewLimit\n ? `${options.input.slice(0, previewLimit)}\u2026`\n : options.input;\n const receivedEnd =\n options.input.length > previewLimit\n ? `\u2026${options.input.slice(-previewLimit)}`\n : options.input;\n const receivedSha256 = createHash(\"sha256\")\n .update(options.input)\n .digest(\"hex\");\n const requestReference = options.requestId\n ? ` Bedrock request ID: ${options.requestId}.`\n : \"\";\n return new OrchaError(\n \"provider_error\",\n [\n `Amazon Bedrock model \"${options.request.model}\" generated invalid arguments for tool \"${options.name}\".`,\n `Expected a JSON object matching ${JSON.stringify(expectedSchema)}.`,\n `Received ${options.input.length} characters. Start: ${JSON.stringify(receivedStart)}. End: ${JSON.stringify(receivedEnd)}.`,\n `JSON decoding failed: ${options.reason}`,\n \"These arguments were generated by the model after Orcha sent the tool definition; they were not accepted application input.\",\n \"Retry the run. If the received payload appears to be valid JSON, report a possible Orcha stream-decoding issue at https://github.com/Amarsia/orcha/issues.\",\n requestReference,\n ].join(\" \"),\n {\n retryable: true,\n details: {\n provider: \"bedrock\",\n model: options.request.model,\n tool: options.name,\n sentToolDefinition: tool\n ? {\n toolSpec: {\n name: tool.name,\n description: tool.description,\n inputSchema: {\n json: toBedrockDocument(tool.parameters),\n },\n },\n }\n : {\n toolSpec: {\n name: options.name,\n inputSchema: {\n json: toBedrockDocument(expectedSchema),\n },\n },\n },\n expectedSchema,\n receivedLength: options.input.length,\n receivedStart,\n receivedEnd,\n receivedSha256,\n decodeError: options.reason,\n ...(options.requestId ? { requestId: options.requestId } : {}),\n issueUrl: \"https://github.com/Amarsia/orcha/issues\",\n },\n },\n );\n}\n\nfunction toProviderResponse(\n request: ProviderRequest,\n response: CollectedBedrockResponse,\n): ProviderResponse {\n const textOutput = response.blocks\n .filter(\n (block): block is PartialTextBlock =>\n block.type === \"text\",\n )\n .map((block) => block.text)\n .join(\"\");\n const toolCalls = response.blocks.filter(\n (block): block is ProviderToolCall =>\n block.type === \"tool_call\",\n );\n const stopReason = normalizeStopReason(response.stopReason);\n return {\n output:\n request.outputType === \"json\" &&\n toolCalls.length === 0 &&\n stopReason !== \"max_tokens\"\n ? parseStructuredOutput(\n textOutput,\n request.outputSchema ?? {},\n )\n : textOutput,\n responseId: response.requestId,\n stopReason,\n content: response.blocks,\n toolCalls,\n usage: {\n inputTokens: response.usage?.inputTokens ?? 0,\n outputTokens: response.usage?.outputTokens ?? 0,\n reasoningTokens: null,\n cacheReadTokens:\n response.usage?.cacheReadInputTokens ?? 0,\n cacheWriteTokens:\n response.usage?.cacheWriteInputTokens ?? 0,\n },\n };\n}\n\nfunction normalizeStopReason(\n reason: string | undefined,\n): ProviderStopReason | undefined {\n if (!reason) {\n return undefined;\n }\n if (reason === \"end_turn\" || reason === \"stop_sequence\") {\n return \"end_turn\";\n }\n if (reason === \"tool_use\") {\n return \"tool_call\";\n }\n if (\n reason === \"max_tokens\" ||\n reason === \"model_context_window_exceeded\"\n ) {\n return \"max_tokens\";\n }\n if (\n reason === \"content_filtered\" ||\n reason === \"guardrail_intervened\"\n ) {\n return \"content_filter\";\n }\n return \"unknown\";\n}\n\nfunction throwStreamError(event: ConverseStreamOutput): void {\n const error =\n event.internalServerException ??\n event.modelStreamErrorException ??\n event.validationException ??\n event.throttlingException ??\n event.serviceUnavailableException;\n if (error) {\n throw new Error(\n error.message ?? \"Amazon Bedrock streaming request failed.\",\n );\n }\n}\n\nfunction isAnthropicModel(model: string): boolean {\n const normalized = model.toLowerCase();\n return (\n normalized.includes(\"anthropic.\") ||\n normalized.includes(\"claude\")\n );\n}\n\nfunction toBedrockDocument(value: unknown): BedrockDocument {\n if (value === undefined || value === null) {\n return null;\n }\n if (\n typeof value === \"string\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new Error(\n \"Amazon Bedrock document values must contain finite numbers.\",\n );\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(toBedrockDocument);\n }\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => [\n key,\n toBedrockDocument(item),\n ]),\n );\n }\n throw new Error(\n `Amazon Bedrock cannot serialize a ${typeof value} document value.`,\n );\n}\n\nfunction isRecord(\n value: unknown,\n): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value)\n );\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oCASO;AACP,oBAA2B;AAC3B,kBAAkC;AAClC,oBAA2B;AAC3B,0BAAqC;AACrC,+BAAsC;AAiE/B,MAAM,kBAAmC;AAAA,EAC9C,MAAM;AAAA,EACN,UAAU;AACZ;AAEA,eAAe,gBACb,eACA,S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AG;AACxB,WAAO,MAAM,IAAI,iBAAiB;AAAA,EACpC;AACA,MAAI,SAAS,KAAK,GAAG;AACnB,WAAO,OAAO;AAAA,MACZ,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,KAAK,IAAI,MAAM;AAAA,QACzC;AAAA,QACA,kBAAkB,IAAI;AAAA,MACxB,CAAC;AAAA,IACH;AAAA,EACF;AACA,QAAM,IAAI;AAAA,IACR,qCAAqC,OAAO,KAAK;AAAA,EACnD;AACF;AAEA,SAAS,SACP,OACkC;AAClC,SACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,KAAK;AAExB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict"; const __orchaImportMetaUrl = require("
|
|
1
|
+
"use strict"; const __orchaImportMetaUrl = require("url").pathToFileURL(__filename).href;
|
|
2
2
|
"use strict";
|
|
3
3
|
var __defProp = Object.defineProperty;
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict"; const __orchaImportMetaUrl = require("
|
|
1
|
+
"use strict"; const __orchaImportMetaUrl = require("url").pathToFileURL(__filename).href;
|
|
2
2
|
"use strict";
|
|
3
3
|
var __defProp = Object.defineProperty;
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict"; const __orchaImportMetaUrl = require("
|
|
1
|
+
"use strict"; const __orchaImportMetaUrl = require("url").pathToFileURL(__filename).href;
|
|
2
2
|
"use strict";
|
|
3
3
|
var __defProp = Object.defineProperty;
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict"; const __orchaImportMetaUrl = require("
|
|
1
|
+
"use strict"; const __orchaImportMetaUrl = require("url").pathToFileURL(__filename).href;
|
|
2
2
|
"use strict";
|
|
3
3
|
var __defProp = Object.defineProperty;
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -19,12 +19,21 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
19
19
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
20
|
var google_gemini_exports = {};
|
|
21
21
|
__export(google_gemini_exports, {
|
|
22
|
-
generateGoogleContent: () => generateGoogleContent
|
|
22
|
+
generateGoogleContent: () => generateGoogleContent,
|
|
23
|
+
toGoogleContentClient: () => toGoogleContentClient
|
|
23
24
|
});
|
|
24
25
|
module.exports = __toCommonJS(google_gemini_exports);
|
|
25
26
|
var import_errors = require("../errors.js");
|
|
26
27
|
var import_file_content = require("../file-content.js");
|
|
27
28
|
var import_structured_output = require("../runtime/structured-output.js");
|
|
29
|
+
function toGoogleContentClient(client) {
|
|
30
|
+
if (typeof client !== "object" || client === null || !("models" in client) || typeof client.models !== "object" || client.models === null || !("generateContentStream" in client.models) || typeof client.models.generateContentStream !== "function") {
|
|
31
|
+
throw new Error(
|
|
32
|
+
"The installed @google/genai package does not expose a compatible client."
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
return client;
|
|
36
|
+
}
|
|
28
37
|
async function generateGoogleContent(client, request, provider) {
|
|
29
38
|
request.signal?.throwIfAborted();
|
|
30
39
|
if (request.outputType === "image" || request.outputType === "audio") {
|
|
@@ -361,6 +370,7 @@ function isRecord(value) {
|
|
|
361
370
|
}
|
|
362
371
|
// Annotate the CommonJS export names for ESM import in node:
|
|
363
372
|
0 && (module.exports = {
|
|
364
|
-
generateGoogleContent
|
|
373
|
+
generateGoogleContent,
|
|
374
|
+
toGoogleContentClient
|
|
365
375
|
});
|
|
366
376
|
//# sourceMappingURL=google-gemini.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/providers/google-gemini.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n Content,\n FinishReason,\n GenerateContentConfig,\n GenerateContentResponse,\n Part,\n ThinkingLevel,\n} from \"@google/genai/web\";\nimport { OrchaError } from \"../errors.js\";\nimport { readLocalFileContent } from \"../file-content.js\";\nimport { parseStructuredOutput } from \"../runtime/structured-output.js\";\nimport type {\n MessageContent,\n ProviderName,\n Usage,\n} from \"../types.js\";\nimport type {\n ProviderAssistantBlock,\n ProviderMessage,\n ProviderRequest,\n ProviderResponse,\n ProviderStopReason,\n ProviderTextBlock,\n ProviderToolCall,\n} from \"./types.js\";\n\nexport interface GoogleContentClient {\n models: {\n generateContentStream(parameters: {\n model: string;\n contents: Content[];\n config: GenerateContentConfig;\n }): Promise<AsyncGenerator<GenerateContentResponse>>;\n };\n}\n\ninterface CollectedGoogleResponse {\n responseId?: string;\n finishReason?: FinishReason;\n promptBlockReason?: string;\n parts: Part[];\n usage?: GenerateContentResponse[\"usageMetadata\"];\n}\n\nexport async function generateGoogleContent(\n client: GoogleContentClient,\n request: ProviderRequest,\n provider: \"googlegenai\" | \"vertexai\",\n): Promise<ProviderResponse> {\n request.signal?.throwIfAborted();\n if (request.outputType === \"image\" || request.outputType === \"audio\") {\n throw new OrchaError(\n \"unsupported_provider_capability\",\n `Google Gemini does not support \"${request.outputType}\" as a direct agent output.`,\n );\n }\n\n const config: GenerateContentConfig = {\n systemInstruction: request.systemPrompt,\n ...(request.maxTokens\n ? { maxOutputTokens: request.maxTokens }\n : {}),\n };\n if (request.tools.length > 0) {\n config.tools = [\n {\n functionDeclarations: request.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parametersJsonSchema: tool.parameters,\n })),\n },\n ];\n }\n if (request.outputType === \"json\") {\n config.responseMimeType = \"application/json\";\n config.responseJsonSchema = request.outputSchema ?? {};\n }\n config.thinkingConfig = {\n includeThoughts: true,\n };\n if (request.reasoningLevel) {\n config.thinkingConfig.thinkingLevel =\n request.reasoningLevel as ThinkingLevel;\n }\n\n const stream = await client.models.generateContentStream({\n model: request.model,\n contents: await toGoogleContents(request.messages, provider),\n config,\n });\n const abort = (): void => {\n void stream.return(undefined);\n };\n request.signal?.addEventListener(\"abort\", abort, { once: true });\n try {\n const response = await collectGoogleStream(\n stream,\n request.publishOutput,\n request.signal,\n );\n request.signal?.throwIfAborted();\n return toProviderResponse(request, response);\n } finally {\n request.signal?.removeEventListener(\"abort\", abort);\n }\n}\n\nasync function collectGoogleStream(\n stream: AsyncGenerator<GenerateContentResponse>,\n publishOutput?: (output: string) => void,\n signal?: AbortSignal,\n): Promise<CollectedGoogleResponse> {\n const collected: CollectedGoogleResponse = { parts: [] };\n let cumulativeText = \"\";\n\n for await (const chunk of stream) {\n signal?.throwIfAborted();\n collected.responseId = chunk.responseId ?? collected.responseId;\n collected.usage = chunk.usageMetadata ?? collected.usage;\n collected.promptBlockReason =\n chunk.promptFeedback?.blockReason ?? collected.promptBlockReason;\n const candidate = chunk.candidates?.[0];\n collected.finishReason =\n candidate?.finishReason ?? collected.finishReason;\n\n for (const part of candidate?.content?.parts ?? []) {\n collected.parts.push(part);\n if (\n typeof part.text === \"string\" &&\n part.text &&\n part.thought !== true\n ) {\n cumulativeText += part.text;\n publishOutput?.(cumulativeText);\n }\n }\n }\n return collected;\n}\n\nfunction toProviderResponse(\n request: ProviderRequest,\n response: CollectedGoogleResponse,\n): ProviderResponse {\n const content: ProviderAssistantBlock[] = [];\n let toolCallIndex = 0;\n\n for (const part of response.parts) {\n if (part.functionCall) {\n const call = part.functionCall;\n if (!call.name) {\n throw new Error(\"Google Gemini returned a function call without a name.\");\n }\n const providerCallId = call.id;\n content.push({\n type: \"tool_call\",\n callId:\n providerCallId ??\n `${response.responseId ?? crypto.randomUUID()}:${toolCallIndex}`,\n name: call.name,\n arguments: call.args ?? {},\n ...(providerCallId || part.thoughtSignature\n ? {\n replay: {\n ...(providerCallId\n ? { providerId: providerCallId }\n : {}),\n ...(part.thoughtSignature\n ? { opaqueData: part.thoughtSignature }\n : {}),\n },\n }\n : {}),\n });\n toolCallIndex += 1;\n continue;\n }\n if (typeof part.text === \"string\") {\n appendGoogleTextPart(content, part);\n continue;\n }\n throw new Error(\"Google Gemini returned an unsupported response part.\");\n }\n\n const toolCalls = content.filter(\n (block): block is ProviderToolCall => block.type === \"tool_call\",\n );\n const textOutput = content\n .filter(\n (block): block is ProviderTextBlock => block.type === \"text\",\n )\n .map((block) => block.text)\n .join(\"\");\n const stopReason = normalizeStopReason(\n response.finishReason,\n toolCalls.length > 0,\n response.promptBlockReason !== undefined,\n );\n const output =\n request.outputType === \"json\" &&\n toolCalls.length === 0 &&\n stopReason !== \"max_tokens\"\n ? parseStructuredOutput(textOutput, request.outputSchema ?? {})\n : textOutput;\n\n return {\n output,\n responseId: response.responseId,\n stopReason,\n content,\n toolCalls,\n usage: normalizeUsage(response.usage),\n };\n}\n\nfunction appendGoogleTextPart(\n content: ProviderAssistantBlock[],\n part: Part,\n): void {\n const text = part.text ?? \"\";\n if (part.thought === true) {\n const previous = content.at(-1);\n if (previous?.type === \"reasoning\") {\n previous.text += text;\n if (part.thoughtSignature) {\n previous.replay = {\n ...previous.replay,\n opaqueData: part.thoughtSignature,\n };\n }\n return;\n }\n content.push({\n type: \"reasoning\",\n text,\n ...(part.thoughtSignature\n ? { replay: { opaqueData: part.thoughtSignature } }\n : {}),\n });\n return;\n }\n\n const previous = content.at(-1);\n if (previous?.type === \"text\") {\n previous.text += text;\n return;\n }\n content.push({ type: \"text\", text });\n}\n\nasync function toGoogleContents(\n messages: ProviderMessage[],\n provider: \"googlegenai\" | \"vertexai\",\n): Promise<Content[]> {\n const contents: Content[] = [];\n const previousCalls = new Map<\n string,\n {\n name: string;\n providerCallId?: string;\n }\n >();\n\n for (const message of messages) {\n if (message.role === \"user\") {\n contents.push({\n role: \"user\",\n parts:\n typeof message.content === \"string\"\n ? [{ text: message.content }]\n : await Promise.all(\n message.content.map(toGoogleUserPart),\n ),\n });\n continue;\n }\n if (message.role === \"assistant\") {\n const parts = message.content.map((block) => {\n if (block.type === \"tool_call\") {\n previousCalls.set(block.callId, {\n name: block.name,\n providerCallId:\n message.provider === provider\n ? block.replay?.providerId\n : undefined,\n });\n }\n return toGoogleAssistantPart(\n block,\n message.provider,\n provider,\n );\n });\n contents.push({ role: \"model\", parts });\n continue;\n }\n\n contents.push({\n role: \"user\",\n parts: message.results.map((result) => {\n const call = previousCalls.get(result.callId);\n if (!call) {\n throw new Error(\n `Google Gemini could not match tool result \"${result.callId}\" to a prior function call.`,\n );\n }\n return {\n functionResponse: {\n name: call.name,\n ...(call.providerCallId\n ? { id: call.providerCallId }\n : {}),\n response: normalizeFunctionResponse(\n result.output,\n result.isError,\n ),\n },\n };\n }),\n });\n }\n return contents;\n}\n\nasync function toGoogleUserPart(\n content: MessageContent,\n): Promise<Part> {\n if (content.type === \"text\") {\n return { text: content.text };\n }\n if (content.type === \"file\") {\n const file = await readLocalFileContent(content);\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: file.base64,\n },\n };\n }\n if (\n content.type === \"url\" &&\n /^https?:\\/\\//i.test(content.fileUri) &&\n !isGoogleFileUri(content.fileUri)\n ) {\n const response = await fetch(content.fileUri);\n if (!response.ok) {\n throw new OrchaError(\n \"invalid_input\",\n `Could not load Google Gemini file URL: HTTP ${response.status}.`,\n );\n }\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: Buffer.from(await response.arrayBuffer()).toString(\"base64\"),\n },\n };\n }\n if (!isGoogleFileUri(content.fileUri)) {\n throw new OrchaError(\n \"unsupported_content_type\",\n \"Google Gemini requires media to use a Gemini Files API URI, a Google Cloud Storage URI, or an inline data URI.\",\n );\n }\n if (content.fileUri.startsWith(\"data:\")) {\n const parsed = parseDataUri(content.fileUri);\n return {\n inlineData: {\n mimeType: parsed.mimeType || content.mimeType,\n data: parsed.data,\n },\n };\n }\n return {\n fileData: {\n mimeType: content.mimeType,\n fileUri: content.fileUri,\n },\n };\n}\n\nfunction toGoogleAssistantPart(\n block: ProviderAssistantBlock,\n messageProvider: ProviderName | undefined,\n currentProvider: \"googlegenai\" | \"vertexai\",\n): Part {\n if (block.type === \"text\") {\n return { text: block.text };\n }\n if (block.type === \"reasoning\") {\n if (messageProvider !== currentProvider) {\n return { text: block.text };\n }\n return {\n text: block.text,\n thought: true,\n ...(block.replay?.opaqueData\n ? { thoughtSignature: block.replay.opaqueData }\n : {}),\n };\n }\n const replay =\n messageProvider === currentProvider ? block.replay : undefined;\n return {\n functionCall: {\n name: block.name,\n args: block.arguments,\n ...(replay?.providerId\n ? { id: replay.providerId }\n : {}),\n },\n ...(replay?.opaqueData\n ? { thoughtSignature: replay.opaqueData }\n : {}),\n };\n}\n\nfunction normalizeFunctionResponse(\n output: unknown,\n isError: boolean | undefined,\n): Record<string, unknown> {\n if (isError) {\n return { error: output };\n }\n return isRecord(output) ? output : { output: output ?? null };\n}\n\nfunction normalizeStopReason(\n reason: FinishReason | undefined,\n hasToolCalls: boolean,\n promptBlocked: boolean,\n): ProviderStopReason | undefined {\n if (promptBlocked) {\n return \"content_filter\";\n }\n if (hasToolCalls) {\n return \"tool_call\";\n }\n if (reason === \"STOP\") {\n return \"end_turn\";\n }\n if (reason === \"MAX_TOKENS\") {\n return \"max_tokens\";\n }\n if (\n reason === \"SAFETY\" ||\n reason === \"RECITATION\" ||\n reason === \"BLOCKLIST\" ||\n reason === \"PROHIBITED_CONTENT\" ||\n reason === \"SPII\" ||\n reason === \"IMAGE_SAFETY\" ||\n reason === \"IMAGE_PROHIBITED_CONTENT\"\n ) {\n return \"content_filter\";\n }\n return reason === undefined ? undefined : \"unknown\";\n}\n\nfunction normalizeUsage(\n usage: GenerateContentResponse[\"usageMetadata\"],\n): Usage {\n return {\n inputTokens: usage?.promptTokenCount ?? 0,\n outputTokens: usage?.candidatesTokenCount ?? 0,\n reasoningTokens: usage?.thoughtsTokenCount ?? null,\n cacheReadTokens: usage?.cachedContentTokenCount ?? 0,\n cacheWriteTokens: 0,\n };\n}\n\nfunction isGoogleFileUri(uri: string): boolean {\n return (\n uri.startsWith(\"data:\") ||\n uri.startsWith(\"gs://\") ||\n uri.startsWith(\"https://generativelanguage.googleapis.com/\")\n );\n}\n\nfunction parseDataUri(uri: string): {\n mimeType: string;\n data: string;\n} {\n const match = /^data:([^;,]+)?;base64,(.+)$/s.exec(uri);\n if (!match) {\n throw new OrchaError(\n \"unsupported_content_type\",\n \"Google Gemini inline media must be a base64-encoded data URI.\",\n );\n }\n return {\n mimeType: match[1] ?? \"\",\n data: match[2],\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;
|
|
4
|
+
"sourcesContent": ["import { OrchaError } from \"../errors.js\";\nimport { readLocalFileContent } from \"../file-content.js\";\nimport { parseStructuredOutput } from \"../runtime/structured-output.js\";\nimport type {\n MessageContent,\n ProviderName,\n Usage,\n} from \"../types.js\";\nimport type {\n ProviderAssistantBlock,\n ProviderMessage,\n ProviderRequest,\n ProviderResponse,\n ProviderStopReason,\n ProviderTextBlock,\n ProviderToolCall,\n} from \"./types.js\";\n\ninterface GooglePart {\n text?: string;\n thought?: boolean;\n thoughtSignature?: string;\n inlineData?: {\n mimeType: string;\n data: string;\n };\n fileData?: {\n mimeType: string;\n fileUri: string;\n };\n functionCall?: {\n id?: string;\n name?: string;\n args?: Record<string, unknown>;\n };\n functionResponse?: {\n id?: string;\n name: string;\n response: Record<string, unknown>;\n };\n}\n\ninterface GoogleContent {\n role: string;\n parts: GooglePart[];\n}\n\ninterface GoogleGenerateContentConfig {\n systemInstruction: string;\n maxOutputTokens?: number;\n tools?: Array<{\n functionDeclarations: Array<{\n name: string;\n description: string;\n parametersJsonSchema: Record<string, unknown>;\n }>;\n }>;\n responseMimeType?: string;\n responseJsonSchema?: Record<string, unknown>;\n thinkingConfig?: {\n includeThoughts: boolean;\n thinkingLevel?: string;\n };\n}\n\ninterface GoogleGenerateContentResponse {\n responseId?: string;\n candidates?: Array<{\n finishReason?: string;\n content?: {\n parts?: GooglePart[];\n };\n }>;\n promptFeedback?: {\n blockReason?: string;\n };\n usageMetadata?: {\n promptTokenCount?: number;\n candidatesTokenCount?: number;\n thoughtsTokenCount?: number;\n cachedContentTokenCount?: number;\n };\n}\n\nexport interface GoogleContentClient {\n models: {\n generateContentStream(parameters: {\n model: string;\n contents: GoogleContent[];\n config: GoogleGenerateContentConfig;\n }): Promise<AsyncGenerator<GoogleGenerateContentResponse>>;\n };\n}\n\nexport function toGoogleContentClient(client: unknown): GoogleContentClient {\n if (\n typeof client !== \"object\" ||\n client === null ||\n !(\"models\" in client) ||\n typeof client.models !== \"object\" ||\n client.models === null ||\n !(\"generateContentStream\" in client.models) ||\n typeof client.models.generateContentStream !== \"function\"\n ) {\n throw new Error(\n \"The installed @google/genai package does not expose a compatible client.\",\n );\n }\n return client as GoogleContentClient;\n}\n\ninterface CollectedGoogleResponse {\n responseId?: string;\n finishReason?: string;\n promptBlockReason?: string;\n parts: GooglePart[];\n usage?: GoogleGenerateContentResponse[\"usageMetadata\"];\n}\n\nexport async function generateGoogleContent(\n client: GoogleContentClient,\n request: ProviderRequest,\n provider: \"googlegenai\" | \"vertexai\",\n): Promise<ProviderResponse> {\n request.signal?.throwIfAborted();\n if (request.outputType === \"image\" || request.outputType === \"audio\") {\n throw new OrchaError(\n \"unsupported_provider_capability\",\n `Google Gemini does not support \"${request.outputType}\" as a direct agent output.`,\n );\n }\n\n const config: GoogleGenerateContentConfig = {\n systemInstruction: request.systemPrompt,\n ...(request.maxTokens\n ? { maxOutputTokens: request.maxTokens }\n : {}),\n };\n if (request.tools.length > 0) {\n config.tools = [\n {\n functionDeclarations: request.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parametersJsonSchema: tool.parameters,\n })),\n },\n ];\n }\n if (request.outputType === \"json\") {\n config.responseMimeType = \"application/json\";\n config.responseJsonSchema = request.outputSchema ?? {};\n }\n config.thinkingConfig = {\n includeThoughts: true,\n };\n if (request.reasoningLevel) {\n config.thinkingConfig.thinkingLevel = request.reasoningLevel;\n }\n\n const stream = await client.models.generateContentStream({\n model: request.model,\n contents: await toGoogleContents(request.messages, provider),\n config,\n });\n const abort = (): void => {\n void stream.return(undefined);\n };\n request.signal?.addEventListener(\"abort\", abort, { once: true });\n try {\n const response = await collectGoogleStream(\n stream,\n request.publishOutput,\n request.signal,\n );\n request.signal?.throwIfAborted();\n return toProviderResponse(request, response);\n } finally {\n request.signal?.removeEventListener(\"abort\", abort);\n }\n}\n\nasync function collectGoogleStream(\n stream: AsyncGenerator<GoogleGenerateContentResponse>,\n publishOutput?: (output: string) => void,\n signal?: AbortSignal,\n): Promise<CollectedGoogleResponse> {\n const collected: CollectedGoogleResponse = { parts: [] };\n let cumulativeText = \"\";\n\n for await (const chunk of stream) {\n signal?.throwIfAborted();\n collected.responseId = chunk.responseId ?? collected.responseId;\n collected.usage = chunk.usageMetadata ?? collected.usage;\n collected.promptBlockReason =\n chunk.promptFeedback?.blockReason ?? collected.promptBlockReason;\n const candidate = chunk.candidates?.[0];\n collected.finishReason =\n candidate?.finishReason ?? collected.finishReason;\n\n for (const part of candidate?.content?.parts ?? []) {\n collected.parts.push(part);\n if (\n typeof part.text === \"string\" &&\n part.text &&\n part.thought !== true\n ) {\n cumulativeText += part.text;\n publishOutput?.(cumulativeText);\n }\n }\n }\n return collected;\n}\n\nfunction toProviderResponse(\n request: ProviderRequest,\n response: CollectedGoogleResponse,\n): ProviderResponse {\n const content: ProviderAssistantBlock[] = [];\n let toolCallIndex = 0;\n\n for (const part of response.parts) {\n if (part.functionCall) {\n const call = part.functionCall;\n if (!call.name) {\n throw new Error(\"Google Gemini returned a function call without a name.\");\n }\n const providerCallId = call.id;\n content.push({\n type: \"tool_call\",\n callId:\n providerCallId ??\n `${response.responseId ?? crypto.randomUUID()}:${toolCallIndex}`,\n name: call.name,\n arguments: call.args ?? {},\n ...(providerCallId || part.thoughtSignature\n ? {\n replay: {\n ...(providerCallId\n ? { providerId: providerCallId }\n : {}),\n ...(part.thoughtSignature\n ? { opaqueData: part.thoughtSignature }\n : {}),\n },\n }\n : {}),\n });\n toolCallIndex += 1;\n continue;\n }\n if (typeof part.text === \"string\") {\n appendGoogleTextPart(content, part);\n continue;\n }\n throw new Error(\"Google Gemini returned an unsupported response part.\");\n }\n\n const toolCalls = content.filter(\n (block): block is ProviderToolCall => block.type === \"tool_call\",\n );\n const textOutput = content\n .filter(\n (block): block is ProviderTextBlock => block.type === \"text\",\n )\n .map((block) => block.text)\n .join(\"\");\n const stopReason = normalizeStopReason(\n response.finishReason,\n toolCalls.length > 0,\n response.promptBlockReason !== undefined,\n );\n const output =\n request.outputType === \"json\" &&\n toolCalls.length === 0 &&\n stopReason !== \"max_tokens\"\n ? parseStructuredOutput(textOutput, request.outputSchema ?? {})\n : textOutput;\n\n return {\n output,\n responseId: response.responseId,\n stopReason,\n content,\n toolCalls,\n usage: normalizeUsage(response.usage),\n };\n}\n\nfunction appendGoogleTextPart(\n content: ProviderAssistantBlock[],\n part: GooglePart,\n): void {\n const text = part.text ?? \"\";\n if (part.thought === true) {\n const previous = content.at(-1);\n if (previous?.type === \"reasoning\") {\n previous.text += text;\n if (part.thoughtSignature) {\n previous.replay = {\n ...previous.replay,\n opaqueData: part.thoughtSignature,\n };\n }\n return;\n }\n content.push({\n type: \"reasoning\",\n text,\n ...(part.thoughtSignature\n ? { replay: { opaqueData: part.thoughtSignature } }\n : {}),\n });\n return;\n }\n\n const previous = content.at(-1);\n if (previous?.type === \"text\") {\n previous.text += text;\n return;\n }\n content.push({ type: \"text\", text });\n}\n\nasync function toGoogleContents(\n messages: ProviderMessage[],\n provider: \"googlegenai\" | \"vertexai\",\n): Promise<GoogleContent[]> {\n const contents: GoogleContent[] = [];\n const previousCalls = new Map<\n string,\n {\n name: string;\n providerCallId?: string;\n }\n >();\n\n for (const message of messages) {\n if (message.role === \"user\") {\n contents.push({\n role: \"user\",\n parts:\n typeof message.content === \"string\"\n ? [{ text: message.content }]\n : await Promise.all(\n message.content.map(toGoogleUserPart),\n ),\n });\n continue;\n }\n if (message.role === \"assistant\") {\n const parts = message.content.map((block) => {\n if (block.type === \"tool_call\") {\n previousCalls.set(block.callId, {\n name: block.name,\n providerCallId:\n message.provider === provider\n ? block.replay?.providerId\n : undefined,\n });\n }\n return toGoogleAssistantPart(\n block,\n message.provider,\n provider,\n );\n });\n contents.push({ role: \"model\", parts });\n continue;\n }\n\n contents.push({\n role: \"user\",\n parts: message.results.map((result) => {\n const call = previousCalls.get(result.callId);\n if (!call) {\n throw new Error(\n `Google Gemini could not match tool result \"${result.callId}\" to a prior function call.`,\n );\n }\n return {\n functionResponse: {\n name: call.name,\n ...(call.providerCallId\n ? { id: call.providerCallId }\n : {}),\n response: normalizeFunctionResponse(\n result.output,\n result.isError,\n ),\n },\n };\n }),\n });\n }\n return contents;\n}\n\nasync function toGoogleUserPart(\n content: MessageContent,\n): Promise<GooglePart> {\n if (content.type === \"text\") {\n return { text: content.text };\n }\n if (content.type === \"file\") {\n const file = await readLocalFileContent(content);\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: file.base64,\n },\n };\n }\n if (\n content.type === \"url\" &&\n /^https?:\\/\\//i.test(content.fileUri) &&\n !isGoogleFileUri(content.fileUri)\n ) {\n const response = await fetch(content.fileUri);\n if (!response.ok) {\n throw new OrchaError(\n \"invalid_input\",\n `Could not load Google Gemini file URL: HTTP ${response.status}.`,\n );\n }\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: Buffer.from(await response.arrayBuffer()).toString(\"base64\"),\n },\n };\n }\n if (!isGoogleFileUri(content.fileUri)) {\n throw new OrchaError(\n \"unsupported_content_type\",\n \"Google Gemini requires media to use a Gemini Files API URI, a Google Cloud Storage URI, or an inline data URI.\",\n );\n }\n if (content.fileUri.startsWith(\"data:\")) {\n const parsed = parseDataUri(content.fileUri);\n return {\n inlineData: {\n mimeType: parsed.mimeType || content.mimeType,\n data: parsed.data,\n },\n };\n }\n return {\n fileData: {\n mimeType: content.mimeType,\n fileUri: content.fileUri,\n },\n };\n}\n\nfunction toGoogleAssistantPart(\n block: ProviderAssistantBlock,\n messageProvider: ProviderName | undefined,\n currentProvider: \"googlegenai\" | \"vertexai\",\n): GooglePart {\n if (block.type === \"text\") {\n return { text: block.text };\n }\n if (block.type === \"reasoning\") {\n if (messageProvider !== currentProvider) {\n return { text: block.text };\n }\n return {\n text: block.text,\n thought: true,\n ...(block.replay?.opaqueData\n ? { thoughtSignature: block.replay.opaqueData }\n : {}),\n };\n }\n const replay =\n messageProvider === currentProvider ? block.replay : undefined;\n return {\n functionCall: {\n name: block.name,\n args: block.arguments,\n ...(replay?.providerId\n ? { id: replay.providerId }\n : {}),\n },\n ...(replay?.opaqueData\n ? { thoughtSignature: replay.opaqueData }\n : {}),\n };\n}\n\nfunction normalizeFunctionResponse(\n output: unknown,\n isError: boolean | undefined,\n): Record<string, unknown> {\n if (isError) {\n return { error: output };\n }\n return isRecord(output) ? output : { output: output ?? null };\n}\n\nfunction normalizeStopReason(\n reason: string | undefined,\n hasToolCalls: boolean,\n promptBlocked: boolean,\n): ProviderStopReason | undefined {\n if (promptBlocked) {\n return \"content_filter\";\n }\n if (hasToolCalls) {\n return \"tool_call\";\n }\n if (reason === \"STOP\") {\n return \"end_turn\";\n }\n if (reason === \"MAX_TOKENS\") {\n return \"max_tokens\";\n }\n if (\n reason === \"SAFETY\" ||\n reason === \"RECITATION\" ||\n reason === \"BLOCKLIST\" ||\n reason === \"PROHIBITED_CONTENT\" ||\n reason === \"SPII\" ||\n reason === \"IMAGE_SAFETY\" ||\n reason === \"IMAGE_PROHIBITED_CONTENT\"\n ) {\n return \"content_filter\";\n }\n return reason === undefined ? undefined : \"unknown\";\n}\n\nfunction normalizeUsage(\n usage: GoogleGenerateContentResponse[\"usageMetadata\"],\n): Usage {\n return {\n inputTokens: usage?.promptTokenCount ?? 0,\n outputTokens: usage?.candidatesTokenCount ?? 0,\n reasoningTokens: usage?.thoughtsTokenCount ?? null,\n cacheReadTokens: usage?.cachedContentTokenCount ?? 0,\n cacheWriteTokens: 0,\n };\n}\n\nfunction isGoogleFileUri(uri: string): boolean {\n return (\n uri.startsWith(\"data:\") ||\n uri.startsWith(\"gs://\") ||\n uri.startsWith(\"https://generativelanguage.googleapis.com/\")\n );\n}\n\nfunction parseDataUri(uri: string): {\n mimeType: string;\n data: string;\n} {\n const match = /^data:([^;,]+)?;base64,(.+)$/s.exec(uri);\n if (!match) {\n throw new OrchaError(\n \"unsupported_content_type\",\n \"Google Gemini inline media must be a base64-encoded data URI.\",\n );\n }\n return {\n mimeType: match[1] ?? \"\",\n data: match[2],\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA2B;AAC3B,0BAAqC;AACrC,+BAAsC;AA4F/B,SAAS,sBAAsB,QAAsC;AAC1E,MACE,OAAO,WAAW,YAClB,WAAW,QACX,EAAE,YAAY,WACd,OAAO,OAAO,WAAW,YACzB,OAAO,WAAW,QAClB,EAAE,2BAA2B,OAAO,WACpC,OAAO,OAAO,OAAO,0BAA0B,YAC/C;AACA,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAUA,eAAsB,sBACpB,QACA,SACA,UAC2B;AAC3B,UAAQ,QAAQ,eAAe;AAC/B,MAAI,QAAQ,eAAe,WAAW,QAAQ,eAAe,SAAS;AACpE,UAAM,IAAI;AAAA,MACR;AAAA,MACA,mCAAmC,QAAQ,UAAU;AAAA,IACvD;AAAA,EACF;AAEA,QAAM,SAAsC;AAAA,IAC1C,mBAAmB,QAAQ;AAAA,IAC3B,GAAI,QAAQ,YACR,EAAE,iBAAiB,QAAQ,UAAU,IACrC,CAAC;AAAA,EACP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AO,KACtB,IAAI,WAAW,4CAA4C;AAE/D;AAEA,SAAS,aAAa,KAGpB;AACA,QAAM,QAAQ,gCAAgC,KAAK,GAAG;AACtD,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,SAAO;AAAA,IACL,UAAU,MAAM,CAAC,KAAK;AAAA,IACtB,MAAM,MAAM,CAAC;AAAA,EACf;AACF;AAEA,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;",
|
|
6
6
|
"names": ["previous"]
|
|
7
7
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict"; const __orchaImportMetaUrl = require("
|
|
1
|
+
"use strict"; const __orchaImportMetaUrl = require("url").pathToFileURL(__filename).href;
|
|
2
2
|
"use strict";
|
|
3
3
|
var __defProp = Object.defineProperty;
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -39,7 +39,7 @@ async function generateGoogleGenAI(configuration, request) {
|
|
|
39
39
|
...configuration.baseUrl ? { httpOptions: { baseUrl: configuration.baseUrl } } : {}
|
|
40
40
|
});
|
|
41
41
|
return (0, import_google_gemini.generateGoogleContent)(
|
|
42
|
-
client,
|
|
42
|
+
(0, import_google_gemini.toGoogleContentClient)(client),
|
|
43
43
|
request,
|
|
44
44
|
"googlegenai"
|
|
45
45
|
);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/providers/google-genai.ts"],
|
|
4
|
-
"sourcesContent": ["import { GoogleGenAI } from \"@google/genai/web\";\nimport type { ProviderConfiguration } from \"../types.js\";\nimport {
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAA4B;AAE5B,
|
|
4
|
+
"sourcesContent": ["import { GoogleGenAI } from \"@google/genai/web\";\nimport type { ProviderConfiguration } from \"../types.js\";\nimport {\n generateGoogleContent,\n toGoogleContentClient,\n} from \"./google-gemini.js\";\nimport type {\n ProviderAdapter,\n ProviderRequest,\n ProviderResponse,\n} from \"./types.js\";\n\nexport const googleGenAIProvider: ProviderAdapter = {\n name: \"googlegenai\",\n generate: generateGoogleGenAI,\n};\n\nasync function generateGoogleGenAI(\n configuration: ProviderConfiguration,\n request: ProviderRequest,\n): Promise<ProviderResponse> {\n if (!configuration.apiKey?.trim()) {\n throw new Error(\n 'Missing Google GenAI API key in orcha.init({ providers: { googlegenai: \"...\" } }).',\n );\n }\n\n const client = new GoogleGenAI({\n apiKey: configuration.apiKey,\n ...(configuration.baseUrl\n ? { httpOptions: { baseUrl: configuration.baseUrl } }\n : {}),\n });\n return generateGoogleContent(\n toGoogleContentClient(client),\n request,\n \"googlegenai\",\n );\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAA4B;AAE5B,2BAGO;AAOA,MAAM,sBAAuC;AAAA,EAClD,MAAM;AAAA,EACN,UAAU;AACZ;AAEA,eAAe,oBACb,eACA,SAC2B;AAC3B,MAAI,CAAC,cAAc,QAAQ,KAAK,GAAG;AACjC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,SAAS,IAAI,uBAAY;AAAA,IAC7B,QAAQ,cAAc;AAAA,IACtB,GAAI,cAAc,UACd,EAAE,aAAa,EAAE,SAAS,cAAc,QAAQ,EAAE,IAClD,CAAC;AAAA,EACP,CAAC;AACD,aAAO;AAAA,QACL,4CAAsB,MAAM;AAAA,IAC5B;AAAA,IACA;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict"; const __orchaImportMetaUrl = require("
|
|
1
|
+
"use strict"; const __orchaImportMetaUrl = require("url").pathToFileURL(__filename).href;
|
|
2
2
|
"use strict";
|
|
3
3
|
var __defProp = Object.defineProperty;
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -51,6 +51,16 @@ function loadProvider(name) {
|
|
|
51
51
|
);
|
|
52
52
|
}
|
|
53
53
|
return provider;
|
|
54
|
+
}).catch((error) => {
|
|
55
|
+
loadedProviders.delete(name);
|
|
56
|
+
if ((name === "googlegenai" || name === "vertexai") && error instanceof Error && error.message.includes("@google/genai")) {
|
|
57
|
+
throw new import_errors.OrchaError(
|
|
58
|
+
"provider_error",
|
|
59
|
+
`Provider "${name}" requires Node.js 20 or newer and the optional "@google/genai" package.`,
|
|
60
|
+
{ cause: error }
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
throw error;
|
|
54
64
|
});
|
|
55
65
|
loadedProviders.set(name, loading);
|
|
56
66
|
return loading;
|