惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Threat Research - Cisco Blogs
G
GRAHAM CLULEY
P
Privacy & Cybersecurity Law Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cyber Attacks, Cyber Crime and Cyber Security
Security Latest
Security Latest
Know Your Adversary
Know Your Adversary
P
Palo Alto Networks Blog
C
Cisco Blogs
AWS News Blog
AWS News Blog
T
Threatpost
L
LINUX DO - 热门话题
Simon Willison's Weblog
Simon Willison's Weblog
Scott Helme
Scott Helme
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tor Project blog
Cyberwarzone
Cyberwarzone
P
Proofpoint News Feed
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
The Exploit Database - CXSecurity.com
The Register - Security
The Register - Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
罗磊的独立博客
云风的 BLOG
云风的 BLOG
V
Vulnerabilities – Threatpost
N
News | PayPal Newsroom
Project Zero
Project Zero
NISL@THU
NISL@THU
博客园_首页
MyScale Blog
MyScale Blog
V2EX - 技术
V2EX - 技术
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
F
Full Disclosure
T
Troy Hunt's Blog
Recorded Future
Recorded Future
N
Netflix TechBlog - Medium
P
Privacy International News Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
A
Arctic Wolf
C
Check Point Blog
W
WeLiveSecurity
Apple Machine Learning Research
Apple Machine Learning Research
C
CERT Recently Published Vulnerability Notes

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
I Built 10 AI Agent Skills and Shrank 300 Lines of Boilerplate to 30
weijhfly · 2026-06-19 · via DEV Community

Over the past six months, I've built about 10 Agent Skills — the kind of scripts that LLM-powered coding agents invoke to get real work done. By the third one, I noticed something embarrassing: I'd copy-pasted three different HTTP wrappers across three different skills.

Cookie auth in one. Bearer token in another. Network error handling in a third. Three copies of http.ts, each slightly different. If the auth method ever changed, I'd have to fix the same logic in three places.

And HTTP was just the start. Command routing, argument parsing, error handling, SKILL.md validation, build output syncing — by Skill #5, these non-business concerns were eating up real time.

So I built skill-kits — a toolchain that turns those recurring engineering problems into a reusable foundation. Here's what it actually solves:

Problem Before (manual) After (skill-kits)
Creating a new Skill Reinvent the directory structure every time pnpm new <name> — one command
HTTP / error handling utils Copy-paste across skills Import from runtime, zero-dependency inlined
Syncing changes to the agent cp -r / manual copy pnpm dev — watch + auto-sync
SKILL.md quality Eyeball review pnpm build — automated lint checks

1. Three copies of http.ts across three skills

Here's what "just copy-paste the HTTP wrapper" actually looks like after a few skills:

// skill1/scripts/http.ts — Cookie auth + error detail extraction
async function request<T>(
  method: "GET" | "POST",
  domain: string,
  path: string,
  token: string,
  options?: { params?: Record<string, string>; body?: unknown },
) {
  const url = new URL(`${domain}/gms_api${path}`);
  if (options?.params) {
    Object.entries(options.params).forEach(([k, v]) => {
      url.searchParams.set(k, v);
    });
  }

  const res = await fetch(url.toString(), {
    method,
    headers: {
      "Content-Type": "application/json",
      Cookie: `x-token=${token}`,
    },
    body: options?.body ? JSON.stringify(options.body) : undefined,
  });

  if (!res.ok) {
    const detail = await res.text().catch(() => "");
    throw new Error(`HTTP ${res.status}: ${res.statusText}\n${detail}`);
  }

  return res.json() as Promise<ApiResponse<T>>;
}

// skill2/scripts/http.ts — Bearer Token + network fallback + response parsing tolerance
async function postJson<T>(url: string, body: unknown, token?: string) {
  let response: Response;

  try {
    response = await fetch(url, {
      method: "POST",
      headers: {
        "content-type": "application/json",
        ...(token ? { authorization: `Bearer ${token}` } : {}),
      },
      body: JSON.stringify(body),
    });
  } catch (error) {
    return {
      httpOk: false,
      status: 0,
      statusText: `NetworkError: ${error instanceof Error ? error.message : String(error)}`,
      data: null,
    };
  }

  const raw = await response.text();
  let data: unknown = null;
  try {
    data = JSON.parse(raw);
  } catch {
    data = { raw };
  }

  return { httpOk: response.ok, status: response.status, data: data as T };
}

// skill3/scripts/http.ts — yet another variant (omitted)

Three skills, three http.ts files. If auth ever switches from Cookie to Bearer, that's three places to update. Not great.

So I added a thin fetch wrapper to skill-kits' runtime. Not a full-blown HTTP client — just enough to stop writing the same boilerplate:

import { httpGet, HttpError } from "skill-kits/runtime";

const res = await httpGet<UserInfo>("https://api.example.com/me", {
  headers: { authorization: `Bearer ${token}` },
  query: { fields: "id,name" },
  timeoutMs: 10_000,
});

if (!res.ok) {
  throw new HttpError(res.status, url, res.statusText);
}

The business-specific wrapping stays in each skill. The boring parts are handled once.

Beyond HTTP, error handling was another mess. Every skill threw new Error("something") and debugging meant guessing from raw messages. I consolidated common errors into a unified code system:

Class Code Typical scenario
UserInputError USER_INPUT_ERROR Missing / malformed arguments
AuthError AUTH_ERROR Expired token / insufficient permissions
HttpError HTTP_ERROR Upstream non-2xx response
BusinessApiError BIZ_<code> HTTP 200 but business code ≠ 0

A few real examples:

import { SkillError, UserInputError, BusinessApiError } from "skill-kits/runtime";

// UserInputError: argument validation failure
throw new UserInputError("activityId is required", { field: "activityId" });
// stderr → {"ok":false,"code":"USER_INPUT_ERROR","error":"activityId is required","details":{"field":"activityId"}}

// Custom BusinessApiError
throw new BusinessApiError(-10000, "token expired", {
  hintMap: { [-10000]: "Please re-login", [-14]: "Record not found" },
});
// stderr → {"ok":false,"code":"BIZ_-10000","error":"[code=-10000] token expired (Please re-login)"}

// Custom error: extend SkillError with any code
class RateLimitError extends SkillError {
  constructor(retryAfterSec?: number) {
    super("RATE_LIMIT", "Too many requests", { retryAfterSec });
  }
}
throw new RateLimitError(30);
// stderr → {"ok":false,"code":"RATE_LIMIT","error":"Too many requests","details":{"retryAfterSec":30}}

Now both humans and LLMs can branch on error codes instead of parsing free-text messages.


2. Seven subcommands, 250 lines of parseArgs + switch

When I built a marketing campaign management Skill with 7 subcommands, main.ts turned into a monster of parseArgs + switch + usage + validation:

// ❌ Manual: parseArgs + switch, ~250 lines
function parseArgs(): CliOptions {
  const args = process.argv.slice(2);
  const opts: Partial<CliOptions> = {};

  for (let i = 1; i < args.length; i++) {
    switch (args[i]) {
      case "--domain":
        opts.domain = args[++i];
        break;
      case "--app-id":
        opts.appId = args[++i];
        break;
      case "--token":
        opts.token = args[++i];
        break;
      case "--activity-id":
        opts.activityId = args[++i];
        break;
      case "--body":
        opts.body = args[++i];
        break;
      // ... a dozen more cases
    }
  }

  if (!opts.domain) {
    console.error("❌ Missing --domain");
    process.exit(1);
  }
  if (!opts.appId) {
    console.error("❌ Missing --app-id");
    process.exit(1);
  }
  if (!opts.token) {
    console.error("❌ Missing --token");
    process.exit(1);
  }

  return opts as CliOptions;
}

async function main() {
  const opts = parseArgs();

  switch (opts.command) {
    case "get_activity":
      if (!opts.activityId) {
        console.error("❌ Requires --activity-id");
        process.exit(1);
      }
      await getActivity(opts.domain, opts.appId, opts.token, opts.activityId);
      break;
    case "create_activity":
      if (!opts.body) {
        console.error("❌ Requires --body");
        process.exit(1);
      }
      await createActivity(opts.domain, opts.appId, opts.token, opts.body);
      break;
    // ... remaining cases
  }
}

The real problem isn't the line count — it's that parsing, validation, usage text, and error handling are scattered across different places. Adding a command means touching several spots, and it's easy to miss one.

I replaced all of that with createRouter:

import { createRouter, writeResult } from "skill-kits/runtime";

// ✅ Declarative: args, validation, routing — all in one place
const router = createRouter({
  name: "redbrick-activity",
  description: "...",
  commonArgs: {
    domain: { type: "string", required: true, desc: "Platform domain" },
    appId: { type: "string", required: true, desc: "App ID" },
    token: { type: "string", required: true, desc: "SSO token" },
  },
});

router.command({
  name: "get-activity",
  description: "Query activity details",
  args: {
    activityId: { type: "string", required: true, desc: "Activity ID" },
  },
  async handler({ domain, appId, token, activityId }) {
    writeResult(await getActivity(domain, appId, token, activityId));
  },
});

router.command({
  name: "create-activity",
  description: "Create an activity",
  args: {
    body: { type: "json", required: true, desc: "Activity fields as JSON" },
  },
  async handler({ domain, appId, token, body }) {
    writeResult(await createActivity(domain, appId, token, body));
  },
});

router.run(process.argv.slice(2));

After this abstraction, I stopped thinking about "how arguments get parsed" and started thinking about "what arguments does this command need, and what do I do with them."


3. stdout and stderr mixed together — the agent can't tell them apart

I used to dump everything with console.log and reserve console.error only for actual errors. The problem? The LLM had to guess which stdout line was the JSON result and which was a progress log. One wrong guess, one wasted invocation.

The better approach: stdout for JSON results, stderr for progress messages. On failure, a non-zero exit code tells the agent status: failed — far more reliable than making the LLM parse error text from stderr.

skill-kits provides three simple output helpers:

writeResult(payload);                          // stdout: single-line JSON for the agent
writeError(errorOrMessage, { code?, extra? }); // stderr: structured error + exitCode=1
notify("Fetching data...");                    // stderr: progress log


4. The agent thought the process was dead — it was just waiting 60 seconds

For D2C code generation, SSO login callbacks, and similar long-running tasks, the real problem isn't "actually timed out" — it's "looks like it timed out."

A naive 60-second sleep:

await new Promise((resolve) => setTimeout(resolve, 60_000));

Zero output for 60 seconds. The agent assumes the process hung and kills it.

Enter sleepWithHeartbeat:

import { sleepWithHeartbeat } from "skill-kits/runtime";

await sleepWithHeartbeat(60_000, {
  message: (rem) => `Waiting for code generation... ${rem}s remaining`,
});

It prints a heartbeat to stderr every 5 seconds, so the agent knows the process is still alive.


5. A "correct" SKILL.md isn't necessarily a good one

I learned this one the hard way. Two problems kept coming up:

  • Wrong triggers: the description was too vague, so the LLM didn't know when to invoke the skill. I had to keep tweaking keywords.
  • Too complete to edit: AI-generated SKILL.md files were thorough, but when I wanted to make changes myself, I didn't know where to start.

SKILL.md can't be fully standardized like code, but some things should absolutely be caught locally:

  • name doesn't match the directory name
  • Body is too long, blowing up the context window
  • references points to a wrong path
  • description is too short to convey trigger scenarios

skill-kits ships a set of lint rules that run automatically on pnpm build:

  • name-matches-dir: name must equal the parent directory name
  • body-line-limit: body over 500 lines → hard error
  • body-line-soft: over 400 lines → warning, suggest splitting into references/
  • description-length: description too short → warning
  • description-trigger / description-negative: checks for "when to trigger" and "when NOT to trigger" hints

You can customize thresholds via .skillkitrc.json:

{
  "lint": {
    "triggerHints": ["when", "trigger", "use when"],
    "negativeHints": ["don't", "do not", "never"],
    "descriptionMinChars": 80,
    "bodyLinesWarn": 400,
    "bodyLinesFail": 500
  }
}

There's also a second layer of reuse beyond the runtime: shared business modules. Internal API clients, domain constants, signing utilities — the kind of helpers that pop up across multiple skills. skill-kits init generates a workspace with packages/shared:

import { signRequest, BIZ_DOMAINS } from "@skills/shared";

At build time, esbuild inlines only the used parts. The output is still a single file, zero dependencies.


6. Change one line → buildcp -r → try again

When developing a Skill, you need to sync it to the agent's local skills directory to test. I used to do this manually:

cp -r dist/xxx ~/.agent/skills

After the tenth time, I added a dev mode:

pnpm dev daily-report --out ~/.agent/skills

It does two things in parallel:

  1. esbuild watches src/.ts changes trigger rebuild
  2. Watches SKILL.md / references/ / assets/ — resource changes sync directly to --out

Now I edit locally, and the agent picks up the latest version on its next invocation.


7. You don't know a Skill is broken until it fails in production

Skills run unattended inside agents. A broken command costs more than a broken CLI — you often don't find out until a run fails silently. Writing tests is worth it.

skill-kits keeps testing simple: test files go in src/**/*.test.ts, run with pnpm test, powered by node:test + tsx. Zero configuration.

The main thing you're testing: the exit behavior of a command — what JSON it writes to stdout, whether the exit code is 0 or 1, what error appears on stderr on failure.

Two helpers from skill-kits/testing:

  • captureOutput(fn): captures writeResult / writeError / notify output, plus process.exitCode
  • mockFetch(routes): replaces global fetch, no real network calls

A typical happy-path test:

import { test } from "node:test";
import assert from "node:assert/strict";
import { mockFetch, captureOutput } from "skill-kits/testing";
import { createActivity } from "./commands/create-activity.js";

const ctx = { domain: "https://example.com", token: "t" };

test("create-activity returns backend data with ok", async () => {
  const mock = mockFetch([
    { match: /\/activity\/create/, json: { code: 0, data: { activity_id: 9001 } } },
  ]);
  try {
    const { json, exitCode } = await captureOutput(() =>
      createActivity(ctx, { act_name: "test" }),
    );
    assert.equal(exitCode, 0);
    assert.equal((json as { activity_id: number }).activity_id, 9001);
  } finally {
    mock.restore();
  }
});

For pure functions, you don't need either helper — just import and assert. For error paths, commands throw a SkillError (the router maps it to exit code 1 + stderr JSON), and you catch it with assert.rejects.

One detail worth mentioning: mockFetch intentionally throws on unmatched requests. A missing mock will never silently pass — no "tests pass but production fails" surprises.

The daily loop is three commands:

pnpm new daily-report
# ... write code + tests ...
pnpm test daily-report     # run tests
pnpm build daily-report    # lint → bundle → zip


Wrapping up

skill-kits doesn't write your scripts or abstract your business logic. What it does is simple: it wraps entry points, build output, runtime utilities, and definition validation into a guardrail layer — so when you're building your 5th or 10th Skill, your brain is still on business logic, not boilerplate.

If you're building Agent Skills too, give it a try:

npx skill-kits init my-skills

GitHub: https://github.com/weijhfly/skill-kits