Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ‘· ci(alint): forbid Node-only imports in browser code, and guard the heterogeneous-agents layers (#20124)

Arvin Xuc04fe48f5343
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 9ab62acad78..eee5aa88bf3 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -330,9 +330,9 @@ jobs:
uses: actions/cache@v4
with:
path: .alintcache
- key: alint-${{ hashFiles('alint.config.toml', 'packages/alint/rules/**') }}-${{ github.sha }}
+ key: alint-${{ hashFiles('alint.config.toml', 'packages/alint/rules/**', 'packages/*/alint/rules/**') }}-${{ github.sha }}
restore-keys: |
- alint-${{ hashFiles('alint.config.toml', 'packages/alint/rules/**') }}-
+ alint-${{ hashFiles('alint.config.toml', 'packages/alint/rules/**', 'packages/*/alint/rules/**') }}-
- name: alint Β· lint changed files
if: ${{ !cancelled() && env.ALINT_API_KEY != '' }}
@@ -356,7 +356,7 @@ jobs:
if: ${{ !cancelled() && env.ALINT_API_KEY != '' }}
continue-on-error: true
run: |
- if git status --porcelain -- alint.config.toml packages/alint | grep -q .; then
+ if git status --porcelain -- alint.config.toml packages/alint ':(glob)packages/*/alint/**' | grep -q .; then
cd packages/alint && bunx vitest run fixtures.test.ts
else
echo "rules and fixtures unchanged; skipping calibration"
diff --git a/alint.config.toml b/alint.config.toml
index 5e8b62dfa08..c823be0428d 100644
--- a/alint.config.toml
+++ b/alint.config.toml
@@ -1,6 +1,8 @@
# alint: model-backed rules that eslint cannot express.
-# Rules live in packages/alint/rules; each has calibration fixtures under
-# packages/alint/fixtures. Set up a provider with `bun run alint:setup`, then
+# Repo-wide rules live in packages/alint/rules (fixtures in packages/alint/fixtures).
+# Package-level rules live next to their package, in packages/<pkg>/alint/rules
+# (fixtures in packages/<pkg>/alint/fixtures), registered under their own plugin
+# prefix and scoped only to that package. Set up a provider with `bun run alint:setup`, then
# `bun run check --alint` or `bun run alint --dirty`. See packages/alint/README.md.
#
# Scope rules with group `files`; never with `includeFiles` inside a rule
@@ -59,6 +61,98 @@ lobehub = "./packages/alint/rules"
"lobehub/no-mode-flags" = "warn"
+# Browser code, everywhere: nothing Node-only may be imported where the SPA
+# (or the Electron renderer) runs it. Global rule, in packages/alint/rules.
+# `src/app` and `src/libs` are left out on purpose: they mix Next.js shells and
+# server helpers (instrumentation, OIDC, MCP) with web code.
+[[config.group]]
+files = [
+ "src/business/**/*.ts",
+ "src/business/**/*.tsx",
+ "src/components/**/*.ts",
+ "src/components/**/*.tsx",
+ "src/features/**/*.ts",
+ "src/features/**/*.tsx",
+ "src/helpers/**/*.ts",
+ "src/helpers/**/*.tsx",
+ "src/hooks/**/*.ts",
+ "src/hooks/**/*.tsx",
+ "src/layout/**/*.ts",
+ "src/layout/**/*.tsx",
+ "src/routes/**/*.ts",
+ "src/routes/**/*.tsx",
+ "src/services/**/*.ts",
+ "src/services/**/*.tsx",
+ "src/spa/**/*.ts",
+ "src/spa/**/*.tsx",
+ "src/store/**/*.ts",
+ "src/store/**/*.tsx",
+ "src/utils/**/*.ts",
+ "src/utils/**/*.tsx",
+ "packages/*/src/**/*.tsx",
+]
+ignores = [ "**/*.test.ts", "**/*.test.tsx", "**/__tests__/**", "**/*.server.ts" ]
+
+[config.group.plugins]
+lobehub = "./packages/alint/rules"
+
+[config.group.rules]
+"lobehub/no-node-in-browser" = "error"
+
+# Heterogeneous agents: the browser-reachable layer (root, adapters, …) stays
+# pure and I/O lives behind Node-only subpaths. A package-level rule, kept
+# next to the code it describes in packages/heterogeneous-agents/alint/rules.
+# Scoped to the browser-reachable layer plus the spawn pipeline: Node-only
+# files are free to use Node, and sending them only buys "no violation" noise.
+# The import graph itself is guarded deterministically by runtimeBoundary.test.ts and the eslint runtime-boundary pattern.
+[[config.group]]
+files = [
+ "packages/heterogeneous-agents/src/*.ts",
+ "packages/heterogeneous-agents/src/adapters/**/*.ts",
+ "packages/heterogeneous-agents/src/client/**/*.ts",
+ "packages/heterogeneous-agents/src/client/**/*.tsx",
+ "packages/heterogeneous-agents/src/errors/**/*.ts",
+ "packages/heterogeneous-agents/src/quota/**/*.ts",
+ "packages/heterogeneous-agents/src/utils/**/*.ts",
+ "packages/heterogeneous-agents/src/mainAgentCoordinator/**/*.ts",
+ "packages/heterogeneous-agents/src/subagentCoordinator/**/*.ts",
+ "packages/heterogeneous-agents/src/providerBinding/**/*.ts",
+ "packages/heterogeneous-agents/src/codex/protocol/**/*.ts",
+ "packages/heterogeneous-agents/src/kimiCode/usage.ts",
+ "packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts",
+ "packages/heterogeneous-agents/src/spawn/spawnAgent.ts",
+]
+ignores = [ "**/*.test.ts", "**/__tests__/**", "**/generated.ts" ]
+
+[config.group.plugins]
+hetero = "./packages/heterogeneous-agents/alint/rules"
+
+[config.group.rules]
+"hetero/agent-layering" = "error"
+
+# Heterogeneous agents: a host capability (CLI credentials, process-failure
+# classification, quota sampling, spawn setup) sits behind a Node-only entry
+# even when it is pure; the fix is moving it, never a browser-portable rewrite.
+# Scoped to the files the browser entries own. Per file the model cannot see
+# who imports a symbol, so it reports only what the file itself proves.
+[[config.group]]
+files = [
+ "packages/heterogeneous-agents/src/*.ts",
+ "packages/heterogeneous-agents/src/client/**/*.ts",
+ "packages/heterogeneous-agents/src/client/**/*.tsx",
+ "packages/heterogeneous-agents/src/errors/**/*.ts",
+ "packages/heterogeneous-agents/src/quota/**/*.ts",
+ "packages/heterogeneous-agents/src/utils/**/*.ts",
+]
+# Barrels are left out: a re-export's browser consumers are not visible from the barrel.
+ignores = [ "**/*.test.ts", "**/__tests__/**", "**/generated.ts", "**/index.ts" ]
+
+[config.group.plugins]
+hetero = "./packages/heterogeneous-agents/alint/rules"
+
+[config.group.rules]
+"hetero/host-capability-placement" = "warn"
+
# Calibration fixtures: one group per rule so a fixture only meets its own rule.
[[config.group]]
files = [ "packages/alint/fixtures/pmap-over-promise-all/**" ]
@@ -94,3 +188,24 @@ files = [ "packages/alint/fixtures/no-transactions-in-models/**" ]
lobehub = "./packages/alint/rules"
[config.group.rules]
"lobehub/no-transactions-in-models" = "warn"
+
+[[config.group]]
+files = [ "packages/alint/fixtures/no-node-in-browser/**" ]
+[config.group.plugins]
+lobehub = "./packages/alint/rules"
+[config.group.rules]
+"lobehub/no-node-in-browser" = "warn"
+
+[[config.group]]
+files = [ "packages/heterogeneous-agents/alint/fixtures/agent-layering/**" ]
+[config.group.plugins]
+hetero = "./packages/heterogeneous-agents/alint/rules"
+[config.group.rules]
+"hetero/agent-layering" = "warn"
+
+[[config.group]]
+files = [ "packages/heterogeneous-agents/alint/fixtures/host-capability-placement/**" ]
+[config.group.plugins]
+hetero = "./packages/heterogeneous-agents/alint/rules"
+[config.group.rules]
+"hetero/host-capability-placement" = "warn"
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts
index 8a77e72454d..b921b754334 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts
@@ -1,9 +1,9 @@
import {
buildClaudeCodeDirectEnv,
+ CLAUDE_CODE_BASE_ARGS,
sanitizeClaudeCodeDirectArgs,
sanitizeClaudeCodeDirectEnv,
-} from '@lobechat/heterogeneous-agents';
-import { CLAUDE_CODE_BASE_ARGS } from '@lobechat/heterogeneous-agents/spawn';
+} from '@lobechat/heterogeneous-agents/spawn';
import { formatServerDefaultHeterogeneousModel } from '@lobechat/types';
import type { HeterogeneousAgentBuildPlanParams, HeterogeneousAgentDriver } from '../types';
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingProxy.ts b/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingProxy.ts
index 3c57a63d809..aab787daf97 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingProxy.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingProxy.ts
@@ -3,10 +3,8 @@ import { createServer, type IncomingHttpHeaders, type ServerResponse } from 'nod
import type { AddressInfo } from 'node:net';
import { pipeline } from 'node:stream/promises';
-import {
- type HeterogeneousProviderBindingProtocol,
- normalizeAnthropicSdkBaseURL,
-} from '@lobechat/heterogeneous-agents';
+import type { HeterogeneousProviderBindingProtocol } from '@lobechat/heterogeneous-agents';
+import { normalizeAnthropicSdkBaseURL } from '@lobechat/heterogeneous-agents/spawn';
import { isRecord, pickString } from '@lobechat/utils/object';
import { request } from 'undici';
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index bb222747dc6..02c85d8b405 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -18,11 +18,11 @@ import type {
} from '@lobechat/heterogeneous-agents';
import {
createMainAgentRunState,
- isHeteroStatusGuideErrorData,
reduceMainAgent,
rehydrateSubagentRunsState,
} from '@lobechat/heterogeneous-agents';
import { isEchoedErrorText } from '@lobechat/heterogeneous-agents/errors';
+import { isHeteroStatusGuideErrorData } from '@lobechat/heterogeneous-agents/processFailure';
import { type ChatToolPayload, ThreadStatus, ThreadType } from '@lobechat/types';
import { createNanoId } from '@lobechat/utils';
import debug from 'debug';
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index fb0071d2060..9f96c5d990c 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -1,12 +1,12 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { type ISnapshotStore, parseOperationId } from '@lobechat/agent-tracing';
import type { LobeChatDatabase } from '@lobechat/database';
+import { type LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
+import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';
import {
classifyHeteroProcessFailure,
isHeteroStatusGuideErrorData,
- type LocalHeterogeneousAgentType,
-} from '@lobechat/heterogeneous-agents';
-import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';
+} from '@lobechat/heterogeneous-agents/processFailure';
import { ThreadStatus } from '@lobechat/types';
import debug from 'debug';
diff --git a/eslint.config.mjs b/eslint.config.mjs
index dc5c1d1d0c7..db4dafe1169 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -1,3 +1,4 @@
+import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { eslint } from '@lobehub/lint';
@@ -80,6 +81,29 @@ const shellRouterRestrictedPaths = [
},
];
+// Runtime boundary of @lobechat/heterogeneous-agents: browser code may import
+// values only from the entries listed in browser-entries.json; every other
+// subpath is Node-only (spawn, rpc, quota-sampler, ...). New entries are
+// Node-only until listed there, and the package's runtimeBoundary test keeps
+// the listed entries free of Node code.
+const heteroBrowserEntries = JSON.parse(
+ readFileSync(
+ new URL('packages/heterogeneous-agents/browser-entries.json', import.meta.url),
+ 'utf8',
+ ),
+);
+const heteroBrowserSubpaths = heteroBrowserEntries
+ .filter((entry) => entry !== '.')
+ .map((entry) => entry.slice(2));
+const runtimeRestrictedImportPatterns = [
+ {
+ allowTypeImports: true,
+ message:
+ 'This @lobechat/heterogeneous-agents entry is Node-only. Browser code may import values only from the entries in packages/heterogeneous-agents/browser-entries.json; type imports are fine.',
+ regex: `^@lobechat/heterogeneous-agents/(?!(?:${heteroBrowserSubpaths.join('|')})$)`,
+ },
+];
+
const createRestrictedImportRule = ({ paths = [], patterns } = {}) => [
'error',
{
@@ -89,9 +113,11 @@ const createRestrictedImportRule = ({ paths = [], patterns } = {}) => [
...performanceRestrictedImportPaths,
...paths,
],
- ...(patterns?.length
- ? { patterns: [...(baseRestrictedImportOptions.patterns ?? []), ...patterns] }
- : {}),
+ patterns: [
+ ...(baseRestrictedImportOptions.patterns ?? []),
+ ...runtimeRestrictedImportPatterns,
+ ...(patterns ?? []),
+ ],
},
];
diff --git a/packages/alint/README.md b/packages/alint/README.md
index 878a8785a39..03c4eb6f5dd 100644
--- a/packages/alint/README.md
+++ b/packages/alint/README.md
@@ -6,18 +6,39 @@ This is Phase 0: the rule set is a private workspace package (`@lobechat/alint`)
## Rules
-| Rule | Severity | Scope | Source of the rule |
-| ----------------------------- | -------- | -------------------------------------- | ----------------------------------------------- |
-| `pmap-over-promise-all` | error | `apps/server/src`, `packages/database` | fan-out over a runtime-sized list needs `pMap` |
-| `no-transactions-in-models` | error | `packages/database/src/models` | cross-table write transactions use repositories |
-| `no-effect-fetching` | error | `src/**/*.tsx` | `data-fetching-architecture` skill |
-| `no-dynamic-import-in-server` | warn | `apps/server/src`, `packages/database` | backend code uses static top-level imports |
-| `no-mode-flags` | warn | `src/**/*.tsx` | `compose-atoms` skill |
+| Rule | Severity | Scope | Source of the rule |
+| ----------------------------- | -------- | ------------------------------------------------------------- | ----------------------------------------------- |
+| `pmap-over-promise-all` | error | `apps/server/src`, `packages/database` | fan-out over a runtime-sized list needs `pMap` |
+| `no-transactions-in-models` | error | `packages/database/src/models` | cross-table write transactions use repositories |
+| `no-effect-fetching` | error | `src/**/*.tsx` | `data-fetching-architecture` skill |
+| `no-dynamic-import-in-server` | warn | `apps/server/src`, `packages/database` | backend code uses static top-level imports |
+| `no-mode-flags` | warn | `src/**/*.tsx` | `compose-atoms` skill |
+| `no-node-in-browser` | error | browser code in `src/` (not `app/`, `libs/`), package `*.tsx` | nothing Node-only where the SPA runs it |
+
+Package-level rules, kept next to the package they describe:
+
+| Rule | Severity | Scope | Lives in |
+| ---------------------------------- | -------- | ---------------------------------------------------------------------------- | ------------------------------------------- |
+| `hetero/agent-layering` | error | the browser-reachable layer of `heterogeneous-agents` and its spawn pipeline | `packages/heterogeneous-agents/alint/rules` |
+| `hetero/host-capability-placement` | warn | files owned by the browser entries of `heterogeneous-agents` (not barrels) | `packages/heterogeneous-agents/alint/rules` |
+
+`hetero/host-capability-placement` encodes two review rejections: code that only one Node host uses (the quota sampler, `lh hetero exec`, the desktop main process) moves behind a Node-only entry even when it is pure, and it is never made browser-portable to stay where it is. It reads one file, so it cannot see who imports a symbol; it reports only a host the file names itself, and misses host-only code whose docs do not say so.
`error` is reserved for rules measured at zero false positives on real PRs; an error turns the ALint check red. A rule starts at `warn` and is promoted only after its findings have been read on real PRs. A rule whose findings are mostly true but not worth acting on per PR does not belong here: `test-the-exit-not-the-entry` was removed after five days because it produced 92% of all findings and drowned out the rest.
Scopes are declared as `[[config.group]]` entries in the root `alint.config.toml`. Never scope a rule with `includeFiles` inside `rule.alint.toml`: it only filters reports, so every file still runs (double the jobs), and it marks the rule uncacheable.
+## Where a rule lives
+
+Rules come in two layers, and each layer is registered as its own plugin in `alint.config.toml`:
+
+- **Repo-wide rules** live in `packages/alint/rules` under the `lobehub/` prefix. They state something true of a kind of code wherever it is, for example "browser code imports nothing Node-only" (`no-node-in-browser`).
+- **Package-level rules** live next to the package they describe, in `packages/<pkg>/alint/rules` with their fixtures in `packages/<pkg>/alint/fixtures`, under a prefix of their own (`hetero/` for `heterogeneous-agents`). They encode that package's architecture, for example which of its layers the web app reaches (`agent-layering`), and are only ever scoped to that package.
+
+A per-file rule cannot see an import graph. When a package's boundary matters, pair its package-level rule with a deterministic test of the graph: `heterogeneous-agents` lists its browser entries in `browser-entries.json`; `src/runtimeBoundary.test.ts` walks everything those entries reach and fails on Node built-ins, Node globals such as `Buffer`, or files owned by a Node-only entry, and the root ESLint config reads the same list to reject value imports of any other entry from `src/`.
+
+To add a package-level rule: register the directory as a plugin in the rule's `[[config.group]]`, add a fixture group for it, and add its fixtures directory with the plugin prefix to `FIXTURE_ROOTS` in `fixtures.test.ts`. CI already keys the cache on `packages/*/alint/rules/**` and runs calibration when `packages/*/alint/**` changes.
+
## Setup and run
```bash
@@ -61,5 +82,5 @@ About 14 input tokens per source line per rule. Two cold runs over the same file
1. Create `rules/<name>/rule.alint.toml` with `name`, `builtInAgent = "basic-structured"`, and an `instruction`. Write the rule as the reviewer would: what to report, which line to anchor on, what the message and suggestion must contain, and an explicit "do not report" list. The carve-outs are where the false positives live.
2. Add a `[[config.group]]` for its scope in `alint.config.toml`, and a fixture group `packages/alint/fixtures/<name>/**`.
3. Add fixtures under `fixtures/<name>/`: at least one `bad-*` file with a standalone `// alint-expect` comment on the line above the one the finding must anchor to, and one `good-*` file per carve-out. Keep them short and realistic.
-4. Run `bun run alint plugin install`, then `cd packages/alint && bunx vitest run fixtures.test.ts` with a provider set up. The suite skips itself when there is no setup.
+4. Run `bun run alint plugin install`, then `cd packages/alint && bunx vitest run fixtures.test.ts` with a provider set up. The suite skips itself when there is no setup. Delete `.alintcache` after every rule edit while calibrating: the local cache is keyed by file content, so an edited rule otherwise replays the previous rule's findings.
5. Before enabling the rule on a scope, run it over a few dozen real files and read every finding.
diff --git a/packages/alint/fixtures.test.ts b/packages/alint/fixtures.test.ts
index 23f2d9fdd8f..5722b70fa0e 100644
--- a/packages/alint/fixtures.test.ts
+++ b/packages/alint/fixtures.test.ts
@@ -14,26 +14,43 @@ import { runFixtureLint } from './runFixtures';
*/
const alintDir = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.resolve(alintDir, '../..');
-const fixturesDir = path.join(alintDir, 'fixtures');
+
+/**
+ * Where rules live, and the plugin prefix `alint.config.toml` registers each
+ * under. Repo-wide rules sit here; a package-level rule sits next to the code
+ * it describes, so it is only ever scoped to that package.
+ */
+const FIXTURE_ROOTS = [
+ { dir: 'packages/alint/fixtures', prefix: 'lobehub' },
+ { dir: 'packages/heterogeneous-agents/alint/fixtures', prefix: 'hetero' },
+];
const hasSetup = await readFile(path.join(rootDir, '.alint/config.toml'), 'utf8')
.then(() => true)
.catch(() => false);
-const ruleDirs = (await readdir(fixturesDir, { withFileTypes: true }))
- .filter((entry) => entry.isDirectory())
- .map((entry) => entry.name)
- .sort();
-
-const fixtureFiles = (
+/** Every fixture file, with the rule id its findings must carry. */
+const fixtures = (
await Promise.all(
- ruleDirs.map(async (rule) =>
- (await readdir(path.join(fixturesDir, rule)))
- .sort()
- .map((file) => path.join('packages/alint/fixtures', rule, file)),
- ),
+ FIXTURE_ROOTS.map(async ({ dir, prefix }) => {
+ const ruleDirs = (await readdir(path.join(rootDir, dir), { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => entry.name)
+ .sort();
+ return Promise.all(
+ ruleDirs.map(async (rule) =>
+ (await readdir(path.join(rootDir, dir, rule))).sort().map((file) => ({
+ file: path.join(dir, rule, file),
+ rule: `${prefix}/${rule}`,
+ })),
+ ),
+ );
+ }),
)
-).flat();
+).flat(2);
+
+const fixtureFiles = fixtures.map(({ file }) => file);
+const ruleOf = (file: string) => fixtures.find((fixture) => fixture.file === file)!.rule;
const expectedLines = async (file: string) =>
(await readFile(path.join(rootDir, file), 'utf8'))
@@ -45,7 +62,7 @@ describe.skipIf(!hasSetup)('alint rule fixtures', async () => {
const byFile = (file: string) => diagnostics.filter((d) => d.file === file);
it.each(fixtureFiles)('%s', async (file) => {
- const rule = `lobehub/${path.basename(path.dirname(file))}`;
+ const rule = ruleOf(file);
const findings = byFile(file);
const foreign = findings.filter((d) => d.rule !== rule).map((d) => d.rule);
expect(foreign, 'a fixture only meets its own rule').toEqual([]);
diff --git a/packages/alint/fixtures/no-node-in-browser/bad-store-spawn-entry.ts b/packages/alint/fixtures/no-node-in-browser/bad-store-spawn-entry.ts
new file mode 100644
index 00000000000..775a96a0c4f
--- /dev/null
+++ b/packages/alint/fixtures/no-node-in-browser/bad-store-spawn-entry.ts
@@ -0,0 +1,6 @@
+// Fixture: a client store action importing the Node-only spawn entry of a workspace package.
+// alint-expect
+import { AgentStreamPipeline } from '@lobechat/heterogeneous-agents/spawn';
+
+export const createLocalPipeline = (operationId: string) =>
+ new AgentStreamPipeline({ agentType: 'kimi-code', operationId });
diff --git a/packages/alint/fixtures/no-node-in-browser/bad-usage-footer.tsx b/packages/alint/fixtures/no-node-in-browser/bad-usage-footer.tsx
new file mode 100644
index 00000000000..e8679781eb9
--- /dev/null
+++ b/packages/alint/fixtures/no-node-in-browser/bad-usage-footer.tsx
@@ -0,0 +1,13 @@
+// Fixture: a client component reading a CLI session log straight from disk.
+// alint-expect
+import { readFile } from 'node:fs/promises';
+
+import { memo, useEffect, useState } from 'react';
+
+export const UsageFooter = memo<{ logPath: string }>(({ logPath }) => {
+ const [total, setTotal] = useState(0);
+ useEffect(() => {
+ readFile(logPath, 'utf8').then((content) => setTotal(content.split('\n').length));
+ }, [logPath]);
+ return <span>{total} requests</span>;
+});
diff --git a/packages/alint/fixtures/no-node-in-browser/good-route-handler.ts b/packages/alint/fixtures/no-node-in-browser/good-route-handler.ts
new file mode 100644
index 00000000000..19f5d74baf1
--- /dev/null
+++ b/packages/alint/fixtures/no-node-in-browser/good-route-handler.ts
@@ -0,0 +1,9 @@
+// Fixture: src/app/(backend)/api/usage/route.ts β€” a Next.js route handler, which
+// runs on the server even though it lives under the web tree.
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+export const GET = async () => {
+ const content = await readFile(path.join(process.cwd(), 'usage.json'), 'utf8');
+ return new Response(content, { headers: { 'content-type': 'application/json' } });
+};
diff --git a/packages/alint/fixtures/no-node-in-browser/good-type-only.ts b/packages/alint/fixtures/no-node-in-browser/good-type-only.ts
new file mode 100644
index 00000000000..87cc1a6bf3c
--- /dev/null
+++ b/packages/alint/fixtures/no-node-in-browser/good-type-only.ts
@@ -0,0 +1,8 @@
+// Fixture: a client helper that only needs a Node-side type.
+import type { ChildProcess } from 'node:child_process';
+
+import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
+
+export type ProcessHandle = Pick<ChildProcess, 'pid'>;
+
+export const needsDevice = (type: string) => !isRemoteHeterogeneousType(type);
diff --git a/packages/alint/report.test.ts b/packages/alint/report.test.ts
index e3ac833761a..04acb6821fc 100644
--- a/packages/alint/report.test.ts
+++ b/packages/alint/report.test.ts
@@ -63,6 +63,28 @@ describe('toFindings', () => {
);
expect(findings).toEqual([]);
});
+
+ /**
+ * Regression: only `packages/alint/fixtures` was recognised, so a package-level
+ * rule's own bad fixtures would have turned the ALint check red on every PR
+ * that touched them.
+ */
+ it('drops the fixtures of package-level rules too, but not ordinary alint paths', () => {
+ const findings = toFindings(
+ {
+ diagnostics: [
+ diagnostic({
+ filePath: '/repo/packages/heterogeneous-agents/alint/fixtures/agent-layering/bad.ts',
+ }),
+ diagnostic({ filePath: '/repo/packages/heterogeneous-agents/src/alint/fixtures.ts' }),
+ ],
+ },
+ '/repo',
+ );
+ expect(findings.map((finding) => finding.file)).toEqual([
+ 'packages/heterogeneous-agents/src/alint/fixtures.ts',
+ ]);
+ });
});
describe('verdict', () => {
diff --git a/packages/alint/report.ts b/packages/alint/report.ts
index 782ce331edc..175dce1a5a5 100644
--- a/packages/alint/report.ts
+++ b/packages/alint/report.ts
@@ -43,7 +43,12 @@ export interface Finding {
}
export const COMMENT_MARKER = '<!-- alint-summary -->';
-const FIXTURES_DIR = 'packages/alint/fixtures/';
+/**
+ * Calibration fixtures fire by design. Rules live in more than one place β€”
+ * repo-wide rules in `packages/alint`, package-level rules next to their
+ * package (`packages/<pkg>/alint`) β€” so match the fixtures directory of any.
+ */
+const isFixture = (file: string) => /^packages\/(?:[^/]+\/)?alint\/fixtures\//.test(file);
/** alint JSON β†’ findings relative to the repo root, fixtures dropped, errors first. */
export const toFindings = (output: AlintOutput, rootDir: string): Finding[] =>
@@ -69,7 +74,7 @@ export const toFindings = (output: AlintOutput, rootDir: string): Finding[] =>
suggestion: suggestion || undefined,
};
})
- .filter((finding) => !finding.file.startsWith(FIXTURES_DIR))
+ .filter((finding) => !isFixture(finding.file))
.sort(
(a, b) =>
Number(b.severity === 'error') - Number(a.severity === 'error') ||
diff --git a/packages/alint/rules/no-node-in-browser/rule.alint.toml b/packages/alint/rules/no-node-in-browser/rule.alint.toml
new file mode 100644
index 00000000000..c9c0a7fe30d
--- /dev/null
+++ b/packages/alint/rules/no-node-in-browser/rule.alint.toml
@@ -0,0 +1,22 @@
+name = "no-node-in-browser"
+builtInAgent = "basic-structured"
+instruction = """
+You are reviewing one TypeScript file from LobeHub's web client: the Vite SPA under `src/` (features, routes, store, services, hooks, components, helpers) or a package module the SPA bundles (React UI, client helpers).
+
+Team rule: code that runs in the browser must not import anything that only exists in Node. The SPA is bundled by Vite, which replaces a Node built-in with a stub that throws on first access; one such import anywhere in the module graph blanks the whole app in development, and production only survives if tree-shaking happens to drop it. The Electron renderer is browser code too β€” it reaches Node only through IPC.
+
+Report each static `import` or `export ... from` in this file whose module is Node-only:
+- a Node built-in, with or without the `node:` prefix (`fs`, `fs/promises`, `path`, `os`, `child_process`, `crypto` used as the Node module, `stream`, `net`, `http`, `worker_threads`, `module`, `url` used for `fileURLToPath`, …);
+- a package that needs Node at runtime (a database driver, `sharp`, `electron` main-process APIs, `server-only`, SDKs that read files or spawn processes);
+- a server-only alias or entry: `@/server/*`, `@/database/*` models or repositories, `@lobechat/database` models, or a workspace package subpath documented as Node-only (for `@lobechat/heterogeneous-agents`: `/spawn`, `/rpc`, `/quota-sampler`, `/scanHost`, `/resolveCliCommand`, `/workingDirectory`, `/askUser`, `/builtinMcp`, `/models`).
+
+Anchor the finding on the import line. In the message, name the module and say why it cannot run in the browser. In the suggestion, say where the work belongs instead: behind a server endpoint (TRPC/service), behind an Electron IPC call, or in a Node-only subpath of the package, with the browser keeping only a pure part (types, parsing, formatting).
+
+Do not report:
+- `import type` / `export type` and `typeof import('...')` in type positions β€” they vanish at build time;
+- a dynamic `import('...')` inside code that only runs on the server or in Electron main, when the file clearly also serves that side (say so only if the file is the browser's);
+- files that run on the server or outside the browser: Next.js route handlers and shells (`src/app/(backend)/**`, `route.ts`, server actions), middleware / proxy, `instrumentation*`, files that import `server-only`, `*.server.ts`, config files, scripts, and tests;
+- browser-safe packages that merely share a name with a Node module (`path-browserify`, `buffer` polyfills, `url` used only for the WHATWG `URL`).
+
+If you cannot tell whether the file runs in the browser, use low confidence rather than forcing a finding.
+"""
diff --git a/packages/database/src/models/__tests__/agentQuota.pipeline.test.ts b/packages/database/src/models/__tests__/agentQuota.pipeline.test.ts
index 8f364aa7802..931ce1aef3b 100644
--- a/packages/database/src/models/__tests__/agentQuota.pipeline.test.ts
+++ b/packages/database/src/models/__tests__/agentQuota.pipeline.test.ts
@@ -9,12 +9,12 @@ import {
type AccountLoad,
calibrateCapacity,
computeTurnCostUsd,
- parseClaudeAccountIdentity,
projectWindows,
type QuotaLimitReading,
selectAccount,
windowsToCalibrationIntervals,
} from '@lobechat/heterogeneous-agents/quota';
+import { parseClaudeAccountIdentity } from '@lobechat/heterogeneous-agents/quota-sampler';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
diff --git a/packages/database/src/models/__tests__/agentQuota.realAccount.e2e.test.ts b/packages/database/src/models/__tests__/agentQuota.realAccount.e2e.test.ts
index 0b61f854348..aa87ec001eb 100644
--- a/packages/database/src/models/__tests__/agentQuota.realAccount.e2e.test.ts
+++ b/packages/database/src/models/__tests__/agentQuota.realAccount.e2e.test.ts
@@ -17,13 +17,15 @@ import path from 'node:path';
import {
calibrateCapacity,
- mapClaudeUsageToReadings,
- parseClaudeAccountIdentity,
projectWindows,
type QuotaAccountIdentity,
type QuotaLimitReading,
windowsToCalibrationIntervals,
} from '@lobechat/heterogeneous-agents/quota';
+import {
+ mapClaudeUsageToReadings,
+ parseClaudeAccountIdentity,
+} from '@lobechat/heterogeneous-agents/quota-sampler';
import { eq } from 'drizzle-orm';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
diff --git a/packages/heterogeneous-agents/alint/fixtures/agent-layering/bad-adapter-reads-log.ts b/packages/heterogeneous-agents/alint/fixtures/agent-layering/bad-adapter-reads-log.ts
new file mode 100644
index 00000000000..69bbf56d4a4
--- /dev/null
+++ b/packages/heterogeneous-agents/alint/fixtures/agent-layering/bad-adapter-reads-log.ts
@@ -0,0 +1,22 @@
+// Fixture: adapters/grokBuild.ts β€” an adapter reading its CLI's usage log from disk.
+// alint-expect
+import { readFile } from 'node:fs/promises';
+
+import type { AgentEventAdapter, HeterogeneousAgentEvent } from '../types';
+
+export class GrokBuildAdapter implements AgentEventAdapter {
+ sessionId?: string;
+
+ adapt(raw: any): HeterogeneousAgentEvent[] {
+ if (typeof raw.session_id === 'string') this.sessionId = raw.session_id;
+ return [];
+ }
+
+ async collectUsage(logPath: string) {
+ return JSON.parse(await readFile(logPath, 'utf8'));
+ }
+
+ flush(): HeterogeneousAgentEvent[] {
+ return [];
+ }
+}
diff --git a/packages/heterogeneous-agents/alint/fixtures/agent-layering/bad-root-exports-node-entry.ts b/packages/heterogeneous-agents/alint/fixtures/agent-layering/bad-root-exports-node-entry.ts
new file mode 100644
index 00000000000..11a06bc20d9
--- /dev/null
+++ b/packages/heterogeneous-agents/alint/fixtures/agent-layering/bad-root-exports-node-entry.ts
@@ -0,0 +1,5 @@
+// Fixture: src/index.ts β€” the package root, which the web app imports for labels.
+export { HETEROGENEOUS_TYPE_LABELS } from './labels';
+export { createAdapter } from './registry';
+// alint-expect
+export { spawnAgent } from './spawn/spawnAgent';
diff --git a/packages/heterogeneous-agents/alint/fixtures/agent-layering/good-adapter-pure-usage.ts b/packages/heterogeneous-agents/alint/fixtures/agent-layering/good-adapter-pure-usage.ts
new file mode 100644
index 00000000000..823e9ba2b5a
--- /dev/null
+++ b/packages/heterogeneous-agents/alint/fixtures/agent-layering/good-adapter-pure-usage.ts
@@ -0,0 +1,27 @@
+// Fixture: adapters/kimiCode.ts β€” the adapter turns usage it is handed into an event.
+import type { AgentEventAdapter, HeterogeneousAgentEvent, PostRunUsage } from '../types';
+
+export class KimiCodeAdapter implements AgentEventAdapter {
+ sessionId?: string;
+ private stepIndex = 0;
+
+ adapt(raw: any): HeterogeneousAgentEvent[] {
+ if (typeof raw.session_id === 'string') this.sessionId = raw.session_id;
+ return [];
+ }
+
+ buildPostRunUsageEvents(result: PostRunUsage): HeterogeneousAgentEvent[] {
+ return [
+ {
+ data: { phase: 'turn_metadata', provider: 'kimi-code', usage: result.usage },
+ stepIndex: this.stepIndex,
+ timestamp: Date.now(),
+ type: 'step_complete',
+ } as HeterogeneousAgentEvent,
+ ];
+ }
+
+ flush(): HeterogeneousAgentEvent[] {
+ return [];
+ }
+}
diff --git a/packages/heterogeneous-agents/alint/fixtures/agent-layering/good-agent-dir-io-half.ts b/packages/heterogeneous-agents/alint/fixtures/agent-layering/good-agent-dir-io-half.ts
new file mode 100644
index 00000000000..d509f2e36d3
--- /dev/null
+++ b/packages/heterogeneous-agents/alint/fixtures/agent-layering/good-agent-dir-io-half.ts
@@ -0,0 +1,11 @@
+// Fixture: kimiCode/sessionUsage.ts β€” the Node-only half of an agent directory.
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import { aggregateKimiCodeUsage, parseKimiCodeWireUsage } from './usage';
+
+export const readSessionUsage = async (kimiHome: string, sessionId: string) => {
+ const file = path.join(kimiHome, 'sessions', sessionId, 'wire.jsonl');
+ const content = await readFile(file, 'utf8').catch(() => undefined);
+ return content ? aggregateKimiCodeUsage(parseKimiCodeWireUsage(content)) : undefined;
+};
diff --git a/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/bad-exec-failure-classifier.ts b/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/bad-exec-failure-classifier.ts
new file mode 100644
index 00000000000..3ea2c588931
--- /dev/null
+++ b/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/bad-exec-failure-classifier.ts
@@ -0,0 +1,12 @@
+// Fixture: src/errors/processFailure.ts β€” under the ./errors entry, which the web app imports to render error specs.
+import { classifyCliQuotaMessage } from './cliQuota';
+
+/**
+ * Process-level failure classification for `lh hetero exec` runs: maps the
+ * spawn errno, exit code and stderr of the CLI process to a status guide.
+ */
+// alint-expect
+export const classifyHeteroProcessFailure = (params: { code?: string; stderr: string }) => {
+ if (params.code === 'ENOENT' || /spawn \S+ ENOENT/.test(params.stderr)) return 'cli-not-found';
+ return classifyCliQuotaMessage(params.stderr) ? 'rate-limited' : 'unknown';
+};
diff --git a/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/bad-quota-identity-portable.ts b/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/bad-quota-identity-portable.ts
new file mode 100644
index 00000000000..f147b9df8cc
--- /dev/null
+++ b/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/bad-quota-identity-portable.ts
@@ -0,0 +1,17 @@
+// Fixture: src/quota/identity.ts β€” the ./quota entry, which the web app imports for quota windows.
+import type { QuotaAccountIdentity } from './types';
+
+// alint-expect
+/** Parse the account identity from `~/.codex/auth.json`; email and plan live inside the `id_token` JWT. */
+export const parseCodexAccountIdentity = (authJsonText: string): QuotaAccountIdentity | null => {
+ const tokens = (
+ JSON.parse(authJsonText) as { tokens?: { account_id?: string; id_token?: string } }
+ ).tokens;
+ if (!tokens?.id_token) return null;
+ const b64 = tokens.id_token.split('.')[1].replaceAll('-', '+').replaceAll('_', '/');
+ // Decoded without Buffer so this module stays browser-safe.
+ // alint-expect
+ const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
+ const claims = JSON.parse(new TextDecoder().decode(bytes)) as { email?: string };
+ return { email: claims.email, externalAccountId: tokens.account_id };
+};
diff --git a/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/good-errors-spec-lookup.ts b/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/good-errors-spec-lookup.ts
new file mode 100644
index 00000000000..919a9a5c1b5
--- /dev/null
+++ b/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/good-errors-spec-lookup.ts
@@ -0,0 +1,16 @@
+// Fixture: src/errors/specs.ts β€” error specs the web app uses to render a hetero error card.
+import type { HeteroErrorCategory } from './taxonomy';
+
+export interface HeteroErrorSpec {
+ category: HeteroErrorCategory;
+ guideKey: string;
+ userSide: boolean;
+}
+
+export const HETERO_ERROR_SPECS: Record<string, HeteroErrorSpec> = {
+ CLI_NOT_FOUND: { category: 'environment', guideKey: 'install', userSide: true },
+ RATE_LIMITED: { category: 'quota', guideKey: 'quota', userSide: true },
+};
+
+export const getHeteroErrorSpec = (code: string): HeteroErrorSpec | undefined =>
+ HETERO_ERROR_SPECS[code];
diff --git a/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/good-quota-windows.ts b/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/good-quota-windows.ts
new file mode 100644
index 00000000000..65e0eb84dd4
--- /dev/null
+++ b/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/good-quota-windows.ts
@@ -0,0 +1,17 @@
+// Fixture: src/quota/windows.ts β€” projects quota readings the device already sampled into display windows.
+import type { QuotaLimitReading } from './types';
+
+export interface ProjectedWindow {
+ endsAt: number;
+ startsAt: number;
+ utilization: number;
+}
+
+export const projectWindows = (readings: QuotaLimitReading[], now: number): ProjectedWindow[] =>
+ readings
+ .filter((reading) => reading.resetsAt > now)
+ .map((reading) => ({
+ endsAt: reading.resetsAt,
+ startsAt: reading.resetsAt - reading.windowSeconds * 1000,
+ utilization: reading.utilization,
+ }));
diff --git a/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/good-renderer-auth-detection.ts b/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/good-renderer-auth-detection.ts
new file mode 100644
index 00000000000..a22f78aad99
--- /dev/null
+++ b/packages/heterogeneous-agents/alint/fixtures/host-capability-placement/good-renderer-auth-detection.ts
@@ -0,0 +1,20 @@
+// Fixture: src/config.ts β€” CLI descriptors the desktop renderer uses to drive the CLI over IPC and read its stderr.
+export interface HeterogeneousAgentDescriptor {
+ authPatterns: RegExp[];
+ defaultCommand: string;
+ installDocsUrl: string;
+}
+
+export const DESCRIPTORS: Record<string, HeterogeneousAgentDescriptor> = {
+ 'claude-code': {
+ authPatterns: [/please run \/login/i, /invalid api key/i],
+ defaultCommand: 'claude',
+ installDocsUrl: 'https://docs.anthropic.com/claude-code',
+ },
+};
+
+export const resolveHeterogeneousAgentCommand = (agentType: string, command?: string) =>
+ command?.trim() || DESCRIPTORS[agentType]?.defaultCommand;
+
+export const isHeterogeneousAgentAuthRequired = (agentType: string, stderr: string) =>
+ DESCRIPTORS[agentType]?.authPatterns.some((pattern) => pattern.test(stderr)) ?? false;
diff --git a/packages/heterogeneous-agents/alint/rules/agent-layering/rule.alint.toml b/packages/heterogeneous-agents/alint/rules/agent-layering/rule.alint.toml
new file mode 100644
index 00000000000..ff20567545f
--- /dev/null
+++ b/packages/heterogeneous-agents/alint/rules/agent-layering/rule.alint.toml
@@ -0,0 +1,35 @@
+name = "agent-layering"
+builtInAgent = "basic-structured"
+instruction = """
+You are reviewing one TypeScript file from `packages/heterogeneous-agents/src`, the package that drives external coding-agent CLIs (Claude Code, Codex, Kimi Code, …) for LobeHub.
+
+The package has two layers. The boundary is what keeps the web app loading: the web app imports this package, and a Node-only module it reaches blanks the page.
+
+Browser-reachable layer β€” the web app imports the entries listed in `browser-entries.json` (the package root, `./client`, `./errors`, `./quota`), so these must run in a browser:
+`index.ts`, `adapters/**`, `registry.ts`, `config.ts`, `labels.ts`, `types.ts`, `imageEcho.ts`, `mainAgentCoordinator/**`, `subagentCoordinator/**`, `providerBinding/**`, `client/**`, `errors/**`, `quota/**`, `utils/**`, `codex/protocol/**`, and a per-agent module that is pure by design (for example `kimiCode/usage.ts`). The root re-exports every adapter and the registry, so anything an adapter imports reaches the web app.
+
+Node-only layer β€” reached only through subpath entries that Node callers import (desktop main, CLI, device, server):
+`spawn/**`, `rpc/**`, `quota-sampler/**`, `scan/**`, `askUser/**`, `builtinMcp/**`, `models/**`, `transcript/**`, everything under `codex/` except `codex/protocol/**`, and the I/O half of a per-agent directory (for example `kimiCode/sessionUsage.ts`). Files here may use Node freely.
+
+Decide the file's layer from its path using these lists. Being inside a per-agent directory does not make a file browser-reachable; only the lists above do.
+
+The lists are authoritative: do not speculate about who else might import a file, and do not hedge with "if it is reached from the browser". If the file is in the Node-only layer, return no findings at all β€” do not report that it is fine. Every finding must name a violation from the list below; when there is none, return an empty list. A finding whose suggestion would be "no change needed" must not be emitted.
+
+Report only these violations:
+1. A browser-reachable file that imports or re-exports (statically) a Node built-in (`node:*`, `fs`, `path`, `os`, `child_process`, `crypto` as the Node module, …), a Node-only package, or a module from the Node-only layer.
+2. A browser-reachable file that uses a Node-only global at runtime: `Buffer`, `__dirname`, `__filename`, `require(...)`, or file-system / process APIs. (`process.env.X` reads guarded by a fallback are allowed.)
+3. An adapter (`adapters/**`) that performs I/O: reading files, spawning processes, opening sockets, or reading `os.homedir()`. Data a CLI keeps outside stdout (session logs, usage files, transcripts) is read by the spawn pipeline and handed to the adapter as a value, the way `buildPostRunUsageEvents(usage)` receives Kimi Code's usage.
+4. A Node-only helper (it reads files, spawns, or imports Node built-ins) placed in a browser-reachable location such as `utils/`, `quota/` or `adapters/`, instead of in its agent's directory next to a pure half.
+5. In `spawn/agentStreamPipeline.ts` or `spawn/spawnAgent.ts` only: per-agent parsing or event mapping written inline, instead of a lookup keyed by agent type (like `spawn/postRunUsage.ts`) or a call into the adapter.
+6. `index.ts`, `client/**`, `errors/**` or `quota/**` re-exporting a Node-only capability; a Node-only capability gets its own subpath entry in `package.json` `exports` that is not listed in `browser-entries.json`.
+
+Anchor on the import or re-export line that crosses the boundary, or on the first line of the offending code for rules 2, 3 and 5. In the message, name the file's layer and what crosses the boundary. In the suggestion, name where the code should live (the agent's directory split into a pure module and a Node-only module, a reader keyed by agent type in `spawn/`, a new subpath entry). Do not suggest a browser-portable rewrite (for example `atob` in place of `Buffer`): code that needs Node belongs in the Node-only layer, and moving it is the fix.
+
+Do not report:
+- anything in a Node-only-layer file, including its Node imports and any per-agent logic it holds;
+- pure per-agent logic (parsing, formats, argument tables, mapping) wherever it lives β€” only I/O and Node dependencies are layering concerns;
+- `import type` / `export type` and type positions;
+- tests (`*.test.ts`) and fixtures.
+
+If you cannot place the file with the lists above, use low confidence rather than forcing a finding.
+"""
diff --git a/packages/heterogeneous-agents/alint/rules/host-capability-placement/rule.alint.toml b/packages/heterogeneous-agents/alint/rules/host-capability-placement/rule.alint.toml
new file mode 100644
index 00000000000..f5dde26fd7d
--- /dev/null
+++ b/packages/heterogeneous-agents/alint/rules/host-capability-placement/rule.alint.toml
@@ -0,0 +1,25 @@
+name = "host-capability-placement"
+builtInAgent = "basic-structured"
+instruction = """
+You are reviewing one TypeScript file from the browser-reachable layer of `packages/heterogeneous-agents/src`, the package that drives external coding-agent CLIs (Claude Code, Codex, Kimi Code, …) for LobeHub. The web app imports the entries listed in `browser-entries.json` (the package root `index.ts`, `client/`, `errors/`, `quota/`); Node callers (desktop main process, `lh` CLI, device, quota sampler) import the other subpath entries (`./spawn`, `./quota-sampler`, `./resolveCliCommand`, `./workingDirectory`, …).
+
+Which layer a module belongs to is decided by who it serves, not by whether its code happens to run in a browser. A module that exists only for one Node host belongs behind a Node-only entry even when it is pure, and it may then use Node freely. Making such a module browser-portable is not a fix; moving it is.
+
+The web app legitimately shares a lot of CLI-flavoured logic, because the desktop renderer drives the CLI over IPC and renders what comes back. Resolving the configured command to send over IPC, detecting "auth required" or "rate limited" in stderr the renderer received, normalizing error messages, CLI descriptor tables (install commands, docs URLs, auth patterns), adapters mapping stream events, quota window math, labels and error specs are all shared. Do not report them.
+
+Report only these violations, and only with evidence in this file:
+1. Host-only module. The file's doc comments or names bind it to exactly one Node host: it parses the CLI's local account state (`~/.claude.json`, `~/.codex/auth.json`, credential blobs, OAuth or `id_token` claims); it builds the spawn environment or argv of the CLI process in the desktop main process; it parses the raw response of a provider usage API that only the quota sampler calls; or its doc says it runs for `lh hetero exec`, the CLI command, or the desktop main process. The computation happening on that host is what counts: a host-only result that is later persisted and rendered by the web app is still host-only, and so is a module that "mirrors" a desktop main-process classifier. Anchor on the first line of the exported function or constant. Quote the doc phrase or name that is the evidence.
+2. Browser-portable rewrite of host code. Inside code that parses host data as in 1, a Node API is swapped for a browser one (`atob` / `btoa` / `TextDecoder` / `Uint8Array.from(...charCodeAt)` in place of `Buffer`, a hand-written join in place of `node:path`, …), often with a comment about staying browser-safe. Anchor on the replacement line.
+
+In the message, name the host and the evidence. In the suggestion, name the Node-only place: `./quota-sampler` for account and quota sampling, `./spawn` or a single-file subpath entry (like `./resolveCliCommand`, `./workingDirectory`) for process and exec concerns. Never suggest a browser-portable rewrite.
+
+Do not report:
+- barrel files (`index.ts`) β€” whether a re-export is used by the browser cannot be seen from the barrel; report the implementing file instead;
+- anything in the shared list above, or anything whose only evidence is that it mentions stderr, a CLI, a command or an error without naming the host it runs on;
+- plain constants (error message strings, codes) that the web app can show, even when they sit in a host-only file;
+- types and `import type` / `export type`;
+- Node built-in imports or Node globals as such β€” another rule covers those;
+- tests and fixtures.
+
+When there is no violation, return an empty list. Never emit a finding whose suggestion is "no change needed".
+"""
diff --git a/packages/heterogeneous-agents/browser-entries.json b/packages/heterogeneous-agents/browser-entries.json
new file mode 100644
index 00000000000..aaeff974308
--- /dev/null
+++ b/packages/heterogeneous-agents/browser-entries.json
@@ -0,0 +1 @@
+[".", "./client", "./errors", "./quota"]
diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.json
index 28bb31d7ee8..6e0ab7beee0 100644
--- a/packages/heterogeneous-agents/package.json
+++ b/packages/heterogeneous-agents/package.json
@@ -10,6 +10,7 @@
"./errors": "./src/errors/index.ts",
"./client": "./src/client/index.ts",
"./models": "./src/models/index.ts",
+ "./processFailure": "./src/spawn/classifyProcessFailure.ts",
"./protocol": "./src/protocol/index.ts",
"./quota": "./src/quota/index.ts",
"./quota-sampler": "./src/quota-sampler/index.ts",
diff --git a/packages/heterogeneous-agents/src/browserSafeRoot.test.ts b/packages/heterogeneous-agents/src/browserSafeRoot.test.ts
deleted file mode 100644
index f7652406b2d..00000000000
--- a/packages/heterogeneous-agents/src/browserSafeRoot.test.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { builtinModules } from 'node:module';
-import path from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-const NODE_BUILTINS = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
-
-const FROM_SPECIFIER = /\bfrom\s*['"]([^'"]+)['"]/g;
-const SIDE_EFFECT_IMPORT = /^import\s*['"]([^'"]+)['"]/gm;
-
-/**
- * Value (non type-only) module specifiers of a file's static imports and
- * re-exports. Dynamic `import()` is skipped on purpose: it loads on call, so
- * it cannot break the page just by being bundled.
- */
-const staticValueImports = (source: string): string[] => {
- const text = `\n${source}`;
- const specifiers: string[] = [];
- for (const match of text.matchAll(FROM_SPECIFIER)) {
- const start = Math.max(
- text.lastIndexOf('\nimport ', match.index),
- text.lastIndexOf('\nexport ', match.index),
- );
- if (start < 0) continue;
- // Type-only imports vanish at build time and cannot reach the browser.
- if (/^\n(?:import|export) type[\s{]/.test(text.slice(start, start + 16))) continue;
- specifiers.push(match[1]);
- }
- for (const match of source.matchAll(SIDE_EFFECT_IMPORT)) specifiers.push(match[1]);
- return specifiers;
-};
-
-const resolveRelative = (from: string, specifier: string): string | undefined => {
- const base = path.resolve(path.dirname(from), specifier);
- for (const candidate of [`${base}.ts`, `${base}.tsx`, path.join(base, 'index.ts')]) {
- try {
- readFileSync(candidate);
- return candidate;
- } catch {
- continue;
- }
- }
-};
-
-/** Every file reachable from `entry` through value imports, with the Node builtins each one pulls. */
-const collectNodeImports = (entry: string) => {
- const seen = new Set<string>();
- const offenders: string[] = [];
- const queue = [entry];
- while (queue.length > 0) {
- const file = queue.pop()!;
- if (seen.has(file)) continue;
- seen.add(file);
- for (const specifier of staticValueImports(readFileSync(file, 'utf8'))) {
- if (NODE_BUILTINS.has(specifier)) {
- offenders.push(`${path.relative(__dirname, file)} -> ${specifier}`);
- } else if (specifier.startsWith('.')) {
- const resolved = resolveRelative(file, specifier);
- if (resolved) queue.push(resolved);
- }
- }
- }
- return offenders;
-};
-
-/**
- * Regression: the package root is imported by the web app for labels and
- * helpers, and it re-exports every adapter. An adapter that pulled in a
- * `node:fs` reader put that module in the SPA's graph, where Vite's
- * externalized stub throws on first access and the whole app rendered blank.
- * Node-only code belongs behind a subpath entry (`./spawn`, `./rpc`, ...).
- */
-describe('package root', () => {
- it('reaches no Node built-in module', () => {
- expect(collectNodeImports(path.join(__dirname, 'index.ts'))).toEqual([]);
- });
-});
diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.ts
index f125d10751f..f059a799aca 100644
--- a/packages/heterogeneous-agents/src/index.ts
+++ b/packages/heterogeneous-agents/src/index.ts
@@ -5,17 +5,6 @@ export {
GrokBuildAdapter,
QoderAdapter,
} from './adapters';
-export {
- buildClaudeCodeDirectEnv,
- type BuildClaudeCodeDirectEnvInput,
- type BuildClaudeCodeDirectEnvResult,
- CLAUDE_CODE_API_LOCAL_ONLY_ERROR,
- HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR,
- HETEROGENEOUS_PROVIDER_BINDING_PERSONAL_ONLY_ERROR,
- normalizeAnthropicSdkBaseURL,
- sanitizeClaudeCodeDirectArgs,
- sanitizeClaudeCodeDirectEnv,
-} from './claudeCodeDirectEnv';
export type {
HeterogeneousAgentCliError,
HeterogeneousAgentDescriptor,
@@ -110,11 +99,14 @@ export type {
ServerDefaultHeterogeneousTokenHeader,
} from './providerBinding';
export {
+ CLAUDE_CODE_API_LOCAL_ONLY_ERROR,
formatHeterogeneousProviderBindingError,
getHeterogeneousProviderBindingCapability,
getProviderInferenceProtocols,
getServerDefaultHeterogeneousAgentConfig,
HETEROGENEOUS_PROVIDER_BINDING_AGENT_TYPES,
+ HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR,
+ HETEROGENEOUS_PROVIDER_BINDING_PERSONAL_ONLY_ERROR,
isHeterogeneousProviderBindingSupported,
isServerDefaultHeterogeneousAgentType,
resolveHeterogeneousProviderBinding,
@@ -124,10 +116,6 @@ export {
} from './providerBinding';
export { createAdapter, listAgentTypes, listLocalAgentTypes } from './registry';
export type { HeterogeneousAgentScanMap, HeterogeneousAgentScanStatus } from './scan/types';
-export {
- classifyHeteroProcessFailure,
- isHeteroStatusGuideErrorData,
-} from './spawn/classifyProcessFailure';
export type {
CreateMessageIntent,
CreateThreadIntent,
diff --git a/packages/heterogeneous-agents/src/providerBinding/index.ts b/packages/heterogeneous-agents/src/providerBinding/index.ts
index 25a87c5b192..1ade90dec5b 100644
--- a/packages/heterogeneous-agents/src/providerBinding/index.ts
+++ b/packages/heterogeneous-agents/src/providerBinding/index.ts
@@ -1,3 +1,8 @@
+export {
+ CLAUDE_CODE_API_LOCAL_ONLY_ERROR,
+ HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR,
+ HETEROGENEOUS_PROVIDER_BINDING_PERSONAL_ONLY_ERROR,
+} from './messages';
export {
formatHeterogeneousProviderBindingError,
getHeterogeneousProviderBindingCapability,
diff --git a/packages/heterogeneous-agents/src/providerBinding/messages.ts b/packages/heterogeneous-agents/src/providerBinding/messages.ts
new file mode 100644
index 00000000000..1c2fa74cd41
--- /dev/null
+++ b/packages/heterogeneous-agents/src/providerBinding/messages.ts
@@ -0,0 +1,16 @@
+export const HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR =
+ 'Heterogeneous agent provider binding is only supported for Desktop local execution.';
+
+/**
+ * Desktop main resolves the binding's providerId in the PERSONAL scope only
+ * (deliberately no workspace header β€” see `providerBindingPort`). A workspace
+ * agent's binding would have been configured against workspace-scoped
+ * providers, so running it locally could silently resolve a personal provider
+ * that shares the same id (builtin ids like `anthropic` collide across scopes)
+ * and bill the wrong account. Blocked before IPC for every entry point.
+ */
+export const HETEROGENEOUS_PROVIDER_BINDING_PERSONAL_ONLY_ERROR =
+ 'Heterogeneous agent provider binding is not supported for workspace agents.';
+
+/** @deprecated Use HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR. */
+export const CLAUDE_CODE_API_LOCAL_ONLY_ERROR = HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR;
diff --git a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts
index 69f6546b954..b9ab22620b3 100644
--- a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts
@@ -3,11 +3,11 @@ import { readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import path from 'node:path';
-import { parseClaudeAccountIdentity } from '../quota/identity';
import { buildClaudeQuotaWindows } from '../quota/readings';
import type { ClaudeCodeQuotaSnapshot, ClaudeCodeQuotaUnavailableReason } from '../quota/snapshot';
-import type { ClaudeUsagePayload } from '../quota/usageApi';
-import { mapClaudeUsageToReadings } from '../quota/usageApi';
+import { parseClaudeAccountIdentity } from './identity';
+import type { ClaudeUsagePayload } from './usageApi';
+import { mapClaudeUsageToReadings } from './usageApi';
/**
* How long a sampler host's snapshot cache may serve a Claude quota reading
diff --git a/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts b/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts
index 6ab577061e2..894a444959d 100644
--- a/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/codexQuota.ts
@@ -13,8 +13,8 @@ import type {
CodexRateLimitSnapshot,
} from '../quota';
import { codexQuotaReadings } from '../quota/codex';
-import { parseCodexAccountIdentity } from '../quota/identity';
import { buildCodexAppServerArgs, resolveCliSpawnPlan } from '../spawn';
+import { parseCodexAccountIdentity } from './identity';
const RPC_TIMEOUT_MS = 10_000;
const CODEX_PRIMARY_WINDOW_MINUTES = 5 * 60;
diff --git a/packages/heterogeneous-agents/src/quota-sampler/identity.test.ts b/packages/heterogeneous-agents/src/quota-sampler/identity.test.ts
new file mode 100644
index 00000000000..5314c8da7ee
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota-sampler/identity.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ parseClaudeAccountIdentity,
+ parseClaudeCredentialPlan,
+ parseCodexAccountIdentity,
+} from './identity';
+
+describe('identity parsing', () => {
+ it('parses Claude ~/.claude.json oauthAccount', () => {
+ const id = parseClaudeAccountIdentity(
+ JSON.stringify({
+ oauthAccount: {
+ accountUuid: '687dc4eb-2aad-45fc-92be-402acbe51661',
+ displayName: 'Arvin',
+ emailAddress: '[email protected]',
+ organizationRateLimitTier: 'default_claude_max_20x',
+ organizationType: 'claude_max',
+ organizationUuid: 'org-1',
+ },
+ }),
+ );
+ expect(id).toEqual({
+ displayName: 'Arvin',
+ email: '[email protected]',
+ externalAccountId: '687dc4eb-2aad-45fc-92be-402acbe51661',
+ organizationId: 'org-1',
+ planTier: 'max',
+ rateLimitTier: 'default_claude_max_20x',
+ });
+ });
+
+ it('returns null without an account uuid', () => {
+ expect(parseClaudeAccountIdentity('{}')).toBeNull();
+ expect(parseClaudeAccountIdentity('not json')).toBeNull();
+ });
+
+ it('reads plan hints from the credential blob', () => {
+ const plan = parseClaudeCredentialPlan(
+ JSON.stringify({
+ claudeAiOauth: {
+ expiresAt: 123,
+ rateLimitTier: 'default_claude_max_20x',
+ subscriptionType: 'max',
+ },
+ }),
+ );
+ expect(plan).toEqual({
+ expiresAt: 123,
+ planTier: 'max',
+ rateLimitTier: 'default_claude_max_20x',
+ });
+ });
+
+ it('parses Codex auth.json + id_token claims', () => {
+ const claims = {
+ 'email': '[email protected]',
+ 'https://api.openai.com/auth': { chatgpt_account_id: 'acc-x', chatgpt_plan_type: 'pro' },
+ };
+ const b64 = Buffer.from(JSON.stringify(claims)).toString('base64url');
+ const idToken = `h.${b64}.s`;
+ const id = parseCodexAccountIdentity(
+ JSON.stringify({ tokens: { account_id: 'acc-x', id_token: idToken } }),
+ );
+ expect(id).toEqual({ email: '[email protected]', externalAccountId: 'acc-x', planTier: 'pro' });
+ });
+
+ it('returns null for empty codex auth', () => {
+ expect(parseCodexAccountIdentity('{}')).toBeNull();
+ });
+});
diff --git a/packages/heterogeneous-agents/src/quota/identity.ts b/packages/heterogeneous-agents/src/quota-sampler/identity.ts
similarity index 98%
rename from packages/heterogeneous-agents/src/quota/identity.ts
rename to packages/heterogeneous-agents/src/quota-sampler/identity.ts
index 220c2f8e484..24abd80f969 100644
--- a/packages/heterogeneous-agents/src/quota/identity.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/identity.ts
@@ -1,4 +1,4 @@
-import type { QuotaAccountIdentity } from './types';
+import type { QuotaAccountIdentity } from '../quota/types';
/** Decode a JWT payload segment (base64url) without verifying the signature. */
const decodeJwtPayload = (jwt: string): Record<string, unknown> | null => {
diff --git a/packages/heterogeneous-agents/src/quota-sampler/index.ts b/packages/heterogeneous-agents/src/quota-sampler/index.ts
index 416d71b206f..f28195878ef 100644
--- a/packages/heterogeneous-agents/src/quota-sampler/index.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/index.ts
@@ -1,4 +1,6 @@
export * from './claudeCodeQuota';
export * from './codexQuota';
+export * from './identity';
export * from './kimiCodeQuota';
export * from './snapshotCache';
+export * from './usageApi';
diff --git a/packages/heterogeneous-agents/src/quota-sampler/usageApi.test.ts b/packages/heterogeneous-agents/src/quota-sampler/usageApi.test.ts
new file mode 100644
index 00000000000..6013e588ec3
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota-sampler/usageApi.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from 'vitest';
+
+import { mapClaudeUsageToReadings, parseResetsAt } from './usageApi';
+
+describe('mapClaudeUsageToReadings', () => {
+ it('parseResetsAt handles ISO / seconds / millis', () => {
+ expect(parseResetsAt('2026-07-12T20:50:00Z')).toBe(Date.parse('2026-07-12T20:50:00Z'));
+ expect(parseResetsAt(1_760_000_000)).toBe(1_760_000_000_000); // seconds β†’ ms
+ expect(parseResetsAt(1_760_000_000_000)).toBe(1_760_000_000_000); // already ms
+ expect(parseResetsAt(null)).toBeNull();
+ expect(parseResetsAt('nonsense')).toBeNull();
+ });
+
+ it('parseResetsAt accepts an epoch delivered as a string', () => {
+ // resets_at is typed `number | string`, so the epoch can arrive quoted.
+ expect(parseResetsAt('1760000000')).toBe(1_760_000_000_000);
+ expect(parseResetsAt('1760000000000')).toBe(1_760_000_000_000);
+ expect(parseResetsAt(' 1760000000 ')).toBe(1_760_000_000_000);
+ // a short digit string must not be read as a year by Date.parse
+ expect(parseResetsAt('1784')).toBe(1_784_000);
+ expect(parseResetsAt('')).toBeNull();
+ });
+
+ it('maps the real /api/oauth/usage limits[] shape (session + weekly + Fable scoped)', () => {
+ // exactly the shape returned by the live endpoint
+ const payload = {
+ five_hour: { resets_at: '2026-07-12T20:50:00Z', utilization: 26 },
+ limits: [
+ {
+ group: 'session',
+ is_active: false,
+ kind: 'session',
+ percent: 26,
+ resets_at: '2026-07-12T20:50:00Z',
+ scope: null,
+ severity: 'normal',
+ },
+ {
+ group: 'weekly',
+ kind: 'weekly_all',
+ percent: 29,
+ resets_at: '2026-07-18T14:00:00Z',
+ scope: null,
+ severity: 'normal',
+ },
+ {
+ group: 'weekly',
+ is_active: true,
+ kind: 'weekly_scoped',
+ percent: 38,
+ resets_at: '2026-07-18T14:00:00Z',
+ scope: { model: { display_name: 'Fable' } },
+ severity: 'normal',
+ },
+ ],
+ seven_day: { resets_at: '2026-07-18T14:00:00Z', utilization: 29 },
+ };
+ const readings = mapClaudeUsageToReadings(payload, 1000);
+ expect(readings).toHaveLength(3);
+ expect(readings[0]).toMatchObject({
+ capturedAt: 1000,
+ limitType: 'session',
+ scopeKey: '',
+ utilization: 26,
+ });
+ expect(readings[0].resetsAt).toBe(Date.parse('2026-07-12T20:50:00Z'));
+ const fable = readings.find((r) => r.limitType === 'weekly_scoped')!;
+ expect(fable.scopeKey).toBe('Fable');
+ expect(fable.utilization).toBe(38);
+ expect(fable.isActive).toBe(true);
+ });
+
+ it('falls back to five_hour/seven_day when limits[] absent', () => {
+ const readings = mapClaudeUsageToReadings(
+ { five_hour: { resets_at: 1_760_000_000, utilization: 40 } },
+ 1000,
+ );
+ expect(readings).toEqual([
+ {
+ capturedAt: 1000,
+ limitType: 'session',
+ resetsAt: 1_760_000_000_000,
+ scopeKey: '',
+ utilization: 40,
+ },
+ ]);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/quota/usageApi.ts b/packages/heterogeneous-agents/src/quota-sampler/usageApi.ts
similarity index 98%
rename from packages/heterogeneous-agents/src/quota/usageApi.ts
rename to packages/heterogeneous-agents/src/quota-sampler/usageApi.ts
index be4e6b1e43d..6f1836b3b8f 100644
--- a/packages/heterogeneous-agents/src/quota/usageApi.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/usageApi.ts
@@ -1,4 +1,4 @@
-import type { QuotaLimitReading } from './types';
+import type { QuotaLimitReading } from '../quota/types';
/**
* Shape of a single entry in the `/api/oauth/usage` `limits[]` array. This is
diff --git a/packages/heterogeneous-agents/src/quota/index.ts b/packages/heterogeneous-agents/src/quota/index.ts
index 3de7965ff4d..0a3cc276528 100644
--- a/packages/heterogeneous-agents/src/quota/index.ts
+++ b/packages/heterogeneous-agents/src/quota/index.ts
@@ -1,11 +1,9 @@
export * from './calibration';
export * from './codex';
export * from './cost';
-export * from './identity';
export * from './kimiCode';
export * from './loadBalancer';
export * from './readings';
export * from './snapshot';
export * from './types';
-export * from './usageApi';
export * from './windows';
diff --git a/packages/heterogeneous-agents/src/quota/quota.test.ts b/packages/heterogeneous-agents/src/quota/quota.test.ts
index ffc3356f0cc..8713f7b658e 100644
--- a/packages/heterogeneous-agents/src/quota/quota.test.ts
+++ b/packages/heterogeneous-agents/src/quota/quota.test.ts
@@ -7,16 +7,10 @@ import {
windowsToCalibrationIntervals,
} from './calibration';
import { computeTurnCostUsd, totalTokens } from './cost';
-import {
- parseClaudeAccountIdentity,
- parseClaudeCredentialPlan,
- parseCodexAccountIdentity,
-} from './identity';
import { selectAccount } from './loadBalancer';
import { buildClaudeQuotaWindows } from './readings';
import type { QuotaLimitReading } from './types';
import { CLAUDE_SESSION_WINDOW_SECONDS, windowSecondsForKind } from './types';
-import { mapClaudeUsageToReadings, parseResetsAt } from './usageApi';
import { findWindowAt, isWindowContaminated, projectWindows } from './windows';
// ── cost ─────────────────────────────────────────────────────────────────────
@@ -60,71 +54,6 @@ describe('computeTurnCostUsd', () => {
});
});
-// ── identity ─────────────────────────────────────────────────────────────────
-describe('identity parsing', () => {
- it('parses Claude ~/.claude.json oauthAccount', () => {
- const id = parseClaudeAccountIdentity(
- JSON.stringify({
- oauthAccount: {
- accountUuid: '687dc4eb-2aad-45fc-92be-402acbe51661',
- displayName: 'Arvin',
- emailAddress: '[email protected]',
- organizationRateLimitTier: 'default_claude_max_20x',
- organizationType: 'claude_max',
- organizationUuid: 'org-1',
- },
- }),
- );
- expect(id).toEqual({
- displayName: 'Arvin',
- email: '[email protected]',
- externalAccountId: '687dc4eb-2aad-45fc-92be-402acbe51661',
- organizationId: 'org-1',
- planTier: 'max',
- rateLimitTier: 'default_claude_max_20x',
- });
- });
-
- it('returns null without an account uuid', () => {
- expect(parseClaudeAccountIdentity('{}')).toBeNull();
- expect(parseClaudeAccountIdentity('not json')).toBeNull();
- });
-
- it('reads plan hints from the credential blob', () => {
- const plan = parseClaudeCredentialPlan(
- JSON.stringify({
- claudeAiOauth: {
- expiresAt: 123,
- rateLimitTier: 'default_claude_max_20x',
- subscriptionType: 'max',
- },
- }),
- );
- expect(plan).toEqual({
- expiresAt: 123,
- planTier: 'max',
- rateLimitTier: 'default_claude_max_20x',
- });
- });
-
- it('parses Codex auth.json + id_token claims', () => {
- const claims = {
- 'email': '[email protected]',
- 'https://api.openai.com/auth': { chatgpt_account_id: 'acc-x', chatgpt_plan_type: 'pro' },
- };
- const b64 = Buffer.from(JSON.stringify(claims)).toString('base64url');
- const idToken = `h.${b64}.s`;
- const id = parseCodexAccountIdentity(
- JSON.stringify({ tokens: { account_id: 'acc-x', id_token: idToken } }),
- );
- expect(id).toEqual({ email: '[email protected]', externalAccountId: 'acc-x', planTier: 'pro' });
- });
-
- it('returns null for empty codex auth', () => {
- expect(parseCodexAccountIdentity('{}')).toBeNull();
- });
-});
-
// ── windows ──────────────────────────────────────────────────────────────────
describe('windowSecondsForKind', () => {
it('maps weekly kinds to 7d and everything else to 5h', () => {
@@ -296,92 +225,6 @@ describe('windowsToCalibrationIntervals', () => {
});
});
-// ── usage API mapping ─────────────────────────────────────────────────────────
-describe('mapClaudeUsageToReadings', () => {
- it('parseResetsAt handles ISO / seconds / millis', () => {
- expect(parseResetsAt('2026-07-12T20:50:00Z')).toBe(Date.parse('2026-07-12T20:50:00Z'));
- expect(parseResetsAt(1_760_000_000)).toBe(1_760_000_000_000); // seconds β†’ ms
- expect(parseResetsAt(1_760_000_000_000)).toBe(1_760_000_000_000); // already ms
- expect(parseResetsAt(null)).toBeNull();
- expect(parseResetsAt('nonsense')).toBeNull();
- });
-
- it('parseResetsAt accepts an epoch delivered as a string', () => {
- // resets_at is typed `number | string`, so the epoch can arrive quoted.
- expect(parseResetsAt('1760000000')).toBe(1_760_000_000_000);
- expect(parseResetsAt('1760000000000')).toBe(1_760_000_000_000);
- expect(parseResetsAt(' 1760000000 ')).toBe(1_760_000_000_000);
- // a short digit string must not be read as a year by Date.parse
- expect(parseResetsAt('1784')).toBe(1_784_000);
- expect(parseResetsAt('')).toBeNull();
- });
-
- it('maps the real /api/oauth/usage limits[] shape (session + weekly + Fable scoped)', () => {
- // exactly the shape returned by the live endpoint
- const payload = {
- five_hour: { resets_at: '2026-07-12T20:50:00Z', utilization: 26 },
- limits: [
- {
- group: 'session',
- is_active: false,
- kind: 'session',
- percent: 26,
- resets_at: '2026-07-12T20:50:00Z',
- scope: null,
- severity: 'normal',
- },
- {
- group: 'weekly',
- kind: 'weekly_all',
- percent: 29,
- resets_at: '2026-07-18T14:00:00Z',
- scope: null,
- severity: 'normal',
- },
- {
- group: 'weekly',
- is_active: true,
- kind: 'weekly_scoped',
- percent: 38,
- resets_at: '2026-07-18T14:00:00Z',
- scope: { model: { display_name: 'Fable' } },
- severity: 'normal',
- },
- ],
- seven_day: { resets_at: '2026-07-18T14:00:00Z', utilization: 29 },
- };
- const readings = mapClaudeUsageToReadings(payload, 1000);
- expect(readings).toHaveLength(3);
- expect(readings[0]).toMatchObject({
- capturedAt: 1000,
- limitType: 'session',
- scopeKey: '',
- utilization: 26,
- });
- expect(readings[0].resetsAt).toBe(Date.parse('2026-07-12T20:50:00Z'));
- const fable = readings.find((r) => r.limitType === 'weekly_scoped')!;
- expect(fable.scopeKey).toBe('Fable');
- expect(fable.utilization).toBe(38);
- expect(fable.isActive).toBe(true);
- });
-
- it('falls back to five_hour/seven_day when limits[] absent', () => {
- const readings = mapClaudeUsageToReadings(
- { five_hour: { resets_at: 1_760_000_000, utilization: 40 } },
- 1000,
- );
- expect(readings).toEqual([
- {
- capturedAt: 1000,
- limitType: 'session',
- resetsAt: 1_760_000_000_000,
- scopeKey: '',
- utilization: 40,
- },
- ]);
- });
-});
-
// ── readings β†’ display windows ────────────────────────────────────────────────
describe('buildClaudeQuotaWindows', () => {
const now = Date.parse('2026-07-12T18:00:00Z');
diff --git a/packages/heterogeneous-agents/src/runtimeBoundary.test.ts b/packages/heterogeneous-agents/src/runtimeBoundary.test.ts
new file mode 100644
index 00000000000..8be3c40ae15
--- /dev/null
+++ b/packages/heterogeneous-agents/src/runtimeBoundary.test.ts
@@ -0,0 +1,119 @@
+import { readFileSync } from 'node:fs';
+import { builtinModules } from 'node:module';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import BROWSER_ENTRIES from '../browser-entries.json';
+import pkg from '../package.json';
+
+/**
+ * The package splits by runtime at its subpath entries. `browser-entries.json`
+ * lists the entries the web app may import values from; every other entry is
+ * Node-only (spawn, rpc, quota-sampler, ...) and may freely use `node:*`,
+ * `Buffer` or `process`. The root ESLint config reads the same list to stop
+ * browser code from value-importing a Node-only entry, and this test stops a
+ * browser entry from reaching Node code inside the package.
+ *
+ * Regression: an adapter re-exported by the root pulled in a `node:fs` reader,
+ * Vite's externalized stub threw on first access, and the SPA rendered blank.
+ */
+
+const PACKAGE_ROOT = path.resolve(__dirname, '..');
+const NODE_BUILTINS = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
+const NODE_GLOBAL = /\b(?:Buffer|__dirname|__filename)\b|\brequire\s*\(|\bprocess\.(?!env\b)/;
+
+const FROM_SPECIFIER = /\bfrom\s*['"]([^'"]+)['"]/g;
+const SIDE_EFFECT_IMPORT = /^import\s*['"]([^'"]+)['"]/gm;
+
+const exportTargets = pkg.exports as Record<string, string>;
+const entryFile = (entry: string) => path.join(PACKAGE_ROOT, exportTargets[entry]);
+
+/** Directories owned by Node-only entries; a browser entry must not reach into them. */
+const NODE_ONLY_DIRS = [
+ ...new Set(
+ Object.keys(exportTargets)
+ .filter((entry) => !BROWSER_ENTRIES.includes(entry))
+ .map((entry) => path.dirname(entryFile(entry))),
+ ),
+].filter((dir) => !BROWSER_ENTRIES.some((entry) => path.dirname(entryFile(entry)) === dir));
+
+const stripComments = (source: string) =>
+ source.replaceAll(/\/\*[\s\S]*?\*\//g, '').replaceAll(/^\s*\/\/.*$/gm, '');
+
+/**
+ * Value (non type-only) module specifiers of a file's static imports and
+ * re-exports. Dynamic `import()` is skipped on purpose: it loads on call, so
+ * it cannot break the page just by being bundled.
+ */
+const staticValueImports = (source: string): string[] => {
+ const text = `\n${source}`;
+ const specifiers: string[] = [];
+ for (const match of text.matchAll(FROM_SPECIFIER)) {
+ const start = Math.max(
+ text.lastIndexOf('\nimport ', match.index),
+ text.lastIndexOf('\nexport ', match.index),
+ );
+ if (start < 0) continue;
+ // Type-only imports vanish at build time and cannot reach the browser.
+ if (/^\n(?:import|export) type[\s{]/.test(text.slice(start, start + 16))) continue;
+ specifiers.push(match[1]);
+ }
+ for (const match of source.matchAll(SIDE_EFFECT_IMPORT)) specifiers.push(match[1]);
+ return specifiers;
+};
+
+const resolveRelative = (from: string, specifier: string): string | undefined => {
+ const base = path.resolve(path.dirname(from), specifier);
+ for (const candidate of [`${base}.ts`, `${base}.tsx`, path.join(base, 'index.ts')]) {
+ try {
+ readFileSync(candidate);
+ return candidate;
+ } catch {
+ continue;
+ }
+ }
+};
+
+/** Every Node dependency reachable from `entry` through value imports. */
+const collectNodeReach = (entry: string) => {
+ const seen = new Set<string>();
+ const offenders: string[] = [];
+ const queue = [entry];
+ while (queue.length > 0) {
+ const file = queue.pop()!;
+ if (seen.has(file)) continue;
+ seen.add(file);
+ const where = path.relative(PACKAGE_ROOT, file);
+
+ const ownerDir = NODE_ONLY_DIRS.find((dir) => file.startsWith(`${dir}${path.sep}`));
+ if (ownerDir) {
+ offenders.push(`${where} belongs to Node-only ${path.relative(PACKAGE_ROOT, ownerDir)}`);
+ continue;
+ }
+
+ const source = stripComments(readFileSync(file, 'utf8'));
+ const global = source.match(NODE_GLOBAL);
+ if (global) offenders.push(`${where} uses ${global[0]}`);
+
+ for (const specifier of staticValueImports(source)) {
+ if (NODE_BUILTINS.has(specifier)) {
+ offenders.push(`${where} -> ${specifier}`);
+ } else if (specifier.startsWith('.')) {
+ const resolved = resolveRelative(file, specifier);
+ if (resolved) queue.push(resolved);
+ }
+ }
+ }
+ return offenders;
+};
+
+describe('runtime boundary', () => {
+ it('lists only real entries as browser entries', () => {
+ expect(BROWSER_ENTRIES.filter((entry) => !(entry in exportTargets))).toEqual([]);
+ });
+
+ it.each(BROWSER_ENTRIES)('browser entry %s reaches no Node code', (entry) => {
+ expect(collectNodeReach(entryFile(entry))).toEqual([]);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/claudeCodeDirectEnv.test.ts b/packages/heterogeneous-agents/src/spawn/claudeCodeDirectEnv.test.ts
similarity index 100%
rename from packages/heterogeneous-agents/src/claudeCodeDirectEnv.test.ts
rename to packages/heterogeneous-agents/src/spawn/claudeCodeDirectEnv.test.ts
diff --git a/packages/heterogeneous-agents/src/claudeCodeDirectEnv.ts b/packages/heterogeneous-agents/src/spawn/claudeCodeDirectEnv.ts
similarity index 83%
rename from packages/heterogeneous-agents/src/claudeCodeDirectEnv.ts
rename to packages/heterogeneous-agents/src/spawn/claudeCodeDirectEnv.ts
index 4f45e560ab5..d1b418e0fb2 100644
--- a/packages/heterogeneous-agents/src/claudeCodeDirectEnv.ts
+++ b/packages/heterogeneous-agents/src/spawn/claudeCodeDirectEnv.ts
@@ -1,22 +1,5 @@
import type { AiProviderSDKType } from '@lobechat/types';
-export const HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR =
- 'Heterogeneous agent provider binding is only supported for Desktop local execution.';
-
-/**
- * Desktop main resolves the binding's providerId in the PERSONAL scope only
- * (deliberately no workspace header β€” see `providerBindingPort`). A workspace
- * agent's binding would have been configured against workspace-scoped
- * providers, so running it locally could silently resolve a personal provider
- * that shares the same id (builtin ids like `anthropic` collide across scopes)
- * and bill the wrong account. Blocked before IPC for every entry point.
- */
-export const HETEROGENEOUS_PROVIDER_BINDING_PERSONAL_ONLY_ERROR =
- 'Heterogeneous agent provider binding is not supported for workspace agents.';
-
-/** @deprecated Use HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR. */
-export const CLAUDE_CODE_API_LOCAL_ONLY_ERROR = HETEROGENEOUS_PROVIDER_BINDING_LOCAL_ONLY_ERROR;
-
export interface BuildClaudeCodeDirectEnvInput {
/** Decrypted provider credentials. This function is for trusted local execution only. */
keyVaults?: Record<string, unknown>;
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index 034444923ff..afacf7348e7 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -142,6 +142,14 @@ export { JsonlStreamProcessor } from './jsonlProcessor';
// `resolveCliSpawnPlan`), so pulling it in would break unrelated suites at
// import time. Import it from the dedicated `@lobechat/heterogeneous-agents/
// resolveCliCommand` subpath instead.
+export {
+ buildClaudeCodeDirectEnv,
+ type BuildClaudeCodeDirectEnvInput,
+ type BuildClaudeCodeDirectEnvResult,
+ normalizeAnthropicSdkBaseURL,
+ sanitizeClaudeCodeDirectArgs,
+ sanitizeClaudeCodeDirectEnv,
+} from './claudeCodeDirectEnv';
export {
ensureClaudeCodeResumeTranscript,
type EnsureResumeTranscriptReason,
diff --git a/tsconfig.json b/tsconfig.json
index 34f4836e74b..692832b13a0 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -48,7 +48,8 @@
".temp",
"e2e/**",
"knip.ts",
- "packages/alint/fixtures/**"
+ "packages/alint/fixtures/**",
+ "packages/*/alint/fixtures/**"
],
"include": [
"src/**/*.d.ts",