Skip to content

fix(auth): sync env-var-backed token credentials into agent auth store - #57137

Closed
amittell wants to merge 3 commits into
openclaw:mainfrom
amittell:fix/sync-oauth-token-env-vars
Closed

amittell wants to merge 3 commits into
openclaw:mainfrom
amittell:fix/sync-oauth-token-env-vars

Conversation

@amittell

Copy link
Copy Markdown
Contributor

Problem

When openclaw.json declares auth profiles with mode: "token" (e.g. anthropic:me.com), the actual bearer token lives in an env var loaded from credentials/*.env at gateway boot. The per-agent auth-profiles.json is written once at setup and never updated when the token refreshes.

The embedded runner (isolated sessions: scheduler jobs, sub-agents, compaction) calls discoverAuthStorage(agentDir) which reads auth-profiles.json from disk. A stale token causes every LLM request to silently time out — the runner exhausts all profiles and the 240s scheduler watchdog kills the session. Main session is unaffected (WebSocket path, live in-memory auth).

Symptoms: scheduler jobs fail with Session idle for 240s — aborted, gateway error log shows repeated embedded run failover decision: reason=timeout across all profiles.

Fix

Extend syncExternalCliCredentials (called on every auth store load) to also resolve env-var-backed token credentials. Env var name derived from profile id: anthropic:me.com → ANTHROPIC_ME_COM_TOKEN. If set and differs from stored token, patches in-memory before use.

Changes

  • src/agents/auth-profiles/external-cli-sync.ts — add syncEnvBackedTokenCredentials, called from syncExternalCliCredentials
  • src/agents/auth-profiles.external-cli-sync.test.ts — 4 new test cases; all 12 pass

schema.help.ts had the help text but schema.labels.ts was missing the label
entry, causing schema.help.quality.test.ts 'keeps labels in parity' to fail
When openclaw.json declares auth profiles with mode 'token' (e.g.
anthropic:me.com), the actual bearer token may live in an env var
loaded from credentials/*.env. The gateway's main session picks this
up at boot, but the per-agent auth-profiles.json can go stale after
a token refresh — causing all embedded runner sessions (sub-agents,
scheduler jobs, compaction) to fail with FailoverError timeout while
the main session works fine.

Extend syncExternalCliCredentials to also resolve env-var-backed token
credentials on every store load. The env var name is derived from the
profile id: 'anthropic:me.com' -> ANTHROPIC_ME_COM_TOKEN.

This ensures the embedded runner always sees the current token without
requiring external sync scripts or manual intervention.

Fixes: embedded sessions timing out after OAuth token refresh
Copilot AI review requested due to automatic review settings March 29, 2026 15:53
@amittell
amittell requested a review from a team as a code owner March 29, 2026 15:53
@aisle-research-bot

aisle-research-bot Bot commented Mar 29, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 2 potential security issue(s) in this PR:

# Severity Title
1 🟠 High Env-var token copied into AuthProfileStore may be persisted to auth-profiles.json in plaintext
2 🟡 Medium Config-controlled backoff maxMs can disable throttling or cause excessive sleep (DoS)
Vulnerabilities

1. 🟠 Env-var token copied into AuthProfileStore may be persisted to auth-profiles.json in plaintext

Property Value
Severity High
CWE CWE-312
Location src/agents/auth-profiles/external-cli-sync.ts:147-166

Description

syncEnvBackedTokenCredentials() reads bearer tokens from process environment and writes them into the in-memory AuthProfileStore.

This becomes a sensitive data exposure risk because the load path persists the mutated store back to disk:

  • Input: process.env[envVarName] (bearer token) derived from profileId
  • Mutation: existing.token = envValue
  • Persistence: loadAuthProfileStore() / loadAuthProfileStoreForAgent() calls syncExternalCliCredentialsTimed(...) and, when mutated, writes the store back using saveJsonFile(authPath, asStore).
  • saveJsonFile writes the full credential object; the token is not stripped unless a tokenRef is present (and syncEnvBackedTokenCredentials does not set tokenRef).

As a result, tokens intended to remain in env vars (e.g., loaded from credentials/*.env) can be written to auth-profiles.json in plaintext, increasing the chance of accidental commit, backups exposure, or local disk disclosure.

Vulnerable code:

const envVarName = profileId.toUpperCase().replace(/[:.]/g, "_") + "_TOKEN";
const envValue = process.env[envVarName]?.trim();
...
existing.token = envValue;

And persistence path:

  • src/agents/auth-profiles/store.ts writes asStore back to disk when synced is true (non-readOnly).

Recommendation

Avoid persisting env-sourced tokens to disk.

Options:

  1. Mark env-backed tokens with tokenRef and strip plaintext on save, similar to api_key handling:
​// when syncing
existing.token = envValue;
existing.tokenRef = { source: "env", provider: "default", id: envVarName };

and ensure all write paths use saveAuthProfileStore() (sanitizing) rather than saveJsonFile() directly.

  1. Do not write back the store when the only mutations come from env sync (treat as runtime-only overlay).

  2. Centralize persistence: replace saveJsonFile(authPath, asStore) in load paths with saveAuthProfileStore(asStore, agentDir) so sanitization rules are always applied.

Also consider preventing secrets from appearing in logs/telemetry by never serializing full credential objects and by keeping env-backed token values out of the store when possible.


2. 🟡 Config-controlled backoff maxMs can disable throttling or cause excessive sleep (DoS)

Property Value
Severity Medium
CWE CWE-400
Location src/agents/pi-embedded-runner/run.ts:313-323

Description

runEmbeddedPiAgent reads agents.defaults.embeddedPi.overloadBackoffMaxMs from config and uses it directly as BackoffPolicy.maxMs. There is no validation that the value is finite, positive, and within sane bounds.

Impact (if an attacker can influence runtime config, e.g., via workspace/project config or other untrusted config sources):

  • Tight retry loop / CPU spike: setting overloadBackoffMaxMs to 0 or a negative number makes computeBackoff() return <= 0, and sleepWithAbort() returns immediately for non-positive durations, causing rapid retries under overload.
  • Availability degradation: setting it to an extremely large value can cause very long sleeps before failover, reducing availability.
  • Numeric edge cases: setting it to NaN/Infinity can propagate non-finite numbers through computeBackoff() (Math.min with NaN yields NaN), potentially causing unexpected behavior or exceptions when passed to setTimeout.

Vulnerable code:

const overloadBackoffMaxMs =
  params.config?.agents?.defaults?.embeddedPi?.overloadBackoffMaxMs ?? 30_000;
const OVERLOAD_FAILOVER_BACKOFF_POLICY: BackoffPolicy = {
  initialMs: 250,
  maxMs: overloadBackoffMaxMs,
  factor: 2,
  jitter: 0.2,
};

Related sink:

  • delayMs = computeBackoff(policy, attempt) (can become <=0 or non-finite)
  • await sleepWithAbort(delayMs, ...) (no sleep when delayMs <= 0; potential error behavior for non-finite)

Recommendation

Validate and clamp overloadBackoffMaxMs before using it, and enforce bounds in the config schema.

  1. Runtime clamp (defense-in-depth):
const raw = params.config?.agents?.defaults?.embeddedPi?.overloadBackoffMaxMs;
const overloadBackoffMaxMs =
  Number.isFinite(raw) ? Math.min(Math.max(raw!, 250), 120_000) : 30_000;
  1. Schema validation (preferred): require an integer and apply bounds, e.g. (Zod):
overloadBackoffMaxMs: z.number().int().min(250).max(120_000).optional(),
  1. Optionally harden computeBackoff() to guard against non-finite policy values before returning a delay.

Analyzed PR: #57137 at commit 17a97e5

Last updated on: 2026-03-29T15:55:56Z

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M r: too-many-prs Auto-close: author has more than twenty active PRs. labels Mar 29, 2026
@greptile-apps

greptile-apps Bot commented Mar 29, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes stale token credentials in the embedded runner by extending syncExternalCliCredentials to patch in-memory token credentials from env vars on every auth store load, and independently raises the overload failover backoff ceiling from 1.5 s to 30 s (config-driven).

Key findings:

  • Regex omits hyphens (P1) — The env var derivation in syncEnvBackedTokenCredentials uses /[:.]/g, which only replaces colons and dots. All of the well-known built-in profile IDs (openai-codex:default, minimax-portal:minimax-cli, anthropic:claude-cli) contain hyphens that are left intact, producing env var names like OPENAI-CODEX_DEFAULT_TOKEN. Hyphens are invalid in POSIX shell variable names, so operators cannot set these vars from a shell script and the sync silently does nothing for those profiles. The fix is to use /[^A-Z0-9]/g after uppercasing. The stated goal of the PR (syncing anthropic:me.com tokens) is unaffected since that ID has no hyphens.
  • Test env var not cleaned up in afterEach (P2) — The "does not touch non-token profile types" test deletes process.env.OPENAI_CODEX_DEFAULT_TOKEN inline; if the assertion throws, the var leaks into later tests.
  • The overload backoff change and config schema additions are clean.

Confidence Score: 4/5

Safe to merge for the specific anthropic:me.com use case, but the hyphen-in-regex bug means env-var sync silently does nothing for profile IDs containing hyphens (most built-ins).

The P1 regex bug is a present defect on the changed code path: operators with hyphenated profile IDs will get no token sync despite following the documented convention, with no error or warning. The PR's stated motivation still works since anthropic:me.com has no hyphens, but the general mechanism is broken for any profile ID containing a hyphen.

src/agents/auth-profiles/external-cli-sync.ts line 148 — regex fix required before the feature works for profiles with hyphens.

Important Files Changed

Filename Overview
src/agents/auth-profiles/external-cli-sync.ts Adds syncEnvBackedTokenCredentials to patch stale token credentials from env vars. The env var naming regex /[:.]/g omits hyphens, causing silent sync failures for all built-in profile IDs that contain hyphens.
src/agents/auth-profiles.external-cli-sync.test.ts Adds 4 new tests for syncEnvBackedTokenCredentials. Coverage is solid, but one test leaks its env var if an assertion fails (cleanup is inline rather than in afterEach).
src/agents/pi-embedded-runner/run.ts Moves OVERLOAD_FAILOVER_BACKOFF_POLICY from a static module-level constant to a per-call computed value, raising the default backoff ceiling from 1.5s to 30s and adding a config-driven override via overloadBackoffMaxMs.
src/agents/pi-embedded-runner/run.overload-backoff.test.ts New test file validating the backoff policy shape and ceiling behaviour. Tests are clear and correctly exercise the computeBackoff cap at maxMs.
src/config/types.agent-defaults.ts Adds optional overloadBackoffMaxMs field to the embeddedPi config block with a clear JSDoc comment.
src/config/schema.base.generated.ts Generated schema entry added for agents.defaults.embeddedPi.overloadBackoffMaxMs; no issues.
src/config/schema.help.ts Help text added for overloadBackoffMaxMs; consistent with the rest of the file.
src/config/schema.labels.ts Label added for agents.defaults.embeddedPi.overloadBackoffMaxMs; no issues.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/auth-profiles/external-cli-sync.ts
Line: 148

Comment:
**Regex omits hyphens — sync silently fails for most built-in profile IDs**

The replacement regex `/[:.]/g` only replaces colons and dots, but leaves hyphens untouched. Looking at the actual constants in `src/agents/auth-profiles/constants.ts`, every well-known built-in profile ID contains a hyphen:

| profile ID | derived env var name (current) |
|---|---|
| `openai-codex:default` | `OPENAI-CODEX_DEFAULT_TOKEN` ❌ |
| `minimax-portal:minimax-cli` | `MINIMAX-PORTAL_MINIMAX-CLI_TOKEN` ❌ |
| `anthropic:claude-cli` | `ANTHROPIC_CLAUDE-CLI_TOKEN` ❌ |

A hyphen is not a valid character in a POSIX shell variable name, so operators can't set these env vars from a shell script. `process.env` would never contain the key the function is looking for, `envValue` will always be `undefined`, and the sync silently does nothing for these profiles. Only profile IDs like `anthropic:me.com` (no hyphens) work as intended.

Suggested fix — replace all non-alphanumeric characters, not just `:` and `.`:

```suggestion
    const envVarName = profileId.toUpperCase().replace(/[^A-Z0-9]/g, "_") + "_TOKEN";
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/agents/auth-profiles.external-cli-sync.test.ts
Line: 249-263

Comment:
**Env var cleanup belongs in `afterEach`, not inline**

`delete process.env.OPENAI_CODEX_DEFAULT_TOKEN` is placed at the end of the test body. If the `expect` on line 257 throws, the `delete` line is never reached and the env var leaks into subsequent tests. The other three tests in this `describe` block consistently use `afterEach` for cleanup — this one should do the same by expanding the existing `afterEach` to also delete `OPENAI_CODEX_DEFAULT_TOKEN` and removing the inline `delete` at the bottom of the test body.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix(auth): sync env-var-backed token cre..." | Re-trigger Greptile

}

// Derive the expected env var name from the profile id.
const envVarName = profileId.toUpperCase().replace(/[:.]/g, "_") + "_TOKEN";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Regex omits hyphens — sync silently fails for most built-in profile IDs

The replacement regex /[:.]/g only replaces colons and dots, but leaves hyphens untouched. Looking at the actual constants in src/agents/auth-profiles/constants.ts, every well-known built-in profile ID contains a hyphen:

profile ID derived env var name (current)
openai-codex:default OPENAI-CODEX_DEFAULT_TOKEN ❌
minimax-portal:minimax-cli MINIMAX-PORTAL_MINIMAX-CLI_TOKEN ❌
anthropic:claude-cli ANTHROPIC_CLAUDE-CLI_TOKEN ❌

A hyphen is not a valid character in a POSIX shell variable name, so operators can't set these env vars from a shell script. process.env would never contain the key the function is looking for, envValue will always be undefined, and the sync silently does nothing for these profiles. Only profile IDs like anthropic:me.com (no hyphens) work as intended.

Suggested fix — replace all non-alphanumeric characters, not just : and .:

Suggested change
const envVarName = profileId.toUpperCase().replace(/[:.]/g, "_") + "_TOKEN";
const envVarName = profileId.toUpperCase().replace(/[^A-Z0-9]/g, "_") + "_TOKEN";
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/auth-profiles/external-cli-sync.ts
Line: 148

Comment:
**Regex omits hyphens — sync silently fails for most built-in profile IDs**

The replacement regex `/[:.]/g` only replaces colons and dots, but leaves hyphens untouched. Looking at the actual constants in `src/agents/auth-profiles/constants.ts`, every well-known built-in profile ID contains a hyphen:

| profile ID | derived env var name (current) |
|---|---|
| `openai-codex:default` | `OPENAI-CODEX_DEFAULT_TOKEN` ❌ |
| `minimax-portal:minimax-cli` | `MINIMAX-PORTAL_MINIMAX-CLI_TOKEN` ❌ |
| `anthropic:claude-cli` | `ANTHROPIC_CLAUDE-CLI_TOKEN` ❌ |

A hyphen is not a valid character in a POSIX shell variable name, so operators can't set these env vars from a shell script. `process.env` would never contain the key the function is looking for, `envValue` will always be `undefined`, and the sync silently does nothing for these profiles. Only profile IDs like `anthropic:me.com` (no hyphens) work as intended.

Suggested fix — replace all non-alphanumeric characters, not just `:` and `.`:

```suggestion
    const envVarName = profileId.toUpperCase().replace(/[^A-Z0-9]/g, "_") + "_TOKEN";
```

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +249 to +263
it("does not touch non-token profile types", () => {
process.env.OPENAI_CODEX_DEFAULT_TOKEN = "should-not-apply";

const oauthCred = makeOAuthCredential({ provider: "openai-codex" });
const store = makeStore(OPENAI_CODEX_DEFAULT_PROFILE_ID, oauthCred);

syncExternalCliCredentials(store);

expect(store.profiles[OPENAI_CODEX_DEFAULT_PROFILE_ID]).toMatchObject({
type: "oauth",
});

delete process.env.OPENAI_CODEX_DEFAULT_TOKEN;
});
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Env var cleanup belongs in afterEach, not inline

delete process.env.OPENAI_CODEX_DEFAULT_TOKEN is placed at the end of the test body. If the expect on line 257 throws, the delete line is never reached and the env var leaks into subsequent tests. The other three tests in this describe block consistently use afterEach for cleanup — this one should do the same by expanding the existing afterEach to also delete OPENAI_CODEX_DEFAULT_TOKEN and removing the inline delete at the bottom of the test body.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/auth-profiles.external-cli-sync.test.ts
Line: 249-263

Comment:
**Env var cleanup belongs in `afterEach`, not inline**

`delete process.env.OPENAI_CODEX_DEFAULT_TOKEN` is placed at the end of the test body. If the `expect` on line 257 throws, the `delete` line is never reached and the env var leaks into subsequent tests. The other three tests in this `describe` block consistently use `afterEach` for cleanup — this one should do the same by expanding the existing `afterEach` to also delete `OPENAI_CODEX_DEFAULT_TOKEN` and removing the inline `delete` at the bottom of the test body.

How can I resolve this? If you propose a fix, please make it concise.

@openclaw-barnacle

Copy link
Copy Markdown

Closing this PR because the author has more than 10 active PRs in this repo. Please reduce the active PR queue and reopen or resubmit once it is back under the limit. You can close your own PRs to get back under the limit.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR addresses embedded-runner failures caused by stale auth credentials by syncing env-var-backed token credentials into the agent auth store, ensuring isolated/embedded sessions see refreshed tokens.

Changes:

  • Add env-var token sync logic to syncExternalCliCredentials so type: "token" profiles can be refreshed from process.env.
  • Introduce a new embedded runner tuning knob agents.defaults.embeddedPi.overloadBackoffMaxMs and use it to build the overload failover backoff policy at runtime.
  • Add/extend Vitest coverage for both the env-backed token sync and overload backoff ceiling behavior.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
src/config/types.agent-defaults.ts Adds overloadBackoffMaxMs to embedded Pi defaults config typing/docs.
src/config/schema.labels.ts Adds a UI label for the new config field.
src/config/schema.help.ts Adds help text for the new config field.
src/config/schema.base.generated.ts Adds generated metadata entry for the new config field (but schema definition needs update).
src/agents/pi-embedded-runner/run.ts Builds overload backoff policy using the new config field.
src/agents/pi-embedded-runner/run.overload-backoff.test.ts Adds unit tests around backoff clamping/ceiling behavior.
src/agents/auth-profiles/external-cli-sync.ts Adds syncEnvBackedTokenCredentials and wires it into the existing sync flow.
src/agents/auth-profiles.external-cli-sync.test.ts Adds tests for env-backed token syncing.

Comment on lines +249 to +262
it("does not touch non-token profile types", () => {
process.env.OPENAI_CODEX_DEFAULT_TOKEN = "should-not-apply";

const oauthCred = makeOAuthCredential({ provider: "openai-codex" });
const store = makeStore(OPENAI_CODEX_DEFAULT_PROFILE_ID, oauthCred);

syncExternalCliCredentials(store);

expect(store.profiles[OPENAI_CODEX_DEFAULT_PROFILE_ID]).toMatchObject({
type: "oauth",
});

delete process.env.OPENAI_CODEX_DEFAULT_TOKEN;
});

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

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

This test mutates process.env.OPENAI_CODEX_DEFAULT_TOKEN and then deletes it, which can clobber an existing value in the environment and affect later tests. Use vi.stubEnv or restore the previous value instead of unconditional delete.

Copilot uses AI. Check for mistakes.
Comment on lines +147 to +150
// Derive the expected env var name from the profile id.
const envVarName = profileId.toUpperCase().replace(/[:.]/g, "_") + "_TOKEN";
const envValue = process.env[envVarName]?.trim();
if (!envValue) {

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

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

envVarName derivation only replaces : and ., but profile IDs commonly contain other characters (e.g. provider IDs like github-copilot:default include -). That yields env var names with -, which generally cannot be set from a shell/dotenv file, so the sync will silently never apply for those profiles. Consider normalizing by replacing all non [A-Z0-9_] characters with _ (or explicitly validating profileId format and documenting the limitation).

Copilot uses AI. Check for mistakes.
help: "Embedded Pi runner hardening controls for how workspace-local Pi settings are trusted and applied in OpenClaw sessions.",
tags: ["advanced"],
},
"agents.defaults.embeddedPi.overloadBackoffMaxMs": {

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

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

This new metadata entry is missing a label field (neighboring entries include one), so consumers that rely on schema.base.generated.ts for labels may display an empty/fallback label. Also, the actual JSON schema section for agents.defaults.embeddedPi currently only allows projectSettingsPolicy (additionalProperties=false), so overloadBackoffMaxMs won't validate/round-trip until it is added to the schema properties and the file is regenerated.

Suggested change
"agents.defaults.embeddedPi.overloadBackoffMaxMs": {
"agents.defaults.embeddedPi.overloadBackoffMaxMs": {
label: "Embedded Pi Overload Backoff Max (ms)",

Copilot uses AI. Check for mistakes.
Comment on lines +316 to +323
const overloadBackoffMaxMs =
params.config?.agents?.defaults?.embeddedPi?.overloadBackoffMaxMs ?? 30_000;
const OVERLOAD_FAILOVER_BACKOFF_POLICY: BackoffPolicy = {
initialMs: 250,
maxMs: overloadBackoffMaxMs,
factor: 2,
jitter: 0.2,
};

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

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

overloadBackoffMaxMs is read directly from config and used as BackoffPolicy.maxMs without any runtime validation. If config validation currently rejects this field (schema needs updating) or the value is non-finite/<=0, computeBackoff can produce NaN/0 delays and alter retry behavior unexpectedly. Suggest ensuring the config schema includes this field (integer, min>0) and defensively clamping/coercing here before building the backoff policy.

Copilot uses AI. Check for mistakes.
Comment on lines +313 to +320
// Read config override if available — default 30s ceiling.
// A higher ceiling preserves the retry budget under sustained overload;
// operators with many auth profiles can lower this for faster rotation.
const overloadBackoffMaxMs =
params.config?.agents?.defaults?.embeddedPi?.overloadBackoffMaxMs ?? 30_000;
const OVERLOAD_FAILOVER_BACKOFF_POLICY: BackoffPolicy = {
initialMs: 250,
maxMs: overloadBackoffMaxMs,

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

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

PR description focuses on syncing env-var-backed token credentials into the auth store, but this hunk also changes embedded runner overload failover behavior (new config overloadBackoffMaxMs and default max backoff 30s). Please either update the PR description to include this behavior change or split it into a separate PR so the review surface matches the stated intent.

Copilot uses AI. Check for mistakes.
Comment on lines +5 to +9
* Tests for the OVERLOAD_FAILOVER_BACKOFF_POLICY ceiling and config-driven override.
*
* The policy is built inside `runEmbeddedPiAgent` from
* `params.config?.agents?.defaults?.embeddedPi?.overloadBackoffMaxMs ?? 30_000`.
* These tests verify the policy shape and that `computeBackoff` respects `maxMs`.

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

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

The comment says these tests verify the policy built inside runEmbeddedPiAgent, but the tests only construct a local BackoffPolicy and exercise computeBackoff. That doesn't actually assert the wiring from params.config?...overloadBackoffMaxMs into the runner. Consider extracting the policy builder into an exported helper (or adding a focused runner test) so the test fails if runEmbeddedPiAgent stops honoring the config.

Suggested change
* Tests for the OVERLOAD_FAILOVER_BACKOFF_POLICY ceiling and config-driven override.
*
* The policy is built inside `runEmbeddedPiAgent` from
* `params.config?.agents?.defaults?.embeddedPi?.overloadBackoffMaxMs ?? 30_000`.
* These tests verify the policy shape and that `computeBackoff` respects `maxMs`.
* Tests for the overload failover backoff policy ceiling and a config-style override.
*
* These tests exercise `computeBackoff` with policies shaped like the default runner
* policy (maxMs = 30_000) and a hypothetical override (e.g. maxMs = 500), and verify
* that `computeBackoff` respects the `maxMs` ceiling for those shapes.
*
* Note: these tests do not exercise the wiring inside `runEmbeddedPiAgent`; they
* only validate the behavior of `computeBackoff` given a `BackoffPolicy`.

Copilot uses AI. Check for mistakes.
Comment on lines +186 to +190

afterEach(() => {
delete process.env[ENV_KEY];
});

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

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

This afterEach unconditionally deletes process.env[ENV_KEY] without restoring any prior value. If a developer/test runner environment happens to have ANTHROPIC_ME_COM_TOKEN set, this can leak state across tests and cause order-dependent failures. Prefer vi.stubEnv (auto-restored) or capture/restore the previous value in beforeEach/afterEach.

Suggested change
afterEach(() => {
delete process.env[ENV_KEY];
});
let originalEnvValue: string | undefined;
beforeEach(() => {
originalEnvValue = process.env[ENV_KEY];
delete process.env[ENV_KEY];
});
afterEach(() => {
if (originalEnvValue === undefined) {
delete process.env[ENV_KEY];
} else {
process.env[ENV_KEY] = originalEnvValue;
}
});

Copilot uses AI. Check for mistakes.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 17a97e50d5

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +316 to +317
const overloadBackoffMaxMs =
params.config?.agents?.defaults?.embeddedPi?.overloadBackoffMaxMs ?? 30_000;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Accept overloadBackoffMaxMs in agent defaults schema

This new override is read at runtime, but it is never added to the strict config validator (embeddedPi in src/config/zod-schema.agent-defaults.ts only allows projectSettingsPolicy). As a result, users who set agents.defaults.embeddedPi.overloadBackoffMaxMs will get a config validation error instead of enabling the feature, so the advertised override is effectively unusable.

Useful? React with 👍 / 👎.

}

// Derive the expected env var name from the profile id.
const envVarName = profileId.toUpperCase().replace(/[:.]/g, "_") + "_TOKEN";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Sanitize profile IDs when deriving token env var names

The env-var derivation only replaces : and ., so profile IDs containing other non-portable characters (for example hyphenated providers like openai-codex:manual) produce names such as OPENAI-CODEX_MANUAL_TOKEN. Those keys are rejected by the runtime dotenv loader, which only accepts portable env keys ([A-Za-z_][A-Za-z0-9_]*), so token sync silently fails for those profiles and stale tokens remain in the auth store.

Useful? React with 👍 / 👎.

amittell added a commit to amittell/openclaw that referenced this pull request Aug 21, 2026
…oken credentials into auth store)

Upstream PR openclaw#57137 (head 17a97e5)
was barnacle-closed unmerged and absent from the carried stack; symptom verified
live on beta.2 HEAD (stale persisted token makes isolated/embedded runs fail every
LLM request until session abort).

Re-derived for the beta.2 layout:
- new syncEnvBackedTokenCredentials(store, {env}) in external-cli-sync.ts:
  profile-id -> env var naming convention (ANTHROPIC_ME_COM_TOKEN), skips
  secret-ref-backed (${ENV} template or tokenRef) and non-token profiles,
  no-op when env var unset or already matching, returns a fresh store clone
- syncPersistedExternalCliAuthProfiles composes it before the CLI-candidate
  path so env-token sync applies even when no external CLI profiles exist
- new test auth-profiles.env-token-sync.test.ts (11 cases)

Verification: 22/22 tests green (incl. the 11 new); no dangling refs.
(Recovered from a crashed dispatch: gpufarm model outage 2026-08-20 23:02-23:04
killed the re-derive job mid-test; source was complete and coherent, one test
callback missing async.)
amittell added a commit to amittell/openclaw that referenced this pull request Aug 21, 2026
amittell added a commit to amittell/openclaw that referenced this pull request Aug 21, 2026
…session runs)

Upstream PR openclaw#75662 (head 990fca0)
was amittell-authored, closed unmerged; never in main. Symptom verified live at
branch HEAD: a main session ended via sessions_yield persists status "running"
(no explicit paused projection, no pauseReason), so dashboards, restart
recovery, and follow-up turns cannot distinguish a queued continuation from an
active model turn and race it.

Re-derived for the beta.2 layout (key adaptations vs the old upstream main):
- SessionRunStatus now derives from the gateway-protocol TypeBox
  SessionRowSchema (sessions-row.ts): added Type.Literal("paused") to status
  + optional pauseReason ("sessions_yield"); the derived type cascades to
  SessionEntry.status, sessions-helpers, session-utils.types, and the UI
  re-export — no per-file union edits needed
- protocol artifacts regenerated (pnpm protocol:gen[:swift|:kotlin]):
  GatewayModels.swift gains the pausereason field exactly as upstream
- src/gateway/session-lifecycle-state.ts: yieldedWaiting terminal events now
  project status "paused" + pauseReason "sessions_yield" (error/aborted ends
  still resolve terminally; the marker is gated on the derived status so it
  cannot leak into failed rows); start events clear pauseReason
- broadcast/row plumbing: server-chat.ts snapshotSource.pauseReason,
  session-event-payload.ts pauseReason field, session-utils-row.ts
  buildGatewaySessionRow entry.pauseReason, session-utils.types.ts row type
- src/config/sessions/types.ts: SessionEntry.pauseReason +
  isTerminalSessionStatus now excludes "paused" (nonterminal)
- src/config/sessions/lifecycle.ts:
  resolveTerminalMainSessionTranscriptRegistryCheck skips paused main
  sessions (even with a positive endedAt) so transcript freshness/rotation
  cannot run while the continuation is pending
- src/agents/main-session-recovery/main-session-recovery-state.ts:
  isMainRestartRecoveryCandidate rejects pauseReason "sessions_yield" so
  restart recovery does not force a "[System] previous turn interrupted"
  resume that races the queued continuation
- sessions-list-tool readSessionRunStatus accepts "paused"
- session-entry-slot-keys.ts reserves pauseReason
- UI: isSessionRunActive treats paused as active (nonterminal);
  session-run-state/reconcile status parsing; workboard lifecycle +
  card-actions route through isSessionRunActive; sessions view badge shows
  the explicit Paused label (idle tone, not live); lobster pet outcome skips
  paused rows; en.ts statusPaused + pnpm ui:i18n:sync catalog artifacts
  (statusPaused already in translation memory)
- Superseded upstream pieces NOT re-derived: main-session-restart-recovery.ts
  markRestartAbortedMainSessionsFromLocks second test (function retired by the
  openclaw#121969 re-architecture; isMainRestartRecoveryCandidate now gates the
  marking path), ui i18n meta fallbackKeys/totalKeys edits (beta.2 uses
  generated catalog baseline files instead), CHANGELOG.md (frozen convention)

Tests: session-lifecycle-state.test.ts (yielded -> paused + no pauseReason
leak on terminals + start clears marker), main-session-restart-recovery.test.ts
(+skip for sessions_yield-paused entries; cleaned-locks variant superseded),
lifecycle.test.ts (+paused transcript-registry-check skips),
session-run-state/reconcile/workboard UI tests (+paused cases).
Verification: 632/632 main-session-recovery suite; 121 lifecycle-state+
lifecycle; 210 UI session-run-state/reconcile/workboard; 487
server-methods/sessions-list/sessions; 922 session utils+message events;
122 chat run-lifecycle; i18n check clean. tsgo core: 5 errors, ALL
pre-existing at HEAD (auth-profiles log + terminal-resolution, recovered
openclaw#57137 stack) — error set byte-identical before/after this change (DIFF=0);
this change adds zero new type errors.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling r: too-many-prs Auto-close: author has more than twenty active PRs. size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants