@draht/router 2026.9.5-1 → 2026.10.4-2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAkD,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/G,OAAO,EAAE,cAAc,EAAE,CAAC;AAE1B;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,KAAK;aACnB,MAAM,EAAE,MAAM,EAAE;IAA5C,YAA4B,MAAM,EAAE,MAAM,EAAE,EAG3C;CACD;AA6CD;;;GAGG;AACH,wBAAgB,UAAU,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,YAAY,CAY7D;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,KAAK,EAAE,SAAS,GAAG,QAAQ,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAaxG;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,EAAE,MAAM,EAAE,YAAY,GAAG,IAAI,GAAG,YAAY,CAgBnG;AA0HD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI,CA+BzD"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAkD,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/G,OAAO,EAAE,cAAc,EAAE,CAAC;AAE1B;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,KAAK;IAC/C,SAAgB,MAAM,EAAE,MAAM,EAAE,CAAC;IAEjC,YAAY,MAAM,EAAE,MAAM,EAAE,EAI3B;CACD;AA6CD;;;GAGG;AACH,wBAAgB,UAAU,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,YAAY,CAY7D;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,KAAK,EAAE,SAAS,GAAG,QAAQ,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAaxG;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,EAAE,MAAM,EAAE,YAAY,GAAG,IAAI,GAAG,YAAY,CAgBnG;AA0HD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI,CA+BzD"}
package/dist/config.js CHANGED
@@ -9,6 +9,7 @@ export { BUILT_IN_ROLES };
9
9
  * Contains all validation issues found.
10
10
  */
11
11
  export class ConfigValidationError extends Error {
12
+ errors;
12
13
  constructor(errors) {
13
14
  super(`Config validation failed:\n${errors.map((e) => ` - ${e}`).join("\n")}`);
14
15
  this.errors = errors;
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAwB,SAAS,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACjF,OAAO,EAAE,cAAc,EAAE,cAAc,EAAqD,MAAM,YAAY,CAAC;AAE/G,OAAO,EAAE,cAAc,EAAE,CAAC;AAE1B;;;GAGG;AACH,MAAM,OAAO,qBAAsB,SAAQ,KAAK;IAC/C,YAA4B,MAAgB;QAC3C,KAAK,CAAC,8BAA8B,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,IAAI,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,6CAA6C;IAC7C,KAAK,MAAM,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACzD,MAAM,CAAC,IAAI,CAAC,GAAG,iCAAiC,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC,CAAC;IACrF,CAAC;IAED,6CAA6C;IAC7C,KAAK,MAAM,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACzD,MAAM,CAAC,IAAI,CAAC,GAAG,qBAAqB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC;IACzD,CAAC;IAED,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACvB,MAAM,IAAI,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;AACF,CAAC","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { type BuiltinProvider, getModels, getProviders } from \"@draht/ai/compat\";\nimport { BUILT_IN_ROLES, DEFAULT_CONFIG, type ModelRef, type RoleConfig, type RouterConfig } from \"./types.js\";\n\nexport { BUILT_IN_ROLES };\n\n/**\n * Error thrown when config validation fails.\n * Contains all validation issues found.\n */\nexport class ConfigValidationError extends Error {\n\tconstructor(public readonly errors: string[]) {\n\t\tsuper(`Config validation failed:\\n${errors.map((e) => ` - ${e}`).join(\"\\n\")}`);\n\t\tthis.name = \"ConfigValidationError\";\n\t}\n}\n\nconst PROJECT_CONFIG = \".draht/router.json\";\nconst GLOBAL_CONFIG = join(homedir(), \".draht\", \"router.json\");\n\n/**\n * Validate that a project root path is safe and doesn't contain path traversal.\n * Throws if the path attempts to escape the current working directory or uses absolute paths to sensitive areas.\n */\nfunction validateProjectRoot(projectRoot: string): void {\n\t// Resolve to absolute path to check for traversal\n\tconst resolved = resolve(projectRoot);\n\tconst cwd = resolve(process.cwd());\n\n\t// For relative paths: ensure resolved path is within or equal to cwd\n\tif (!projectRoot.startsWith(\"/\")) {\n\t\tif (!resolved.startsWith(`${cwd}/`) && resolved !== cwd) {\n\t\t\tthrow new Error(`Invalid project root: path traversal detected (${projectRoot})`);\n\t\t}\n\t\treturn;\n\t}\n\n\t// For absolute paths: allow safe locations (user home, temp dirs, current working directory)\n\tconst home = homedir();\n\tconst tmpDir = tmpdir();\n\tconst safePaths = [home, tmpDir, cwd, \"/tmp\", \"/private/tmp\"];\n\tconst isSafe = safePaths.some((safe) => resolved.startsWith(`${safe}/`) || resolved === safe);\n\tif (isSafe) {\n\t\treturn;\n\t}\n\n\t// Reject paths to system directories\n\tconst dangerousPaths = [\"/etc\", \"/usr\", \"/bin\", \"/sbin\", \"/sys\", \"/proc\", \"/dev\", \"/boot\"];\n\tfor (const dangerous of dangerousPaths) {\n\t\tif (resolved.startsWith(dangerous)) {\n\t\t\tthrow new Error(`Invalid project root: access to ${dangerous} is not allowed`);\n\t\t}\n\t}\n\n\t// Reject any other absolute path that's not explicitly safe\n\tthrow new Error(\n\t\t`Invalid project root: absolute path must be within home, temp, or current directory (${projectRoot})`,\n\t);\n}\n\n/**\n * Load router config. Project config overrides global, both fall back to defaults.\n * Validates the merged config and throws ConfigValidationError if invalid.\n */\nexport function loadConfig(projectRoot?: string): RouterConfig {\n\tif (projectRoot) {\n\t\tvalidateProjectRoot(projectRoot);\n\t}\n\n\tconst globalConfig = loadFile(GLOBAL_CONFIG);\n\tconst projectPath = projectRoot ? resolve(projectRoot, PROJECT_CONFIG) : resolve(PROJECT_CONFIG);\n\tconst projectConfig = loadFile(projectPath);\n\n\tconst result = mergeConfig(projectConfig, globalConfig);\n\tvalidateConfig(result);\n\treturn result;\n}\n\n/**\n * Save router config to project or global scope.\n * Validates the config and throws ConfigValidationError if invalid.\n */\nexport function saveConfig(config: RouterConfig, scope: \"project\" | \"global\", projectRoot?: string): void {\n\t// Validate before writing to ensure we don't save invalid configs\n\tvalidateConfig(config);\n\n\tif (scope === \"project\" && projectRoot) {\n\t\tvalidateProjectRoot(projectRoot);\n\t}\n\n\tconst path =\n\t\tscope === \"global\" ? GLOBAL_CONFIG : projectRoot ? resolve(projectRoot, PROJECT_CONFIG) : resolve(PROJECT_CONFIG);\n\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, JSON.stringify(config, null, \"\\t\"), \"utf-8\");\n}\n\n/**\n * Merge project config over global config over defaults.\n * Project overrides global per-role.\n */\nexport function mergeConfig(project: RouterConfig | null, global: RouterConfig | null): RouterConfig {\n\tconst base = { ...DEFAULT_CONFIG };\n\n\tif (global) {\n\t\tfor (const [role, config] of Object.entries(global)) {\n\t\t\tbase[role] = config;\n\t\t}\n\t}\n\n\tif (project) {\n\t\tfor (const [role, config] of Object.entries(project)) {\n\t\t\tbase[role] = config;\n\t\t}\n\t}\n\n\treturn base;\n}\n\nfunction loadFile(path: string): RouterConfig | null {\n\tif (!existsSync(path)) return null;\n\ttry {\n\t\treturn JSON.parse(readFileSync(path, \"utf-8\")) as RouterConfig;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Validate a ModelRef has non-empty provider and model.\n */\nfunction validateModelRef(ref: ModelRef, role: string, position: string): string[] {\n\tconst errors: string[] = [];\n\tif (!ref.provider || ref.provider.trim() === \"\") {\n\t\terrors.push(`Empty provider string for role ${role} (${position})`);\n\t}\n\tif (!ref.model || ref.model.trim() === \"\") {\n\t\terrors.push(`Empty model string for role ${role} (${position})`);\n\t}\n\treturn errors;\n}\n\n/**\n * Validate a RoleConfig has valid structure.\n */\nfunction validateRoleConfig(roleConfig: RoleConfig, role: string): string[] {\n\tconst errors: string[] = [];\n\n\t// Validate primary\n\terrors.push(...validateModelRef(roleConfig.primary, role, \"primary\"));\n\n\t// Validate fallbacks\n\tfor (let i = 0; i < roleConfig.fallbacks.length; i++) {\n\t\terrors.push(...validateModelRef(roleConfig.fallbacks[i], role, `fallback[${i}]`));\n\t}\n\n\treturn errors;\n}\n\n/**\n * Validate a ModelRef against the @draht/ai registry.\n * Returns errors if provider or model is not found.\n */\nfunction validateModelRefAgainstRegistry(\n\tref: ModelRef,\n\trole: string,\n\tposition: string,\n\tvalidProviders: Set<string>,\n): string[] {\n\tconst errors: string[] = [];\n\n\t// Skip if empty (already caught by structure validation)\n\tif (!ref.provider || !ref.model) {\n\t\treturn errors;\n\t}\n\n\t// Check provider exists\n\tif (!validProviders.has(ref.provider)) {\n\t\terrors.push(`Invalid provider '${ref.provider}' for role ${role} (not in @draht/ai registry)`);\n\t\treturn errors; // Don't check model if provider is invalid\n\t}\n\n\t// Check model exists for this provider\n\tconst models = getModels(ref.provider as BuiltinProvider);\n\tconst modelExists = models.some((m) => m.id === ref.model);\n\tif (!modelExists) {\n\t\terrors.push(`Invalid model '${ref.model}' for provider '${ref.provider}' in role ${role} (${position})`);\n\t}\n\n\treturn errors;\n}\n\n/**\n * Validate a RoleConfig against the @draht/ai registry.\n */\nfunction validateRoleConfigAgainstRegistry(\n\troleConfig: RoleConfig,\n\trole: string,\n\tvalidProviders: Set<string>,\n): string[] {\n\tconst errors: string[] = [];\n\n\t// Validate primary\n\terrors.push(...validateModelRefAgainstRegistry(roleConfig.primary, role, \"primary\", validProviders));\n\n\t// Validate fallbacks\n\tfor (let i = 0; i < roleConfig.fallbacks.length; i++) {\n\t\terrors.push(...validateModelRefAgainstRegistry(roleConfig.fallbacks[i], role, `fallback[${i}]`, validProviders));\n\t}\n\n\treturn errors;\n}\n\n/**\n * Format a ModelRef as \"provider/model\" for display.\n */\nfunction formatModelRefForValidation(ref: ModelRef): string {\n\treturn `${ref.provider}/${ref.model}`;\n}\n\n/**\n * Detect duplicate models in a fallback chain (primary + fallbacks).\n */\nfunction detectDuplicateModels(roleConfig: RoleConfig, role: string): string[] {\n\tconst errors: string[] = [];\n\tconst allModels: ModelRef[] = [roleConfig.primary, ...roleConfig.fallbacks];\n\tconst seen = new Set<string>();\n\n\tfor (const ref of allModels) {\n\t\tconst key = formatModelRefForValidation(ref);\n\t\tif (seen.has(key)) {\n\t\t\terrors.push(`Duplicate model ${key} in fallback chain for role ${role}`);\n\t\t}\n\t\tseen.add(key);\n\t}\n\n\treturn errors;\n}\n\n/**\n * Validate a router config.\n * Throws ConfigValidationError if any issues are found.\n */\nexport function validateConfig(config: RouterConfig): void {\n\tconst errors: string[] = [];\n\n\t// Check all built-in roles are present\n\tfor (const role of BUILT_IN_ROLES) {\n\t\tif (!(role in config)) {\n\t\t\terrors.push(`Missing required role: ${role}`);\n\t\t}\n\t}\n\n\t// Validate structure of each role config\n\tfor (const [role, roleConfig] of Object.entries(config)) {\n\t\terrors.push(...validateRoleConfig(roleConfig, role));\n\t}\n\n\t// Cache valid providers for registry validation\n\tconst validProviders = new Set(getProviders());\n\n\t// Validate each role config against registry\n\tfor (const [role, roleConfig] of Object.entries(config)) {\n\t\terrors.push(...validateRoleConfigAgainstRegistry(roleConfig, role, validProviders));\n\t}\n\n\t// Detect duplicate models in fallback chains\n\tfor (const [role, roleConfig] of Object.entries(config)) {\n\t\terrors.push(...detectDuplicateModels(roleConfig, role));\n\t}\n\n\tif (errors.length > 0) {\n\t\tthrow new ConfigValidationError(errors);\n\t}\n}\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAwB,SAAS,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACjF,OAAO,EAAE,cAAc,EAAE,cAAc,EAAqD,MAAM,YAAY,CAAC;AAE/G,OAAO,EAAE,cAAc,EAAE,CAAC;A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IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACzD,MAAM,CAAC,IAAI,CAAC,GAAG,kBAAkB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC;IACtD,CAAC;IAED,gDAAgD;IAChD,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,YAAY,EAAE,CAAC,CAAC;IAE/C,6CAA6C;IAC7C,KAAK,MAAM,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACzD,MAAM,CAAC,IAAI,CAAC,GAAG,iCAAiC,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC,CAAC;IACrF,CAAC;IAED,6CAA6C;IAC7C,KAAK,MAAM,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACzD,MAAM,CAAC,IAAI,CAAC,GAAG,qBAAqB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC;IACzD,CAAC;IAED,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACvB,MAAM,IAAI,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;AACF,CAAC","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { type BuiltinProvider, getModels, getProviders } from \"@draht/ai/compat\";\nimport { BUILT_IN_ROLES, DEFAULT_CONFIG, type ModelRef, type RoleConfig, type RouterConfig } from \"./types.js\";\n\nexport { BUILT_IN_ROLES };\n\n/**\n * Error thrown when config validation fails.\n * Contains all validation issues found.\n */\nexport class ConfigValidationError extends Error {\n\tpublic readonly errors: string[];\n\n\tconstructor(errors: string[]) {\n\t\tsuper(`Config validation failed:\\n${errors.map((e) => ` - ${e}`).join(\"\\n\")}`);\n\t\tthis.errors = errors;\n\t\tthis.name = \"ConfigValidationError\";\n\t}\n}\n\nconst PROJECT_CONFIG = \".draht/router.json\";\nconst GLOBAL_CONFIG = join(homedir(), \".draht\", \"router.json\");\n\n/**\n * Validate that a project root path is safe and doesn't contain path traversal.\n * Throws if the path attempts to escape the current working directory or uses absolute paths to sensitive areas.\n */\nfunction validateProjectRoot(projectRoot: string): void {\n\t// Resolve to absolute path to check for traversal\n\tconst resolved = resolve(projectRoot);\n\tconst cwd = resolve(process.cwd());\n\n\t// For relative paths: ensure resolved path is within or equal to cwd\n\tif (!projectRoot.startsWith(\"/\")) {\n\t\tif (!resolved.startsWith(`${cwd}/`) && resolved !== cwd) {\n\t\t\tthrow new Error(`Invalid project root: path traversal detected (${projectRoot})`);\n\t\t}\n\t\treturn;\n\t}\n\n\t// For absolute paths: allow safe locations (user home, temp dirs, current working directory)\n\tconst home = homedir();\n\tconst tmpDir = tmpdir();\n\tconst safePaths = [home, tmpDir, cwd, \"/tmp\", \"/private/tmp\"];\n\tconst isSafe = safePaths.some((safe) => resolved.startsWith(`${safe}/`) || resolved === safe);\n\tif (isSafe) {\n\t\treturn;\n\t}\n\n\t// Reject paths to system directories\n\tconst dangerousPaths = [\"/etc\", \"/usr\", \"/bin\", \"/sbin\", \"/sys\", \"/proc\", \"/dev\", \"/boot\"];\n\tfor (const dangerous of dangerousPaths) {\n\t\tif (resolved.startsWith(dangerous)) {\n\t\t\tthrow new Error(`Invalid project root: access to ${dangerous} is not allowed`);\n\t\t}\n\t}\n\n\t// Reject any other absolute path that's not explicitly safe\n\tthrow new Error(\n\t\t`Invalid project root: absolute path must be within home, temp, or current directory (${projectRoot})`,\n\t);\n}\n\n/**\n * Load router config. Project config overrides global, both fall back to defaults.\n * Validates the merged config and throws ConfigValidationError if invalid.\n */\nexport function loadConfig(projectRoot?: string): RouterConfig {\n\tif (projectRoot) {\n\t\tvalidateProjectRoot(projectRoot);\n\t}\n\n\tconst globalConfig = loadFile(GLOBAL_CONFIG);\n\tconst projectPath = projectRoot ? resolve(projectRoot, PROJECT_CONFIG) : resolve(PROJECT_CONFIG);\n\tconst projectConfig = loadFile(projectPath);\n\n\tconst result = mergeConfig(projectConfig, globalConfig);\n\tvalidateConfig(result);\n\treturn result;\n}\n\n/**\n * Save router config to project or global scope.\n * Validates the config and throws ConfigValidationError if invalid.\n */\nexport function saveConfig(config: RouterConfig, scope: \"project\" | \"global\", projectRoot?: string): void {\n\t// Validate before writing to ensure we don't save invalid configs\n\tvalidateConfig(config);\n\n\tif (scope === \"project\" && projectRoot) {\n\t\tvalidateProjectRoot(projectRoot);\n\t}\n\n\tconst path =\n\t\tscope === \"global\" ? GLOBAL_CONFIG : projectRoot ? resolve(projectRoot, PROJECT_CONFIG) : resolve(PROJECT_CONFIG);\n\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, JSON.stringify(config, null, \"\\t\"), \"utf-8\");\n}\n\n/**\n * Merge project config over global config over defaults.\n * Project overrides global per-role.\n */\nexport function mergeConfig(project: RouterConfig | null, global: RouterConfig | null): RouterConfig {\n\tconst base = { ...DEFAULT_CONFIG };\n\n\tif (global) {\n\t\tfor (const [role, config] of Object.entries(global)) {\n\t\t\tbase[role] = config;\n\t\t}\n\t}\n\n\tif (project) {\n\t\tfor (const [role, config] of Object.entries(project)) {\n\t\t\tbase[role] = config;\n\t\t}\n\t}\n\n\treturn base;\n}\n\nfunction loadFile(path: string): RouterConfig | null {\n\tif (!existsSync(path)) return null;\n\ttry {\n\t\treturn JSON.parse(readFileSync(path, \"utf-8\")) as RouterConfig;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Validate a ModelRef has non-empty provider and model.\n */\nfunction validateModelRef(ref: ModelRef, role: string, position: string): string[] {\n\tconst errors: string[] = [];\n\tif (!ref.provider || ref.provider.trim() === \"\") {\n\t\terrors.push(`Empty provider string for role ${role} (${position})`);\n\t}\n\tif (!ref.model || ref.model.trim() === \"\") {\n\t\terrors.push(`Empty model string for role ${role} (${position})`);\n\t}\n\treturn errors;\n}\n\n/**\n * Validate a RoleConfig has valid structure.\n */\nfunction validateRoleConfig(roleConfig: RoleConfig, role: string): string[] {\n\tconst errors: string[] = [];\n\n\t// Validate primary\n\terrors.push(...validateModelRef(roleConfig.primary, role, \"primary\"));\n\n\t// Validate fallbacks\n\tfor (let i = 0; i < roleConfig.fallbacks.length; i++) {\n\t\terrors.push(...validateModelRef(roleConfig.fallbacks[i], role, `fallback[${i}]`));\n\t}\n\n\treturn errors;\n}\n\n/**\n * Validate a ModelRef against the @draht/ai registry.\n * Returns errors if provider or model is not found.\n */\nfunction validateModelRefAgainstRegistry(\n\tref: ModelRef,\n\trole: string,\n\tposition: string,\n\tvalidProviders: Set<string>,\n): string[] {\n\tconst errors: string[] = [];\n\n\t// Skip if empty (already caught by structure validation)\n\tif (!ref.provider || !ref.model) {\n\t\treturn errors;\n\t}\n\n\t// Check provider exists\n\tif (!validProviders.has(ref.provider)) {\n\t\terrors.push(`Invalid provider '${ref.provider}' for role ${role} (not in @draht/ai registry)`);\n\t\treturn errors; // Don't check model if provider is invalid\n\t}\n\n\t// Check model exists for this provider\n\tconst models = getModels(ref.provider as BuiltinProvider);\n\tconst modelExists = models.some((m) => m.id === ref.model);\n\tif (!modelExists) {\n\t\terrors.push(`Invalid model '${ref.model}' for provider '${ref.provider}' in role ${role} (${position})`);\n\t}\n\n\treturn errors;\n}\n\n/**\n * Validate a RoleConfig against the @draht/ai registry.\n */\nfunction validateRoleConfigAgainstRegistry(\n\troleConfig: RoleConfig,\n\trole: string,\n\tvalidProviders: Set<string>,\n): string[] {\n\tconst errors: string[] = [];\n\n\t// Validate primary\n\terrors.push(...validateModelRefAgainstRegistry(roleConfig.primary, role, \"primary\", validProviders));\n\n\t// Validate fallbacks\n\tfor (let i = 0; i < roleConfig.fallbacks.length; i++) {\n\t\terrors.push(...validateModelRefAgainstRegistry(roleConfig.fallbacks[i], role, `fallback[${i}]`, validProviders));\n\t}\n\n\treturn errors;\n}\n\n/**\n * Format a ModelRef as \"provider/model\" for display.\n */\nfunction formatModelRefForValidation(ref: ModelRef): string {\n\treturn `${ref.provider}/${ref.model}`;\n}\n\n/**\n * Detect duplicate models in a fallback chain (primary + fallbacks).\n */\nfunction detectDuplicateModels(roleConfig: RoleConfig, role: string): string[] {\n\tconst errors: string[] = [];\n\tconst allModels: ModelRef[] = [roleConfig.primary, ...roleConfig.fallbacks];\n\tconst seen = new Set<string>();\n\n\tfor (const ref of allModels) {\n\t\tconst key = formatModelRefForValidation(ref);\n\t\tif (seen.has(key)) {\n\t\t\terrors.push(`Duplicate model ${key} in fallback chain for role ${role}`);\n\t\t}\n\t\tseen.add(key);\n\t}\n\n\treturn errors;\n}\n\n/**\n * Validate a router config.\n * Throws ConfigValidationError if any issues are found.\n */\nexport function validateConfig(config: RouterConfig): void {\n\tconst errors: string[] = [];\n\n\t// Check all built-in roles are present\n\tfor (const role of BUILT_IN_ROLES) {\n\t\tif (!(role in config)) {\n\t\t\terrors.push(`Missing required role: ${role}`);\n\t\t}\n\t}\n\n\t// Validate structure of each role config\n\tfor (const [role, roleConfig] of Object.entries(config)) {\n\t\terrors.push(...validateRoleConfig(roleConfig, role));\n\t}\n\n\t// Cache valid providers for registry validation\n\tconst validProviders = new Set(getProviders());\n\n\t// Validate each role config against registry\n\tfor (const [role, roleConfig] of Object.entries(config)) {\n\t\terrors.push(...validateRoleConfigAgainstRegistry(roleConfig, role, validProviders));\n\t}\n\n\t// Detect duplicate models in fallback chains\n\tfor (const [role, roleConfig] of Object.entries(config)) {\n\t\terrors.push(...detectDuplicateModels(roleConfig, role));\n\t}\n\n\tif (errors.length > 0) {\n\t\tthrow new ConfigValidationError(errors);\n\t}\n}\n"]}
package/dist/router.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { AssistantMessageEvent } from "@draht/ai";
1
2
  import { type Api, type Context, type Model, type SimpleStreamOptions, type StreamOptions } from "@draht/ai/compat";
