Compare commits

..
5 Commits
Author SHA1 Message Date
AlexKucera e534b27f94 release v0.1.0 2026-11-25 16:15:56 +01:00
AlexKucera 1af3a1360e feat: make the package installable from npm
pi loads a package's extensions through the `pi` manifest or an
`extensions/` directory, so a root index.ts loaded nothing as a
package. Add "pi": { "extensions": ["./index.ts"] }, a files
whitelist that keeps tests and docs out of the tarball, and the
repository links the pi.dev/packages gallery shows.

Add publish.sh for releases: checks, tarball preview, changelog
heading, commit, tag, npm publish, push. No CI (ADR 0003).

Lead the README with pi install npm:pi-nous-portal, document the
release script, and label the package unofficial and
community-maintained. The README also gets a plainer voice.

The publish itself is still pending. Refs #3
2026-11-25 16:15:15 +01:00
AlexKucera 8829d3142c docs: add review and audit session logs
Record the architecture review unit (tier property, login clock) and
its two-round finish audit as session logs, register both in
docs/devlog/INDEX.md and the root AGENTS.md window, and carry the
round-1 corrections into the review log (exports, diff counts, which
tests use the fake clock).
2026-11-25 13:50:41 +01:00
AlexKucera 544af1eeea test: drive login poll loop with a fake clock
Give login an optional clock ({ now, sleep }) with the real timers as
the default, so the device-code poll loop can be tested without
wall-clock time. Neither t.mock.timers nor jiti aliasing reaches
node:timers/promises, so a seam is the only way in; auth.oauth.login
still passes only the interaction, so pi's interface is unchanged.

Six tests cover pending to slow_down to success, the interval fallback
and floor, the deadline cap, a non-retryable error and a non-OK device
code response. The token mock gives up after 100 polls: an
auto-advancing fake starves the event loop, so a sleep-less regression
would otherwise hang the suite with no test timeout able to fire.
2026-11-25 13:50:00 +01:00
AlexKucera cb5aecf815 refactor: carry catalog tier on the model
Move the catalog tier from the x-nous-catalog-tier request header to a
catalogTier property on each model. pi forwards only model.headers to
the provider and copies them into the request options, so a header
needed stripping on both the model and the options before every
request; that adapter leaked for two audit rounds. A property never
reaches the wire, survives pi's model store, and needs no wrapper, so
TIER_HEADER, untier and withoutTierHeader are deleted and pi's stream
passes through untouched.

Models stored by the previous version come back without the property
until the next interactive start rewrites the store; the CHANGELOG
tells the user to start pi once interactively after upgrading.
2026-11-25 13:49:58 +01:00
14 changed files with 367 additions and 96 deletions

No files matched your search

+8 -1
View File
@@ -9,12 +9,15 @@
- `npm run check`: `tsc --noEmit` then `node --test tests/*.test.mjs`. - `npm run check`: `tsc --noEmit` then `node --test tests/*.test.mjs`.
- Install dev deps with `npm install --legacy-peer-deps --no-package-lock`. Plain `npm install` ignores the `"*"` peer ranges and pulls a full duplicate copy of `@earendil-works/pi-ai` into `node_modules`, which pi's loader explicitly warns against. - Install dev deps with `npm install --legacy-peer-deps --no-package-lock`. Plain `npm install` ignores the `"*"` peer ranges and pulls a full duplicate copy of `@earendil-works/pi-ai` into `node_modules`, which pi's loader explicitly warns against.
- Local install for pi: `ln -s "$PWD" ~/.pi/agent/extensions/nous-portal` (sibling convention in `~/Projects/scripting/pi-extensions`). - Local install for pi: `ln -s "$PWD" ~/.pi/agent/extensions/nous-portal` (sibling convention in `~/Projects/scripting/pi-extensions`).
- `./publish.sh`: cuts a release (clean tree on `main`, `npm run check`, `npm pack --dry-run`, changelog heading, commit, tag, `npm publish`, push). The changelog's `## [Unreleased]` heading is required.
## Architecture ## Architecture
- Uses the **native** pi-ai `Provider` (`createProvider`) rather than the legacy `ProviderConfig` + `oauth` block. The legacy `getApiKey` contract pushes an extension toward minting an agent key; Nous retired that endpoint (`410 session_key_minting_retired`). Here `OAuthAuth.toAuth` returns the access token itself, and pi owns the locked refresh pattern. See `docs/adr/0001-stack.md`. - Uses the **native** pi-ai `Provider` (`createProvider`) rather than the legacy `ProviderConfig` + `oauth` block. The legacy `getApiKey` contract pushes an extension toward minting an agent key; Nous retired that endpoint (`410 session_key_minting_retired`). Here `OAuthAuth.toAuth` returns the access token itself, and pi owns the locked refresh pattern. See `docs/adr/0001-stack.md`.
- Streaming is delegated to pi's built-in `openai-completions` API. No custom wire protocol. - Streaming is delegated to pi's built-in `openai-completions` API. No custom wire protocol.
- `Model.headers["x-nous-catalog-tier"]` carries the catalog tier **on the model**, because pi persists and restores model objects across runs and a side table would miss restored entries. `withoutTierHeader` strips it from both the model and the request options before every request (pi copies `model.headers` into `options.headers` before calling the provider). - The catalog tier rides **on the model** as the `catalogTier` property, because pi persists and restores model objects across runs and a side table would miss restored entries. It is a property, not a header: pi forwards only `model.headers` to requests (and copies them into the options first), so nothing is stripped before a request. Do not move it into `headers` without bringing back a strip on both the model and the options. The persisted catalog is `<agentDir>/models-store.json` (`ModelsStore`); `models.json` holds only user overrides, so check the store when verifying anything carried on a model.
- `login` accepts an optional clock (`{ now, sleep }`): production uses `node:timers/promises` and `Date.now`, tests an auto-advancing fake. `auth.oauth.login` passes only the interaction, so pi's interface is unchanged.
- **The `pi` manifest is what makes the package load.** pi's package loader reads `pi.extensions` from `package.json`, or scans an `extensions/` directory when there is no manifest. A root `index.ts` is only found by the legacy `~/.pi/agent/extensions/` loader, which is why the symlink install works and a package install would not. Keep `"pi": { "extensions": ["./index.ts"] }`, the `pi-package` keyword (the pi.dev/packages gallery lists only npm packages that carry it), and the `files` whitelist in `package.json`.
## Conventions and gotchas ## Conventions and gotchas
@@ -23,6 +26,7 @@
- **`pi -p` and `--list-models` never fetch live catalogs** (`allowModelNetwork` is hard-coded `false`). That is why the provider ships `BASELINE`; interactive startup overlays the live list. - **`pi -p` and `--list-models` never fetch live catalogs** (`allowModelNetwork` is hard-coded `false`). That is why the provider ships `BASELINE`; interactive startup overlays the live list.
- **Tests load `index.ts` through jiti with the host packages aliased to `tests/stubs/pi-ai.mjs`.** Alias keys are longest-prefix first, so `pi-ai/compat` must precede `pi-ai` or the bare key swallows the subpath. - **Tests load `index.ts` through jiti with the host packages aliased to `tests/stubs/pi-ai.mjs`.** Alias keys are longest-prefix first, so `pi-ai/compat` must precede `pi-ai` or the bare key swallows the subpath.
- **Never blanket-inject `tags.user` into request bodies.** As of 2026-11-25 Nous free and discounted models return 500 when that field is present, and only `upstage/solar-mini4:free` requires it. `solar-mini4:free` is therefore left out of `BASELINE` on purpose. - **Never blanket-inject `tags.user` into request bodies.** As of 2026-11-25 Nous free and discounted models return 500 when that field is present, and only `upstage/solar-mini4:free` requires it. `solar-mini4:free` is therefore left out of `BASELINE` on purpose.
- **Releases are local, through `publish.sh`.** No CI and no npm token: `npm publish` prompts for the 2FA code. The script renames the changelog's `## [Unreleased]` heading to the released version, so new entries always go under `## [Unreleased]`.
## Catalog tiers ## Catalog tiers
@@ -127,5 +131,8 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start --> <!-- write-log: window-start -->
| Date | Log | | Date | Log |
|------|-----| |------|-----|
| 2026-11-25 | [20261125-issue03-publish-pi-nous-portal-to-npm_log.md](docs/devlog/20261125-issue03-publish-pi-nous-portal-to-npm_log.md) |
| 2026-11-25 | [20261125-finish-audit-architecture-review-unit_log.md](docs/devlog/20261125-finish-audit-architecture-review-unit_log.md) |
| 2026-11-25 | [20261125-architecture-review-tier-property-and-login-clock_log.md](docs/devlog/20261125-architecture-review-tier-property-and-login-clock_log.md) |
| 2026-11-25 | [20261125-fresh-context-audit-rounds-1-5_log.md](docs/devlog/20261125-fresh-context-audit-rounds-1-5_log.md) | | 2026-11-25 | [20261125-fresh-context-audit-rounds-1-5_log.md](docs/devlog/20261125-fresh-context-audit-rounds-1-5_log.md) |
<!-- write-log: window-end --> <!-- write-log: window-end -->
+6 -1
View File
@@ -2,11 +2,16 @@
All notable changes to this project will be documented in this file. The format is based on [Common Changelog](https://common-changelog.org) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). All notable changes to this project will be documented in this file. The format is based on [Common Changelog](https://common-changelog.org) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased] ## [0.1.0] - 2026-11-25
### Added ### Added
- Native `nous-portal` provider: device-code OAuth (subscription) and API-key login, with the OAuth access token used directly as the inference bearer credential. - Native `nous-portal` provider: device-code OAuth (subscription) and API-key login, with the OAuth access token used directly as the inference bearer credential.
- npm package. `pi install npm:pi-nous-portal` installs it, the `pi` manifest points pi at `index.ts`, and `publish.sh` cuts a release.
- Live model discovery from `inference-api.nousresearch.com/v1/models`, delegated to pi's built-in `openai-completions` streaming. - Live model discovery from `inference-api.nousresearch.com/v1/models`, delegated to pi's built-in `openai-completions` streaming.
- Offline baseline catalog so `pi -p` and `pi --list-models` stay usable without a network fetch. - Offline baseline catalog so `pi -p` and `pi --list-models` stay usable without a network fetch.
- `/nous-catalog` cycles `/model` between full, free and promo catalogs; `/nous-free` jumps to free. Switching never touches a session on another provider, and swaps the current model only if it was filtered out. - `/nous-catalog` cycles `/model` between full, free and promo catalogs; `/nous-free` jumps to free. Switching never touches a session on another provider, and swaps the current model only if it was filtered out.
### Changed
- The catalog tier rides on each model as the `catalogTier` property instead of the `x-nous-catalog-tier` request header, so requests are no longer rewritten to strip it. After upgrading, start pi once interactively so persisted models pick up the new carrier; until then, a non-interactive run with the free or promo catalog active lists no Nous models.
+30 -14
View File
@@ -1,27 +1,34 @@
# pi-nous-portal # pi-nous-portal
Nous Portal provider for [pi](https://github.com/earendil-works/pi): subscription OAuth and API key, without agent-key minting. An unofficial, community-maintained provider that lets [pi](https://github.com/earendil-works/pi) sign in to Nous Portal and use its models. Not affiliated with Nous Research.
## Why this exists ## Why this exists
Nous retired Hermes-style agent-key minting (`POST /api/oauth/agent-key` returns `410 session_key_minting_retired`). Both existing community extensions end their login at that endpoint, so neither can sign in with a Portal subscription. The inference API now accepts the **OAuth access token directly** as a bearer credential, so this extension never mints or stores an agent key. Nous retired Hermes-style agent-key minting. `POST /api/oauth/agent-key` returns `410 session_key_minting_retired`, and both existing community extensions end their login at that endpoint, so neither can sign in with a Portal subscription. The inference API does accept the OAuth access token itself as a bearer credential, so this extension never mints or stores an agent key.
## Requirements ## Requirements
- pi 1.6.0 or newer (`@earendil-works/pi-ai` native provider interface) - pi 1.6.0 or newer, for the `@earendil-works/pi-ai` native provider interface
- Node.js 22+ - Node.js 22 or newer
- A Nous Portal subscription, or an inference API key from the Portal - a Nous Portal subscription, or an inference API key from the Portal
## Getting started ## Install
```bash
pi install npm:pi-nous-portal
```
To run from a checkout instead, symlink it into pi's extensions directory:
```bash ```bash
# from a checkout
ln -s "$PWD" ~/.pi/agent/extensions/nous-portal ln -s "$PWD" ~/.pi/agent/extensions/nous-portal
``` ```
Then in pi: ## Use
- `/login nous-portal` offers two methods: **Sign in to Nous Portal (subscription)** for the device-code OAuth flow, or **Nous Portal API key** to store an `sk-nous-…` key. In pi:
- `/login nous-portal` offers two methods: "Sign in to Nous Portal (subscription)" for the device-code OAuth flow, or "Nous Portal API key" to store an `sk-nous-…` key.
- The API-key route also reads `$NOUS_API_KEY`. - The API-key route also reads `$NOUS_API_KEY`.
- `/model` lists the live catalog in interactive sessions. - `/model` lists the live catalog in interactive sessions.
@@ -42,13 +49,13 @@ The choice is saved in `~/.pi/agent/nous-portal-catalog` and survives restarts.
### Offline baseline ### Offline baseline
`pi -p` and `pi --list-models` never fetch live catalogs (pi hard-codes `allowModelNetwork: false` there), so the provider ships a small static baseline so it is always usable. Interactive pi overlays the live list on the baseline by model id; a baseline id that disappears from the live catalog stays listed, with its frozen baseline price and context, until the next release. `pi -p` and `pi --list-models` never fetch live catalogs, because pi hard-codes `allowModelNetwork: false` there. The provider ships a small static baseline so those modes still list something. Interactive pi overlays the live list on the baseline by model id. A baseline id that disappears from the live catalog stays listed, with its frozen baseline price and context, until the next release.
## Known limits ## Known limits
- `upstage/solar-mini4:free` is left out of the baseline on purpose: it alone requires a `tags` body field that the other free models reject with a 500, so no single request shape serves all of them. - `upstage/solar-mini4:free` is left out of the baseline. It alone requires a `tags` body field that the other free models reject with a 500, so no single request shape serves all of them.
- Subscription quota is per day. When the "Today" gauge is exhausted, inference returns `503 ChatGPT subscription inference is temporarily unavailable`. Purchased credits keep the API-key route working. - Subscription quota is per day. When the "Today" gauge is empty, inference returns `503 ChatGPT subscription inference is temporarily unavailable`. Purchased credits keep the API-key route working.
- Requests to the portal's OAuth endpoints send a browser-like `User-Agent`, `Origin` and `Referer` (only to `portal.nousresearch.com`, never to inference). This gets past the Vercel browser checkpoint that otherwise rejects CLI clients. It is a robustness and terms-of-use risk, not a security one: if Nous tightens the checkpoint or treats the client as evasion, login can break or the account can be flagged. - Requests to the portal's OAuth endpoints send a browser-like `User-Agent`, `Origin` and `Referer`, and only to `portal.nousresearch.com`, never to inference. This gets past the Vercel browser checkpoint that otherwise rejects CLI clients. It is a terms-of-use risk, not a security one. If Nous tightens the checkpoint or treats the client as evasion, login can break or the account can be flagged.
## Development ## Development
@@ -57,7 +64,16 @@ npm install --legacy-peer-deps --no-package-lock # typescript + jiti only; pi
npm run check # tsc --noEmit + node --test npm run check # tsc --noEmit + node --test
``` ```
Typechecking needs a local pi install: `tsconfig.json` `paths` point `@earendil-works/pi-ai` and `pi-coding-agent` at the type declarations under `~/.pi/agent/install/releases/<version>/`. Update those three paths when pi is upgraded. The extension itself runs against any pi with the native provider interface; only `tsc` is pinned. Typechecking needs a local pi install. The `paths` in `tsconfig.json` point `@earendil-works/pi-ai` and `pi-coding-agent` at the type declarations under `~/.pi/agent/install/releases/<version>/`, so update those three paths when pi is upgraded. The extension itself runs on any pi with the native provider interface. Only `tsc` is pinned.
## Releasing
```bash
./publish.sh # release the version in package.json
./publish.sh patch # bump first; minor and major work too
```
The script runs the checks, shows the tarball contents, moves the `Unreleased` section of the changelog under the new version, commits, tags, publishes to npm, and pushes. npm asks for your 2FA code during the publish. You need `npm login` with publish rights to the package first.
## License ## License
+1 -1
View File
@@ -19,7 +19,7 @@ Durable documentation that explains *why* the project is shaped the way it is: a
- `0001-stack.md`: native pi-ai `Provider` over legacy `ProviderConfig`, because the legacy form leads to agent-key minting that Nous retired. - `0001-stack.md`: native pi-ai `Provider` over legacy `ProviderConfig`, because the legacy form leads to agent-key minting that Nous retired.
- `0002-license.md`: GPL-3.0-or-later. - `0002-license.md`: GPL-3.0-or-later.
- `0003-forge-and-ci.md`: Gitea remote, no CI file yet. - `0003-forge-and-ci.md`: Gitea remote, no CI file yet.
- An ADR records a decision that is hard to reverse, surprising without context, and the result of a real trade-off. Easy-to-reverse choices do not get an ADR. - `0003-forge-and-ci.md`: Gitea remote, no CI file. Releases go through the local `publish.sh`.
## Work Guidance ## Work Guidance
+1 -1
View File
@@ -1,3 +1,3 @@
# Gitea remote, no CI yet # Gitea remote, no CI yet
The repository already had an `origin` on `git.babylondreams.de` (Gitea) when it was initialised, so that is the forge. No CI file: a single-file extension has nothing to build, and the test suite is `node --test` over offline assertions. Add a Gitea Actions workflow when the suite grows or a published npm package needs a release gate. The repository already had an `origin` on `git.babylondreams.de` (Gitea) when it was initialised, so that is the forge. No CI file: a single-file extension has nothing to build, and the test suite is `node --test` over offline assertions. Add a Gitea Actions workflow when the suite grows or a published npm package needs a release gate. Until then, releases are cut locally with `publish.sh`, which runs `npm run check` and `npm pack --dry-run` before `npm publish`.
@@ -0,0 +1,58 @@
# Architecture review: catalog tier as a model property, and a clock seam for the login poll loop
> **Date:** 2026-11-25
> **Type:** generic
> **Reference:** improve-codebase-architecture review (HTML report in `$TMPDIR`, not committed); grilling round 1–2; supersedes the round-3 decision row in `20261125-fresh-context-audit-rounds-1-5_log.md`
## Goal
Run the architecture review on `index.ts`, surface where a module is shallow or a rule has no locality, and implement the candidates the grilling settled, in priority order.
## What Was Done
- **Review.** Hot spots taken from `git log` (every fix commit touched `index.ts` and the tests); a fresh-context scout walked the code independently and ranked the same two friction points first. Report: three candidates, a Coherence note, one top recommendation.
- **Candidate 2, retire the tier strip.** The catalog tier now rides on the model as the `catalogTier` property (`TieredModel = Model<Api> & { catalogTier?: Tier }`, written by `toModel`, read by `tierOfModel`). `TIER_HEADER`, `untier`, `withoutTierHeader` and the adapter around pi's stream are deleted; `api` hands `openAICompletionsApi()` through untouched. The 35-line strip test is gone; the `toModel` test pins that a tiered model has **no** `headers`.
- **Candidate 1, poll loop testable through `login`.** `login(interaction, clock = realClock)`; `Clock = { now, sleep }`; `realClock` wraps `node:timers/promises` + `Date.now`; `auth.oauth.login` still passes only the interaction. `login` is exported. Five tests drive it through `driveLogin` with an auto-advancing clock: pending → `slow_down` → success (`[5000, 10000]`, one `device_code` event), missing interval → 5000, `0.5` → 1000 floor, deadline cap (`[5000, 5000, 2000]` then "Nous login timed out."), `expired_token` propagates without sleeping; the sixth test uses the real clock and a bare `fetch` mock: a non-OK device-code response throws with its status.
- **Candidate 3, catalog switch owner.** Parked (see Decisions).
- **Closeout.** Root `AGENTS.md` Architecture bullets, `tests/AGENTS.md` export list and clock contract, `CHANGELOG.md` `### Changed` with the upgrade note. `npm run check`: `tsc` clean, 25/25 tests (was 20).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Tier carried as a model property, not as `Model.headers["x-nous-catalog-tier"]` | pi forwards only `model.headers` into requests (pi-ai `dist/models.js:361,450`; coding-agent `dist/core/model-runtime.js:476`) but persists whole entries and restores them as-is: pi-ai `createProvider.refreshModels` (`dist/models.js:594-619`) sets `dynamicModels` from `context.stored` before any fetch, then persists the refreshed list through `context.publish`. The store is `ModelsStore` (`models-store.js:30`, `<agentDir>/models-store.json`). The header carrier needed four strip points and leaked for two audit rounds; a property needs none. A `tsc` probe against the repo's `paths` exited 0, with and without a new type. |
| One-line `TieredModel` intersection type | `tsc` then checks the write side: the property is written explicitly in a literal typed `TieredModel`, so a misspelled key is an excess-property error. The read side keeps one cast, where it already had one. |
| Accept the one-session edge for models persisted by the old version | Nous ignores the old header and the first interactive start rewrites the store entry (confirmed after the fact: 0 legacy headers in `models-store.json`). A legacy fallback read would need a removal condition and a verification step for no lasting gain. CHANGELOG tells the user to start pi once interactively after upgrading. The premise recorded at decision time was wrong (see Gotchas): whether a legacy-carrier entry existed locally was never established, because the check read `models.json`. |
| Optional clock parameter on `login`, over a hand-rolled mock-timer sleep or a pure wait-decision extraction | Zero-production-change paths are closed: `t.mock.timers` does not capture `node:timers/promises` and jiti does not alias `node:` builtins (both probed on Node 26.12.1). A hand-rolled abortable sleep re-adds code round 1 removed; pure extraction leaves the deadline loop and error propagation untested. Two adapters (real timers, fake clock) make it a real seam, and pi's interface is unchanged. |
| Auto-advancing fake clock (`sleep` adds its ms to `now`) | The deadline falls out of the recorded sleeps, which pins the round-3 cap exactly. A hand-advanced clock was rejected as ceremony. |
| Candidate 3 parked | Deletion test: `apply` already concentrates the rule (two commands, one implementation); the three fixed bugs were ordering and await mistakes a new owner would not have prevented; the `drive()` harness weight is unchanged. Do not re-raise without new evidence. |
| No `GLOSSARY.md`, no ADR | "Catalog tier" is already defined in root `AGENTS.md`; the carrier is easy to reverse and ADR-0001 is untouched. The round-3 devlog row is superseded by this log, not rewritten. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| The whole `index.ts` edit was rejected, nothing written | Two `LINE:HASH` anchors mistyped by hand for lines 310 and 313 | Re-sent with the hashes from the read output; the edit tool rejects atomically, so no partial state |
| `login` treated as already exported in the plan | Misread of line 112 (`async function login`, no `export`) | The export is part of the new signature; `tests/AGENTS.md` lists it |
| Persisted-model check read the wrong file | `~/.pi/agent/models.json` is the user's overrides (`ModelConfig`); the dynamic catalog that `createProvider` restores and persists is `~/.pi/agent/models-store.json` (`ModelsStore`). The earlier recipe (`grep -c x-nous-catalog-tier ~/.pi/agent/models.json`) therefore proved nothing | After the user's test, read `models-store.json`: 0 `x-nous-catalog-tier`, 45 `catalogTier`. Recipe and root `AGENTS.md` now name the right file |
## Files Changed
| File | Change Summary |
|------|---------------|
| `index.ts` | `Tier`, `TieredModel`; `toModel` writes `catalogTier`; `tierOfModel` reads it; `TIER_HEADER`, `untier`, `withoutTierHeader` and the then-unused `ProviderStreams` import deleted; `api` passes pi's stream through. internal `Clock` and `realClock`; `login(interaction, clock)` exported; `auth.oauth.login` wraps it. Net +20 −36. |
| `tests/index.test.mjs` | Strip test deleted; `toModel` tier test retargeted to the property with `headers === undefined`; `drive()` helper uses `catalogTier`; `driveLogin` + six `login` tests (five on the fake clock); the fetch mock throws after 100 token polls so a sleep-less regression fails instead of hanging |
| `AGENTS.md` | Architecture: carrier bullet rewritten; `login` clock bullet added; session-log window refreshed |
| `tests/AGENTS.md` | Purpose mentions the poll loop and no wall-clock time; export list; `login` clock and `driveLogin` contract; why mock timers and jiti aliasing cannot be used |
| `CHANGELOG.md` | `### Changed`: carrier move and the upgrade note |
| `docs/devlog/20261125-architecture-review-tier-property-and-login-clock_log.md`, `docs/devlog/INDEX.md` | This log and the index row |
## Open Items & Next Steps
- [x] Live check of the carrier: done by the user on 2026-11-25 — toggled full, free and promo, restarted with free active, `/model` listed only free models, then returned to full (which removes the flag file). On disk afterwards: `~/.pi/agent/models-store.json` `nous-portal` entry with 409 models, 45 `catalogTier` (3 free, 42 promo), 0 `x-nous-catalog-tier`, 0 models with `headers`, `checkedAt` 2026-11-25T10:58:50Z.
- [x] Mutation check of the six poll-loop tests, run the same day in a scratch copy (temp dir with `index.ts`, `tests/`, `node_modules` symlinked; the repo file was never touched). Six mutations — `slow_down` bump removed, interval fallback 5 → 1, 1 s floor removed, deadline cap removed, non-retryable error swallowed, non-OK device-code check removed — each failed exactly its own test (1 fail / 24 pass, baseline 25/25).
- [x] Committed in the closeout as two atomic commits, each gated on its own tree: `cb5aecf` (carrier move, `refactor:`, 19/19) and `544af1e` (clock seam + tests, `test:`, 25/25).
- [ ] Delete the review report from `$TMPDIR` when no longer needed.
---
*Log written by write-log skill*
@@ -0,0 +1,59 @@
# Finish audit of the architecture-review unit: two rounds to a clean-or-docs-only round
> **Date:** 2026-11-25
> **Type:** generic
> **Reference:** procedure `/Users/alex/.pi/agent/prompts/finish_audit.md`; audits the unit recorded in `20261125-architecture-review-tier-property-and-login-clock_log.md`
## Goal
Run the finish-audit procedure over this session's uncommitted changes (catalog tier moved to a model property, `login` clock seam with six tests, docs and wiki): fresh-context reviewer fanout, synthesize the three reports, fix accepted findings, and repeat until one full clean-or-docs-only round follows the last code-change finding.
## What Was Done
- **Before each round:** five patches re-materialized into `_code_review/` by explicit path list (production / tests / docs / new devlog / agent-wikis), each verified by reverse-apply against the working tree; `after/` snapshots byte-identical; secret scan clean. The morning audit's stale patches were moved to `_code_review/_rounds-1-5-stale/`. Round 2 also materialized README, the ADR and `tsconfig.json` under `after/`, which round-1 reviewers had to skip.
- **Each round:** three fresh-context, read-only reviewers (`ponytail-review`, `security-review`, `review`) in ONE `workflow: true` call with `runs.all` and `worktree: false`; brief at `_code_review/BRIEF.md`; the cumulative "already fixed, do NOT re-report" ledger pasted into every task (17 items carried forward, then 22, then 24). Launched async, armed `goal_wait`, resumed on the native completion wake.
- **Round 1 verdicts:** ponytail code 2 / security CLEAN / general code 1, docs 1, tests 1. Deduplicated: two code-change findings, so round 2 was required.
- **Round 1 fixes:** dead `type ProviderStreams` import deleted; `toModel` writes `catalogTier: tier,` directly instead of a conditional spread; the `driveLogin` fetch mock throws after 100 token polls; the devlog's export wording corrected.
- **Round 2 verdicts:** ponytail CLEAN / security CLEAN / general code 0, docs 2, tests 0. Zero code-change findings in a full round after the last code-change round: stopping rule met, no round 3.
- **Round 2 fixes (docs):** the devlog `index.ts` row says +20 −36 and names the dropped import; "five tests on the fake clock, the sixth on the real clock" in the devlog and `tests/AGENTS.md`; the wiki's injected-clock recipe gained the poll cap, with its INDEX summary and `log.md`.
- **Gates:** `npm run check` after each round: `tsc` clean, 25/25. Wiki lint: 0 errors (its one warning is the unrelated `tea-api-output-flag.md` taxonomy tag).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Accept the conditional-spread deletion (ponytail) | No reader distinguishes an absent key from `undefined`: `tierOfModel` returns `undefined` both ways and the JSON store drops the key. `exactOptionalPropertyTypes` stays at its default (tsconfig checked), and an explicit property in a literal typed `TieredModel` is better for `tsc` than a spread, where a misspelled key would not be an excess-property error. |
| Reproduce the hang before accepting the test finding | In a scratch copy under a 10 s watchdog, `else throw error;` to `else {}` left the non-retryable test with no result until killed; after the guard the same mutation fails in 273 ms. A plain `Error` from the mock bypasses the `instanceof OAuthError` filter in `login`, so it surfaces even when the loop swallows OAuth errors. |
| Stop after round 2 | It was a full round with zero code-change findings following the last code-change round, the procedure's Goodhart edge. Its two docs findings were counts and wording; fixing them does not reopen the loop. |
| Mutation checks in a scratch copy, not after a commit | The unit is uncommitted and the user has not asked for commits. A temp dir with `node_modules` symlinked exercises the same code with no `git checkout`, so the earlier "checkout discards the fix" trap cannot occur. |
| No commits | Outside the goal's scope and not requested. Both repos are left with uncommitted changes. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Round-1 reviewers had to skip README, the ADR and `tsconfig.json` | Unchanged files were not materialized | Added under `after/` for round 2; README and ADR confirmed free of header-carrier wording |
| A five-part exact-text edit of the devlog was rejected whole | One target read "a non-OK device-code response" where the file says "non-OK device-code response" | Re-applied the three affected lines by `LINE:HASH` anchor |
| `_code_review/` still held the morning audit's patches | Scratch from the previous loop was never cleared | Moved to `_rounds-1-5-stale/`; the morning's ledger is carried forward in the brief |
| `goal_complete` rejected the first completion summary | Negated phrasing about an out-of-scope leftover ("NOT DONE: commits") is read as incompleteness | Same facts rephrased affirmatively; accepted |
## Files Changed
| File | Change Summary |
|------|---------------|
| `index.ts` | `ProviderStreams` import removed; `catalogTier: tier,` written directly. Unit total: +20 −36 |
| `tests/index.test.mjs` | 100-poll runaway guard in the `driveLogin` mock; the untiered assertion is `.catalogTier === undefined` |
| `tests/AGENTS.md` | Five-of-six wording; the 100-poll guard contract and why no test timeout can fire |
| `docs/devlog/20261125-architecture-review-tier-property-and-login-clock_log.md` | Export wording, diff counts, five-vs-six wording, decision row |
| `docs/devlog/20261125-finish-audit-architecture-review-unit_log.md`, `docs/devlog/INDEX.md`, `AGENTS.md` | This log, its index row, the refreshed session-log window |
| agent-wikis: `pi/gotchas/pi-device-code-login-dialog.md`, `pi/INDEX.md`, `pi/log.md` | Poll cap added to the injected-clock recipe; summary and action log |
| `_code_review/` (gitignored) | Round briefs with the cumulative ledger (24 items), patches, snapshots |
## Open Items & Next Steps
- [x] Committed in the closeout: `cb5aecf` (carrier move, with the audit's dead-import and explicit-property fixes) and `544af1e` (clock seam and tests, with the runaway guard), each gated on its own tree; this log and its index rows follow in a `docs:` commit. `agent-wikis`: `27b6aa8` (review, audit and distill learnings; that repo has no remote, so nothing to push there).
- [x] The six poll-loop mutations re-run against the final files after the `driveLogin` guard (fresh scratch copy; each mutation asserted to apply exactly once): each fails exactly its own test (1 fail / 24 pass, baseline 25/25); the repo file was untouched.
- [ ] Abort-during-sleep in `login` remains untested (security reviewer, both rounds; not introduced by this unit).
---
*Log written by write-log skill*
@@ -0,0 +1,66 @@
# Issue #3: Publish pi-nous-portal 0.1.0 to npm
> **Date:** 2026-11-25
> **Type:** issue
> **Reference:** https://git.babylondreams.de/AlexKucera/nous-portal/issues/3
## Goal
Make the extension installable with `pi install npm:pi-nous-portal` and listed on https://pi.dev/packages, with a repeatable local release. Grew out of the research in #2.
## What Was Done
- Researched the gallery. It lists only npm packages that carry the `pi-package` keyword, and a git source installs but never lists. Posted that as the resolution of #2 and closed it.
- Settled the publishing decisions with Alexander: npm, unscoped `pi-nous-portal`, Gitea as `repository`, labelled unofficial, semver with a `v0.1.0` tag, a local `publish.sh` instead of CI. Recorded on #3.
- `package.json`: added `"pi": { "extensions": ["./index.ts"] }`, `repository`, `homepage`, `bugs`, `"files": ["index.ts", "CHANGELOG.md"]`, and "Unofficial, community-maintained" in `description`.
- `publish.sh`: guards (clean tree, `main`, `npm whoami`), `npm run check`, `npm pack --dry-run`, changelog heading rename, commit, tag, `npm publish`, `git push --follow-tags`.
- `README.md`: the install section now leads with `pi install npm:pi-nous-portal`, a new Releasing section, and an edit pass for a plainer voice at Alexander's request.
- `CHANGELOG.md`: entry under Unreleased.
- `AGENTS.md`, `docs/AGENTS.md`, `docs/adr/0003-forge-and-ci.md`: release steps and the manifest rule recorded.
Verified before stopping: `npm run check` (25 tests pass), `shellcheck`, `npm pack --dry-run` (5 files: `CHANGELOG.md`, `LICENSE`, `README.md`, `index.ts`, `package.json`), the dirty-tree guard stops the script with exit 1, the changelog rename turns `## [Unreleased]` into `## [0.1.0] - 2026-11-25` on a copy, and `npm version patch --no-git-tag-version` bumps a copy to 0.1.1.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Publish to npm, not a git source | The gallery indexes npm only. The issue asked "npm or git", and only npm reaches the destination. |
| Keep the unscoped name `pi-nous-portal` | Already in `package.json`, unused on npm, and it matches most gallery entries. A scope would have needed an npm org. |
| `publish.sh` over CI | Alexander asked for a script, not a pipeline. The instance has Actions enabled but no runner, and npm's trusted publishers exclude Gitea Actions, so CI would also have needed a bypass-2FA token. |
| A `pi.extensions` manifest instead of moving `index.ts` | Moving the file would touch `tsconfig.json`, the tests that load `index.ts`, and the symlink install. One manifest entry leaves all three alone. |
| Label the package unofficial | It carries Nous in its name and ships the public `hermes-cli` client id. The label keeps it from reading as a Nous product. |
| No new ADR | The release setup is reversible, and the no-CI decision is already `0003-forge-and-ci.md`, which gained one sentence. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| A package install of the old tree would load no extension | pi 1.6.0's `collectDefaultResources` (`core/package-manager.js`) reads `manifest[resourceType]` or scans `<packageRoot>/extensions/`. A root `index.ts` is only found by the legacy `~/.pi/agent/extensions/` loader, which is why the symlink install works. | Add `"pi": { "extensions": ["./index.ts"] }`. |
| The gallery would have shown no repo link | `package.json` had no `repository` field. | Added `repository`, `homepage` and `bugs`. |
| `tests/`, `docs/` and `tsconfig.json` would have shipped | No `files` whitelist, so npm fell back to `.gitignore`. | `"files": ["index.ts", "CHANGELOG.md"]`. |
| I read "automated publishing" as CI and wrote a runner-and-token plan | An assumption that was never asked for. | Alexander corrected it. #3 now describes `publish.sh`. |
| `package.json` ended up with two `description` keys | The edit tool auto-relocated the line anchor to the wrong line and inserted instead of replacing. | Replaced both lines with one. `JSON.parse` takes the last key, so `npm pack` had hidden it. |
## Files Changed
| File | Change Summary |
|------|---------------|
| `publish.sh` | New release script |
| `package.json` | `pi` manifest, `files`, repo links, description |
| `README.md` | Install and Releasing sections, edit pass |
| `CHANGELOG.md` | Unreleased entry for the npm package |
| `AGENTS.md` | Release command, manifest rule, release convention, log window |
| `docs/AGENTS.md` | ADR 0003 one-liner mentions `publish.sh` |
| `docs/adr/0003-forge-and-ci.md` | One sentence on the local release gate |
| `docs/devlog/INDEX.md` | Row for this log |
## Open Items & Next Steps
- [ ] Run `./publish.sh`. It prompts for the npm 2FA code. Not run in this session.
- [ ] After the publish, check `pi -e npm:pi-nous-portal` in a throwaway agent dir, then `/login nous-portal`.
- [ ] Confirm the package shows up on https://pi.dev/packages.
- [ ] Close #3 once the listing is live.
---
*Log written by write-log skill*
+3
View File
@@ -5,4 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index --> <!-- write-log: full-index -->
| Date | Type | File | Summary | | Date | Type | File | Summary |
|------|------|------|---------| |------|------|------|---------|
| 2026-11-25 | issue | [20261125-issue03-publish-pi-nous-portal-to-npm_log.md](20261125-issue03-publish-pi-nous-portal-to-npm_log.md) | npm package made publishable (manifest, `files`, repo links, `publish.sh`) and README edited, publish still pending |
| 2026-11-25 | generic | [20261125-finish-audit-architecture-review-unit_log.md](20261125-finish-audit-architecture-review-unit_log.md) | Two-round finish audit of the carrier move and clock seam: two code nits and a test-hang guard fixed, then a docs-only round |
| 2026-11-25 | generic | [20261125-architecture-review-tier-property-and-login-clock_log.md](20261125-architecture-review-tier-property-and-login-clock_log.md) | Architecture review: tier moves from a request header to a model property, `login` gains a clock seam, poll loop now tested |
| 2026-11-25 | generic | [20261125-fresh-context-audit-rounds-1-5_log.md](20261125-fresh-context-audit-rounds-1-5_log.md) | Five-round fresh-context audit of the Nous Portal provider: two P1s surfaced in round 3, clean in round 5 | | 2026-11-25 | generic | [20261125-fresh-context-audit-rounds-1-5_log.md](20261125-fresh-context-audit-rounds-1-5_log.md) | Five-round fresh-context audit of the Nous Portal provider: two P1s surfaced in round 3, clean in round 5 |
+20 -36
View File
@@ -21,7 +21,6 @@ import {
type OAuthCredential, type OAuthCredential,
type ProviderAuth, type ProviderAuth,
type ProviderAuthInteraction, type ProviderAuthInteraction,
type ProviderStreams,
type RefreshModelsContext, type RefreshModelsContext,
} from "@earendil-works/pi-ai"; } from "@earendil-works/pi-ai";
import { setTimeout as sleep } from "node:timers/promises"; import { setTimeout as sleep } from "node:timers/promises";
@@ -108,8 +107,11 @@ export function toCredential(token: TokenResponse, previous?: OAuthCredential):
}; };
} }
type Clock = { now: () => number; sleep: (ms: number, signal?: AbortSignal) => Promise<void> };
// Production adapter: the node:timers/promises sleep, which rejects on abort. Tests pass an auto-advancing fake.
const realClock: Clock = { now: Date.now, sleep: (ms, signal) => sleep(ms, undefined, { signal }) };
async function login(interaction: ProviderAuthInteraction): Promise<OAuthCredential> { export async function login(interaction: ProviderAuthInteraction, clock: Clock = realClock): Promise<OAuthCredential> {
const { signal } = interaction; const { signal } = interaction;
const response = await fetch(`${PORTAL}/api/oauth/device/code`, { const response = await fetch(`${PORTAL}/api/oauth/device/code`, {
method: "POST", method: "POST",
@@ -131,14 +133,14 @@ async function login(interaction: ProviderAuthInteraction): Promise<OAuthCredent
// pi's dialog shows the code and opens the browser on Enter. Do NOT prompt here: a prompt clears that // pi's dialog shows the code and opens the browser on Enter. Do NOT prompt here: a prompt clears that
// confirm action (login-dialog.js showPrompt → clearDeviceCodeAction), so Enter would open nothing. // confirm action (login-dialog.js showPrompt → clearDeviceCodeAction), so Enter would open nothing.
const deadline = Date.now() + device.expires_in * 1000; const deadline = clock.now() + device.expires_in * 1000;
// Floor at 1 s and reject non-finite values like pi-ai's own poller: a missing, zero, non-numeric or // Floor at 1 s and reject non-finite values like pi-ai's own poller: a missing, zero, non-numeric or
// overflowing interval must not become a tight loop (Node clamps an overflowing setTimeout to 1 ms). // overflowing interval must not become a tight loop (Node clamps an overflowing setTimeout to 1 ms).
const requested = Number(device.interval); const requested = Number(device.interval);
let interval = Number.isFinite(requested) && requested > 0 ? Math.max(requested, 1) : 5; let interval = Number.isFinite(requested) && requested > 0 ? Math.max(requested, 1) : 5;
// Never sleep past the deadline. // Never sleep past the deadline.
const nap = () => sleep(Math.min(interval * 1000, deadline - Date.now()), undefined, { signal }); const nap = () => clock.sleep(Math.min(interval * 1000, deadline - clock.now()), signal);
while (Date.now() < deadline) { while (clock.now() < deadline) {
try { try {
return toCredential( return toCredential(
await tokenRequest({ grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: device.device_code }, signal), await tokenRequest({ grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: device.device_code }, signal),
@@ -162,7 +164,7 @@ const auth: ProviderAuth = {
name: "Nous Portal (subscription)", name: "Nous Portal (subscription)",
isSubscription: true, isSubscription: true,
loginLabel: "Sign in to Nous Portal (subscription)", loginLabel: "Sign in to Nous Portal (subscription)",
login, login: (interaction) => login(interaction),
refresh: (credential, signal) => refresh: (credential, signal) =>
tokenRequest({ grant_type: "refresh_token", refresh_token: credential.refresh }, signal).then((t) => toCredential(t, credential)), tokenRequest({ grant_type: "refresh_token", refresh_token: credential.refresh }, signal).then((t) => toCredential(t, credential)),
// The access token is the inference credential; no agent key is minted. // The access token is the inference credential; no agent key is minted.
@@ -173,11 +175,13 @@ const auth: ProviderAuth = {
const num = (v: string | number | undefined) => Number(v) || 0; const num = (v: string | number | undefined) => Number(v) || 0;
// Pi persists and restores model objects across runs, so the catalog tier travels ON the model (as an // Pi persists and restores model objects across runs, so the catalog tier travels ON the model rather than in a
// inert header Nous ignores) rather than in a side table that restored models would miss. // side table that restored models would miss. It is a plain property, not a header: pi forwards only `headers`
const TIER_HEADER = "x-nous-catalog-tier"; // to the provider (copying them into the request options too), so a property needs no stripping before a request.
type Tier = Exclude<Catalog, "full">;
type TieredModel = Model<Api> & { catalogTier?: Tier };
export function toModel(item: ModelListItem): Model<Api> { export function toModel(item: ModelListItem): TieredModel {
const id = item.id.toLowerCase(); const id = item.id.toLowerCase();
const tier = tierOf(item); const tier = tierOf(item);
const image = item.architecture?.input_modalities?.includes("image") ?? /(claude|gpt|gemini|grok|vl|vision)/.test(id); const image = item.architecture?.input_modalities?.includes("image") ?? /(claude|gpt|gemini|grok|vl|vision)/.test(id);
@@ -193,17 +197,17 @@ export function toModel(item: ModelListItem): Model<Api> {
cost: { input: num(item.pricing?.prompt) * 1e6, output: num(item.pricing?.completion) * 1e6, cacheRead: 0, cacheWrite: 0 }, cost: { input: num(item.pricing?.prompt) * 1e6, output: num(item.pricing?.completion) * 1e6, cacheRead: 0, cacheWrite: 0 },
contextWindow: item.context_length ?? 131072, contextWindow: item.context_length ?? 131072,
maxTokens: 32768, maxTokens: 32768,
...(tier ? { headers: { [TIER_HEADER]: tier } } : {}), catalogTier: tier,
}; };
} }
const tierOfModel = (model: Model<Api>) => model.headers?.[TIER_HEADER] as Exclude<Catalog, "full"> | undefined; const tierOfModel = (model: Model<Api>) => (model as TieredModel).catalogTier;
const CATALOGS = ["full", "free", "promo"] as const; const CATALOGS = ["full", "free", "promo"] as const;
type Catalog = (typeof CATALOGS)[number]; type Catalog = (typeof CATALOGS)[number];
/** Classify a live catalog entry. Nous marks free models with synthesizedFreeVariant and discounts with pricing.original. */ /** Classify a live catalog entry. Nous marks free models with synthesizedFreeVariant and discounts with pricing.original. */
export function tierOf(item: ModelListItem): Exclude<Catalog, "full"> | undefined { export function tierOf(item: ModelListItem): Tier | undefined {
if (item.synthesizedFreeVariant || item.id.toLowerCase().endsWith(":free")) return "free"; if (item.synthesizedFreeVariant || item.id.toLowerCase().endsWith(":free")) return "free";
const now = Number(item.pricing?.prompt); const now = Number(item.pricing?.prompt);
const was = Number(item.pricing?.original?.prompt); const was = Number(item.pricing?.original?.prompt);
@@ -239,25 +243,6 @@ export async function fetchModels(credential: Credential | undefined, signal: Ab
return (payload.data ?? []).filter((m) => m.id && !/hermes/i.test(m.id)).map(toModel); return (payload.data ?? []).filter((m) => m.id && !/hermes/i.test(m.id)).map(toModel);
} }
// The tier header is metadata only; strip it before the request so it never reaches Nous. pi copies
// model.headers into options.headers before calling the provider (pi-ai getAuth → prepareRequest) and the
// client applies options.headers last, so BOTH the model and the options must be stripped.
// (Nous free/discounted models 500 on an injected `tags.user` body field as of 2026-11-25, so no body
// rewriting happens here — if that changes, chain options.onPayload.)
const untier = <T extends { headers?: Record<string, string | null> } | undefined>(value: T): T => {
if (!value?.headers?.[TIER_HEADER]) return value;
const headers = { ...value.headers };
delete headers[TIER_HEADER];
return { ...value, headers };
};
export function withoutTierHeader(api: ProviderStreams): ProviderStreams {
return {
stream: (model, context, options) => api.stream(untier(model), context, untier(options)),
streamSimple: (model, context, options) => api.streamSimple(untier(model), context, untier(options)),
};
}
export default function nousPortal(pi: ExtensionAPI) { export default function nousPortal(pi: ExtensionAPI) {
let models: Model<Api>[] = BASELINE.map(toModel); let models: Model<Api>[] = BASELINE.map(toModel);
const flagPath = join(getAgentDir(), "nous-portal-catalog"); const flagPath = join(getAgentDir(), "nous-portal-catalog");
@@ -307,10 +292,9 @@ export default function nousPortal(pi: ExtensionAPI) {
models, models,
// Honored by Models.getAvailable(): /model lists only what this returns. // Honored by Models.getAvailable(): /model lists only what this returns.
filterModels: (all) => all.filter(inCatalog), filterModels: (all) => all.filter(inCatalog),
api: { // pi's stream passes through untouched: no header or body rewriting. Nous free and discounted models
// Strips the catalog-tier header only; no body rewriting (see untier). // 500 on an injected `tags.user` body field (2026-11-25); if that changes, chain options.onPayload.
"openai-completions": withoutTierHeader(openAICompletionsApi()), api: { "openai-completions": openAICompletionsApi() },
},
async fetchModels(context: RefreshModelsContext) { async fetchModels(context: RefreshModelsContext) {
const fetched = await fetchModels(context.credential, context.signal); const fetched = await fetchModels(context.credential, context.signal);
// Empty live result → keep the last good list. createProvider persists and publishes whatever is // Empty live result → keep the last good list. createProvider persists and publishes whatever is
+16 -2
View File
@@ -1,9 +1,23 @@
{ {
"name": "pi-nous-portal", "name": "pi-nous-portal",
"version": "0.1.0", "version": "0.1.0",
"description": "Nous Portal provider for pi: subscription OAuth and API key, no agent-key minting.", "description": "Unofficial, community-maintained Nous Portal provider for pi: subscription OAuth and API key, no agent-key minting.",
"license": "GPL-3.0-or-later",
"type": "module", "type": "module",
"homepage": "https://git.babylondreams.de/AlexKucera/nous-portal",
"bugs": "https://git.babylondreams.de/AlexKucera/nous-portal/issues",
"repository": {
"type": "git",
"url": "https://git.babylondreams.de/AlexKucera/nous-portal.git"
},
"files": [
"index.ts",
"CHANGELOG.md"
],
"pi": {
"extensions": [
"./index.ts"
]
},
"engines": { "engines": {
"node": ">=22" "node": ">=22"
}, },
Executable
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
# Release pi-nous-portal to npm and push the tag.
#
# ./publish.sh release the version in package.json
# ./publish.sh patch bump first (minor, major, or an explicit version work too)
#
# npm asks for your 2FA code at the publish step. If the publish fails after
# the tag exists, fix the cause and rerun: npm publish && git push origin main --follow-tags
set -euo pipefail
bump="${1:-}"
cd "$(dirname "$0")"
[ -z "$(git status --porcelain)" ] || { echo "working tree is not clean" >&2; exit 1; }
[ "$(git branch --show-current)" = "main" ] || { echo "not on main" >&2; exit 1; }
npm whoami >/dev/null
if [ -n "$bump" ]; then
npm version "$bump" --no-git-tag-version
fi
version=$(node -p "require('./package.json').version")
grep -qx '## \[Unreleased\]' CHANGELOG.md || { echo "CHANGELOG.md has no '## [Unreleased]' heading" >&2; exit 1; }
npm run check
npm pack --dry-run
# The Unreleased section becomes the entry for this version.
perl -0pi -e "s/^## \[Unreleased\]\$/## [$version] - $(date +%F)/m" CHANGELOG.md
git commit -am "release v$version"
git tag -a "v$version" -m "v$version"
npm publish
git push origin main --follow-tags
+3 -2
View File
@@ -2,7 +2,7 @@
## Purpose ## Purpose
Offline unit tests for `index.ts`. They pin the pure logic that has real branching: model mapping, credential construction, model fetching, token-endpoint error handling, and the slash commands (driven through a recording `pi`). No network, no real credentials. Offline unit tests for `index.ts`. They pin the pure logic that has real branching: model mapping, credential construction, the device-code poll loop, model fetching, token-endpoint error handling, and the slash commands (driven through a recording `pi`). No network, no real credentials, no wall-clock time.
## Ownership ## Ownership
@@ -15,7 +15,8 @@ Offline unit tests for `index.ts`. They pin the pure logic that has real branchi
- `index.test.mjs` loads `index.ts` through jiti, the same TS loader pi uses, because the host packages are not installed in `node_modules`. - `index.test.mjs` loads `index.ts` through jiti, the same TS loader pi uses, because the host packages are not installed in `node_modules`.
- Host imports are aliased to `stubs/pi-ai.mjs`. Alias keys are matched longest-prefix first: `@earendil-works/pi-ai/compat` must be listed before `@earendil-works/pi-ai`, or the bare key swallows the subpath and resolution fails. - Host imports are aliased to `stubs/pi-ai.mjs`. Alias keys are matched longest-prefix first: `@earendil-works/pi-ai/compat` must be listed before `@earendil-works/pi-ai`, or the bare key swallows the subpath and resolution fails.
- `stubs/pi-ai.mjs` exports only what `index.ts` imports: `envApiKeyAuth`, `createProvider`, `openAICompletionsApi`, `getAgentDir` (plus `agentDir` so tests can find the flag file). `getAgentDir` is called inside the default export, so it is reached only by tests that drive the commands; it returns a private `mkdtemp` dir per run, shared through `globalThis` because jiti loads the stub as a separate instance from a native import. It is a type-less stub; correctness of those functions is pi's concern and is verified live, not here. - `stubs/pi-ai.mjs` exports only what `index.ts` imports: `envApiKeyAuth`, `createProvider`, `openAICompletionsApi`, `getAgentDir` (plus `agentDir` so tests can find the flag file). `getAgentDir` is called inside the default export, so it is reached only by tests that drive the commands; it returns a private `mkdtemp` dir per run, shared through `globalThis` because jiti loads the stub as a separate instance from a native import. It is a type-less stub; correctness of those functions is pi's concern and is verified live, not here.
- Exported functions under test: `toModel`, `toCredential`, `tokenRequest`, `fetchModels`, `tierOf`, `withoutTierHeader`, and the default export via the `drive()` harness. `drive(flag)` returns `run(name, model, available, refresh)` — pass a deferred promise as `refresh` to simulate overlapping command invocations, and a Nous `model` when the `setModel` half of a contract is under test — plus the registered `provider`, which is how the provider-level `fetchModels` last-good retention is reached. Anything else is not unit-tested (notably the device-code poll loop inside `login`, which would need timer control and extraction). - Exported functions under test: `toModel`, `toCredential`, `login`, `tokenRequest`, `fetchModels`, `tierOf`, and the default export via the `drive()` harness. `drive(flag)` returns `run(name, model, available, refresh)` — pass a deferred promise as `refresh` to simulate overlapping command invocations, and a Nous `model` when the `setModel` half of a contract is under test — plus the registered `provider`, which is how the provider-level `fetchModels` last-good retention is reached.
- `login` takes an optional clock (`{ now, sleep }`) and defaults to real timers. Five of the six `login` tests drive it with `driveLogin(t, replies, device)`; the sixth exercises the default clock: an auto-advancing clock (each sleep adds its ms to `now`) plus a mocked device-code and token endpoint, where the last reply repeats and the mock gives up after 100 token polls, so a sleep-less regression fails instead of hanging (the fake clock starves the event loop; no test timeout can fire). Never wait on wall-clock time in tests: `t.mock.timers` does not capture `node:timers/promises` and jiti does not alias `node:` builtins (both probed on Node 26).
- Network calls are replaced with `t.mock.method(globalThis, "fetch", …)` from `node:test`, which restores itself when the test ends. Do not hand-roll a `globalThis.fetch` swap. - Network calls are replaced with `t.mock.method(globalThis, "fetch", …)` from `node:test`, which restores itself when the test ends. Do not hand-roll a `globalThis.fetch` swap.
- `fetchModels` reads a key only from the `credential` argument. Env resolution of `$NOUS_API_KEY` is `envApiKeyAuth`'s job upstream. The one test that touches `process.env` sets it deliberately, to pin that `fetchModels` ignores it; it restores the previous value in `t.after`. - `fetchModels` reads a key only from the `credential` argument. Env resolution of `$NOUS_API_KEY` is `envApiKeyAuth`'s job upstream. The one test that touches `process.env` sets it deliberately, to pin that `fetchModels` ignores it; it restores the previous value in `t.after`.
+62 -38
View File
@@ -17,7 +17,7 @@ const jiti = createJiti(import.meta.url, {
}, },
}); });
const extension = await jiti.import("../index.ts"); const extension = await jiti.import("../index.ts");
const { toModel, toCredential, tokenRequest, fetchModels, tierOf, withoutTierHeader } = extension; const { toModel, toCredential, login, tokenRequest, fetchModels, tierOf } = extension;
// The stub shares its private agent dir through globalThis (see stubs/pi-ai.mjs); the catalog flag lives there. // The stub shares its private agent dir through globalThis (see stubs/pi-ai.mjs); the catalog flag lives there.
const { agentDir } = await import("./stubs/pi-ai.mjs"); const { agentDir } = await import("./stubs/pi-ai.mjs");
const flagPath = join(agentDir, "nous-portal-catalog"); const flagPath = join(agentDir, "nous-portal-catalog");
@@ -43,49 +43,73 @@ test("tierOf: free by synthesizedFreeVariant or :free suffix, promo only when pr
assert.equal(tierOf({ id: "x" }), undefined); assert.equal(tierOf({ id: "x" }), undefined);
}); });
test("toModel: the catalog tier rides on the model as the tier header (pi persists and restores model objects)", () => { test("toModel: the catalog tier is a model property, never a header, so nothing needs stripping before a request", () => {
const free = toModel({ id: "upstage/solar-mini4:free" }); const free = toModel({ id: "upstage/solar-mini4:free" });
assert.equal(free.headers["x-nous-catalog-tier"], "free"); assert.equal(free.catalogTier, "free");
assert.equal(free.headers, undefined);
assert.deepEqual(free.input, ["text"]); assert.deepEqual(free.input, ["text"]);
assert.equal(free.reasoning, false); assert.equal(free.reasoning, false);
assert.equal(free.cost.input, 0); assert.equal(free.cost.input, 0);
assert.equal(free.contextWindow, 131072); assert.equal(free.contextWindow, 131072);
const promo = toModel({ id: "google/gemini-4-carbon", pricing: { prompt: "0.000002", original: { prompt: "0.000004" } } });
assert.equal(promo.catalogTier, "promo");
assert.equal(toModel({ id: "openai/gpt-5.4-nano" }).catalogTier, undefined, "untiered models carry no tier");
}); });
test("withoutTierHeader: strips the tier header from model AND options on both stream entry points; everything else untouched", async () => { // login() is driven with an auto-advancing clock: each sleep adds its ms to `now` and resolves at once, so the
const calls = []; // deadline falls out of the sleeps themselves. The token endpoint is mocked; the last reply repeats, and the mock
const api = { // gives up after 100 polls so a sleep-less regression FAILS instead of hanging (the fake clock starves the event
stream: (m, c, o) => (calls.push(["stream", m, c, o]), "s"), // loop, so no test timeout can fire).
streamSimple: (m, c, o) => (calls.push(["streamSimple", m, c, o]), "ss"), const DEVICE = { device_code: "d", user_code: "USER-1", verification_uri: "https://portal.nousresearch.com/device", expires_in: 60, interval: 5 };
}; const oauthError = (error) => ({ ok: false, status: 400, text: async () => JSON.stringify({ error }) });
const wrapped = withoutTierHeader(api); const token = (access_token) => ({ ok: true, text: async () => JSON.stringify({ access_token, expires_in: 3600 }) });
const tiered = { id: "m", headers: { "x-nous-catalog-tier": "free", "x-keep": "1" } }; const driveLogin = (t, replies, device = DEVICE) => {
const ctx = { messages: [] }; const sleeps = [], events = [];
// pi copies model.headers into options.headers before calling the provider, so options carry the tier too. let now = 1_000_000, call = 0;
const opts = { apiKey: "k", headers: { "x-nous-catalog-tier": "free", "x-keep": "1" } }; t.mock.method(globalThis, "fetch", async (url) => {
assert.equal(await wrapped.stream(tiered, ctx, opts), "s"); if (String(url).endsWith("/device/code")) return { ok: true, json: async () => device };
assert.equal(await wrapped.streamSimple(tiered, ctx, opts), "ss"); if (call >= 100) throw new Error("runaway poll loop: 100 token polls without reaching the deadline");
for (const [entry, model, , options] of calls) { return replies[Math.min(call++, replies.length - 1)];
assert.equal(model.headers["x-nous-catalog-tier"], undefined, entry + " model"); });
assert.equal(model.headers["x-keep"], "1", "other model headers survive"); const clock = { now: () => now, sleep: async (ms) => { sleeps.push(ms); now += ms; } };
assert.notEqual(model, tiered, "original model object is not mutated"); return { sleeps, events, run: () => login({ notify: (event) => events.push(event), signal: new AbortController().signal }, clock) };
assert.equal(options.headers["x-nous-catalog-tier"], undefined, entry + " options"); };
assert.equal(options.headers["x-keep"], "1", "other option headers survive");
assert.equal(options.apiKey, "k"); test("login: shows the device code once, waits the server interval on pending and 5 s more on slow_down, then returns the credential", async (t) => {
assert.notEqual(options, opts, "stripped options are a copy"); const { run, sleeps, events } = driveLogin(t, [oauthError("authorization_pending"), oauthError("slow_down"), token("tok")]);
assert.equal(tiered.headers["x-nous-catalog-tier"], "free", "caller's model is not mutated"); const credential = await run();
assert.equal(opts.headers["x-nous-catalog-tier"], "free", "caller's options are not mutated"); assert.deepEqual(sleeps, [5000, 10000]);
} assert.deepEqual(events, [{ type: "device_code", userCode: "USER-1", verificationUri: "https://portal.nousresearch.com/device", intervalSeconds: 5, expiresInSeconds: 60 }]);
// An untiered model is passed through by identity; tiered options are still stripped. assert.equal(credential.access, "tok");
const plain = { id: "p" }; });
wrapped.stream(plain, ctx, opts);
assert.equal(calls[2][1], plain); test("login: a missing interval falls back to 5 s", async (t) => {
assert.equal(calls[2][3].headers["x-nous-catalog-tier"], undefined); const { run, sleeps } = driveLogin(t, [oauthError("authorization_pending"), token("a")], { ...DEVICE, interval: undefined });
// Nothing to strip on either side → both by identity. await run();
const bare = { apiKey: "k" }; assert.deepEqual(sleeps, [5000]);
wrapped.stream(plain, ctx, bare); });
assert.equal(calls[3][1], plain);
assert.equal(calls[3][3], bare); test("login: a fractional interval is floored at 1 s", async (t) => {
const { run, sleeps } = driveLogin(t, [oauthError("authorization_pending"), token("b")], { ...DEVICE, interval: 0.5 });
await run();
assert.deepEqual(sleeps, [1000]);
});
test("login: never sleeps past the deadline; a poll that stays pending times out", async (t) => {
const { run, sleeps } = driveLogin(t, [oauthError("authorization_pending")], { ...DEVICE, expires_in: 12 });
await assert.rejects(run(), /Nous login timed out/);
assert.deepEqual(sleeps, [5000, 5000, 2000]);
});
test("login: a non-retryable OAuth error propagates without sleeping", async (t) => {
const { run, sleeps } = driveLogin(t, [oauthError("expired_token")]);
await assert.rejects(run(), /expired_token/);
assert.deepEqual(sleeps, []);
});
test("login: a non-OK device-code response throws with its status (real clock; no sleep is reached)", async (t) => {
t.mock.method(globalThis, "fetch", async () => ({ ok: false, status: 403 }));
await assert.rejects(login({ notify() {}, signal: new AbortController().signal }), /device code request failed: 403/);
}); });
test("toCredential: keeps the previous refresh token when the server rotates only the access token", () => { test("toCredential: keeps the previous refresh token when the server rotates only the access token", () => {
@@ -176,7 +200,7 @@ const drive = (flag) => {
}); });
return { run, provider, switched, notes }; return { run, provider, switched, notes };
}; };
const nous = (id, tier) => ({ id, provider: "nous-portal", ...(tier && { headers: { "x-nous-catalog-tier": tier } }) }); const nous = (id, tier) => ({ id, provider: "nous-portal", ...(tier && { catalogTier: tier }) });
const other = (id) => ({ id, provider: "anthropic" }); const other = (id) => ({ id, provider: "anthropic" });
test("/nous-free: a session whose model survives the filter is left alone, and the notice names that model", async () => { test("/nous-free: a session whose model survives the filter is left alone, and the notice names that model", async () => {