runaway-guard – skill Khác cho agent AI
Kỷ luật an toàn chi phí cho API AI/suy luận có tính phí: coi chi phí ($) là chiều độ phức tạp thứ ba bên cạnh thời gian và không gian. Yêu cầu khai báo trước giới hạn $ mỗi lần chạy, giới hạn $ mỗi ngày, số vòng lặp tối đa, giới hạn đồng thời và giới hạn cứng tương ứng trên bảng điều khiển nhà cung cấp, TRƯỚC khi viết bất kỳ call site nào.
Cài skill runaway-guard bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/runaway-guard-6b04e.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /runaway-guard – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/runaway-guard-6b04e.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $runaway-guard – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/runaway-guard-6b04e.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /runaway-guard – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/runaway-guard-6b04e.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /runaway-guard – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
runaway-guard — $-Cost is the Third Complexity Dimension
> Catalog review modification (2026-10-23): corrected cost arithmetic, retry/idempotency claims and unsupported provider-cap guarantees. Upstream authorship and Apache-2.0 attribution are retained.
Every loop has time complexity and space complexity. A loop that calls a paid API has a third: dollars per execution. The model tracks the first two automatically. It does not track the third, so it ships code where a single bug — a retry without bound, a stream reconnect storm, an agent that re-queues itself, a webhook that fires the same job twice — silently spends real money.
Illustrative, unverified incident narrative: developer writes a Fal.ai image-generation loop. Loop "obviously terminates" because it iterates over a fixed list. The list comes from a callback that fires on every Inngest retry. Each retry doubles the list. By morning, the bill is $200. Tests pass. Code review passed. The bug is not in the loop body. The bug is that no one stated the wallet invariant.
runaway-guard helps identify this design risk. State the max calls. State the max dollars per run. State the max dollars per day. Set the same caps in the provider dashboard so a code bug cannot bypass them. Then write the code.
Violating the letter of these rules is violating the spirit of the skill. "I'm only testing locally" is the exact rationalization that ships the $200 bill — local code hits the same paid API as production.
When to Use This Skill
Use runaway-guard when:
- Writing or reviewing code that calls a paid AI / inference API in a loop, queue, retry path, agent step, webhook handler, or background job.
- Importing or wrapping any paid-inference SDK:
@fal-ai/*,fal-client,@anthropic-ai/sdk,anthropic,openai,replicate,elevenlabs,together-ai,groq-sdk,cohere-ai,@mistralai/*. - Designing an agent loop, fan-out pipeline, retry wrapper, polling job, stream reconnect, or self-rescheduling job that may call a billed endpoint.
- Auditing a codebase / PR for unbounded fan-out, unbounded retries, missing idempotency keys, or missing provider-side spend caps.
- Diagnosing an unexpected bill, runaway loop incident, or surprise overage.
The Iron Law
NO CALL TO A PAID API WITHOUT A WRITTEN $-CAP AT BOTH THE CODE AND PROVIDER LEVELA cap only in code can be bypassed by a bug in that code. A cap only at the provider can be hit during normal usage and degrade the product. You need both. If you cannot state both in one sentence each, you have not designed the call site — you have written a wish.
Non-negotiable rules
1. Every call site gets a one-line cost contract. Before writing any paid-API call, state in one sentence:
- Max calls per run: the strict upper bound on invocations in a single execution of this code path.
- Max $ per run:
max_calls × unit_cost— compute it, don't estimate. - Max $ per day: the provider-side hard cap that backstops the code-side bound.
Examples:
- "Fal flux-pro at $0.05/image; max 20 images per job; max $1 per job; provider Spend Limit $50/day."
- "Anthropic Sonnet at ~$0.015 per request (cached); max 50 requests per agent run; max $0.75 per run; Workspace Budget hard cap $30/day."
If you cannot fill in all three numbers, you have not designed the call site.
2. Every loop calling a paid API gets an explicit iteration bound, not just a termination argument. invariant-guard requires a termination measure. runaway-guard requires the bound to be a concrete integer in code, not just "eventually terminates":
// ❌ Terminates in theory. Bills $200 in practice.
while (job.status !== 'done') {
await fal.run(...);
}
// ✅ Concrete bound — wallet invariant explicit.
const MAX_CALLS = 20;
for (let i = 0; i < MAX_CALLS && job.status !== 'done'; i++) {
await fal.run(...);
}
if (job.status !== 'done') throw new Error('exceeded MAX_CALLS budget');
3. Every retry path is bounded by attempts AND total elapsed cost, not by time alone. Exponential backoff with no attempt cap is a wallet attack on yourself.
- Max attempts: an explicit small integer chosen for the provider and error class.
- Cap counts across the whole pipeline, not just one library — Inngest retries × SDK retries × your own retry wrapper multiply.
- Do not retry permanent invalid requests. Some 4xx errors, including 429 and provider-defined transient statuses, can be retryable under a bounded policy; respect Retry-After and the shared spend reservation.
4. Every fan-out path declares a concurrency limit. Parallel calls multiply cost per wall-clock second. State the limit in code, at the queue (Inngest concurrency), and at the provider where supported:
- Inngest:
concurrency: { limit: N }on the function. - BullMQ / Sidekiq / Cloud Tasks: queue-level concurrency.
- In-process:
p-limit, semaphore, or batchedPromise.allchunks — never an unboundedPromise.all(items.map(...))on a paid API.
5. Every paid API has a matching provider-side hard cap, configured out of band. Defense in depth: if the code is wrong, the provider stops the bleeding. Document the cap in the same file as the call site so future readers know it exists.
Inspect the account's current provider documentation and dashboard. Record enforcement scope, period, delay, override behavior and which keys/workspaces it covers. An alert or prepaid balance is not proof of an instantaneous hard stop. If no enforceable cap exists, keep calls disabled until an approved fail-closed gateway/atomic reservation ledger and bounded in-flight exposure are in place. Historical provider menu names and prices below are illustrative, not verified settings.
6. Idempotency keys on every mutating or charging call. A webhook that fires twice should bill once. Without an idempotency key, retry policies you cannot see (load balancer, framework, gateway) silently double-charge.
7. Make the "amplifier" patterns explicit and forbidden by default. These are the shapes that turn small bugs into large bills:
- Self-rescheduling jobs. A job that re-enqueues itself with no decrementing measure is an unbounded loop with extra steps.
- Webhook handlers that call the API that called the webhook. Cycle detection or it will cycle.
- Recursion over LLM output. "Ask the model what to do next" with no depth cap is a depth-unbounded recursion in dollars.
- Polling without a deadline.
while (!done) await poll()with nomaxWaitMsis a wallet leak. - Streaming reconnect storms. A WebSocket / SSE reconnect with no backoff and no attempt cap can hammer a billed endpoint thousands of times per minute.
- Cache-miss stampede on a paid call. N concurrent requests for the same uncached key → N billed calls. Use
singleflight/ request coalescing.
The pre-write protocol
Before producing code that calls a paid API, your message must contain — in this order:
1. Provider + unit cost. "Fal flux-pro: $0.05/image, billed per success."
2. Max calls per run. A literal integer that will appear as a constant in the code.
3. Max $ per run. max_calls × unit_cost. Compute it.
4. Max $ per day (provider hard cap). The dashboard setting that backstops the code.
5. Concurrency limit. In code, at the queue, at the provider.
6. Retry policy. Max attempts, which error codes retry, idempotency key strategy.
7. Amplifier audit. Walk the list in rule 7; declare "none apply" or address each that does.
8. The code — with the cost contract in a comment above the call site.
9. Self-check. One line: "in the worst case, this code bills $X and the provider cap stops it at $Y."
If any of 1–7 is missing, do not emit code.
Worked trap — the Inngest + Fal $200 night
This is the canonical case. Observe how each rule would have caught it.
What shipped:
// inngest function: generate images for a campaign
export const generateCampaign = inngest.createFunction(
{ id: 'gen-campaign' }, // ❌ no concurrency limit
{ event: 'campaign/start' },
async ({ event, step }) => {
const prompts = await step.run('fetch', () => fetchPrompts(event.data.id));
// ❌ unbounded fan-out, no per-run cap, no idempotency
await Promise.all(prompts.map(p => fal.run('fal-ai/flux-pro', { input: { prompt: p } })));
}
);What went wrong. fetchPrompts had a bug: on a transient DB error it returned the partial list *plus the previous run's list appended*. Inngest retried the function at its default retry count (multiple attempts in addition to the initial one). This account is inconsistent with the shown code: a successfully completed fetch step is memoized, so ordinary later-step retries do not re-run it. A growth bug would need an additional path not shown. Promise.all fanned all 320 out conc
… (nội dung đầy đủ có trong gói tải về)
Skill liên quan
- salary-wage-accounting – Sổ bảng lương: lương gross, phụ cấp, khấu trừ TDS và quỹ dự phòng (provident fund)…
- salesforce-development – Mẫu chuyên sâu cho phát triển nền tảng Salesforce, gồm Lightning Web Components (LWC)…
- sam-altman – Persona hư cấu lấy cảm hứng từ các chủ đề công khai gắn với Sam Altman; không đại diện…
- satori – Người bạn đồng hành tư duy có nền tảng lâm sàng, kết hợp tâm lý học và triết học thành…
- sbom-supply-chain – Tạo, ký và xác minh SBOM và chứng thực nguồn gốc (provenance) để bảo vệ chuỗi cung ứng…
- scarf-single-cell – Phân tích RNA-seq đơn tế bào ở quy mô hàng triệu tế bào với Scarf: kho Zarr out-of-core…
- score-eval – Dùng khi chấm điểm diff đánh giá theo rubric và fixture baseline được cung cấp: lưu bằng…
- search-preview-simulator – Search Preview Simulator. Dùng khi làm việc với tiêu đề, mô tả và URL trang.