2
3
  import type { ModelRef, RouterConfig, RouterRole } from "./types.js";
3
4
  /**
@@ -28,7 +29,7 @@ export declare class ModelRouter {
28
29
  * Events are buffered and only yielded after successful completion,
29
30
  * preventing partial responses from failed providers from leaking through.
30
31
  */
31
- stream(role: RouterRole, context: Context, options?: StreamOptions): AsyncGenerator<import("@draht/ai").AssistantMessageEvent>;
32
+ stream(role: RouterRole, context: Context, options?: StreamOptions): AsyncGenerator<AssistantMessageEvent>;
32
33
  /**
33
34
  * Stream a simple completion (no tool use) with fallback.
34
35
  *
@@ -36,7 +37,7 @@ export declare class ModelRouter {
36
37
  * Events are buffered and only yielded after successful completion,
37
38
  * preventing partial responses from failed providers from leaking through.
38
39
  */
39
- streamSimple(role: RouterRole, context: Context, options?: SimpleStreamOptions): AsyncGenerator<import("@draht/ai").AssistantMessageEvent>;
40
+ streamSimple(role: RouterRole, context: Context, options?: SimpleStreamOptions): AsyncGenerator<AssistantMessageEvent>;
40
41
  /**
41
42
  * Internal helper for streaming with fallback support.
42
43
  * Buffers events and checks for error events to trigger fallback.
@@ -1 +1 @@
1
- {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,GAAG,EACR,KAAK,OAAO,EAGZ,KAAK,KAAK,EACV,KAAK,mBAAmB,EACxB,KAAK,aAAa,EAClB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,KAAK,EAAa,QAAQ,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAEhF;;GAEG;AACH,qBAAa,WAAW;IACvB,OAAO,CAAC,MAAM,CAAe;IAC7B,OAAO,CAAC,SAAS,CAAS;IAE1B,YAAY,MAAM,CAAC,EAAE,YAAY,EAAE,SAAS,CAAC,EAAE,MAAM,EAGpD;IAED;;OAEG;IACH,OAAO,CAAC,IAAI,EAAE,UAAU,GAAG,QAAQ,CAMlC;IAED;;OAEG;IACH,oBAAoB,CAAC,IAAI,EAAE,UAAU,GAAG,QAAQ,EAAE,CAMjD;IAED;;;OAG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1
- import { getApiProvider, getModel, } from "@draht/ai/compat";
1
+ import { getApiProvider, getModel, normalizeContext, } from "@draht/ai/compat";
2
2
  import { loadConfig } from "./config.js";
3
3
  import { estimateCost, logCost } from "./cost.js";
4
4
  /**
5
5
  * Model router with role-based resolution, automatic fallback, and @draht/ai integration.
6
6
  */
7
7
  export class ModelRouter {
8
+ config;
9
+ sessionId;
8
10
  constructor(config, sessionId) {
9
11
  this.config = config ?? loadConfig();
10
12
  this.sessionId = sessionId ?? `session-${Date.now()}`;
@@ -50,7 +52,7 @@ export class ModelRouter {
50
52
  * preventing partial responses from failed providers from leaking through.
51
53
  */
52
54
  async *stream(role, context, options) {
53
- yield* this.streamWithFallback(role, context, options, (provider, model, opts) => provider.stream(model, context, opts));
55
+ yield* this.streamWithFallback(role, context, options, (provider, model, opts) => provider.stream(model, normalizeContext(context), opts));
54
56
  }
55
57
  /**
56
58
  * Stream a simple completion (no tool use) with fallback.
@@ -60,7 +62,7 @@ export class ModelRouter {
60
62
  * preventing partial responses from failed providers from leaking through.
61
63
  */
62
64
  async *streamSimple(role, context, options) {
63
- yield* this.streamWithFallback(role, context, options, (provider, model, opts) => provider.streamSimple(model, context, opts));
65
+ yield* this.streamWithFallback(role, context, options, (provider, model, opts) => provider.streamSimple(model, normalizeContext(context), opts));
64
66
  }
65
67
  /**
66
68
  * Internal helper for streaming with fallback support.
@@ -1 +1 @@
1
- {"version":3,"file":"router.js","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,cAAc,EACd,QAAQ,GAIR,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGlD;;GAEG;AACH,MAAM,OAAO,WAAW;IAIvB,YAAY,MAAqB,EAAE,SAAkB;QACpD,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,UAAU,EAAE,CAAC;QACrC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AAI,CAAC;QACnE,IAAI,GAAG,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,WAAW,CAAC;YAAE,OAAO,IAAI,CAAC;QACnG,IAAI,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAC1G,IAAI,GAAG,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,gBAAgB,CAAC;YAAE,OAAO,IAAI,CAAC;QAChF,IAAI,GAAG,CAAC,QAAQ,CAAC,YAAY,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,UAAU,CAAC;YAAE,OAAO,IAAI,CAAC;IACzE,CAAC;IACD,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,IAAI,KAAK,EAAE,CAAC;QAC7D,MAAM,MAAM,GAAI,KAAiC,CAAC,MAAM,CAAC;QACzD,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC,CAAC;YAAE,OAAO,IAAI,CAAC;IACpG,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import {\n\ttype Api,\n\ttype Context,\n\tgetApiProvider,\n\tgetModel,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@draht/ai/compat\";\nimport { loadConfig } from \"./config.js\";\nimport { estimateCost, logCost } from \"./cost.js\";\nimport type { CostEntry, ModelRef, RouterConfig, RouterRole } from \"./types.js\";\n\n/**\n * Model router with role-based resolution, automatic fallback, and @draht/ai integration.\n */\nexport class ModelRouter {\n\tprivate config: RouterConfig;\n\tprivate sessionId: string;\n\n\tconstructor(config?: RouterConfig, sessionId?: string) {\n\t\tthis.config = config ?? loadConfig();\n\t\tthis.sessionId = sessionId ?? `session-${Date.now()}`;\n\t}\n\n\t/**\n\t * Resolve the primary model for a role.\n\t */\n\tresolve(role: RouterRole): ModelRef {\n\t\tconst roleConfig = this.config[role];\n\t\tif (!roleConfig) {\n\t\t\tthrow new Error(`Unknown role: ${role}. Available: ${Object.keys(this.config).join(\", \")}`);\n\t\t}\n\t\treturn roleConfig.primary;\n\t}\n\n\t/**\n\t * Resolve all models for a role: [primary, ...fallbacks].\n\t */\n\tresolveWithFallbacks(role: RouterRole): ModelRef[] {\n\t\tconst roleConfig = this.config[role];\n\t\tif (!roleConfig) {\n\t\t\tthrow new Error(`Unknown role: ${role}`);\n\t\t}\n\t\treturn [roleConfig.primary, ...roleConfig.fallbacks];\n\t}\n\n\t/**\n\t * Resolve a ModelRef to an actual @draht/ai Model object.\n\t * Looks up in the model registry by provider + model ID.\n\t */\n\tresolveModel(ref: ModelRef): Model<Api> | null {\n\t\ttry {\n\t\t\treturn getModel(ref.provider as any, ref.model as any) ?? null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Stream a completion using the role's model chain.\n\t * Automatically falls back on retryable errors (429, 5xx, timeout).\n\t *\n\t * Mid-stream failures are detected via error events in the stream.\n\t * Events are buffered and only yielded after successful completion,\n\t * preventing partial responses from failed providers from leaking through.\n\t */\n\tasync *stream(\n\t\trole: RouterRole,\n\t\tcontext: Context,\n\t\toptions?: StreamOptions,\n\t): AsyncGenerator<import(\"@draht/ai\").AssistantMessageEvent> {\n\t\tyield* this.streamWithFallback(role, context, options, (provider, model, opts) =>\n\t\t\tprovider.stream(model, context, opts),\n\t\t);\n\t}\n\n\t/**\n\t * Stream a simple completion (no tool use) with fallback.\n\t *\n\t * Mid-stream failures are detected via error events in the stream.\n\t * Events are buffered and only yielded after successful completion,\n\t * preventing partial responses from failed providers from leaking through.\n\t */\n\tasync *streamSimple(\n\t\trole: RouterRole,\n\t\tcontext: Context,\n\t\toptions?: SimpleStreamOptions,\n\t): AsyncGenerator<import(\"@draht/ai\").AssistantMessageEvent> {\n\t\tyield* this.streamWithFallback(role, context, options, (provider, model, opts) =>\n\t\t\tprovider.streamSimple(model, context, opts as SimpleStreamOptions),\n\t\t);\n\t}\n\n\t/**\n\t * Internal helper for streaming with fallback support.\n\t * Buffers events and checks for error events to trigger fallback.\n\t */\n\tprivate async *streamWithFallback<T extends StreamOptions>(\n\t\trole: RouterRole,\n\t\t_context: Context,\n\t\toptions: T | undefined,\n\t\tstreamFn: (\n\t\t\tprovider: NonNullable<ReturnType<typeof getApiProvider>>,\n\t\t\tmodel: Model<Api>,\n\t\t\toptions: T | undefined,\n\t\t) => AsyncIterable<import(\"@draht/ai\").AssistantMessageEvent>,\n\t): AsyncGenerator<import(\"@draht/ai\").AssistantMessageEvent> {\n\t\tconst models = this.resolveWithFallbacks(role);\n\t\tlet lastError: unknown;\n\n\t\tfor (const ref of models) {\n\t\t\tconst model = this.resolveModel(ref);\n\t\t\tif (!model) continue;\n\n\t\t\tconst provider = getApiProvider(model.api);\n\t\t\tif (!provider) continue;\n\n\t\t\t// Buffer events to prevent partial responses from leaking on failure\n\t\t\tconst bufferedEvents: import(\"@draht/ai\").AssistantMessageEvent[] = [];\n\t\t\tlet streamError: Error | null = null;\n\n\t\t\ttry {\n\t\t\t\tconst stream = streamFn(provider, model, options);\n\n\t\t\t\tfor await (const event of stream) {\n\t\t\t\t\t// Check for error events in the stream (mid-stream failures)\n\t\t\t\t\tif (event.type === \"error\") {\n\t\t\t\t\t\tconst errorMessage = event.error.errorMessage ?? \"Stream error\";\n\t\t\t\t\t\tstreamError = new Error(errorMessage);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tbufferedEvents.push(event);\n\n\t\t\t\t\t// If we got a done event, stream completed successfully\n\t\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\t\t// Yield all buffered events\n\t\t\t\t\t\tfor (const bufferedEvent of bufferedEvents) {\n\t\t\t\t\t\t\tyield bufferedEvent;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// If we exited the loop without a done event and no error, something is wrong\n\t\t\t\tif (!streamError) {\n\t\t\t\t\tstreamError = new Error(\"Stream ended without completion\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tstreamError = error instanceof Error ? error : new Error(String(error));\n\t\t\t}\n\n\t\t\t// Handle stream error - check if retryable for fallback\n\t\t\tif (streamError) {\n\t\t\t\tlastError = streamError;\n\t\t\t\tif (!isRetryableError(streamError)) {\n\t\t\t\t\tthrow streamError;\n\t\t\t\t}\n\t\t\t\t// Continue to next fallback, discarding buffered events\n\t\t\t}\n\t\t}\n\n\t\tthrow lastError ?? new Error(`No available model for role: ${role}`);\n\t}\n\n\t/**\n\t * Execute a function with automatic fallback on retryable errors.\n\t * For non-streaming use cases.\n\t */\n\tasync route<T>(role: RouterRole, fn: (model: ModelRef) => Promise<T>): Promise<T> {\n\t\tconst models = this.resolveWithFallbacks(role);\n\t\tlet lastError: unknown;\n\n\t\tfor (const model of models) {\n\t\t\ttry {\n\t\t\t\tconst result = await fn(model);\n\t\t\t\treturn result;\n\t\t\t} catch (error) {\n\t\t\t\tlastError = error;\n\t\t\t\tif (!isRetryableError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow lastError ?? new Error(`All models failed for role: ${role}`);\n\t}\n\n\t/**\n\t * Log a cost entry for tracking.\n\t */\n\ttrackCost(role: string, ref: ModelRef, inputTokens: number, outputTokens: number, reasoningTokens = 0): void {\n\t\tconst cost = estimateCost(ref.provider, ref.model, inputTokens, outputTokens, reasoningTokens);\n\t\tconst entry: CostEntry = {\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\trole,\n\t\t\tprovider: ref.provider,\n\t\t\tmodel: ref.model,\n\t\t\tinputTokens,\n\t\t\toutputTokens,\n\t\t\t...(reasoningTokens > 0 && { reasoningTokens }),\n\t\t\testimatedCostUsd: cost,\n\t\t\tsessionId: this.sessionId,\n\t\t};\n\t\tlogCost(entry);\n\t}\n\n\t/**\n\t * Get current config.\n\t */\n\tgetConfig(): RouterConfig {\n\t\treturn this.config;\n\t}\n}\n\n/**\n * Check if an error is retryable (rate limit, timeout, server error).\n */\nexport function isRetryableError(error: unknown): boolean {\n\tif (error instanceof Error) {\n\t\tconst msg = error.message.toLowerCase();\n\t\tif (msg.includes(\"rate limit\") || msg.includes(\"429\")) return true;\n\t\tif (msg.includes(\"timeout\") || msg.includes(\"timed out\") || msg.includes(\"etimedout\")) return true;\n\t\tif (msg.includes(\"500\") || msg.includes(\"502\") || msg.includes(\"503\") || msg.includes(\"504\")) return true;\n\t\tif (msg.includes(\"server error\") || msg.includes(\"internal error\")) return true;\n\t\tif (msg.includes(\"overloaded\") || msg.includes(\"capacity\")) return true;\n\t}\n\tif (error && typeof error === \"object\" && \"status\" in error) {\n\t\tconst status = (error as Record<string, unknown>).status;\n\t\tif (typeof status === \"number\" && (status === 429 || (status >= 500 && status < 600))) return true;\n\t}\n\treturn false;\n}\n"]}
1
+ {"version":3,"file":"router.js","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AACA,OAAO,EAGN,cAAc,EACd,QAAQ,EAER,gBAAgB,GAGhB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGlD;;GAEG;AACH,MAAM,OAAO,WAAW;IACf,MAAM,CAAe;IACrB,SAAS,CAAS;IAE1B,YAAY,MAAqB,EAAE,SAAkB;QACpD,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,UAAU,EAAE,CAAC;QAC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AC,QAAQ,CAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QACnE,IAAI,GAAG,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,WAAW,CAAC;YAAE,OAAO,IAAI,CAAC;QACnG,IAAI,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAC1G,IAAI,GAAG,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,gBAAgB,CAAC;YAAE,OAAO,IAAI,CAAC;QAChF,IAAI,GAAG,CAAC,QAAQ,CAAC,YAAY,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,UAAU,CAAC;YAAE,OAAO,IAAI,CAAC;IACzE,CAAC;IACD,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,IAAI,KAAK,EAAE,CAAC;QAC7D,MAAM,MAAM,GAAI,KAAiC,CAAC,MAAM,CAAC;QACzD,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC,CAAC;YAAE,OAAO,IAAI,CAAC;IACpG,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import type { AssistantMessageEvent } from \"@draht/ai\";\nimport {\n\ttype Api,\n\ttype Context,\n\tgetApiProvider,\n\tgetModel,\n\ttype Model,\n\tnormalizeContext,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@draht/ai/compat\";\nimport { loadConfig } from \"./config.js\";\nimport { estimateCost, logCost } from \"./cost.js\";\nimport type { CostEntry, ModelRef, RouterConfig, RouterRole } from \"./types.js\";\n\n/**\n * Model router with role-based resolution, automatic fallback, and @draht/ai integration.\n */\nexport class ModelRouter {\n\tprivate config: RouterConfig;\n\tprivate sessionId: string;\n\n\tconstructor(config?: RouterConfig, sessionId?: string) {\n\t\tthis.config = config ?? loadConfig();\n\t\tthis.sessionId = sessionId ?? `session-${Date.now()}`;\n\t}\n\n\t/**\n\t * Resolve the primary model for a role.\n\t */\n\tresolve(role: RouterRole): ModelRef {\n\t\tconst roleConfig = this.config[role];\n\t\tif (!roleConfig) {\n\t\t\tthrow new Error(`Unknown role: ${role}. Available: ${Object.keys(this.config).join(\", \")}`);\n\t\t}\n\t\treturn roleConfig.primary;\n\t}\n\n\t/**\n\t * Resolve all models for a role: [primary, ...fallbacks].\n\t */\n\tresolveWithFallbacks(role: RouterRole): ModelRef[] {\n\t\tconst roleConfig = this.config[role];\n\t\tif (!roleConfig) {\n\t\t\tthrow new Error(`Unknown role: ${role}`);\n\t\t}\n\t\treturn [roleConfig.primary, ...roleConfig.fallbacks];\n\t}\n\n\t/**\n\t * Resolve a ModelRef to an actual @draht/ai Model object.\n\t * Looks up in the model registry by provider + model ID.\n\t */\n\tresolveModel(ref: ModelRef): Model<Api> | null {\n\t\ttry {\n\t\t\treturn getModel(ref.provider as any, ref.model as any) ?? null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Stream a completion using the role's model chain.\n\t * Automatically falls back on retryable errors (429, 5xx, timeout).\n\t *\n\t * Mid-stream failures are detected via error events in the stream.\n\t * Events are buffered and only yielded after successful completion,\n\t * preventing partial responses from failed providers from leaking through.\n\t */\n\tasync *stream(role: RouterRole, context: Context, options?: StreamOptions): AsyncGenerator<AssistantMessageEvent> {\n\t\tyield* this.streamWithFallback(role, context, options, (provider, model, opts) =>\n\t\t\tprovider.stream(model, normalizeContext(context), opts),\n\t\t);\n\t}\n\n\t/**\n\t * Stream a simple completion (no tool use) with fallback.\n\t *\n\t * Mid-stream failures are detected via error events in the stream.\n\t * Events are buffered and only yielded after successful completion,\n\t * preventing partial responses from failed providers from leaking through.\n\t */\n\tasync *streamSimple(\n\t\trole: RouterRole,\n\t\tcontext: Context,\n\t\toptions?: SimpleStreamOptions,\n\t): AsyncGenerator<AssistantMessageEvent> {\n\t\tyield* this.streamWithFallback(role, context, options, (provider, model, opts) =>\n\t\t\tprovider.streamSimple(model, normalizeContext(context), opts as SimpleStreamOptions),\n\t\t);\n\t}\n\n\t/**\n\t * Internal helper for streaming with fallback support.\n\t * Buffers events and checks for error events to trigger fallback.\n\t */\n\tprivate async *streamWithFallback<T extends StreamOptions>(\n\t\trole: RouterRole,\n\t\t_context: Context,\n\t\toptions: T | undefined,\n\t\tstreamFn: (\n\t\t\tprovider: NonNullable<ReturnType<typeof getApiProvider>>,\n\t\t\tmodel: Model<Api>,\n\t\t\toptions: T | undefined,\n\t\t) => AsyncIterable<AssistantMessageEvent>,\n\t): AsyncGenerator<AssistantMessageEvent> {\n\t\tconst models = this.resolveWithFallbacks(role);\n\t\tlet lastError: unknown;\n\n\t\tfor (const ref of models) {\n\t\t\tconst model = this.resolveModel(ref);\n\t\t\tif (!model) continue;\n\n\t\t\tconst provider = getApiProvider(model.api);\n\t\t\tif (!provider) continue;\n\n\t\t\t// Buffer events to prevent partial responses from leaking on failure\n\t\t\tconst bufferedEvents: AssistantMessageEvent[] = [];\n\t\t\tlet streamError: Error | null = null;\n\n\t\t\ttry {\n\t\t\t\tconst stream = streamFn(provider, model, options);\n\n\t\t\t\tfor await (const event of stream) {\n\t\t\t\t\t// Check for error events in the stream (mid-stream failures)\n\t\t\t\t\tif (event.type === \"error\") {\n\t\t\t\t\t\tconst errorMessage = event.error.errorMessage ?? \"Stream error\";\n\t\t\t\t\t\tstreamError = new Error(errorMessage);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tbufferedEvents.push(event);\n\n\t\t\t\t\t// If we got a done event, stream completed successfully\n\t\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\t\t// Yield all buffered events\n\t\t\t\t\t\tfor (const bufferedEvent of bufferedEvents) {\n\t\t\t\t\t\t\tyield bufferedEvent;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// If we exited the loop without a done event and no error, something is wrong\n\t\t\t\tif (!streamError) {\n\t\t\t\t\tstreamError = new Error(\"Stream ended without completion\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tstreamError = error instanceof Error ? error : new Error(String(error));\n\t\t\t}\n\n\t\t\t// Handle stream error - check if retryable for fallback\n\t\t\tif (streamError) {\n\t\t\t\tlastError = streamError;\n\t\t\t\tif (!isRetryableError(streamError)) {\n\t\t\t\t\tthrow streamError;\n\t\t\t\t}\n\t\t\t\t// Continue to next fallback, discarding buffered events\n\t\t\t}\n\t\t}\n\n\t\tthrow lastError ?? new Error(`No available model for role: ${role}`);\n\t}\n\n\t/**\n\t * Execute a function with automatic fallback on retryable errors.\n\t * For non-streaming use cases.\n\t */\n\tasync route<T>(role: RouterRole, fn: (model: ModelRef) => Promise<T>): Promise<T> {\n\t\tconst models = this.resolveWithFallbacks(role);\n\t\tlet lastError: unknown;\n\n\t\tfor (const model of models) {\n\t\t\ttry {\n\t\t\t\tconst result = await fn(model);\n\t\t\t\treturn result;\n\t\t\t} catch (error) {\n\t\t\t\tlastError = error;\n\t\t\t\tif (!isRetryableError(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow lastError ?? new Error(`All models failed for role: ${role}`);\n\t}\n\n\t/**\n\t * Log a cost entry for tracking.\n\t */\n\ttrackCost(role: string, ref: ModelRef, inputTokens: number, outputTokens: number, reasoningTokens = 0): void {\n\t\tconst cost = estimateCost(ref.provider, ref.model, inputTokens, outputTokens, reasoningTokens);\n\t\tconst entry: CostEntry = {\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\trole,\n\t\t\tprovider: ref.provider,\n\t\t\tmodel: ref.model,\n\t\t\tinputTokens,\n\t\t\toutputTokens,\n\t\t\t...(reasoningTokens > 0 && { reasoningTokens }),\n\t\t\testimatedCostUsd: cost,\n\t\t\tsessionId: this.sessionId,\n\t\t};\n\t\tlogCost(entry);\n\t}\n\n\t/**\n\t * Get current config.\n\t */\n\tgetConfig(): RouterConfig {\n\t\treturn this.config;\n\t}\n}\n\n/**\n * Check if an error is retryable (rate limit, timeout, server error).\n */\nexport function isRetryableError(error: unknown): boolean {\n\tif (error instanceof Error) {\n\t\tconst msg = error.message.toLowerCase();\n\t\tif (msg.includes(\"rate limit\") || msg.includes(\"429\")) return true;\n\t\tif (msg.includes(\"timeout\") || msg.includes(\"timed out\") || msg.includes(\"etimedout\")) return true;\n\t\tif (msg.includes(\"500\") || msg.includes(\"502\") || msg.includes(\"503\") || msg.includes(\"504\")) return true;\n\t\tif (msg.includes(\"server error\") || msg.includes(\"internal error\")) return true;\n\t\tif (msg.includes(\"overloaded\") || msg.includes(\"capacity\")) return true;\n\t}\n\tif (error && typeof error === \"object\" && \"status\" in error) {\n\t\tconst status = (error as Record<string, unknown>).status;\n\t\tif (typeof status === \"number\" && (status === 429 || (status >= 500 && status < 600))) return true;\n\t}\n\treturn false;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@draht/router",
3
- "version": "2026.9.5-1",
3
+ "version": "2026.10.4-2",
4
4
  "description": "Role-based model routing with direct API calls, auto-fallback, and cost tracking",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -25,9 +25,9 @@
25
25
  "test": "bun test"
26
26
  },
27
27
  "dependencies": {
28
- "@draht/ai": "2026.9.5-1"
28
+ "@draht/ai": "2026.10.4-2"
29
29
  },
30
30
  "devDependencies": {
31
- "@draht/coding-agent": "2026.9.5-1"
31
+ "@draht/coding-agent": "2026.10.4-2"
32
32
  }
33
33
  }