Skip to content

fix(pi): resolve API key for custom models.json providers (fixes 401 on self-hosted gateways)#1995

Open
bjornrun wants to merge 1 commit into
coleam00:devfrom
bjornrun:fix/pi-custom-provider-key
Open

fix(pi): resolve API key for custom models.json providers (fixes 401 on self-hosted gateways)#1995
bjornrun wants to merge 1 commit into
coleam00:devfrom
bjornrun:fix/pi-custom-provider-key

Conversation

@bjornrun

@bjornrun bjornrun commented Jun 15, 2026

Copy link
Copy Markdown

Problem

The Pi provider only injects an API key when the provider id is present in the
generated PI_PROVIDER_ENV_VARS map (pi-vendor-map.generated.ts, derived from
pi-ai's built-in SDK backends). For a custom provider the user defines in
pi's models.json — e.g. a self-hosted, OpenAI-compatible gateway —

// ~/.pi/agent/models.json
{ "providers": { "mygw": {
    "baseUrl": "https://gateway.example/v1",
    "api": "openai-completions",
    "apiKey": "$MYGW_API_KEY"
} } }

PI_PROVIDER_ENV_VARS["mygw"] is undefined, so setRuntimeApiKey is never
called. Execution then takes the "unmapped provider" branch, logs auth_missing,
and continues without credentials — the upstream request goes out with no
key and the gateway returns 401. The model resolves fine (it's in
models.json), so the failure is purely auth and is confusing to debug.

Using such a provider works with pi's own CLI (which reads the apiKey: "$ENV"
reference from models.json), but not through Archon.

Fix

Add a small, pure helper customProviderApiKeyEnvVar(provider, configDir?) that,
for a provider not in the generated map, reads
$PI_CODING_AGENT_DIR/models.json (falling back to ~/.pi/agent/models.json
the same file pi's CLI reads) and returns the bare env-var name from that
provider's apiKey: "$ENV_VAR" reference. The Pi provider uses it as a fallback:

const envVarName =
  PI_PROVIDER_ENV_VARS[parsed.provider] ?? customProviderApiKeyEnvVar(parsed.provider);

so any custom OpenAI-compatible provider authenticates with no per-provider code
change. The lookup is best-effort: missing/unreadable/malformed models.json,
an absent provider, or a non-$ apiKey all return undefined, falling through
to the existing no-credentials path. Built-in SDK backends are unchanged.

Testing

  • New custom-provider-key.test.ts (6 cases: $ENV reference, literal key,
    missing provider, missing file, malformed JSON, bare $) — all pass via
    bun test (100% coverage of the new module).
  • Change is additive; existing mapped-provider behavior is untouched.

Notes

  • Does not modify pi-vendor-map.generated.ts or the check:pi-vendor-map
    drift guard — this is a runtime fallback only.
  • Verified end-to-end against a self-hosted OpenAI-compatible gateway: the Pi
    assistant now authenticates (was 401) and routes correctly.

Summary by CodeRabbit

  • New Features

    • Added support for resolving API keys from provider configuration files, enabling environment variable references for custom Pi providers beyond the default set.
  • Tests

    • Added comprehensive test suite covering API key environment variable resolution, including validation of configuration formats and error handling.

Custom providers defined in pi models.json (self-hosted OpenAI-compatible gateways) were never sent an API key because only providers in the generated PI_PROVIDER_ENV_VARS map get injected, so requests returned 401. Resolve the key env-var name from the provider models.json apiKey reference as a fallback. Additive; adds custom-provider-key.ts + unit tests.
@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a new customProviderApiKeyEnvVar helper that reads models.json from the Pi config directory and extracts the environment-variable name when a custom provider's apiKey is a "$VAR"-prefixed string. PiProvider is updated to call this helper as a fallback. Six Bun tests validate all resolution paths.

Changes

Custom Pi provider API key env-var resolution

Layer / File(s) Summary
customProviderApiKeyEnvVar implementation
packages/providers/src/community/pi/custom-provider-key.ts
New exported function reads and parses models.json from PI_CODING_AGENT_DIR or ~/.pi/agent, returns the bare env-var name from a "$VAR"-formatted apiKey, and returns undefined on any failure or non-conforming value.
PiProvider fallback wiring
packages/providers/src/community/pi/provider.ts
Imports customProviderApiKeyEnvVar and adds it as a fallback in envVarName resolution when PI_PROVIDER_ENV_VARS has no static entry for the provider.
Tests
packages/providers/src/community/pi/custom-provider-key.test.ts
Six Bun test cases with temporary directories cover successful resolution, literal apiKey, missing provider, absent models.json, malformed JSON, and bare "$" edge cases.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • coleam00/Archon#1284: Also modifies packages/providers/src/community/pi/provider.ts to change how unmapped/custom Pi providers handle missing credentials and environment-variable hints.

Poem

🐇 Hopping through config files with glee,
A $VAR in models.json — now I can see!
No more bare "$" to leave me confused,
The env var name found, no longer refused.
With temp dirs for tests, all cleaned up neat,
This little Pi key helper's quite the feat! 🥕

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive Description covers Problem, Fix, Testing, and Notes sections well but is missing several required template sections (UX Journey, Architecture Diagram, Label Snapshot, Validation Evidence, Security Impact, Compatibility, Human Verification, Side Effects, Rollback Plan, Risks). Add missing template sections including Validation Evidence (test results), Security Impact assessment, Compatibility statement, Human Verification details, and Side Effects/Rollback Plan to fully comply with the repository's PR description template.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed Title clearly and specifically identifies the fix (API key resolution for custom models.json providers) and its impact (401 errors on self-hosted gateways).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/providers/src/community/pi/custom-provider-key.test.ts`:
- Around line 39-42: The test uses a fixed hardcoded directory name
`pi-nonexistent-dir-xyz` which could exist on a test runner, causing flakiness.
Replace this by creating a unique temporary directory path before the test runs
(using a library like `unique-temp-dir` or Node's built-in `fs` and `path`
utilities), explicitly delete it to guarantee it doesn't exist, and then pass
that guaranteed-missing path to the `customProviderApiKeyEnvVar` function call
instead of the fixed string. This ensures the test condition (missing
models.json) is deterministically satisfied on every run regardless of the
runner's state.

In `@packages/providers/src/community/pi/custom-provider-key.ts`:
- Around line 49-50: The condition checking for environment variable references
in the apiKey parsing is too permissive and accepts invalid tokens like `$$` or
`$A-B`. Tighten the validation by adding a check to ensure the characters
following the `$` form a valid environment variable name (typically matching a
pattern like alphanumeric characters and underscores). When the token after `$`
does not match a valid environment variable format, return `undefined` instead
of slicing the string, allowing the no-credentials fallback path to handle it
correctly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 975a64ea-6c6c-4038-9f19-1a02e093f9e1

📥 Commits

Reviewing files that changed from the base of the PR and between ece2a68 and 25f737c.

📒 Files selected for processing (3)
  • packages/providers/src/community/pi/custom-provider-key.test.ts
  • packages/providers/src/community/pi/custom-provider-key.ts
  • packages/providers/src/community/pi/provider.ts

Comment on lines +39 to +42
test('returns undefined when models.json does not exist', () => {
expect(
customProviderApiKeyEnvVar('x', join(tmpdir(), 'pi-nonexistent-dir-xyz'))
).toBeUndefined();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Make the “missing models.json” case guaranteed-missing per run.

Using a fixed temp path (pi-nonexistent-dir-xyz) can become flaky if that directory appears on a runner. Create a unique temp directory and delete it first, then assert against that path.

Suggested patch
   test('returns undefined when models.json does not exist', () => {
-    expect(
-      customProviderApiKeyEnvVar('x', join(tmpdir(), 'pi-nonexistent-dir-xyz'))
-    ).toBeUndefined();
+    const missingDir = mkdtempSync(join(tmpdir(), 'pi-missing-'));
+    rmSync(missingDir, { recursive: true, force: true });
+    expect(customProviderApiKeyEnvVar('x', missingDir)).toBeUndefined();
   });

As per coding guidelines, “Keep tests deterministic — no flaky timing or network dependence without guardrails.”

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
test('returns undefined when models.json does not exist', () => {
expect(
customProviderApiKeyEnvVar('x', join(tmpdir(), 'pi-nonexistent-dir-xyz'))
).toBeUndefined();
test('returns undefined when models.json does not exist', () => {
const missingDir = mkdtempSync(join(tmpdir(), 'pi-missing-'));
rmSync(missingDir, { recursive: true, force: true });
expect(customProviderApiKeyEnvVar('x', missingDir)).toBeUndefined();
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/providers/src/community/pi/custom-provider-key.test.ts` around lines
39 - 42, The test uses a fixed hardcoded directory name `pi-nonexistent-dir-xyz`
which could exist on a test runner, causing flakiness. Replace this by creating
a unique temporary directory path before the test runs (using a library like
`unique-temp-dir` or Node's built-in `fs` and `path` utilities), explicitly
delete it to guarantee it doesn't exist, and then pass that guaranteed-missing
path to the `customProviderApiKeyEnvVar` function call instead of the fixed
string. This ensures the test condition (missing models.json) is
deterministically satisfied on every run regardless of the runner's state.

Source: Coding guidelines

Comment on lines +49 to +50
if (typeof apiKey === 'string' && apiKey.startsWith('$') && apiKey.length > 1) {
return apiKey.slice(1);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Tighten $ENV_VAR parsing to avoid false positives.

The current check accepts any non-empty string starting with $ (for example $$ or $A-B) as an env-var reference. This should only resolve valid env-var tokens, otherwise return undefined and keep the no-credentials fallback path.

Suggested patch
-    if (typeof apiKey === 'string' && apiKey.startsWith('$') && apiKey.length > 1) {
-      return apiKey.slice(1);
-    }
+    if (typeof apiKey === 'string') {
+      const match = apiKey.match(/^\$([A-Za-z_][A-Za-z0-9_]*)$/);
+      if (match) return match[1];
+    }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/providers/src/community/pi/custom-provider-key.ts` around lines 49 -
50, The condition checking for environment variable references in the apiKey
parsing is too permissive and accepts invalid tokens like `$$` or `$A-B`.
Tighten the validation by adding a check to ensure the characters following the
`$` form a valid environment variable name (typically matching a pattern like
alphanumeric characters and underscores). When the token after `$` does not
match a valid environment variable format, return `undefined` instead of slicing
the string, allowing the no-credentials fallback path to handle it correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants