Skip to content

feat(x): enforce daily and monthly X API cost limits - #165351

Merged
steipete merged 1 commit into
mainfrom
steipete/x-cost-limits
Oct 5, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/x-cost-limits

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The X channel could make paid API calls without an account budget, including fetching 100 conversation posts when much less context was requested.

User Impact

Accounts default to $100 per UTC day and $1,000 per billing cycle, with inherited costLimits.dailyUsd, monthlyUsd, and cycleStartDay settings. Zero blocks paid calls. Channel status and the X replies page show spend, limits, and reset timing. Unaffordable polls pause, thread context degrades with an explicit notice, and unaffordable replies fail without retries.

Activity streaming closes below a fixed $0.50 headroom and uses gated polling until reset. Already delivered events remain charged and admitted, so a provider burst can exceed a limit; headroom reduces that risk but is not a hard bound. Model tokens are outside these limits.

Why This Change Was Made

One plugin-owned SQLite ledger persists integer micro-dollar reservations before dispatch and serializes account mutations. Responses settle against returned resources; lost responses, 5xx, malformed successes, and interrupted reservations retain their maximum cost. Cross-midnight requests count toward both days but once within a shared cycle, including after restart.

Search respects the requested context allowance, and mentions use ten-post pages with a persisted continuation. Received mentions survive budget pauses and recoverable backfill, recipient, and pagination errors. Invalid continuations are cleared without advancing the cursor; uncertain recipients remain queued for verification.

Accounting deliberately ignores X's daily resource deduplication and counts expanded users, including Activity expansions, because their billing is unconfirmed. X's Activity and pricing pages disagree about post.delete; all post.* events are conservatively counted. Published rate inputs come from the maintainer's verified pricing facts and are documented in one module.

Evidence

  • X suite: 171 tests passed across 15 files in 166.11 seconds wall time (pnpm test extensions/x --maxWorkers=1). After final lint cleanup, all 46 affected transport/monitor tests passed again in 54.45 seconds. Both extension typechecks were rerun and passed.
  • Production/test extension typechecks, typed lint, formatting, whitespace, config docs/channel/schema/inventory checks, and docs examples/links/MDX passed. Required generated config artifacts are refreshed.
  • A real worker-backed SQLite proof passed in 35.73 seconds across two fresh processes, with independent SQLite reads and integrity checks. It verified fresh state, interrupted reservations, exact cross-midnight cycle totals, legacy cursor compatibility, actual polling from a persisted continuation, exact settlement, and persisted deferred-recipient queue data. No SQL schema migration is introduced. Recipient resolution and agent dispatch use the controlled runtime tests, not this storage harness.
  • Regression controls demonstrated the search over-read, malformed-lookup undercount, and buffered/partial-page event loss before their fixes. Tests use controlled fetches, promises, and clocks; no real X requests or invoice comparison were performed.
  • Synthetic before/after captures show the actual current guest UI with spend cards added. The guest toggle was inspected and preserves the spend display.

