Files
PaperClipAI/packages/adapters/hermes/src/server/detect-model.ts
T
DottaandPaperclip fd2f82ac5b [codex] Add built-in Hermes adapters (#8543)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent adapters are the boundary between the control plane and the
runtimes that actually do work.
> - Hermes support needs to be available as first-class local and
gateway adapters while still preserving the adapter-manager override
path for external packages.
> - The adapter work touches runtime execution, UI adapter metadata,
onboarding prompts, scoped credentials, release packaging, and smoke
coverage, so the handoff needs concrete verification rather than only
unit tests.
> - This pull request adds built-in Hermes local and Hermes gateway
support, keeps external adapter overrides compatible, and
documents/tests the gateway flow end to end.
> - The benefit is that operators can hire Hermes-backed agents without
a manual plugin install, while self-hosted installs can still
override/shadow the built-ins through Adapter manager packages.

## Linked Issues or Issue Description

No public GitHub issue exists for this exact Hermes built-in adapter,
gateway onboarding, and release-source work.

Problem description:
- Hermes local and gateway adapters need a public, reviewable source
path in the monorepo so package artifacts and built-in adapter behavior
match the application source.
- Operators need built-in `hermes_local` and `hermes_gateway` adapter
choices without losing the ability to install external Hermes packages
as overrides.
- Gateway onboarding needs secure defaults for API server URLs, API
keys, and generated agent setup text.
- Hermes-originated task bridge credentials need narrower API-key scope
configuration.
- Related public PRs found during duplicate search include #3027, #2363,
#7544, #7950, #8095, and #8543.

## What Changed

- Added the unified Hermes adapter package with local and gateway
server/UI/CLI exports, config schemas, transcript parsing, model
detection, and package metadata.
- Registered `hermes_local` and `hermes_gateway` as built-in adapters
across shared constants, server registries, CLI packaging, and UI
adapter registries.
- Kept the external adapter override path compatible so installed Hermes
packages can shadow built-ins and restore the built-in parser when
disabled.
- Added Hermes gateway onboarding docs, board-operator docs, Docker
smoke assets, and shell smoke harnesses for join/e2e validation.
- Added scoped task-bridge API-key support, authorization checks,
issue-origin handling, and tests for Hermes-created Paperclip tasks.
- Hardened gateway transport and redaction behavior for API keys,
headers, session data, and smoke diagnostics.
- Updated release packaging/bootstrap checks for the Hermes packages
while leaving `pnpm-lock.yaml` out of the PR per repository policy.

## Verification

Targeted local verification recorded before PR handoff:
- `pnpm --filter @paperclipai/hermes-paperclip-adapter exec vitest run
src/gateway/server/execute.test.ts` — 14/14 passed.
- `pnpm test:hermes-gateway-smoke` — 6/6 passed.
- Hermes package typecheck/build checks passed.
- Focused server/UI adapter tests passed — 31/31.
- Release helper Node tests passed — 18/18.
- `git diff --check origin/master..HEAD` passed.

Fresh Docker E2E smoke evidence:
- Ran `pnpm smoke:hermes-gateway-e2e` on 2026-06-26 with a fresh state
directory and fresh Docker container against a live Paperclip dev
server.
- Hermes direct execution reached `completed`.
- Hermes stop/cancel path reached `cancelled`.
- Hermes gateway created a Paperclip task, Paperclip ran the Hermes
agent, and the task reached `done` with the expected marker response.
- Temporary board auth keys, token files, smoke state, and Docker
containers were cleaned up after the run.

PR checks on head `b5eae40ce`:
- GitHub Actions passed: `policy`, `review`, `Typecheck + Release
Registry`, all general test shards, all serialized server shards,
`Build`, `Canary Dry Run`, `e2e`, and aggregate `verify`.
- External checks passed: Snyk and Socket Project Report.
- External Socket Pull Request Alerts remained pending after the
first-party CI matrix completed.

## Risks

- Medium risk: this spans adapter registration, package publishing,
gateway execution, onboarding docs, API-key scoping, and UI adapter
metadata.
- Migration risk is low: the scope-config migration adds a nullable
column and does not rewrite existing keys.
- Gateway execution depends on operator-provided Hermes API
configuration; the smoke covers the Docker gateway path but real
deployments may differ by network/auth setup.
- Direct Greptile review on the latest expanded diff is file-count
limited, although the commitperclip review gate passed.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI Codex, GPT-5 coding agent, tool use enabled in a local repository
workspace. Context window size is not exposed in this environment.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Commitperclip review gate is green; direct Greptile review is
file-count limited on the latest expanded diff
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-06-26 16:04:58 -05:00

218 lines
7.4 KiB
TypeScript

/**
* Detect the current model and provider from the user's Hermes config.
*
* Reads ~/.hermes/config.yaml and extracts the default model,
* provider, base_url, api_key presence, and api_mode settings.
*
* Also provides provider resolution logic that merges explicit config,
* Hermes config detection, and model-name prefix inference.
*/
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { homedir } from "node:os";
import { MODEL_PREFIX_PROVIDER_HINTS, VALID_PROVIDERS } from "../shared/constants.js";
export interface DetectedModel {
/** Model name from config (e.g. "gpt-5.4", "anthropic/claude-sonnet-4") */
model: string;
/** Provider name from config (e.g. "copilot", "zai"). May be empty. */
provider: string;
/** Base URL override from config (e.g. "https://api.githubcopilot.com"). May be empty. */
baseUrl: string;
/** Whether Hermes config includes a non-empty API key. */
hasApiKey: boolean;
/** API mode from config (e.g. "chat_completions", "codex_responses"). May be empty. */
apiMode: string;
/** Where the detection came from */
source: "config";
}
/**
* Read the Hermes config file and extract the default model config.
*/
export async function detectModel(
configPath?: string,
): Promise<DetectedModel | null> {
const filePath = configPath ?? join(homedir(), ".hermes", "config.yaml");
let content: string;
try {
content = await readFile(filePath, "utf-8");
} catch {
return null;
}
return parseModelFromConfig(content);
}
/**
* Parse model.default, model.provider, model.base_url, model.api_key, and model.api_mode
* from raw YAML content. Uses simple regex parsing to avoid a YAML dependency.
*/
export function parseModelFromConfig(content: string): DetectedModel | null {
const lines = content.split("\n");
let model = "";
let provider = "";
let baseUrl = "";
let hasApiKey = false;
let apiMode = "";
let inModelSection = false;
let modelSectionIndent = 0;
for (const line of lines) {
const trimmed = line.trimEnd();
const indent = line.length - line.trimStart().length;
// Track model: section (indent 0)
if (/^model:\s*$/.test(trimmed) && indent === 0) {
inModelSection = true;
modelSectionIndent = 0;
continue;
}
// We left the model section if indent drops back to the section level or below
if (inModelSection && indent <= modelSectionIndent && trimmed && !trimmed.startsWith("#")) {
inModelSection = false;
}
if (inModelSection) {
const match = trimmed.match(/^\s*(\w+)\s*:\s*(.+)$/);
if (match) {
const key = match[1];
const val = match[2].trim().replace(/#.*$/, "").trim().replace(/^['"]|['"]$/g, "");
if (key === "default") model = val;
if (key === "provider") provider = val;
if (key === "base_url") baseUrl = val;
if (key === "api_key") hasApiKey = val.length > 0;
if (key === "api_mode") apiMode = val;
}
}
}
if (!model) return null;
return { model, provider, baseUrl, hasApiKey, apiMode, source: "config" };
}
/**
* Infer a provider from the model name using prefix-based hints.
*
* For example:
* "gpt-5.4" → "copilot"
* "claude-sonnet-4" → "anthropic"
* "glm-5-turbo" → "zai"
*
* Returns undefined if no hint matches (caller should fall back to "auto").
*/
export function inferProviderFromModel(model: string): string | undefined {
const lower = model.toLowerCase();
// Strip provider/ prefix if present (e.g. "anthropic/claude-sonnet-4")
const bareName = lower.includes("/") ? lower.split("/").pop()! : lower;
for (const [prefix, hint] of MODEL_PREFIX_PROVIDER_HINTS) {
if (bareName.startsWith(prefix)) {
return hint;
}
}
return undefined;
}
/**
* Resolve the correct provider for a model, using a priority chain:
*
* 1. Explicit provider from adapterConfig (highest priority — user override)
* 2. Provider from Hermes config file — ONLY if the config model matches
* the requested model (otherwise the config provider is for a different model)
* 3. If Hermes config matches the requested model but uses runtime settings that
* the adapter cannot represent directly, return "auto" and let Hermes resolve it itself
* 4. Provider inferred from model name prefix
* 5. "auto" (let Hermes figure it out — lowest priority)
*
* Always returns a valid provider string.
* The `resolvedFrom` field indicates which source was used, useful for logging.
*/
export function resolveProvider(options: {
/** Explicit provider from adapterConfig (user override) */
explicitProvider?: string | null;
/** Provider detected from Hermes config file */
detectedProvider?: string;
/** Model name from Hermes config file (to check consistency) */
detectedModel?: string;
/** Base URL detected from Hermes config file */
detectedBaseUrl?: string;
/** Whether Hermes config includes a non-empty API key */
detectedHasApiKey?: boolean;
/** API mode detected from Hermes config file */
detectedApiMode?: string;
/** Model name to infer from if no explicit/detected provider */
model?: string;
}): { provider: string; resolvedFrom: string } {
const {
explicitProvider,
detectedProvider,
detectedModel,
detectedBaseUrl,
detectedHasApiKey,
detectedApiMode,
model,
} = options;
// 1. Explicit provider from adapterConfig — user override, always wins
if (explicitProvider && (VALID_PROVIDERS as readonly string[]).includes(explicitProvider)) {
return { provider: explicitProvider, resolvedFrom: "adapterConfig" };
}
const supportedProviders = VALID_PROVIDERS as readonly string[];
const configMatchesRequestedModel =
!!detectedModel &&
!!model &&
detectedModel.toLowerCase() === model.toLowerCase();
// 2. Provider from Hermes config file — but ONLY if the config model matches
// the requested model. Otherwise the config provider is for a different model
// and would cause exactly the kind of routing bug we're fixing.
if (
configMatchesRequestedModel &&
!!detectedProvider &&
supportedProviders.includes(detectedProvider)
) {
return { provider: detectedProvider, resolvedFrom: "hermesConfig" };
}
const hasRuntimeSignals = !!detectedBaseUrl || !!detectedHasApiKey || !!detectedApiMode;
// 3a. Matching Hermes config with an unsupported provider (for example "custom")
// should not fall through to model-name inference, because that can route to
// the wrong provider entirely. Defer back to Hermes's own runtime resolution.
if (configMatchesRequestedModel && !!detectedProvider && !supportedProviders.includes(detectedProvider)) {
return {
provider: "auto",
resolvedFrom: `hermesConfigUnsupported:${detectedProvider}`,
};
}
// 3b. Matching Hermes config may omit provider entirely while still specifying
// enough runtime information (base_url, api_key, api_mode) for Hermes itself.
// In that case, also defer to Hermes instead of doing a wrong prefix inference.
if (configMatchesRequestedModel && !detectedProvider && hasRuntimeSignals) {
return {
provider: "auto",
resolvedFrom: "hermesConfigRuntime",
};
}
// 4. Infer from model name prefix
if (model) {
const inferred = inferProviderFromModel(model);
if (inferred) {
return { provider: inferred, resolvedFrom: "modelInference" };
}
}
// 5. Let Hermes auto-detect
return { provider: "auto", resolvedFrom: "auto" };
}