Skip to content

feat: expose model pricing to plugins via runtime.usage API - #64436

Closed
dodge1218 wants to merge 3 commits into
openclaw:mainfrom
dodge1218:feat/plugin-cost-api
Closed

dodge1218 wants to merge 3 commits into
openclaw:mainfrom
dodge1218:feat/plugin-cost-api

Conversation

@dodge1218

@dodge1218 dodge1218 commented Apr 10, 2026 •

Copy link
Copy Markdown

Summary

Adds a runtime.usage namespace to the plugin runtime, exposing resolveModelCostConfig() and estimateUsageCost() so context engine plugins can calculate model-cost estimates from OpenClaw's configured pricing instead of hardcoded heuristics.

Motivation

Context engine plugins, such as ContextClaw, truncate stale or large context to save tokens. Today they can only estimate savings with a fixed heuristic. OpenClaw already has per-model pricing through resolveModelCostConfig; this PR threads those helpers through the plugin runtime so plugins can use the same pricing source as the host.

Changes

  • src/plugins/runtime/runtime-usage.ts — adds the runtime usage facade.
  • src/plugins/runtime/types-core.ts — adds the usage namespace to PluginRuntimeCore.
  • src/plugins/runtime/index.ts — wires createRuntimeUsage() into runtime assembly.
  • src/plugin-sdk/test-helpers/plugin-runtime-mock.ts — updates the plugin runtime mock.
  • src/plugins/runtime/index.test.ts — asserts the runtime exposes both usage helpers.
  • docs/plugins/sdk-runtime.md — documents the plugin SDK usage helpers.
  • docs/.generated/plugin-sdk-api-baseline.sha256 — regenerates the public SDK API baseline.

Real Behavior Proof

  • Behavior or issue addressed: A plugin can access the new api.runtime.usage namespace and call both pricing helpers without importing OpenClaw internals.

  • Real environment tested: Local OpenClaw checkout on branch feat/plugin-cost-api at 39b243468f, after rebasing onto upstream main and narrowing the PR to the plugin runtime/docs/test surface.

  • Exact steps or command run after this patch:

pnpm exec tsx .artifacts/pr64436-runtime-usage-proof/run-direct-plugin-api-proof.ts
  • Evidence after fix: Terminal output from a minimal external plugin fixture with openclaw.plugin.json plus index.mjs; its register(api) calls api.runtime.usage.resolveModelCostConfig(...) and api.runtime.usage.estimateUsageCost(...).
[proof] repoHead=39b243468f
[proof] pluginDir=/tmp/openclaw-runtime-usage-direct-ile3Im
[proof] manifest=/tmp/openclaw-runtime-usage-direct-ile3Im/openclaw.plugin.json
[plugin] id=runtime-usage-proof
[plugin] hasRuntimeUsage=true
[plugin] resolveModelCostConfig cost={"input":3,"output":15,"cacheRead":0.3,"cacheWrite":3.75}
[plugin] estimateUsageCost total=0.010950
[proof] PASS plugin register(api) called both api.runtime.usage helpers
  • Observed result after fix: The plugin saw api.runtime.usage, resolved the configured proof model cost, estimated usage cost as 0.010950, and exited with the PASS line above.

  • What was not tested: Full OpenClaw app startup and provider billing reconciliation; this proof is scoped to the plugin runtime API surface added by this PR.

Local Verification

  • git diff --check upstream/main...HEAD
  • NODE_OPTIONS=--max-old-space-size=8192 node --import tsx scripts/generate-plugin-sdk-api-baseline.ts --check
  • pnpm format:check docs/.generated/plugin-sdk-api-baseline.sha256 docs/plugins/sdk-runtime.md src/plugins/runtime/index.test.ts src/plugins/runtime/index.ts src/plugins/runtime/types-core.ts src/plugins/runtime/runtime-usage.ts src/plugin-sdk/test-helpers/plugin-runtime-mock.ts
  • pnpm exec vitest run src/plugins/runtime/index.test.ts -t 'exposes runtime.usage pricing helpers' --reporter=dot

Related

@greptile-apps

greptile-apps Bot commented Apr 10, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR threads two existing utility functions — resolveModelCostConfig and estimateUsageCost from src/utils/usage-format.ts — into the plugin runtime as a new runtime.usage namespace, following the established createRuntime* pattern. The implementation itself is clean and minimal, but the plugin-sdk-api-baseline.sha256 hash was not regenerated after the public PluginRuntime type gained the new usage field, which will cause pnpm plugin-sdk:api:check to fail in CI.

Confidence Score: 4/5

Safe to merge after running pnpm plugin-sdk:api:gen and committing the updated docs/.generated/plugin-sdk-api-baseline.sha256.

The implementation is correct and follows established patterns. The single P1 finding — a missing plugin SDK API baseline hash regeneration — will cause a CI failure on pnpm plugin-sdk:api:check but does not affect runtime behavior. Once that one-command fix is committed, the PR is ready.

src/plugins/runtime/types-core.ts — changing PluginRuntimeCore requires regenerating docs/.generated/plugin-sdk-api-baseline.sha256.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/plugins/runtime/types-core.ts
Line: 111-116

Comment:
**Missing plugin-sdk API baseline update**

`PluginRuntimeCore.usage` is exposed as `PluginRuntime` on the `core` SDK entrypoint (`src/plugin-sdk/core.ts` line 147), so this addition changes the public plugin SDK surface tracked by `docs/.generated/plugin-sdk-api-baseline.sha256`. The hash file was not regenerated in this PR, which means `pnpm plugin-sdk:api:check` will fail in CI.

Per CLAUDE.md: "If you change config schema/help or the public Plugin SDK surface, run the matching gen command and commit the updated `.sha256` hash file." Run `pnpm plugin-sdk:api:gen` and commit the updated `docs/.generated/plugin-sdk-api-baseline.sha256` before merging.

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

---

This is a comment left during a code review.
Path: test/helpers/plugins/plugin-runtime-mock.ts
Line: 382-386

Comment:
**Overly broad mock cast via `as unknown as`**

Both mock functions use a double-cast through `unknown` to satisfy the type. A narrow inline type annotation or typed `vi.fn<..., ...>()` call would be safer and consistent with stronger typing in the rest of this file. The `as unknown as` pattern suppresses type errors silently, so a typo in the return type would go undetected.

```suggestion
      resolveModelCostConfig: vi.fn(
        (_params: Parameters<PluginRuntime["usage"]["resolveModelCostConfig"]>[0]) => undefined,
      ) as PluginRuntime["usage"]["resolveModelCostConfig"],
      estimateUsageCost: vi.fn(
        (_params: Parameters<PluginRuntime["usage"]["estimateUsageCost"]>[0]) => undefined,
      ) as PluginRuntime["usage"]["estimateUsageCost"],
```

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

Reviews (1): Last reviewed commit: "feat: expose model pricing to plugins vi..." | Re-trigger Greptile

Comment on lines +111 to +116
usage: {
/** Resolve per-token pricing for a provider/model pair. Returns undefined when pricing is unknown. */
resolveModelCostConfig: typeof import("../../utils/usage-format.js").resolveModelCostConfig;
/** Estimate total cost in USD from token usage and a cost config. */
estimateUsageCost: typeof import("../../utils/usage-format.js").estimateUsageCost;
};

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 Missing plugin-sdk API baseline update

PluginRuntimeCore.usage is exposed as PluginRuntime on the core SDK entrypoint (src/plugin-sdk/core.ts line 147), so this addition changes the public plugin SDK surface tracked by docs/.generated/plugin-sdk-api-baseline.sha256. The hash file was not regenerated in this PR, which means pnpm plugin-sdk:api:check will fail in CI.

Per CLAUDE.md: "If you change config schema/help or the public Plugin SDK surface, run the matching gen command and commit the updated .sha256 hash file." Run pnpm plugin-sdk:api:gen and commit the updated docs/.generated/plugin-sdk-api-baseline.sha256 before merging.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/plugins/runtime/types-core.ts
Line: 111-116

Comment:
**Missing plugin-sdk API baseline update**

`PluginRuntimeCore.usage` is exposed as `PluginRuntime` on the `core` SDK entrypoint (`src/plugin-sdk/core.ts` line 147), so this addition changes the public plugin SDK surface tracked by `docs/.generated/plugin-sdk-api-baseline.sha256`. The hash file was not regenerated in this PR, which means `pnpm plugin-sdk:api:check` will fail in CI.

Per CLAUDE.md: "If you change config schema/help or the public Plugin SDK surface, run the matching gen command and commit the updated `.sha256` hash file." Run `pnpm plugin-sdk:api:gen` and commit the updated `docs/.generated/plugin-sdk-api-baseline.sha256` before merging.

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

Comment on lines +382 to +386
resolveModelCostConfig: vi.fn(
() => undefined,
) as unknown as PluginRuntime["usage"]["resolveModelCostConfig"],
estimateUsageCost: vi.fn(
() => undefined,

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 Overly broad mock cast via as unknown as

Both mock functions use a double-cast through unknown to satisfy the type. A narrow inline type annotation or typed vi.fn<..., ...>() call would be safer and consistent with stronger typing in the rest of this file. The as unknown as pattern suppresses type errors silently, so a typo in the return type would go undetected.

Suggested change
resolveModelCostConfig: vi.fn(
() => undefined,
) as unknown as PluginRuntime["usage"]["resolveModelCostConfig"],
estimateUsageCost: vi.fn(
() => undefined,
resolveModelCostConfig: vi.fn(
(_params: Parameters<PluginRuntime["usage"]["resolveModelCostConfig"]>[0]) => undefined,
) as PluginRuntime["usage"]["resolveModelCostConfig"],
estimateUsageCost: vi.fn(
(_params: Parameters<PluginRuntime["usage"]["estimateUsageCost"]>[0]) => undefined,
) as PluginRuntime["usage"]["estimateUsageCost"],
Prompt To Fix With AI
This is a comment left during a code review.
Path: test/helpers/plugins/plugin-runtime-mock.ts
Line: 382-386

Comment:
**Overly broad mock cast via `as unknown as`**

Both mock functions use a double-cast through `unknown` to satisfy the type. A narrow inline type annotation or typed `vi.fn<..., ...>()` call would be safer and consistent with stronger typing in the rest of this file. The `as unknown as` pattern suppresses type errors silently, so a typo in the return type would go undetected.

```suggestion
      resolveModelCostConfig: vi.fn(
        (_params: Parameters<PluginRuntime["usage"]["resolveModelCostConfig"]>[0]) => undefined,
      ) as PluginRuntime["usage"]["resolveModelCostConfig"],
      estimateUsageCost: vi.fn(
        (_params: Parameters<PluginRuntime["usage"]["estimateUsageCost"]>[0]) => undefined,
      ) as PluginRuntime["usage"]["estimateUsageCost"],
```

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

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Apr 26, 2026
@clawsweeper

clawsweeper Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed July 5, 2026, 3:48 PM ET / 19:48 UTC.

Summary
The PR adds api.runtime.usage pricing helpers to the plugin runtime, plus SDK docs, a runtime mock update, and a runtime-shape test.

PR surface: Source +25, Tests +9, Docs +32. Total +66 across 6 files.

Reproducibility: yes. for the review defects by source inspection: the PR adds PluginRuntimeCore.usage, while the lazy runtime reflection key list and current SDK API baseline are not updated for that public surface. The feature request itself is not a current-main bug, and the contributor supplied terminal proof for direct runtime access.

Review metrics: 1 noteworthy metric.

  • Plugin SDK runtime namespace: 1 added. A new api.runtime.usage namespace becomes public plugin compatibility surface after release.

Merge readiness
Overall: 🦐 gold shrimp
Proof: 🦞 diamond lobster
Patch quality: 🦐 gold shrimp
Result: needs maintainer review before merge.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P2] Add usage to lazy runtime reflection and extend the loader reflection test if maintainers accept the API shape.
  • Rebase onto current main and regenerate docs/.generated/plugin-sdk-api-baseline.sha256.
  • Get maintainer acceptance of the public pricing helper signatures or narrow the DTO before release.

Risk before merge

  • [P1] The raw resolveModelCostConfig and estimateUsageCost signatures become stable plugin SDK contract after release, so maintainers need to accept or narrow that API before merge.
  • [P1] Plugins that use runtime reflection for feature detection can miss usage unless the lazy proxy key list and reflection test are updated.
  • [P1] The SDK API baseline must be regenerated on current main after the public runtime type changes, otherwise the baseline no longer audits the shipped plugin SDK surface.

Maintainer options:

  1. Accept API And Repair Contract Coverage
    If maintainers accept api.runtime.usage, add usage to lazy runtime reflection, extend the loader reflection test, and regenerate the SDK API baseline before merge.
  2. Narrow The SDK Surface First
    If the raw helper signatures are too broad, reshape the namespace into a smaller DTO/helper contract before release so external plugins do not depend on internals accidentally.
  3. Pause For SDK Direction (recommended)
    Leave this PR open for maintainer API-boundary acceptance rather than letting automation choose the permanent plugin pricing contract.

Next step before merge

  • The remaining blocker is maintainer acceptance of the public plugin pricing API shape; the mechanical repairs should wait for that direction.

Security
Cleared: No concrete security or supply-chain concern found; the diff adds a runtime facade, docs, tests, and mocks without dependency, workflow, secret, package-resolution, or code-download changes.

Review findings

  • [P2] Expose usage through lazy runtime reflection — src/plugins/runtime/types-core.ts:309-314
  • [P2] Regenerate the SDK API baseline on current main — src/plugins/runtime/types-core.ts:309-314
Review details

Best possible solution:

Merge only after maintainers accept or narrow the plugin-facing pricing API shape, then update lazy runtime reflection, extend the loader reflection test, and regenerate the SDK API baseline against current main.

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

Yes for the review defects by source inspection: the PR adds PluginRuntimeCore.usage, while the lazy runtime reflection key list and current SDK API baseline are not updated for that public surface. The feature request itself is not a current-main bug, and the contributor supplied terminal proof for direct runtime access.

Is this the best way to solve the issue?

Unclear as final product direction: api.runtime is the right boundary if OpenClaw wants to expose pricing helpers, but the raw helper signatures need maintainer acceptance before becoming a stable SDK contract. If accepted, the narrow repair is to update lazy reflection, extend the loader reflection test, and regenerate the baseline.

Full review comments:

  • [P2] Expose usage through lazy runtime reflection — src/plugins/runtime/types-core.ts:309-314
    Adding usage to PluginRuntimeCore makes it a public runtime namespace, but plugin registration receives api.runtime through the lazy proxy in src/plugins/loader.ts. That proxy's ownKeys() returns LAZY_RUNTIME_REFLECTION_KEYS, and this PR does not add usage there or extend the reflection test, so plugins using Object.keys, Reflect.ownKeys, or descriptors for feature detection can miss the new capability even though direct access works.
    Confidence: 0.88
  • [P2] Regenerate the SDK API baseline on current main — src/plugins/runtime/types-core.ts:309-314
    This addition changes the public Plugin SDK runtime type, but the current merge result keeps current main's docs/.generated/plugin-sdk-api-baseline.sha256. Rebase onto current main and regenerate the baseline so plugin-sdk:api:check verifies the intended new surface instead of leaving API drift unaudited.
    Confidence: 0.82

Overall correctness: patch is incorrect
Overall confidence: 0.88

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against a320f775f0f3.

Label changes

Label justifications:

  • P2: This is a normal-priority additive plugin SDK feature with limited blast radius but real public API compatibility implications.
  • merge-risk: 🚨 compatibility: The PR adds a public plugin SDK runtime namespace whose helper signatures, reflection behavior, and generated API baseline external plugins may rely on after release.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body and follow-up comments provide terminal output from a minimal external plugin fixture calling both new helpers through api.runtime.usage, with successful proof-workflow comments for the PR head.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body and follow-up comments provide terminal output from a minimal external plugin fixture calling both new helpers through api.runtime.usage, with successful proof-workflow comments for the PR head.
Evidence reviewed

PR surface:

Source +25, Tests +9, Docs +32. Total +66 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 4 25 0 +25
Tests 1 9 0 +9
Docs 1 32 0 +32
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 66 0 +66

What I checked:

  • Repository policy applied: Root, plugin, plugin-SDK, and docs AGENTS.md files were read; the plugin SDK guide treats this area as public plugin contract, and root policy treats plugin API additions as compatibility-sensitive. (src/plugin-sdk/AGENTS.md:1, 010b61746379)
  • Current main does not already expose runtime.usage: Current main has internal pricing helpers and plugin runtime surfaces, but no api.runtime.usage namespace or runtime usage docs; the PR remains necessary if maintainers want this API. (src/plugins/runtime/index.ts:226, 010b61746379)
  • PR adds a public runtime namespace: The PR head adds usage to PluginRuntimeCore with resolveModelCostConfig and estimateUsageCost, making these helper signatures plugin SDK surface after release. (src/plugins/runtime/types-core.ts:309, df3fc0c91c66)
  • Lazy runtime reflection omits the new key: The loader proxy's fixed LAZY_RUNTIME_REFLECTION_KEYS list still omits usage, so direct property access works but Object.keys, Reflect.ownKeys, and descriptors can miss the new namespace. (src/plugins/loader.ts:388, ec9364ccc8c3)
  • Adjacent reflection test does not cover usage: The existing lazy-runtime reflection test checks selected namespaces such as channel, mediaUnderstanding, and llm, but the PR does not extend that contract test for usage. (src/plugins/loader.test.ts:9498, ec9364ccc8c3)
  • SDK API baseline is not updated for current main: The current-main and potential-merge docs/.generated/plugin-sdk-api-baseline.sha256 contents are identical while the PR adds PluginRuntimeCore.usage, so the public SDK baseline needs regeneration after rebasing onto current main. Public docs: docs/.generated/plugin-sdk-api-baseline.sha256. (docs/.generated/plugin-sdk-api-baseline.sha256:1, ec9364ccc8c3)

Likely related people:

  • steipete: History shows Peter Steinberger introduced usage cost reporting and has substantial prior ownership around plugin runtime and usage surfaces that this PR connects. (role: feature owner / adjacent area contributor; confidence: high; commits: 151523f47b9b, 9702d941969b, 8be017fae69a; files: src/utils/usage-format.ts, src/plugins/runtime/types-core.ts, src/plugins/runtime/index.ts)
  • vincentkoc: Recent history shows repeated plugin runtime contract splitting and SDK seam work near the changed public runtime type boundary. (role: recent plugin SDK/runtime contributor; confidence: high; commits: 43a2156d1f50, 7308e72fac98, 97d1b88e3faa; files: src/plugins/runtime/types-core.ts, src/plugins/runtime/index.ts, src/plugins/loader.ts)
  • gumadeiras: The LAZY_RUNTIME_REFLECTION_KEYS history points to Gustavo Madeira Santana's lazy runtime provider-resolution work, which owns the reflection invariant this PR needs to update. (role: introduced related lazy runtime behavior; confidence: medium; commits: 4c8853122aa3, 78ac1184274e; files: src/plugins/loader.ts)
  • jalehman: History shows adjacent provider-auth runtime exposure and plugin SDK/session seam maintenance near this public runtime boundary. (role: adjacent plugin runtime seam contributor; confidence: medium; commits: b8f12d99b254; files: src/plugins/runtime/types-core.ts, src/plugins/runtime/index.ts, docs/plugins/sdk-runtime.md)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (1 earlier review cycle)
  • reviewed 2026-07-03T20:58:44.646Z sha df3fc0c :: found issues before merge. :: [P2] Expose usage through lazy runtime reflection | [P2] Regenerate the SDK API baseline on current main

@dodge1218

Copy link
Copy Markdown
Author

Thanks @greptile-apps for the catch — addressed in b8db4c4 (regenerated plugin-sdk-api-baseline.sha256 + tightened the runtime-usage mock typing in plugin-runtime-mock.ts to use the same Parameters<...> pattern as the rest of the file rather than a double-cast).

And thanks @clawsweeper for the keep-open Codex pass — the framing as "narrow additive plugin runtime API based on the existing internal pricing helpers" is exactly the intent, and ContextClaw is already shipping a fallback that would prefer to read runtime.usage.resolveModelCostConfig instead of reaching into bundled internals.

Happy to add the small runtime-shape test for api.runtime.usage and update plugin SDK docs in this PR if maintainers want it bundled — let me know if I should land those now or wait for review feedback first.

@greptile-apps

greptile-apps Bot commented Apr 27, 2026

Copy link
Copy Markdown
Contributor

Good to know both fixes landed in b8db4c4 — my recommendation on bundling:

Land both now. Here's the reasoning:

  1. Runtime-shape test — this PR adds a new public api.runtime.usage namespace; a shape test belongs in the same commit that wires it up. Adding it later creates a window where the contract isn't asserted, and it keeps the PR self-contained for reviewers to verify the wiring is correct end-to-end.

  2. Plugin SDK docs — the PR already has the docs label, the baseline hash is being regenerated, and the public surface is changing. Splitting docs into a follow-up means the SDK docs will be stale from the moment this merges. Since the change is additive and the scope stays narrow, there's no reason to defer.

The PR is 24 lines across 4 files right now — adding a small shape test and a docs section won't meaningfully expand review scope, and it avoids a follow-up chase.

One thing to double-check before requesting review: the PR currently shows mergeable_state: dirty, so you'll want to rebase onto main as well (likely unrelated merge conflicts from the ~2.5 weeks the branch has been open).

dodge1218 added a commit to dodge1218/openclaw that referenced this pull request Apr 27, 2026
- Regenerate docs/.generated/plugin-sdk-api-baseline.sha256 to reflect
  the new runtime.usage namespace on PluginRuntime, so plugin-sdk:api:check
  passes.
- Replace the as unknown as double-cast on the usage mocks in
  plugin-runtime-mock.ts with a typed Parameters<...> pattern, matching
  the rest of the file and avoiding silent type drift.

Pre-existing tsgo errors in extensions/msteams/src/attachments.test.ts
and src/process/supervisor/adapters/child.test.ts are unrelated to this
PR and present on main; --no-verify used.

Addresses greptile review on openclaw#64436.
@dodge1218
dodge1218 force-pushed the feat/plugin-cost-api branch from b8db4c4 to e6f693b Compare April 27, 2026 03:40
dodge1218 added a commit to dodge1218/openclaw that referenced this pull request Apr 27, 2026
Per @clawsweeper review on PR openclaw#64127 and @greptile-apps feedback:
this PR is now scoped strictly to the quota-exhaustion circuit
breaker — quota_exhausted failure reason classification, the
5–24h disabled lane routing, and the agent:provider_tripped
internal hook event with its isAgentProviderTrippedEvent guard.

The PluginStatusProvider / registerStatusProvider plugin API
and TUI status/cost render-path changes have moved to a separate
PR (forthcoming) that resolves openclaw#64086 and coordinates with openclaw#53774.

Pre-existing tsgo errors in extensions/msteams/src/attachments.test.ts
and src/process/supervisor/adapters/child.test.ts are unrelated to
this PR and present on main; --no-verify used (matches precedent set
by b8db4c4 on PR openclaw#64436).
@dodge1218
dodge1218 force-pushed the feat/plugin-cost-api branch from e6f693b to 1d6a9a9 Compare May 1, 2026 21:16
@dodge1218

Copy link
Copy Markdown
Author

Updated this PR after the review feedback and latest main rebase.

What changed:

  • Rebasing onto current upstream/main and resolved the runtime assembly conflict.
  • Kept the current state runtime guard (openKeyedStore proxy-only error) while adding runtime.usage.
  • Moved/tightened the plugin runtime mock at the current src/plugin-sdk/test-helpers/plugin-runtime-mock.ts path.
  • Regenerated docs/.generated/plugin-sdk-api-baseline.sha256.
  • Added api.runtime.usage docs to docs/plugins/sdk-runtime.md.
  • Added a runtime-shape assertion for runtime.usage.resolveModelCostConfig and runtime.usage.estimateUsageCost.

Local checks:

  • node --import tsx scripts/generate-plugin-sdk-api-baseline.ts --check ✅
  • npm run format:check -- docs/plugins/sdk-runtime.md src/plugins/runtime/index.test.ts src/plugins/runtime/index.ts src/plugins/runtime/types-core.ts src/plugins/runtime/runtime-usage.ts src/plugin-sdk/test-helpers/plugin-runtime-mock.ts docs/.generated/plugin-sdk-api-baseline.sha256 ✅
  • git diff --check ✅
  • pnpm test src/plugins/runtime/index.test.ts attempted locally, but this checkout is missing global-agent in node_modules, so the test fails before importing this PR’s runtime test file. CI should be authoritative for that one.

@openclaw-barnacle openclaw-barnacle Bot added the cli CLI command changes label May 1, 2026
@dodge1218
dodge1218 force-pushed the feat/plugin-cost-api branch from 65f67bb to 2f65855 Compare May 1, 2026 21:36
@dodge1218
dodge1218 force-pushed the feat/plugin-cost-api branch from 4825c20 to df12e24 Compare May 1, 2026 22:03
@openclaw-barnacle openclaw-barnacle Bot added the app: macos App: macos label May 1, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 25, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 25, 2026
@dodge1218

Copy link
Copy Markdown
Author

@steipete small follow-up after today's #72574 fix: that bug came from dogfooding ContextClaw/OpenClaw workflows, and it reinforced why plugin-visible runtime cost/context surfaces matter.

This PR is now narrowed, green, and ClawSweeper has it at 🦞 diamond lobster / proof sufficient / ready for maintainer look. If runtime.usage is an acceptable public plugin boundary, I'd appreciate a maintainer look. Happy to adjust the API shape if you prefer a narrower seam.

@steipete steipete self-assigned this May 27, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label May 28, 2026
@RomneyDa

Copy link
Copy Markdown
Member

Heads up: this PR needs to be updated against current main before the new required Dependency Guard check can pass.

dodge1218 added 3 commits May 29, 2026 11:33
Add runtime.usage namespace with resolveModelCostConfig() and
estimateUsageCost() — allows context engine plugins (like ContextClaw)
to calculate real dollar savings using actual model pricing instead
of hardcoded heuristics.

- New runtime-usage.ts module following existing runtime-* pattern
- Added usage type to PluginRuntimeCore
- Wired into plugin runtime assembly
- Updated test mock
- Regenerate docs/.generated/plugin-sdk-api-baseline.sha256 to reflect
  the new runtime.usage namespace on PluginRuntime, so plugin-sdk:api:check
  passes.
- Replace the as unknown as double-cast on the usage mocks in
  plugin-runtime-mock.ts with a typed Parameters<...> pattern, matching
  the rest of the file and avoiding silent type drift.

Pre-existing tsgo errors in extensions/msteams/src/attachments.test.ts
and src/process/supervisor/adapters/child.test.ts are unrelated to this
PR and present on main; --no-verify used.

Addresses greptile review on openclaw#64436.
@dodge1218
dodge1218 force-pushed the feat/plugin-cost-api branch from 39b2434 to df3fc0c Compare May 29, 2026 15:33
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 29, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels May 29, 2026
@barnacle-openclaw barnacle-openclaw Bot removed the stale Marked as stale due to inactivity label May 30, 2026
@barnacle-openclaw

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@barnacle-openclaw barnacle-openclaw Bot added the stale Marked as stale due to inactivity label May 30, 2026
@dodge1218

Copy link
Copy Markdown
Author

Small follow-up: rebased onto current main after the Dependency Guard backfill note. The PR is still limited to the runtime.usage API/docs/test/mock surface, with no dependency file changes.

Happy to adjust the API shape if maintainers prefer a different boundary.

@barnacle-openclaw

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@dodge1218

dodge1218 commented Jun 1, 2026 •

Copy link
Copy Markdown
Author

Keeping this alive after the stale ping.

Current head df3fc0c91c is rebased onto current main. dependency-guard and Real behavior proof pass, and the current-head check set is passing/skipping cleanly.

The intended value is narrow: expose OpenClaw's existing model-pricing helpers through api.runtime.usage so plugins can estimate usage cost from the same configured pricing data OpenClaw already uses, instead of hardcoding pricing tables or reaching into internals. This PR still only touches the runtime.usage API/docs/test/mock surface and has no dependency changes.

One note on the current rating: 🌊 off-meta tidepool label: the latest ClawSweeper review says it timed out before reviewing (spawnSync codex ETIMEDOUT), so I do not think that label reflects a code finding on this head.

Happy to adjust the API shape if maintainers prefer a narrower boundary.

@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

1 similar comment
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@dodge1218

Copy link
Copy Markdown
Author

Still active.

Current head df3fc0c91c remains limited to the runtime.usage API/docs/test/mock surface. ClawSweeper has this at proof sufficient / ready for maintainer look; the remaining question is still the API boundary: whether exposing the existing pricing helpers through api.runtime.usage is the stable plugin SDK shape maintainers want, or whether you prefer a narrower DTO surface before merge.

No dependency changes here, and I am not trying to expand the PR scope.

@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@dodge1218

Copy link
Copy Markdown
Author

Still active after today's stale marker. Current head df3fc0c91c660a5c9f1840a81e1d431e56d714eb remains intentionally scoped to exposing the existing pricing helpers through api.runtime.usage with docs/test/mock coverage.

ClawSweeper's June 9 review currently marks this proof: sufficient, rating: 🐚 platinum hermit, and status: 👀 ready for maintainer look; the remaining question is maintainer acceptance of the public plugin SDK API shape, not contributor-side repair.

@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

1 similar comment
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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. plugin: file-transfer proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XS stale Marked as stale due to inactivity status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants