Skip to content

feat(pi): Use ModelRegistry & allow empty auth to support custom models/providers.#1284

Merged
Wirasm merged 6 commits intocoleam00:devfrom
matt2000:patch-pi-local-models
Apr 27, 2026
Merged

feat(pi): Use ModelRegistry & allow empty auth to support custom models/providers.#1284
Wirasm merged 6 commits intocoleam00:devfrom
matt2000:patch-pi-local-models

Conversation

@matt2000
Copy link
Copy Markdown
Contributor

@matt2000 matt2000 commented Apr 18, 2026

Summary

Closes #1096

Describe this PR in 2-5 bullets:

  • Problem: Pi Provider can't find custom models or providers (in the 'pi' sense) that have been configured for Pi.
  • Why it matters: This is necessary to use, e.g., offline model via ollama, etc, or to use any provider or model that is not predefined in PI's static catalog. It also allows you to override some model configuration values.
  • What changed: Removed the use of pi-ai package getModel function, which only checks static catalog, and instead we use the find() method of the ModelRegistry that we have to construct anyway, which will load the user's Pi model configurations.
    This also has the side benefit of removing the lookupPiModel method which was doing some weird backflips to get type casting that ModelRegistry.find already does.
  • What did not change (scope boundary): Anything outside of the pi/provider.ts.
    There was a comment about not hitting ~/.pi, but this was always a lie, because we had to read auth.json. If we want to minimize disk reads by caching the 2 disk reads, I suggest we address that in a follow-up task unless we have actual evidence that this change introduces significant performance burden to existing use cases.

UX Journey

Context

User has Pi configured to use custom models, perhaps fine-tuned models on a major cloud provider, perhaps standard models on a less known but compatible cloud provider, or perhaps a model running locally via ollama, llamacpp, mlx, or similar.

Before

This works fine for Pi, but when Archon is configured to use the Pi provider, with the same model, Archon reports the model as not found.

After

Now this works fine in Archon too.

Label Snapshot

  • Risk: risk: low
  • Size: size: S
  • Scope: adapters
  • Module: providers:community.pi

Change Metadata

  • Change type: bug|feature
  • Primary scope: adapters

Validation Evidence (required)

Commands and result summary:

bun run type-check
bun run lint
bun run format:check
bun run test
# Or all at once:
bun run validate
  • Evidence provided (test/log/trace/screenshot):
Archon % bun run validate
$ bun run check:bundled && bun run type-check && bun run lint --max-warnings 0 && bun run format:check && bun run test
$ bun run scripts/generate-bundled-defaults.ts --check
bundled-defaults.generated.ts is up to date (36 commands, 20 workflows).
$ bun --filter '*' type-check && bun x tsc --noEmit -p scripts/tsconfig.json
@archon/isolation type-check $ bun x tsc --noEmit
└─ Done in 531 ms
@archon/isolation type-check $ bun x tsc --noEmit
└─ Done in 531 ms
@archon/isolation type-check $ bun x tsc --noEmit
└─ Done in 531 ms
@archon/adapters type-check $ bun x tsc --noEmit
└─ Done in 1.99 s
@archon/git type-check $ bun x tsc --noEmit
└─ Done in 447 ms
@archon/providers type-check $ bun x tsc --noEmit
└─ Done in 810 ms
@archon/web type-check $ tsc --noEmit
└─ Done in 2.30 s
@archon/paths type-check $ bun x tsc --noEmit
└─ Done in 378 ms
@archon/workflows type-check $ bun x tsc --noEmit
└─ Done in 1.25 s
@archon/core type-check $ bun x tsc --noEmit
└─ Done in 1.25 s
@archon/cli type-check $ bun x tsc --noEmit
│ src/search_esc.ts(9,40): error TS2339: Property 'promises' does not exist on type 'Promise<{ default: typeof import("fs"); rename: typeof rename; renameSync(oldPath: PathLike, newPath: PathLike): void; truncate: typeof truncate; truncateSync(path: PathLike, len?: number | undefined): void; ... 95 more ...; constants: typeof constants; }>'.
│ src/search_esc.ts(15,30): error TS2345: Argument of type 'Buffer<ArrayBuffer>' is not assignable to parameter of type 'string'.
└─ Exited with code 2
@archon/server type-check $ bun x tsc --noEmit
└─ Done in 2.14 s
  • If any command is intentionally skipped, explain why:
    n/a

Security Impact (required)

  • New permissions/capabilities? (No)
  • New external network calls? (No)
  • Secrets/tokens handling changed? (No)
  • File system access scope changed? (No)
  • If any Yes, describe risk and mitigation:
    n/a

Compatibility / Migration

  • Backward compatible? (Yes)
  • Config/env changes? (No)
  • Database migration needed? (No)
  • If yes, exact upgrade steps:
    n/a

Human Verification (required)

What was personally validated beyond CI:

  • Verified scenarios: Ran a workflow using custom provider and model.
  • Edge cases checked: n/a
  • What was not verified: Custom provider requiring authentication

Side Effects / Blast Radius (required)

  • Affected subsystems/workflows: n/a
  • Potential unintended effects: A command may now try to run without valid credentials because we must allow for the possibility of providers that do not require any credentials.
  • Guardrails/monitoring for early detection: Log message.

Rollback Plan (required)

  • Fast rollback command/path: git revert
  • Feature flags or config toggles (if any): No
  • Observable failure symptoms: n/a

Summary by CodeRabbit

  • Bug Fixes

    • Unmapped Pi providers now log an informational message (with an env-var hint) when credentials are missing instead of throwing; env-mapped providers still fail fast with a login hint. Model-not-found errors now surface clearer diagnostics.
  • Refactor

    • Streamlined per-request model resolution and authentication lifecycle so credential checks and model lookup share the same storage and error handling.
  • Tests

    • Tests updated to use registry-based model lookup, remove the old model mock, and clear logger/registry mocks between tests.
  • Documentation

    • Docs updated to describe local/custom inference paths, supported local backends, model naming, and auth-missing runtime behavior.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 18, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Refactors Pi provider model resolution and auth to use pi-coding-agent's AuthStorage + ModelRegistry.create(authStorage).find(). Credential behavior now throws for env-var-mapped providers but logs info (pi.auth_missing) for unmapped ones. Tests and docs updated to match new resolution, error, and logging behavior.

Changes

Cohort / File(s) Summary
Provider implementation — Pi
packages/providers/src/community/pi/provider.ts
Replaced @mariozechner/pi-ai lookup with runtime pi-coding-agent flow: create AuthStorage, call ModelRegistry.create(authStorage), use modelRegistry.find(provider, modelId); surface models.json load errors in "model not found" messages; change credential handling to throw for env-var-mapped providers and emit pi.auth_missing info for unmapped providers; trim outdated comments.
Tests — Pi provider
packages/providers/src/community/pi/provider.test.ts
Switch test mocks from @mariozechner/pi-ai.getModel to ModelRegistry.create().find behavior; assert ModelRegistry.create() called with AuthStorage; add assertions for pi.auth_storage_init_failed, pi.auth_missing, and pi.model_not_found logs; update cleanup to clear logger and ModelRegistry mocks.
Docs — Getting started (Pi)
packages/docs-web/src/content/docs/getting-started/ai-assistants.md
Document local/custom inference backends (LM Studio, ollama, llamacpp, custom OpenAI-compatible endpoints via ~/.pi/agent/models.json), note pi.auth_missing info emission for missing creds, and clarify model naming and credential expectations for local vs cloud providers.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant PiProvider
  participant AuthStorage
  participant ModelRegistry
  participant Model
  participant Logger

  Client->>PiProvider: sendQuery(provider, modelId, ...)
  PiProvider->>AuthStorage: AuthStorage.create(config)
  alt authStorage init fails
    AuthStorage-->>PiProvider: throw Error
    PiProvider->>Logger: error("pi.auth_storage_init_failed", ...)
    PiProvider-->>Client: throw Pi-framed error
  else authStorage created
    PiProvider->>ModelRegistry: ModelRegistry.create(AuthStorage)
    ModelRegistry-->>PiProvider: registry
    PiProvider->>ModelRegistry: registry.find(provider, modelId)
    alt model found
      ModelRegistry-->>PiProvider: Model
      PiProvider->>Model: execute request
      Model-->>PiProvider: response
      PiProvider-->>Client: response
    else model not found
      ModelRegistry-->>PiProvider: undefined (maybe with getError() detail)
      PiProvider->>Logger: error("pi.model_not_found", { provider, modelId, modelsJsonError })
      PiProvider-->>Client: throw "Pi model not found" (includes models.json load error if present)
    end
    alt missing credentials & provider mapped to env var
      PiProvider->>Logger: error("missing credentials", { piProvider }, "env-var table + 'pi /login' hint")
      PiProvider-->>Client: throw missing-credentials error
    else missing credentials & provider unmapped
      PiProvider->>Logger: info("pi.auth_missing", { piProvider }, "env-var table hint")
      PiProvider-->>Model: proceed (allow local/uncredentialed providers)
    end
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I hopped from getModel to a tidy registry line,
AuthStorage born once, now every call is fine.
find() seeks models, returns truth or none,
For unmapped providers I whisper info — then run.
Tests tidy their mocks; I nibble a carrot, done.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: switching to ModelRegistry and enabling empty auth for custom models/providers support.
Description check ✅ Passed The description includes most required sections (Summary, UX Journey context, Security/Compatibility/Validation/etc.) with sufficient detail on problem, scope, and validation evidence.
Linked Issues check ✅ Passed The PR addresses #1096 by enabling ModelRegistry-based resolution of user-configured custom models and providers (ollama, etc.), allowing credentialless local providers; direct config of base URLs and per-provider model overrides remain out of scope per author.
Out of Scope Changes check ✅ Passed All changes are scoped to Pi provider refactoring (test mocks, provider.ts logic, docs); no unrelated file modifications or scope creep detected beyond the stated objective.

✏️ 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.

@matt2000 matt2000 changed the title Use ModelRegistry & allow empty auth to support custom models/providers. Pi provider: Use ModelRegistry & allow empty auth to support custom models/providers. Apr 18, 2026
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/providers/src/community/pi/provider.ts (1)

89-100: ⚠️ Potential issue | 🟠 Major

ModelRegistry.create() reads from disk — contradicts the "in-memory" invariant documented in comments.

The class-level doc (lines 52–57) and inline comment (lines 199–201) claim that "the server never touches ~/.pi/" and that "ModelRegistry … stay in-memory". However, lines 92–93 call AuthStorage.create() and ModelRegistry.create(authStorage), both of which read from disk (~/.pi/agent/auth.json and ~/.pi/agent/models.json). This breaks the documented invariant on every request.

To preserve the guarantee:

  • Use ModelRegistry.inMemory(authStorage) as the default to keep only the built-in catalog (no disk access), or
  • Update the comments to reflect that disk reads now happen per-request and explain why this is necessary.

Additionally, AuthStorage.create() and ModelRegistry.create() are instantiated inside sendQuery() on every invocation. Consider hoisting to module scope or caching on the provider instance to avoid repeated filesystem access per-request (similar to the cached logger at lines 46–49).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/providers/src/community/pi/provider.ts` around lines 89 - 100, The
code currently calls AuthStorage.create() and ModelRegistry.create(authStorage)
inside sendQuery which performs disk reads and violates the in-memory invariant;
change to use ModelRegistry.inMemory(authStorage) (or otherwise call
ModelRegistry.inMemory() directly) to avoid reading ~/.pi/ per request, and
hoist or cache AuthStorage and ModelRegistry at module scope or as fields on the
provider instance (mirroring the cached logger pattern) so they are created once
instead of on every sendQuery invocation; alternatively, if disk reads are
required, update the class-level and inline comments to state that
AuthStorage.create() and ModelRegistry.create() read from disk and justify
per-request behavior.
packages/providers/src/community/pi/provider.test.ts (1)

77-128: ⚠️ Potential issue | 🔴 Critical

Mock must provide ModelRegistry.create—tests calling sendQuery() will fail at runtime.

Production code (provider.ts line 93) calls ModelRegistry.create(authStorage), but the mock only exposes ModelRegistry: { inMemory: mockModelRegistryInMemory }. Every test from line 195 onward that calls sendQuery() will throw TypeError: ModelRegistry.create is not a function before reaching any assertions.

Additionally, both provider.test.ts and session-resolver.test.ts mock @mariozechner/pi-coding-agent with different partial implementations (violating the guideline to use spyOn() instead and separate test invocations to avoid process-global pollution). The mock should expose create alongside inMemory to match what production actually calls.

Suggested fix
 const mockModelRegistryFind = mock((provider: string, modelId: string) => {
   if (provider === 'nonexistent') return undefined;
   return { id: modelId, provider, name: `${provider}/${modelId}` };
 });
-const mockModelRegistryInMemory = mock(() => ({
-  find: mockModelRegistryFind,
-}));
+const mockModelRegistryFactory = mock(() => ({
+  find: mockModelRegistryFind,
+}));
@@
-  ModelRegistry: { inMemory: mockModelRegistryInMemory },
+  ModelRegistry: {
+    create: mockModelRegistryFactory,
+    inMemory: mockModelRegistryFactory,
+  },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/providers/src/community/pi/provider.test.ts` around lines 77 - 128,
The mock for `@mariozechner/pi-coding-agent` is missing ModelRegistry.create which
production code (provider.ts -> sendQuery()) calls; add a
mockModelRegistryCreate (e.g., const mockModelRegistryCreate =
mock((authStorage: unknown) => mockModelRegistryInMemory(authStorage))) and
export it alongside inMemory in the mock.module call (ModelRegistry: { create:
mockModelRegistryCreate, inMemory: mockModelRegistryInMemory }) so sendQuery()
won’t throw; also replace conflicting full-module mocks in other tests with
spyOn(...) calls or reuse this same module mock to avoid process-global mock
pollution.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/providers/src/community/pi/provider.ts`:
- Around line 137-142: Fix the typo and make the log a structured Pino event:
change "necesssarily" to "necessarily" in the message and move the prose into
the context (e.g., msg) while using a structured event name like
"pi.credentials_missing_warn" as the second argument to
getLog().info/getLog().warn; additionally, only suppress throwing when
parsed.provider is not in PI_PROVIDER_ENV_VARS (i.e., allow local/custom
providers to proceed) and otherwise log at warn (or keep throwing) so built-in
providers (parsed.provider checked against PI_PROVIDER_ENV_VARS) fail fast —
include envHint and loginHint in the context object when calling
getLog().warn/getLog().info.

---

Outside diff comments:
In `@packages/providers/src/community/pi/provider.test.ts`:
- Around line 77-128: The mock for `@mariozechner/pi-coding-agent` is missing
ModelRegistry.create which production code (provider.ts -> sendQuery()) calls;
add a mockModelRegistryCreate (e.g., const mockModelRegistryCreate =
mock((authStorage: unknown) => mockModelRegistryInMemory(authStorage))) and
export it alongside inMemory in the mock.module call (ModelRegistry: { create:
mockModelRegistryCreate, inMemory: mockModelRegistryInMemory }) so sendQuery()
won’t throw; also replace conflicting full-module mocks in other tests with
spyOn(...) calls or reuse this same module mock to avoid process-global mock
pollution.

In `@packages/providers/src/community/pi/provider.ts`:
- Around line 89-100: The code currently calls AuthStorage.create() and
ModelRegistry.create(authStorage) inside sendQuery which performs disk reads and
violates the in-memory invariant; change to use
ModelRegistry.inMemory(authStorage) (or otherwise call ModelRegistry.inMemory()
directly) to avoid reading ~/.pi/ per request, and hoist or cache AuthStorage
and ModelRegistry at module scope or as fields on the provider instance
(mirroring the cached logger pattern) so they are created once instead of on
every sendQuery invocation; alternatively, if disk reads are required, update
the class-level and inline comments to state that AuthStorage.create() and
ModelRegistry.create() read from disk and justify per-request behavior.
🪄 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: b27a4546-e838-4d81-84c7-f662007d9090

📥 Commits

Reviewing files that changed from the base of the PR and between d89bc76 and 0f56f8f.

📒 Files selected for processing (2)
  • packages/providers/src/community/pi/provider.test.ts
  • packages/providers/src/community/pi/provider.ts

Comment thread packages/providers/src/community/pi/provider.ts Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/providers/src/community/pi/provider.test.ts`:
- Around line 238-249: The test currently only checks that a hint is logged but
doesn't assert that the no-auth custom-provider path doesn't throw; update the
test for 'logs credential hint when Pi provider id is unknown AND no creds
available' to explicitly assert the call to PiProvider.sendQuery (via consume)
resolves without throwing (e.g., expect(...).resolves.not.toThrow or await
expect(consume(...)).resolves.toBeUndefined) and adjust the comment from
"fail-fast" to reflect that it should not throw when hinting about env-var
table; keep references to PiProvider.sendQuery and the test name so the change
is applied to the right test.
🪄 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: 5647bf79-a0d0-4899-9490-bb66018b2da7

📥 Commits

Reviewing files that changed from the base of the PR and between dc34e59 and 3f55a97.

📒 Files selected for processing (2)
  • packages/providers/src/community/pi/provider.test.ts
  • packages/providers/src/community/pi/provider.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/providers/src/community/pi/provider.ts

Comment thread packages/providers/src/community/pi/provider.test.ts
@matt2000
Copy link
Copy Markdown
Contributor Author

@coderabbitai resume

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 20, 2026

✅ Actions performed

Reviews resumed.

@Wirasm
Copy link
Copy Markdown
Collaborator

Wirasm commented Apr 20, 2026

@matt2000 related to #1096 — overlapping area or partial fix.

@matt2000 matt2000 changed the title Pi provider: Use ModelRegistry & allow empty auth to support custom models/providers. feat(pi): Use ModelRegistry & allow empty auth to support custom models/providers. Apr 21, 2026
@b1skit
Copy link
Copy Markdown

b1skit commented Apr 22, 2026

@matt2000 @Wirasm Thanks for the fix here. I'm a new user, I decided to try out Archon when I saw the recent Pi announcement on YouTube and hit this exact problem while trying to use a custom Lemonade-backed model through Archon’s Pi provider.

From my testing, the failure was happening during Pi model resolution, so switching from the static catalog lookup to ModelRegistry looks like the right fix and should unblock custom/local providers and models.

If there are no remaining concerns, I’d appreciate getting this merged! :)

@b1skit
Copy link
Copy Markdown

b1skit commented Apr 23, 2026

@coleam00 @matt2000 @Wirasm Apologies for the spam, mind submitting this to unblock those of us using local models? 🙏

@loopyd
Copy link
Copy Markdown

loopyd commented Apr 24, 2026

We need this in for local models, please. Also same issue. This works perfectly with qwen3.6 running thru llama-cpp-local provider or other custom providers in ~/.pi/agent/models.json. Thank you for your contribution! Please keep pinging the maintainers, this one is important.

@stalsma
Copy link
Copy Markdown

stalsma commented Apr 24, 2026

Chiming in here. Also so the YouTube intro, and thought I would try it out. Using LM Studio via pi.

Pi can see and connect to the models w/o issue.

{
  "providers": {
    "lm-studio": {
      "baseUrl": "http://localhost:1234/v1",
      "api": "openai-completions",
      "apiKey": "lm-studio",
      "compat": {
        "supportsDeveloperRole": false,
        "supportsReasoningEffort": false
      },
      "models": [
        {
          "id": "qwen/qwen2.5-coder-14b",
          "name": "Qwen 2.5 Coder 14B",
          "contextWindow": 131072,
          "maxTokens": 8192
        },
        {
          "id": "apriel-1.5-15b-thinker",
          "name": "Apriel 1.5 15B Thinker",
          "reasoning": true,
          "contextWindow": 131072,
          "maxTokens": 8192
        }
      ]
    }
  }
}

But when I configure archon's config.yaml:

# Bot display name (shown in messages)
botName: Archon

# Default AI assistant (must match a registered provider, e.g. claude, codex)
defaultAssistant: pi

#Assistant defaults
assistants:
    pi:
      model: lm-studio/apriel-1.5-15b-thinker

and then run archon-assist command

description: |
  General assistance workflow using Pi instead of Claude.

nodes:
  - id: assist
    provider: pi
    model: lm-studio/apriel-1.5-15b-thinker 
    command: archon-assist

It eventually errors out:

INFO [2026-04-24 18:09:38.506 +0200]: dag_workflow_starting
module: "workflow.dag-executor"
workflowName: "archon-assist"
nodeCount: 1
layerCount: 1
hasIssueContext: false
issueContextLength: 0
[archon-assist] Started
INFO [2026-04-24 18:09:38.509 +0200]: dag_node_started
module: "workflow.dag-executor"
nodeId: "assist"
provider: "pi"
ERROR [2026-04-24 18:09:38.922 +0200]: dag_node_failed
module: "workflow.dag-executor"
nodeId: "assist"
err: {
"type": "Error",
"message": "Pi model not found: provider='lm-studio' model='apriel-1.5-15b-thinker'. See https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/models.generated.ts for the Pi model catalog.",
"stack":
Error: Pi model not found: provider='lm-studio' model='apriel-1.5-15b-thinker'. See https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/models.generated.ts for the Pi model catalog.
at sendQuery (C:\Users\xxxxx\Archon\packages\providers\src\community\pi\provider.ts:235:17)
at processTicksAndRejections (native:7:39)
}
[archon-assist] Failed: Pi model not found: provider='lm-studio' model='apriel-1.5-15b-thinker'. See https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/models.generated.ts for the Pi model catalog.
WARN [2026-04-24 18:09:38.926 +0200]: dag_layer_had_failures
module: "workflow.dag-executor"
layerIdx: 0
nodeCount: 1
INFO [2026-04-24 18:09:38.927 +0200]: dag_workflow_finished

@b1skit
Copy link
Copy Markdown

b1skit commented Apr 24, 2026

@coleam00 @matt2000 @Wirasm mind taking a look at this? Would unblock a lot of people using local models. Happy to test and report back if that would be helpful

@matt2000 matt2000 force-pushed the patch-pi-local-models branch from a8cc61a to 86e1c97 Compare April 24, 2026 19:25
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/providers/src/community/pi/provider.ts (1)

107-114: ⚠️ Potential issue | 🔴 Critical

Fix unbound-method error on line 225: call modelRegistry.find() directly.

Line 225 passes modelRegistry.find as a function without its receiver context, which ESLint flags as @typescript-eslint/unbound-method. More critically, ModelRegistry.find is a prototype method that reads this (the internal registry state). Extracting it without binding breaks the method: it will either throw Cannot read properties of undefined or silently search an empty/wrong store at runtime.

The wrapper lookupPiModel + GetModelFn was originally a workaround for Pi's getModel generic constraints. Since ModelRegistry.find already accepts runtime strings directly, the indirection is now just dead code hiding the bug:

🛠 Proposed fix
-/**
- * Typed wrapper around Pi's `getModel` for a runtime-string provider/model
- * pair. Pi's getModel signature constrains `TModelId` to
- * `keyof MODELS[TProvider]`, which isn't knowable from a runtime string —
- * the local `GetModelFn` alias is the narrowest shape that still lets us
- * bypass that constraint. Isolating the escape hatch behind one searchable
- * name keeps it auditable. Takes `getModel` as a parameter because the Pi
- * SDK is loaded dynamically (see the header comment on this file for why).
- */
-type GetModelFn = (provider: string, modelId: string) => Model<Api> | undefined;
-function lookupPiModel(
-  getModel: GetModelFn,
-  provider: string,
-  modelId: string
-): Model<Api> | undefined {
-  return getModel(provider, modelId);
-}
@@
     const authStorage = piCodingAgent.AuthStorage.create();
     const modelRegistry = piCodingAgent.ModelRegistry.create(authStorage);
-    // 2. Look up the Model via Pi's Registry. `lookupPiModel` returns
-    //    undefined when not found; we guard explicitly below.
-    // Cast to the runtime-string-friendly shape — see `lookupPiModel`'s docblock.
-    const model = lookupPiModel(modelRegistry.find as GetModelFn, parsed.provider, parsed.modelId);
+    // 2. Look up the Model via Pi's Registry. `find` returns undefined when
+    //    not found; we guard explicitly below. Call as a method to preserve
+    //    `this` binding to the registry's internal state.
+    const model = modelRegistry.find(parsed.provider, parsed.modelId);

Also remove the now-unused Api and Model type imports from line 6.

Unit tests at line 308 already cover the unhappy path (undefined return), so the direct call slots in without additional test work.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/providers/src/community/pi/provider.ts` around lines 107 - 114, The
wrapper lookupPiModel and its GetModelFn indirection are causing an
unbound-method error when passing ModelRegistry.find as a callback; replace uses
of lookupPiModel/getModel with a direct call to modelRegistry.find(...) so the
method retains its receiver context, and remove the now-unused lookupPiModel and
GetModelFn definitions plus the unused Api and Model type imports referenced at
the top of the file.
🧹 Nitpick comments (1)
packages/providers/src/community/pi/provider.ts (1)

233-252: Stale step-3 heading — AuthStorage.create() moved up to line 220.

The prose still reads "3. Build AuthStorage. AuthStorage.create() reads ~/.pi/agent/auth.json …", but the actual construction now happens in step 2 (line 220) alongside the registry. Readers following the numbered steps will hunt for a build that isn't here. The resolution-order detail is still valuable — just relabel and trim:

📝 Suggested rewording
-    // 3. Build AuthStorage. `AuthStorage.create()` reads ~/.pi/agent/auth.json
-    //    (or $PI_CODING_AGENT_DIR/auth.json), so any credential the user has
-    //    populated via `pi` → `/login` (OAuth subscriptions: Claude Pro/Max,
+    // 3. Credential resolution. The `AuthStorage` built above reads
+    //    ~/.pi/agent/auth.json (or $PI_CODING_AGENT_DIR/auth.json), so any
+    //    credential the user populated via `pi` → `/login` (OAuth
+    //    subscriptions: Claude Pro/Max,
     //    ChatGPT Plus, GitHub Copilot, Gemini CLI, Antigravity) or by editing
     //    the file directly (api_key entries) is picked up transparently.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/providers/src/community/pi/provider.ts` around lines 233 - 252,
Update the stale "3. Build AuthStorage" heading and surrounding prose to reflect
that AuthStorage.create() is now constructed earlier (at the registry step
around where AuthStorage.create() is called), e.g., remove or renumber the "3."
label and change wording to indicate this is an explanatory note about
AuthStorage resolution rather than a build step; keep the Pi internal resolution
order list and the OAuth refresh note but trim any lines that claim the build
occurs here and instead reference AuthStorage.create() where it actually runs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/providers/src/community/pi/provider.ts`:
- Around line 343-348: The comment block in provider.ts is broken: the
parenthetical about piConfig.enableExtensions interrupts the sentence so the
fragment "discovery except for explicitly-passed skill paths." is orphaned;
update the comment so it is a single grammatical sentence (or two clear
sentences) that preserves the intended meaning. Specifically, in the comment
near the Resource loader/enableExtensions text (reference
piConfig.enableExtensions and the description of the community extension
ecosystem), rephrase to either move the parenthetical so the main clause reads
"...Resource loader still suppresses filesystem discovery except for
explicitly-passed skill paths." and then append a separate sentence describing
Pi's community extension ecosystem when piConfig.enableExtensions is true, or
combine them into one coherent sentence that includes both the suppression of
filesystem discovery and the exception for extensions. Ensure the comment
mentions piConfig.enableExtensions, the extension paths
(~/.pi/agent/extensions/) and `pi install npm:<pkg>` exactly as before.

---

Outside diff comments:
In `@packages/providers/src/community/pi/provider.ts`:
- Around line 107-114: The wrapper lookupPiModel and its GetModelFn indirection
are causing an unbound-method error when passing ModelRegistry.find as a
callback; replace uses of lookupPiModel/getModel with a direct call to
modelRegistry.find(...) so the method retains its receiver context, and remove
the now-unused lookupPiModel and GetModelFn definitions plus the unused Api and
Model type imports referenced at the top of the file.

---

Nitpick comments:
In `@packages/providers/src/community/pi/provider.ts`:
- Around line 233-252: Update the stale "3. Build AuthStorage" heading and
surrounding prose to reflect that AuthStorage.create() is now constructed
earlier (at the registry step around where AuthStorage.create() is called),
e.g., remove or renumber the "3." label and change wording to indicate this is
an explanatory note about AuthStorage resolution rather than a build step; keep
the Pi internal resolution order list and the OAuth refresh note but trim any
lines that claim the build occurs here and instead reference
AuthStorage.create() where it actually runs.
🪄 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: 71822697-8d45-4646-997e-f9709e779b17

📥 Commits

Reviewing files that changed from the base of the PR and between a8cc61a and 86e1c97.

📒 Files selected for processing (2)
  • packages/providers/src/community/pi/provider.test.ts
  • packages/providers/src/community/pi/provider.ts

Comment thread packages/providers/src/community/pi/provider.ts Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/providers/src/community/pi/provider.ts (1)

213-232: Stale step-numbering / narrative in the AuthStorage comment block.

This block opens with "3. Build AuthStorage. AuthStorage.create() reads ~/.pi/agent/auth.json…", but authStorage is now constructed at line 201 (before the model lookup), so the "3." label and the "Build AuthStorage" framing no longer match the code below it — what actually starts here is the runtime-override step, not the construction. Consider retitling (e.g., "3. Apply per-request API key override on the existing AuthStorage…") and moving the auth-file/OAuth explainer up next to line 201 where the instance is actually created.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/providers/src/community/pi/provider.ts` around lines 213 - 232,
Update the comment to reflect actual ordering: clarify that authStorage is
already constructed earlier via AuthStorage.create() and this section is
applying a per-request runtime override using setRuntimeApiKey; retitle the
header from "3. Build AuthStorage" to something like "3. Apply per-request API
key override to existing AuthStorage" and move or copy the detailed explanation
about AuthStorage.create(), ~/.pi/agent/auth.json, OAuth refresh and resolution
order up next to where authStorage is instantiated (AuthStorage.create()) so the
narrative matches the code flow around authStorage and setRuntimeApiKey.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/providers/src/community/pi/provider.ts`:
- Around line 213-232: Update the comment to reflect actual ordering: clarify
that authStorage is already constructed earlier via AuthStorage.create() and
this section is applying a per-request runtime override using setRuntimeApiKey;
retitle the header from "3. Build AuthStorage" to something like "3. Apply
per-request API key override to existing AuthStorage" and move or copy the
detailed explanation about AuthStorage.create(), ~/.pi/agent/auth.json, OAuth
refresh and resolution order up next to where authStorage is instantiated
(AuthStorage.create()) so the narrative matches the code flow around authStorage
and setRuntimeApiKey.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c50e0d55-a425-4fee-af4d-6d60dd712157

📥 Commits

Reviewing files that changed from the base of the PR and between 86e1c97 and bcaf70d.

📒 Files selected for processing (1)
  • packages/providers/src/community/pi/provider.ts

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
packages/providers/src/community/pi/provider.ts (1)

254-258: ⚠️ Potential issue | 🟡 Minor

Log msg argument still isn't a structured event name.

The typo and the env-mapped vs. unmapped branch split were addressed, but Pino's second positional arg here is still a prose sentence rather than a {domain}.{action}_{state} event. Every other log in this file (pi.config_env_applied, pi.session_started, pi.prompt_completed, pi.prompt_failed) follows that format, so log queries can't group on this one. Move the prose into the merging object (or a msg field) and use something like pi.credentials_missing as the event name.

✏️ Suggested edit
-      const envHint = `Provider '${parsed.provider}' is not in the Archon adapter's env-var table — file an issue if you want a shortcut env var for it.`;
-      const loginHint = `Or run \`pi\` and type \`/login\` locally to authenticate '${parsed.provider}' via OAuth; credentials land in ~/.pi/agent/auth.json and are picked up automatically.`;
-      // No credentials for unmapped providers is not necessarily a problem, e.g., local models.
-      getLog().info(
-        { piProvider: parsed.provider },
-        `No Pi credentials found for provider. ${envHint} ${loginHint}`
-      );
+      const envHint = `Provider '${parsed.provider}' is not in the Archon adapter's env-var table — file an issue if you want a shortcut env var for it.`;
+      const loginHint = `Or run \`pi\` and type \`/login\` locally to authenticate '${parsed.provider}' via OAuth; credentials land in ~/.pi/agent/auth.json and are picked up automatically.`;
+      // No credentials for unmapped providers is not necessarily a problem, e.g., local models.
+      getLog().info(
+        {
+          piProvider: parsed.provider,
+          envHint,
+          loginHint,
+          detail: 'No Pi credentials found for provider',
+        },
+        'pi.credentials_missing'
+      );

As per coding guidelines: "event naming format: {domain}.{action}_{state}; avoid generic events like 'processing' or 'handling'".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/providers/src/community/pi/provider.ts` around lines 254 - 258, The
log call using getLog().info currently passes a prose string as the second
positional arg; change it to use a structured event name (e.g.,
"pi.credentials_missing") as the second arg and move the human-readable sentence
into the merged object (for example a msg or message field) alongside
parsed.provider, envHint and loginHint so the log becomes a structured event
consistent with other events like pi.config_env_applied and pi.session_started;
update the getLog().info invocation where parsed.provider is referenced to
include these fields in the object and use "pi.credentials_missing" as the event
name.
🧹 Nitpick comments (1)
packages/providers/src/community/pi/provider.ts (1)

201-217: Step-numbered narration is now out of order with code flow.

With AuthStorage.create() hoisted above the model lookup, the numbered comments no longer match the execution order: step "3. Build AuthStorage" (line 213) narrates code that actually ran before step "2. Look up the Model" (line 203). Since the block at 213-232 is now purely explanatory (the construction already happened at line 201), consider either renumbering or moving the doc block up to the AuthStorage.create() call so readers following the numbered steps don't get disoriented.

♻️ One way to reorganize
-    const authStorage = piCodingAgent.AuthStorage.create();
-    const modelRegistry = piCodingAgent.ModelRegistry.create(authStorage);
-    // 2. Look up the Model via Pi's Registry. `modelRegistry.find` returns
-    //    undefined when not found; we guard explicitly below.
+    // 2. Build AuthStorage + ModelRegistry. `AuthStorage.create()` reads
+    //    ~/.pi/agent/auth.json (or $PI_CODING_AGENT_DIR/auth.json), so
+    //    credentials populated via `pi` → `/login` (OAuth: Claude Pro/Max,
+    //    ChatGPT Plus, Copilot, Gemini CLI, Antigravity) or edited directly
+    //    (api_key entries) are picked up transparently.
+    //
+    //    Pi's internal resolution order:
+    //      1. runtime override  (setRuntimeApiKey below)
+    //      2. auth.json api_key entry
+    //      3. auth.json oauth entry  (auto-refreshes expired tokens)
+    //      4. env var fallback  (Pi's getEnvApiKey, e.g. ANTHROPIC_API_KEY)
+    const authStorage = piCodingAgent.AuthStorage.create();
+    const modelRegistry = piCodingAgent.ModelRegistry.create(authStorage);
+
+    // 3. Look up the Model via Pi's Registry. `modelRegistry.find` returns
+    //    undefined when not found; we guard explicitly below.
     const model = modelRegistry.find(parsed.provider, parsed.modelId);
     if (!model) {
       throw new Error(
         `Pi model not found: provider='${parsed.provider}' model='${parsed.modelId}'. ` +
           'See https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/models.generated.ts for the Pi model catalog.'
       );
     }
 
-    // 3. Build AuthStorage. `AuthStorage.create()`, above, read ~/.pi/agent/auth.json
-    //    (or $PI_CODING_AGENT_DIR/auth.json), so any credentials the user has
-    //    populated via `pi` → `/login` (OAuth subscriptions: Claude Pro/Max,
-    //    ChatGPT Plus, GitHub Copilot, Gemini CLI, Antigravity) or by editing
-    //    the file directly (api_key entries) are picked up transparently.
-    //
-    //    Per-request env vars override the file via setRuntimeApiKey — this
-    //    mirrors Claude's process-env + request-env merge pattern and
-    //    ensures codebase-scoped env vars (from .archon/config.yaml `env:`)
-    //    win over the user's global Pi login.
-    //
-    //    Pi's internal resolution order:
-    //      1. runtime override  (our setRuntimeApiKey below)
-    //      2. auth.json api_key entry
-    //      3. auth.json oauth entry  (auto-refreshes expired tokens)
-    //      4. env var fallback  (Pi's getEnvApiKey, e.g. ANTHROPIC_API_KEY)
-    //
-    //    OAuth refresh note: Pi refreshes expired access tokens against the
-    //    provider's OAuth server and rewrites ~/.pi/agent/auth.json under a
-    //    file lock (same mechanism pi CLI uses — safe for concurrent access).
+    // 4. Per-request env vars override the file via setRuntimeApiKey — this
+    //    mirrors Claude's process-env + request-env merge pattern and
+    //    ensures codebase-scoped env vars (from .archon/config.yaml `env:`)
+    //    win over the user's global Pi login. Pi refreshes expired OAuth
+    //    tokens under a file lock (same mechanism as the pi CLI).
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/providers/src/community/pi/provider.ts` around lines 201 - 217, The
numbered explanatory comments are out of order: AuthStorage.create() is called
before the "2. Look up the Model" block but the narrative labels step 3 as
building AuthStorage; fix by either moving the paragraph that begins "3. Build
AuthStorage..." up to directly above the AuthStorage.create() call (so the steps
read 1→2→3 in execution order) or renumber the steps so the narration matches
the actual flow (e.g., make AuthStorage the earlier step and adjust the "2. Look
up the Model" text); update references to AuthStorage.create(),
modelRegistry.find, and the model/parsed variables to ensure the comment sits
adjacent to the code it describes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@packages/providers/src/community/pi/provider.ts`:
- Around line 254-258: The log call using getLog().info currently passes a prose
string as the second positional arg; change it to use a structured event name
(e.g., "pi.credentials_missing") as the second arg and move the human-readable
sentence into the merged object (for example a msg or message field) alongside
parsed.provider, envHint and loginHint so the log becomes a structured event
consistent with other events like pi.config_env_applied and pi.session_started;
update the getLog().info invocation where parsed.provider is referenced to
include these fields in the object and use "pi.credentials_missing" as the event
name.

---

Nitpick comments:
In `@packages/providers/src/community/pi/provider.ts`:
- Around line 201-217: The numbered explanatory comments are out of order:
AuthStorage.create() is called before the "2. Look up the Model" block but the
narrative labels step 3 as building AuthStorage; fix by either moving the
paragraph that begins "3. Build AuthStorage..." up to directly above the
AuthStorage.create() call (so the steps read 1→2→3 in execution order) or
renumber the steps so the narration matches the actual flow (e.g., make
AuthStorage the earlier step and adjust the "2. Look up the Model" text); update
references to AuthStorage.create(), modelRegistry.find, and the model/parsed
variables to ensure the comment sits adjacent to the code it describes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a2e35f61-65bb-4f3d-bc7e-06995de31776

📥 Commits

Reviewing files that changed from the base of the PR and between bcaf70d and bcaac3d.

📒 Files selected for processing (1)
  • packages/providers/src/community/pi/provider.ts

@loopyd
Copy link
Copy Markdown

loopyd commented Apr 24, 2026

@matt2000 hard-coded model names in Archon default workflows/commands will cause node SDK Error crashes when using local LLMs, I ran into that this morning when trying to run idea-to-pr workflow and ended up having to copy them to my project folder's .archon location for modification To use default Archon workflows provided by the project, it requires heavy customization of both workflows and commands to move away from hard-coded Claude Code/Codex model values and from those that generate titles as well (trying to use haiku by default) Unfortunately the default template-generator.ts isn't smart enough to regenerate the defaults with values that work for local LLMs. Consider a path to demangle this edge case for packed "user friendly" workflows/commands to keep the out of the box user experience robust for local users:

A. Docs updates that let local LLM users know forking default template-baked commands/workflows is nessecary to fix provider: and model: references as well as update command: and {runner} pointers to refer to custom commands run from workflows -- a regression to UX but will keep default workflows untouched and this PR simple. Consider in this solution path that local LLM users will need to go back to spec engineering for their specific model in most cases to fix tool calls and provide model-specific token directives, and will probably need to fork defaults anyway...

B. Improve actual template regeneration and catch SDK Error exceptions to call regeneration of a template/retry on SDK Error fail with user's model settings injected (baked failsafe execution path for local LLM users), where the default provided templates regenerate with properly updated values to avoid node SDK errors when user is using local LLMs -- will require more complex modifications and may inflate the size/scope of this PR, but will commit the outstanding issue to code in the case of SDK Error when using empty auth/local.

Unfortunately there more upstream to this one than meet the eye. >.<` Good work, though.

@matt2000
Copy link
Copy Markdown
Contributor Author

hard-coded model names in Archon default workflows/commands will cause node SDK Error crashes when using local LLMs

I don't really use default workflows much, so this isnt a priority for me. But I think the real fix is that Archon should have configurable "model aliases" that are interchangable with model IDs, like "default", "small," "tooluser," etc, that can default to anthropic models or whatever Cole likes, but be overridden in user config. All the default workflows should only use aliases, and never "concrete" model names.

@matt2000 matt2000 force-pushed the patch-pi-local-models branch from 88c3a30 to f3d1657 Compare April 24, 2026 21:26
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/providers/src/community/pi/provider.ts (1)

213-233: Step numbering in the comment block is now misaligned.

This block is titled "3. Build AuthStorage" and opens with "AuthStorage.create(), above, read …", but AuthStorage is now constructed at line 201 (before the model lookup labeled "2."). The step headers read a bit confusingly — consider renumbering so the comment reflects the new ordering (e.g., fold the AuthStorage construction into step 2, or relabel this block "Resolve credentials" without a step number). Purely editorial; no behavior impact.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/providers/src/community/pi/provider.ts` around lines 213 - 233, The
comment block heading "3. Build AuthStorage" is out of order relative to where
AuthStorage is actually constructed (AuthStorage.create() / AuthStorage
constructor appears earlier near the model lookup labeled "2."); update the
comment to reflect the actual flow by either renumbering the step to match the
current ordering, folding the AuthStorage construction discussion into the "2."
section, or replace the step number with a neutral label like "Resolve
credentials" while keeping references to AuthStorage.create() and
setRuntimeApiKey so readers can locate the relevant code.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/providers/src/community/pi/provider.ts`:
- Around line 213-233: The comment block heading "3. Build AuthStorage" is out
of order relative to where AuthStorage is actually constructed
(AuthStorage.create() / AuthStorage constructor appears earlier near the model
lookup labeled "2."); update the comment to reflect the actual flow by either
renumbering the step to match the current ordering, folding the AuthStorage
construction discussion into the "2." section, or replace the step number with a
neutral label like "Resolve credentials" while keeping references to
AuthStorage.create() and setRuntimeApiKey so readers can locate the relevant
code.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 08391f05-9e64-4d0a-8a2d-85fd2d551bf3

📥 Commits

Reviewing files that changed from the base of the PR and between bcaac3d and f3d1657.

📒 Files selected for processing (2)
  • packages/providers/src/community/pi/provider.test.ts
  • packages/providers/src/community/pi/provider.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/providers/src/community/pi/provider.test.ts

@loopyd
Copy link
Copy Markdown

loopyd commented Apr 24, 2026

All the default workflows should only use aliases, and never "concrete" model names.

This makes sense, as I had indicated most local LLM users will need to procure their own workflows anyway to deal with model-baked token directives for tool calls/specific baked instruction calling sequences their local models use. Aliases is a good idea but may be outside the scope of this PR.

@matt2000
Copy link
Copy Markdown
Contributor Author

Aliases is a good idea but may be outside the scope of this PR.

100%. I have no intention of implementing that here. I'm trying to keep this PR focused on the minimum to get local models working at all.

@matt2000
Copy link
Copy Markdown
Contributor Author

@Wirasm I think this is ready to go. Can you take a look and let me know if you need anything else from me in order to get this merged?

@loopyd
Copy link
Copy Markdown

loopyd commented Apr 27, 2026

I saw some new YouTube uploads, I have a feeling there's some other priorities right now. Till this is merged I'm using your fork and tellin' my buds!

@Wirasm
Copy link
Copy Markdown
Collaborator

Wirasm commented Apr 27, 2026

Hello, sorry for the wait here, there have been a lot of PR's starting a check on this now, will test also some archon workflows on this so sorry if there is spam

@Wirasm
Copy link
Copy Markdown
Collaborator

Wirasm commented Apr 27, 2026

Multi-Agent Review Summary — PR #1284

Ran code review, test analysis, silent-failure hunt, and docs-impact across the diff. Verdict: NEEDS FIXES (small) — direction is good, scope is disciplined, but a few items should be addressed before merge.

Reference IDs: C = critical, I = important, S = suggestion (using prefixed IDs to avoid GitHub issue auto-linking).


Strengths

  • Scope is tight and matches the description: only packages/providers/src/community/pi/provider.{ts,test.ts}.
  • Replacing lookupPiModel + getModel with ModelRegistry.find is the right move — lookupPiModel was doing manual type-cast acrobatics for what the registry already provides.
  • The split between env-mapped providers (still throws, with an actionable pi /login hint) and unmapped providers (info-log + continue) cleanly captures the local-model use case without weakening fail-fast for the common cloud providers.
  • Tests are updated to match the new branches; logger mocks now reset per test.

Important Issues

I1 — Comment block at provider.ts:213 is stale after the reorder
The comment header says "3. Build AuthStorage" and uses past tense ("AuthStorage.create(), above, read ~/.pi/agent/auth.json") because the construction was moved up to step 2 (line 201). The numbered-step structure is now misleading. Either renumber the comments or merge the step 2/3 commentary into one block.

I2 — Pino log shape collides with reserved msg field at provider.ts:255-261

getLog().info(
  { piProvider: parsed.provider, msg: \`No Pi credentials found...\` },
  'pi.auth_missing'
);

The second-positional arg 'pi.auth_missing' is correct per CLAUDE.md's {domain}.{action}_{state} convention. But Pino sets msg itself from that second arg, so the msg key inside the data object collides — depending on serializer settings it either shadows Pino's msg or doubles up in the output. Move the prose into separate fields:

getLog().info(
  { piProvider: parsed.provider, envHint, loginHint },
  'pi.auth_missing'
);

The corresponding test at provider.test.ts:253-259 asserts the msg-in-data shape, so it'll pass while validating the wrong thing — update the assertion to match the corrected shape.

I3 — Class doc / inline comments still assert an "in-memory / never touches ~/.pi/" invariant that this PR breaks
provider.ts still has commentary (around the class doc and the resource-loader comment) implying the server doesn't read ~/.pi/. After this PR, every sendQuery does two synchronous disk reads (AuthStorage.create() reads auth.json; ModelRegistry.create() reads models.json). The PR description acknowledges "this was always a lie because we read auth.json," which is fair — but the docs should now reflect reality. Either:

  • update the comments to say "per-request reads of ~/.pi/agent/{auth.json,models.json}; in-memory after that", or
  • use ModelRegistry.inMemory(authStorage) (which would defeat the PR's purpose for custom-model discovery — so option 1 is preferred).

I4 — AuthStorage.create() and ModelRegistry.create() are unguarded (provider.ts:201-202)
A malformed ~/.pi/agent/auth.json (or a permissions error) will throw a raw SDK SyntaxError / EACCES with no Archon-level framing — the user sees an SDK stack with no indication that Pi credential storage init failed. CLAUDE.md "Fail Fast + Explicit Errors" calls for actionable error messages at boundaries. Wrap with try/catch and re-throw with context, or at least log pi.auth_storage_init_failed before letting it bubble.

I5 — ModelRegistry.find returning undefined throws but never logs (provider.ts:206-211)
The throw is good, but no pi.model_not_found structured event is emitted before it, breaking the _started/_failed pairing convention used elsewhere in the file. More importantly: ModelRegistry swallows models.json parse/validation errors into a loadError accessible via modelRegistry.getError(). If the user's models.json fails validation (e.g., a non-built-in provider missing apiKey), the registry silently drops all custom models and find() returns undefined — they then see "model not found" with no idea their config was rejected. Suggest:

const model = modelRegistry.find(parsed.provider, parsed.modelId);
if (!model) {
  const loadError = modelRegistry.getError?.();
  getLog().error(
    { piProvider: parsed.provider, modelId: parsed.modelId, loadError },
    'pi.model_not_found'
  );
  throw new Error(
    \`Pi model not found: provider='\${parsed.provider}' model='\${parsed.modelId}'.\${loadError ? \` Note: ~/.pi/agent/models.json load failed — \${loadError}\` : ''} See https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/models.generated.ts for the catalog.\`
  );
}

This addresses the "why doesn't my LM Studio model show up" debugging path that several PR commenters are about to hit.

I6 — Per-request disk I/O on a hot path (provider.ts:201-202)
AuthStorage.create() + ModelRegistry.create() run on every sendQuery, doing two synchronous filesystem reads per request. The PR description proposes addressing this in a follow-up if it becomes a performance problem, which is a reasonable YAGNI call — but worth noting that a per-instance cache (set once in the constructor) would be a ~3-line change and eliminate the regression from the previous inMemory path. Acceptable as-is given the stated rollback path.

I7 (tests) — No assertion that ModelRegistry.create receives the authStorage instance
This is the structural guarantee that the headline fix works (the registry needs to be paired with an AuthStorage that knows about the user's config). The tests currently mock both but never assert the wiring. A 2-line addition:

expect(mockModelRegistryCreate).toHaveBeenCalledWith(authStorageInstance);

catches any future refactor that accidentally drops the argument.

I8 (tests) — No coverage for AuthStorage.create() / ModelRegistry.create() throwing
The construction was moved earlier in the function; the failure path is unguarded (see I4) and untested. One mockImplementationOnce test would close this.


Documentation

I9 — packages/docs-web/src/content/docs/getting-started/ai-assistants.md is silent on the new credential-free path
The "Authenticate" section (around L242) presents auth as the only setup topic for Pi, which was true before this PR. After merge:

  • Mapped providers (anthropic, openai, …) still throw on missing creds — docs accurate.
  • Unmapped providers (LM Studio, ollama, llamacpp, custom OpenAI-compatible endpoints in ~/.pi/agent/models.json) now log info and continue — undocumented.

Suggested edits:

  • Lead sentence (~L232): append "…and local inference (LM Studio, ollama, llamacpp via ~/.pi/agent/models.json)."
  • Before the env-var table (~L242): add "Credentials are not required for local or custom providers configured in ~/.pi/agent/models.json — Archon logs an info notice and continues."
  • Line ~L265: split "unmapped" into "unmapped cloud backends (file an issue for env-var shortcuts)" vs "local/custom providers (no Archon-side config needed beyond the model ref)".

Suggestions

S1 — info vs warn for pi.auth_missing on unmapped providers
For a genuinely local provider (LM Studio, ollama) this is expected steady state, so info is defensible. But CodeRabbit and the silent-failure pass both flagged it — for an unmapped provider that does require auth (a less-common backend not in the env-var table), this becomes the only breadcrumb between the missing creds and a cryptic SDK-layer 401 later. warn would better reflect "unusual but not necessarily fatal." Author's call.

S2 — Env-mapped throw at provider.ts:244-249 doesn't log before throwing
Minor pairing-convention breach. Caller surfaces the message anyway, so low urgency.


Notes on the stalsma report in PR comments

The user reporting that LM Studio still fails with "model not found" after this PR has a models.json config with apiKey: \"lm-studio\" set, which would pass the SDK's validateConfig — so their report is most likely either (a) tested against dev, not the PR head, or (b) a Windows-specific path issue with getAgentDir(). Other commenters (b1skit, loopyd) report the PR works for them. Not blocking — but I5 above would surface the underlying "models.json failed validation" case clearly if any user does hit it.


Recommended Action Order

  1. Fix I2 (log shape) and I5 (surface loadError in model-not-found) — highest user-debuggability impact.
  2. Fix I3 (update stale "in-memory" docs) — accuracy.
  3. Fix I1 (renumber/merge stale comment block) and I4 (guard SDK init).
  4. Add tests I7 + I8.
  5. Update docs I9 in this PR or a follow-up.

Direction is solid and the community demand is real — happy to re-review after fixes.

Wirasm added 2 commits April 27, 2026 12:31
Address review feedback on the ModelRegistry migration:

- Surface modelRegistry.getError() in the "model not found" message and
  emit a pi.model_not_found structured event. ModelRegistry catches
  models.json parse/validation errors into an internal loadError rather
  than throwing, so a malformed entry (e.g. custom provider missing
  baseUrl) was silently degrading to a vague "model not found" with no
  hint at the actual cause.
- Wrap AuthStorage.create() and ModelRegistry.create() in try/catch and
  rethrow with Pi-framed context. A malformed ~/.pi/agent/auth.json
  was previously surfacing as a raw SDK SyntaxError stack with no
  indication of where it came from.
- Renumber the Step 2 / Step 3 / Step 4 comment block to match the
  actual code order after auth+registry construction was hoisted earlier
  in the function.
- Move the missing-credentials log message out of the Pino-reserved
  msg field (which would collide with the log line message) into
  separate envHint/loginHint structured fields. The pi.auth_missing
  event name stays as the second-positional arg per the
  {domain}.{action}_{state} convention.

Tests:
- Update the existing auth_missing assertion to match the new log shape.
- Add a test that ModelRegistry.create receives the AuthStorage instance
  (the wiring that makes the headline fix work for custom models).
- Add a test that AuthStorage.create() failure surfaces as
  pi.auth_storage_init_failed with the underlying error message.
- Add a test that models.json load errors flow into the not-found
  message and the pi.model_not_found structured log.
After the ModelRegistry migration, providers not in PI_PROVIDER_ENV_VARS
(LM Studio, ollama, llamacpp, custom OpenAI-compatible endpoints
configured in ~/.pi/agent/models.json) work without any Archon-side
credentials — Archon logs a pi.auth_missing info notice and continues.
Add a "Local / custom providers" subsection under Authenticate so users
find this path without reading the source. Also call it out in the
section opener alongside the cloud backends.
@Wirasm
Copy link
Copy Markdown
Collaborator

Wirasm commented Apr 27, 2026

Pushed two follow-up commits addressing the review (maintainer edit, since the PR allows it):

d4fedc02 — fix(pi): surface models.json errors and guard auth/registry init

  • I5: Surface modelRegistry.getError() in the not-found message + emit pi.model_not_found event so users debugging custom-provider configs (LM Studio, etc.) see the real cause instead of a vague "model not found".
  • I4: Wrap AuthStorage.create() / ModelRegistry.create() in try/catch — malformed ~/.pi/agent/auth.json no longer surfaces as a raw SDK SyntaxError.
  • I1: Renumber Step 2 / Step 3 / Step 4 comments to match the actual code order after the registry/auth construction was hoisted earlier.
  • I2: Move missing-credentials prose out of the Pino-reserved msg field into separate envHint/loginHint structured fields. Event name pi.auth_missing stays as the second-positional arg per the project's {domain}.{action}_{state} convention.
  • Tests: updated existing assertion to match new shape; added three new tests — ModelRegistry.create receives the AuthStorage instance (the headline-fix wiring), AuthStorage.create() throwing surfaces with context, and models.json load errors flow into the not-found message.

14ba080b — docs(pi): document credential-free path for local providers

  • I9: Added "Local / custom providers (no credentials needed)" subsection under Authenticate in ai-assistants.md, plus a mention in the section opener. Users running LM Studio / ollama / llamacpp via ~/.pi/agent/models.json shouldn't need to read the source to discover this works.

Deferred (per author's call):

  • I6 (per-request disk I/O caching) — author flagged this as a possible follow-up in the PR description; agreeing this is YAGNI for now.
  • S1 (infowarn for unmapped-provider auth_missing) — kept as info since for genuinely-local providers this is steady state. The new structured fields make either level greppable.
  • S2 (logging on env-mapped throw) — minor pairing-convention nit, left alone.

bun run validate clean (type-check + lint + format + tests across all packages). Mind giving the new diff a look?

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/providers/src/community/pi/provider.test.ts (1)

389-402: ⚠️ Potential issue | 🟡 Minor

Stale comment: the adapter no longer "rejects unknown providers."

Inline comment claims 'nonexistent' is handled in mockModelRegistryFind to return undefined, but the adapter rejects unknown providers. After this PR's pi.auth_missing change, the adapter no longer rejects unknown providers — it logs and continues — so the rationale for switching to a known-provider/unknown-model is now "to bypass the credential-missing log path," not "to avoid the unknown-provider rejection." Worth updating so the next reader doesn't assume the old behavior still exists.

📝 Suggested rewrite
-    // 'nonexistent' is handled in mockModelRegistryFind to return undefined, but
-    // the adapter rejects unknown providers. To exercise
-    // the not-found branch, use a known provider but unknown modelId by
-    // temporarily swapping mockModelRegistryFind to always return undefined.
+    // Use a known provider (`google`, with GEMINI_API_KEY set) so the
+    // credential path resolves cleanly and we exercise *only* the
+    // ModelRegistry.find()-returns-undefined branch.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/providers/src/community/pi/provider.test.ts` around lines 389 - 402,
The test comment is outdated about adapter behavior; update the inline comment
in packages/providers/src/community/pi/provider.test.ts to reflect that after
the pi.auth_missing change the adapter no longer rejects unknown providers but
logs and continues. Specifically, revise the comment around
mockModelRegistryFind.mockImplementationOnce and the call to new
PiProvider().sendQuery(...) to state the swap is done to bypass the
credential-missing log path (not to avoid an unknown-provider rejection), and
mention mockModelRegistryFind and PiProvider.sendQuery by name so readers can
locate the affected test logic.
packages/providers/src/community/pi/provider.ts (1)

251-457: ⚠️ Potential issue | 🟡 Minor

Section comment numbering has duplicate "4." and "5." after the registry/lookup insertions.

The new sections "2. Build AuthStorage + ModelRegistry" (line 201) and "3. Look up the model" (line 227) were inserted, but the downstream comment numbering wasn't bumped, so the file now reads 1, 2, 3, 4, 4, 5, 5, 6 (Resolve creds → Translate nodeConfig → Session management → Structured output → Bridge events) and the inner sub-bullets 4a–4f straddle two different "4." sections. This was specifically called out as a needed fix during prior review.

♻️ Suggested renumbering
-    // 4. Resolve credentials. authStorage already loaded ~/.pi/agent/auth.json
+    // 4. Resolve credentials. authStorage already loaded ~/.pi/agent/auth.json
@@
-    // 4. Translate Archon nodeConfig to Pi SDK options. All three translations
+    // 5. Translate Archon nodeConfig to Pi SDK options. All three translations
@@
-    //    4a. thinkingLevel: covers `thinking`/`effort` nodeConfig fields.
+    //    5a. thinkingLevel: covers `thinking`/`effort` nodeConfig fields.
@@
-    //    4b. tools: covers allowed_tools / denied_tools. `undefined` leaves Pi
+    //    5b. tools: covers allowed_tools / denied_tools. `undefined` leaves Pi
@@
-    //    4c. systemPrompt: request-level (AgentRequestOptions) wins over
+    //    5c. systemPrompt: request-level (AgentRequestOptions) wins over
@@
-    //    4d. skills: Archon uses name references (e.g. `skills: [agent-browser]`).
+    //    5d. skills: Archon uses name references (e.g. `skills: [agent-browser]`).
@@
-    // 5. Session management. Pi stores each session as a JSONL file under
+    // 6. Session management. Pi stores each session as a JSONL file under
@@
-    // 4e. Extension flag pass-through. Must happen before bindExtensions
+    // 6a. Extension flag pass-through. Must happen before bindExtensions
@@
-    // 4f. Bind UI context (so ctx.hasUI is true and ctx.ui.notify() forwards
+    // 6b. Bind UI context (so ctx.hasUI is true and ctx.ui.notify() forwards
@@
-    // 5. Structured output (best-effort). Pi has no SDK-level JSON schema
+    // 7. Structured output (best-effort). Pi has no SDK-level JSON schema
@@
-    // 6. Bridge callback-based events to the async generator contract.
+    // 8. Bridge callback-based events to the async generator contract.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/providers/src/community/pi/provider.ts` around lines 251 - 457, The
section comment numbers are out of sync after inserting "2. Build AuthStorage +
ModelRegistry" and "3. Look up the model"; update the subsequent top-level
comment numbers and their sublabels so they increment correctly (so "Resolve
credentials" becomes 4, "Translate Archon nodeConfig to Pi SDK options" becomes
5 with its sublabels 5a–5f, "Session management" becomes 6, "Structured output"
becomes 7, and "Bridge callback..." becomes 8). Edit the inline numbered comment
prefixes around the blocks that call resolvePiThinkingLevel, resolvePiTools,
resolvePiSkills, resolvePiSession, createAgentSession, and
augmentPromptForJsonSchema so the labels and any references (e.g., "4a–4f",
"5.", "6.") match the new numbering.
🧹 Nitpick comments (1)
packages/providers/src/community/pi/provider.ts (1)

213-225: Optional: cache AuthStorage / ModelRegistry per Pi-config-dir to avoid disk I/O on every sendQuery().

Both AuthStorage.create() and ModelRegistry.create() synchronously read ~/.pi/agent/{auth.json,models.json} on every call. The inline comment correctly justifies why you don't cache (users edit those files between calls and OAuth refresh rewrites auth.json under a file lock), but in workflow runs with many sequential Pi nodes this is N redundant reads per invocation. A simple TTL cache (e.g. 1–2 s) keyed on process.env.PI_CODING_AGENT_DIR ?? '~/.pi/agent' would preserve the "edit-and-rerun" UX while collapsing tight bursts. Treat this as a follow-up — not a blocker.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/providers/src/community/pi/provider.ts` around lines 213 - 225,
AuthStorage.create() and ModelRegistry.create() are being called on every
sendQuery() causing redundant disk reads; add a small TTL cache keyed by the Pi
agent directory (process.env.PI_CODING_AGENT_DIR ?? '~/.pi/agent') that returns
cached instances of AuthStorage and ModelRegistry for e.g. 1–2 seconds, and have
sendQuery() (or the code that currently calls piCodingAgent.AuthStorage.create /
piCodingAgent.ModelRegistry.create) use the cache instead of creating new
instances each time; ensure the cache still re-reads after TTL expires so edits
or OAuth refreshes are picked up and preserve existing error handling around
pi.auth_storage_init_failed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/providers/src/community/pi/provider.ts`:
- Around line 213-217: The code defensively uses optional chaining when invoking
modelRegistry.getError (calling modelRegistry.getError?.()), but
ModelRegistry.create guarantees a public getError(): string | undefined method,
so remove the unnecessary optional chaining and call modelRegistry.getError()
directly; update the invocation where modelRegistry.getError?.() is used (in the
block after ModelRegistry.create) to modelRegistry.getError() to match the
documented API and existing tests.

---

Outside diff comments:
In `@packages/providers/src/community/pi/provider.test.ts`:
- Around line 389-402: The test comment is outdated about adapter behavior;
update the inline comment in
packages/providers/src/community/pi/provider.test.ts to reflect that after the
pi.auth_missing change the adapter no longer rejects unknown providers but logs
and continues. Specifically, revise the comment around
mockModelRegistryFind.mockImplementationOnce and the call to new
PiProvider().sendQuery(...) to state the swap is done to bypass the
credential-missing log path (not to avoid an unknown-provider rejection), and
mention mockModelRegistryFind and PiProvider.sendQuery by name so readers can
locate the affected test logic.

In `@packages/providers/src/community/pi/provider.ts`:
- Around line 251-457: The section comment numbers are out of sync after
inserting "2. Build AuthStorage + ModelRegistry" and "3. Look up the model";
update the subsequent top-level comment numbers and their sublabels so they
increment correctly (so "Resolve credentials" becomes 4, "Translate Archon
nodeConfig to Pi SDK options" becomes 5 with its sublabels 5a–5f, "Session
management" becomes 6, "Structured output" becomes 7, and "Bridge callback..."
becomes 8). Edit the inline numbered comment prefixes around the blocks that
call resolvePiThinkingLevel, resolvePiTools, resolvePiSkills, resolvePiSession,
createAgentSession, and augmentPromptForJsonSchema so the labels and any
references (e.g., "4a–4f", "5.", "6.") match the new numbering.

---

Nitpick comments:
In `@packages/providers/src/community/pi/provider.ts`:
- Around line 213-225: AuthStorage.create() and ModelRegistry.create() are being
called on every sendQuery() causing redundant disk reads; add a small TTL cache
keyed by the Pi agent directory (process.env.PI_CODING_AGENT_DIR ??
'~/.pi/agent') that returns cached instances of AuthStorage and ModelRegistry
for e.g. 1–2 seconds, and have sendQuery() (or the code that currently calls
piCodingAgent.AuthStorage.create / piCodingAgent.ModelRegistry.create) use the
cache instead of creating new instances each time; ensure the cache still
re-reads after TTL expires so edits or OAuth refreshes are picked up and
preserve existing error handling around pi.auth_storage_init_failed.
🪄 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: df057206-81aa-4845-9c20-fa255cf9d44a

📥 Commits

Reviewing files that changed from the base of the PR and between f3d1657 and 14ba080.

📒 Files selected for processing (3)
  • packages/docs-web/src/content/docs/getting-started/ai-assistants.md
  • packages/providers/src/community/pi/provider.test.ts
  • packages/providers/src/community/pi/provider.ts

Comment on lines +213 to +217
let authStorage: ReturnType<typeof piCodingAgent.AuthStorage.create>;
let modelRegistry: ReturnType<typeof piCodingAgent.ModelRegistry.create>;
try {
authStorage = piCodingAgent.AuthStorage.create();
modelRegistry = piCodingAgent.ModelRegistry.create(authStorage);
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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Look for the ModelRegistry definition / getError member in any installed pi-coding-agent typings.
fd -t f -i 'model-?registry' --exec rg -n -C3 'getError|loadError|class ModelRegistry|^\s*(static\s+)?create\b' {} \;
fd -t f -i 'pi-coding-agent' -e d.ts --exec rg -n -C2 'getError|loadError|ModelRegistry' {} \;

Repository: coleam00/Archon

Length of output: 41


🌐 Web query:

@mariozechner/pi-coding-agent ModelRegistry getError loadError API

💡 Result:

In the @mariozechner/pi-coding-agent package (part of the badlogic/pi-mono GitHub repository), the ModelRegistry class manages loading and caching models from built-in sources and a custom models.json file. It includes a private loadError field that stores any error encountered during loading custom models. The relevant API methods are: - ModelRegistry.create(authStorage: AuthStorage, modelsJsonPath?: string): ModelRegistry - Creates a new instance, optionally loading from a custom models.json path. - ModelRegistry.inMemory(authStorage: AuthStorage): ModelRegistry - Creates without loading from disk. - refresh: void - Reloads models from disk, clears caches, resets loadError to undefined, then calls loadModels. - getError: string | undefined - Returns the loadError if models.json failed to load (undefined if no error or after successful refresh). The loadError is set in the private loadModels method if this.loadCustomModels(this.modelsJsonPath) returns an error. Even if custom models fail, built-in models are retained. {value: In the @mariozechner/pi-coding-agent package (part of the badlogic/pi-mono GitHub repository), the ModelRegistry class manages loading and caching models from built-in sources and a custom models.json file. It includes a private loadError field that stores any error encountered during loading custom models. The relevant API methods are: - ModelRegistry.create(authStorage: AuthStorage, modelsJsonPath?: string): ModelRegistry - Creates a new instance, optionally loading from a custom models.json path. - ModelRegistry.inMemory(authStorage: AuthStorage): ModelRegistry - Creates without loading from disk. - refresh: void - Reloads models from disk, clears caches, resets loadError to undefined, then calls loadModels. - getError: string | undefined - Returns the loadError if models.json failed to load (undefined if no error or after successful refresh). The loadError is set in the private loadModels method if this.loadCustomModels(this.modelsJsonPath) returns an error. Even if custom models fail, built-in models are retained., citations: [2,12], confidence: high}

Citations:


🏁 Script executed:

# Check the provider.ts file around lines 213-217 and 233
cat -n packages/providers/src/community/pi/provider.ts | sed -n '210,240p'

Repository: coleam00/Archon

Length of output: 1751


🏁 Script executed:

# Check the test file around lines 317-320
cat -n packages/providers/src/community/pi/provider.test.ts | sed -n '310,330p'

Repository: coleam00/Archon

Length of output: 1246


Remove unnecessary optional chaining from getError() call.

Line 233 calls modelRegistry.getError?.() defensively, but getError() is a documented public method on ModelRegistry that always exists (returns string | undefined). The optional chaining is unnecessary; call it directly as modelRegistry.getError(). The test correctly shows this expectation (line 319).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/providers/src/community/pi/provider.ts` around lines 213 - 217, The
code defensively uses optional chaining when invoking modelRegistry.getError
(calling modelRegistry.getError?.()), but ModelRegistry.create guarantees a
public getError(): string | undefined method, so remove the unnecessary optional
chaining and call modelRegistry.getError() directly; update the invocation where
modelRegistry.getError?.() is used (in the block after ModelRegistry.create) to
modelRegistry.getError() to match the documented API and existing tests.

@Wirasm Wirasm merged commit 686bec6 into coleam00:dev Apr 27, 2026
4 checks passed
popemkt added a commit to popemkt/Archon that referenced this pull request Apr 27, 2026
Resolves the conflict on packages/providers/src/community/pi/provider.ts.

- Upstream's coleam00#1284 (ModelRegistry) and our shared/structured-output
  extraction both touch the same region. Upstream removed the inline
  augmentPromptForJsonSchema call site that coleam00#1284 didn't itself need;
  our branch had moved that function to shared/. Resolution keeps the
  shared/ extraction (single source of truth for both Pi and Copilot)
  and re-exports it from pi/provider.ts under the original name so
  existing Pi callers and tests stay byte-for-byte.
- Drops the dead-code lookupPiModel/GetModelFn helper that was a stale
  leftover from an earlier merge attempt — never had a caller and was
  superseded by ModelRegistry upstream.
- Picks up coleam00#1431 — moves e2e-copilot-smoke.yaml under test-workflows/
  alongside the other e2e-*.yaml smokes.

Adds e2e-copilot-all-features smoke (mirrors e2e-minimax-smoke):
  basic chat (PONG) + effort: high (17×23 = 391) + denied_tools: [shell,
  write] (DENIED_OK) + output_format JSON (best-effort via shared/
  structured-output, parsed as {model, ok}). Single bash assert verifies
  all four end-to-end. Doubles as adoption docs.

Validation:
- bun run check:bundled, type-check, lint, format:check — all green.
- bun --filter @archon/providers test — fully green (Pi included).
- Live smoke (Linux + gpt-5-mini, Copilot CLI 1.0.36):
    e2e-copilot-smoke           → 12s, PASS
    e2e-copilot-all-features    → 25s, PASS (all four caps)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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.

How to setup ollama and config a model and base url

5 participants