The full build passed before conflict integration (1 hour 19 seconds, mostly declaration generation); affected tests and static checks were rerun afterward. Conflicts were resolved while retaining Activity authentication/envelopes (#165337), guest mode (#165354), and periodic backfill/unparsed-event diagnostics (#165376). Only polls advance the cursor; an in-flight paid poll settles before stream teardown. Guest quota admission follows deferred-recipient verification. Generated config/UI metadata and guest-aware before/after screenshots were refreshed.

Fresh full-scope independent Codex review is scoped-clean at P2 and above. Replacement head: cedd3524651ae14b2694928047ba2d1f5eede2d7. The exact-head native review checkout passed all 171 tests in 104.39 seconds. CI run 37289170037 passed in 489 seconds (43 jobs passed, 23 skipped), and Security Review 37288987038 passed. Native review artifacts validate with zero findings. Both final PR images render correctly.

Before: X replies with guest controls

After: guest controls and API spend limits

@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: x size: XL labels Oct 5, 2026
@steipete
steipete marked this pull request as ready for review October 5, 2026 05:21
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 5, 2026, 5:26 AM ET / 09:26 UTC (Revision 5).

ClawSweeper review

What this changes

The X plugin adds persistent account spending limits, budget-aware reads and replies, resumable mention processing, and operator-visible spend totals.

Merge readiness

⛔ Blocked before merge - 3 items remain

The work remains useful and is not implemented on main. No concrete introduced code defect was found, but the repository’s external-API proof requirement remains unresolved.

Priority: P2
Reviewed head: cedd3524651ae14b2694928047ba2d1f5eede2d7
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation and regression coverage are coherent, with useful storage and UI evidence, but required external contract proof remains incomplete.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Evidence reviewed 11 items Pinned introduced change: Reviewed the merge-base-to-head production and test hunks. The actual checkout and original PR head are cedd352; base-branch changes were excluded from ownership claims.
Work remains necessary: Fetched main has no costLimits schema or spend-owner files. The related merged Activity, guest-mode, and backfill PRs implement adjacent behavior rather than account cost enforcement.
Latest release boundary: The latest release’s extensions tree contains no X plugin. This corrects any implication that the new ceilings replace a shipped unlimited-X contract; currently configured main-branch accounts can nevertheless acquire the new defaults.
Findings None None.
Security None None.

How this fits together

The X plugin turns mentions into agent requests and posts public replies. Its API client now reserves estimated costs through a shared account ledger before dispatch, while its monitor preserves mentions during budget pauses.

flowchart TD
  A[X mentions and reply requests] --> B[X plugin API client]
  C[Account spending limits] --> D[Persistent spend ledger]
  B --> D
  D --> E{Request affordable?}
  E -->|Yes| F[X API and cost settlement]
  E -->|No| G[Pause reads or refuse replies]
  F --> H[Agent delivery and operator status]
  G --> H
Loading

Decision needed

Question Recommendation
Require authenticated X contract evidence before landing, or explicitly accept a scoped non-deployment exception for this cost-limit change? Require scoped X evidence: Establish bounded reads, resource settlement, and refusal before paid dispatch with fresh and retained account settings.

Why: The repository requires live external-API proof; accepting storage, UI, and controlled transport evidence instead requires explicit human authorization.

Before merge

  • Resolve merge risk (P1) - Currently configured X accounts without explicit limits acquire ceilings that can pause polling and refuse replies; authenticated fresh-account and retained-account transition evidence remains absent.
  • Complete next step (P2) - Provide scoped authenticated X contract evidence for fresh and retained accounts, or record an explicit maintainer non-deployment exception.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source +971, Tests +1533, Docs +87, Generated 0. Total +2591 across 37 files.

View PR surface stats
Area Files Added Removed Net
Source 17 1222 251 +971
Tests 16 1574 41 +1533
Docs 1 99 12 +87
Config 0 0 0 0
Generated 3 5 5 0
Other 0 0 0 0
Total 37 2900 309 +2591

Review metrics

Metric Value Why it matters
Budget configuration 3 new inherited fields; $100 daily and $1,000 cycle defaults Accounts without explicit settings immediately inherit operational spending ceilings.
Production versus regression coverage production +971 lines; tests and support +1,533 lines Production growth is explained by durable accounting, stream draining, continuation recovery, and spend presentation.

Stored data model

Persistent data-model change detected: migration/backfill/repair: extensions/x/src/events.ts. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Merge-risk options

Maintainer options:

  1. Validate existing account behavior (recommended)
    Demonstrate the default ceilings and explicit overrides on a retained X account alongside a fresh account.
  2. Accept the bounded validation gap
    Record an explicit scoped exception acknowledging that existing main-branch accounts can pause under the new ceilings.

Technical review

Best possible solution:

Keep one conservative spending ledger with clear operator-visible pauses and demonstrated bounded X requests for fresh and retained accounts.

Do we have a high-confidence way to reproduce the issue?

Not applicable to the spending-control feature; source confirms main lacks account budgets and requests up to 100 conversation results.

Is this the best way to solve the issue?

Yes, one plugin-owned reservation ledger is a maintainable approach; storage compatibility is supported, while the changed external contract still needs scoped proof or an exception.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 10080eaf91bc.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded X-channel spending-control improvement without an established urgent runtime regression.
  • merge-risk: 🚨 compatibility: New default ceilings can pause currently configured main-branch accounts; their authenticated transition remains unverified.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the merge-base-to-head production and test hunks. The actual checkout and original PR head are cedd352; base-branch changes were excluded from ownership claims. (cedd3524651a)
  • Work remains necessary: Fetched main has no costLimits schema or spend-owner files. The related merged Activity, guest-mode, and backfill PRs implement adjacent behavior rather than account cost enforcement. (extensions/x/src/config-schema.ts:18, 10080eaf91bc)
  • Latest release boundary: The latest release’s extensions tree contains no X plugin. This corrects any implication that the new ceilings replace a shipped unlimited-X contract; currently configured main-branch accounts can nevertheless acquire the new defaults. (fc23bc864e45)
  • Reservation and recovery owner: Paid requests reserve capacity before OAuth and final fetch dispatch. One plugin-owned keyed-store ledger serializes account operations, retains uncertain reservations, and reconciles cross-midnight charges conservatively. (extensions/x/src/api.ts:350, cedd3524651a)
  • Stored-state compatibility evidence: The captured PR body reports a 35.73-second worker-backed SQLite proof across two fresh processes, including interrupted reservations, exact cycle totals, legacy cursor compatibility, persisted continuation polling, settlement, and deferred-recipient payloads. Source adds optional cursor/envelope fields and a separate ledger namespace without SQL DDL changes. (extensions/x/src/monitor.ts:70, cedd3524651a)
  • Inspected visual proof: Inspected both prepared primary-PR screenshots. The after image adds daily and cycle spend cards while retaining the enabled guest controls and allowlist. These synthetic captures establish the displayed layout, not authenticated X accounting. (extensions/x/src/control-ui.ts:222, cedd3524651a)

Likely related people:

  • Peter Steinberger: Raw commit b878998 adds extensions/x/src/send.ts:134 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b878998dbb19; files: extensions/x/src/send.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Add redacted live X output showing bounded reads, settlement, and refusal before paid dispatch for fresh and retained accounts, or obtain an explicit scoped exception. Terminal output and logs count; redact credentials, IP addresses, phone numbers, and private endpoints. Update the PR body for automatic review, or ask a maintainer for @clawsweeper re-review.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-05T05:28:01.433Z sha 5b98668 :: blocked before merge. :: none
  • reviewed 2026-10-05T05:44:38.281Z sha 5b98668 :: blocked before merge. :: none
  • reviewed 2026-10-05T08:06:58.239Z sha 6a9d778 :: blocked before merge. :: none
  • reviewed 2026-10-05T08:48:18.780Z sha 6a9d778 :: blocked before merge. :: none

@steipete
steipete force-pushed the steipete/x-cost-limits branch from 5b98668 to 6a9d778 Compare October 5, 2026 07:59
@clawsweeper clawsweeper Bot added the proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. label Oct 5, 2026
@openclaw-barnacle openclaw-barnacle Bot closed this Oct 5, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Oct 5, 2026
@clawsweeper clawsweeper Bot removed the proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. label Oct 5, 2026
@steipete
steipete force-pushed the steipete/x-cost-limits branch from 6a9d778 to cedd352 Compare October 5, 2026 09:16
@steipete
steipete merged commit a9f4779 into main Oct 5, 2026
133 checks passed
@steipete
steipete deleted the steipete/x-cost-limits branch October 5, 2026 09:55
@steipete

steipete commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

MarMarLabs added a commit to MarMarLabs/openclaw that referenced this pull request Oct 5, 2026
69 upstream commits. Upstream's X cost limits (openclaw#165351) add 8 channel
config entries. Upstream also reworked extensions/feishu/src/async.ts
(openclaw#165340) and pruned Feishu tests in bot.*.test.ts and monitor.*.test.ts
(openclaw#165438). This branch touches none of those files, and none of the 12
removed test names appears in the test files this branch adds.

Three generated files conflicted, docs/.generated/config-baseline.counts.json,
config-baseline.sha256 and src/config/bundled-channel-config-metadata.generated.ts.
All three were regenerated from this merge rather than hand-merged.
build:docker ran in a separate detached checkout of this commit. Counts are
core 2505, channel 3874 and plugin 4490, which is upstream's counts plus
this branch's two channel entries. The core and plugin hashes match
upstream/main and the channel hash is new, as predicted. The three
generated-file checks pass there.

Feishu: 101 files and 1520 tests in the extension project, 17 files and 218
tests in the database-workers project, all passing. Both counts are lower
than before this merge only because of upstream's pruning, which deletes
bot.stripBotMention.test.ts and trims bot.test.ts. The merge leaves every
Feishu test file this branch adds or changes untouched. The forwarder test
and the routing guards pass, 503 tests. tsgo:core, tsgo:extensions,
tsgo:extensions:test, tsgo:test:root, the line-cap, max-lines,
assertion-safety, database-worker, test-timeout-race and test-mock-exports
ratchets against upstream/main, oxlint and oxfmt on the 43 changed code
files all pass.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: x docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant