CLI for AI Agents: Scenario Domains, Skills & Orchestratable Output

The article explains how to design CLIs for AI hosts like Cursor by organizing commands into lifecycle-based scenario domains, binding Skills that define trigger boundaries and workflows, and emitting structured JSON with next_command for orchestration, avoiding pitfalls like resource-path mirroring, verbose output, and missing workspace context.

James' Growth Diary
James' Growth Diary
James' Growth Diary
CLI for AI Agents: Scenario Domains, Skills & Orchestratable Output

Introduction: CLI as an Engineer's Tool for AI Hosts

The author, James, continues a series on platform usage patterns. The previous article covered OpenAPI as a stable contract for system integration. This article focuses on the third usage: a platform CLI designed for AI hosts (e.g., Cursor, CodeBuddy) that can read Skills and execute commands. The key insight: the real users of this CLI are not humans but AI hosts, which changes every design decision.

A personal failure illustrates the problem: when the author first installed their CLI into Cursor, the model confidently ran a deploy command but deployed to the wrong workspace. The command tree mirrored the API resource paths and lacked any concept of "development / usage / evolution" workspaces. The model had no way to establish the prerequisite context of which workspace it was operating on.

Terminology Alignment

Core terms defined:

Agent : A configured instance on the platform that can be configured, published, and conversed with.

Workspace : Three landing zones for the same Agent — development (edit & publish), usage (published, runs user conversations), evolution (collect experience, distill, push back).

Scenario Domain : Command families sliced by lifecycle — create / develop-publish / evolution / usage-chat / materials — not by REST paths.

Skill : A document read by the host Agent describing when to invoke the CLI, when not to, and what to tell the user.

References : Skill-attached manuals that encode composite flows so the model doesn't have to stitch parameters itself.

AI Host : An Agent environment that reads Skills and invokes commands (Cursor, CodeBuddy, etc.).

Orchestratable Output : Structured command results (one-line JSON + next_command) so the host can continue without regex parsing logs.

CLI-first : Atomic capabilities exposed as commands first, rather than letting the Agent craft raw HTTP.

Core Judgment 1: Command Trees Are Path Tables, Models Only Guess

The author uses a car-navigation analogy:

Navigation by destination type (airport, gas station) → Scenario domains: create / develop / evolution / usage / materials.

Handing a street-name list → Command tree sliced by API paths (model guesses by literal similarity).

Traffic rules (where you can turn) → Skill trigger boundaries: when to act, when not to.

"Turn right in 200m" → next_command: explicit next step for the host.

Navigation takes you to the wrong city → Wrong workspace selected: editing the wrong disk.

Voice says "turn right", not coordinates → Hide commands from user; foreground speaks business language.

Three core judgments follow:

Give destination types, not street lists. A resource-path command tree forces the host to pick by literal similarity — as absurd as making a driver guess from a street directory.

Traffic rules are more valuable than maps. Maps tell how to get there; rules tell whether you may go now. "Let's discuss release strategy" must not trigger a write operation.

Every step must provide the next hop. Good navigation doesn't go silent on arrival; it says "destination reached, parking ahead." Output must include next_command or the host must regex session IDs from logs.

Humans read --help, browse docs, remember previous invocations. The host Agent has only two things: the Skill's instructions and the previous command's output. A resource-path command tree leaves it guessing by literal match.

Four Failure Modes

Symptoms mapped to root causes:

A: Wrong workspace — Deploys wrong version, overwrites others. Misdiagnosed as "model is dumb." Root cause: domains sliced by REST resources, missing "dev / usage / evolution" mental model.

B: User sees a screen of commands — Chat window full of bash. Misdiagnosed as needing --verbose. Root cause: Skill didn't agree to hide commands from user; backend leaks to frontend.

C: Model stalls after send — Can't get session, flow breaks. Misdiagnosed as needing better prompts to parse streaming output. Root cause: stdout is log prose, no single-line JSON and explicit next hop.

D: Chit-chat mutates production — Model is "too proactive." Misdiagnosed as needing a dangerous-command blocklist. Root cause: Skill didn't define "when not to trigger"; recall width equals misfire count.

CLI stands on three pillars: commands grouped by lifecycle domains, Skills that clarify when to act and when not to, and output that tells the model what to run next. Miss one, and it degrades to a wrapped API table.

Core Judgment 2: Callable ≠ Should Call ≠ Will Call Correctly

A CLI generated directly from the API spec solves only "callable." The three remaining gaps are exactly where AI hosts get stuck.

Can the Resource Tree Express "Where in the Lifecycle Are We?"

OpenAPI slices by Agent / materials / tasks / files — correct for system readers. But user intent never stays in one resource: create → develop-publish → user chat yields experience → evolution distill → republish. A single command belongs to one domain, so domains must be sliced by lifecycle so "which segment this intent belongs to" is visible in the command name.

Does Runnable Mean Right Timing?

CLI installed globally ≠ every conversation should mutate platform state. "Let's discuss release strategy" is a sentence but must not trigger writes. Triggering is a semantic judgment , not solvable by tagging commands as dangerous — tags only block known bad commands, not right commands at wrong times.

Are Backend Commands and Frontend Human Talk the Same?

User wants "publish and explain impact scope." Command line is implementation detail; pasting it into chat feeds implementation detail to the user, who then bypasses the Skill to hand-craft commands. Visibility itself is an inducement , so default hidden, expose only for debugging.

Comparative Evaluation

The author's team adopted "scenario domains + Skill trigger boundaries + structured orchestratable output" and rejected:

Path-to-command mirroring

CLI as user tutorial pasted verbatim

Dangerous-command blocklist as substitute for trigger judgment

Approach comparison:

API spec → command mirror : fast generation, full coverage → rejects: no intent, no workspace mental model.

Monolithic agent command : easy to remember → rejects: parameter explosion, model more confused.

Scenario domains + Skill + references : orchestratable, teachable, convergent → rejects: must maintain domain docs and trigger specs.

TUI for humans only : great interactive UX → rejects: host Agent completely unusable.

Blocklist for dangerous commands : quick to ship → rejects: cannot block "right command, wrong timing."

Three Layers, Each Owns One Concern

Domain answers "which lifecycle segment is this intent in", Skill answers "should we act now", command answers "which specific bolt to turn". Responsibilities must not cross: domain crossing into triggers grows an ever-longer exception list; Skill crossing into parameters duplicates command docs; command crossing into business becomes another BFF.

Layer responsibilities:

Scenario Domain — Map intent to workspace and command family. Example: create / develop-publish / evolution / usage-chat / materials

Skill + references — Trigger boundaries, workspace mental model, composite flows. Example: When to use / not use, how to pick among three workspaces, high-risk confirmations

Atomic Command — One indivisible action, stable I/O. Example: publish, add collaborator, send message, query status

Workspace mental model must precede command design — no shortcut:

Development : Where makers edit Agent, publish outward. Cost of mistake: push half-baked version to prod.

Usage : Where published Agent runs user conversations. Cost: pollute live sessions and user data.

Evolution : Where experience aggregates, distills, pushes back to dev / materials / Git. Cost: experience flows to wrong target, evolution drifts.

Picking the wrong domain = editing the wrong disk. As the navigation analogy: navigation takes you to the neighboring city, you diligently renovate a house there — every step correct, wrong place. Same class of accident as "request routed to wrong container," but on the command side.

Inside References: Skill as Atomic "Scenario → Capability" Lesson Units

The CLI skill directory resembles a course syllabus, not a feature list:

skill/dagent-cli/├── SKILL.md          # Entry: three-workspace model for intent classification└── references/    ├── command-map.md    # Intent → lifecycle domain → which manual to read    ├── agent-create.md   # Teaches "create" this one thing    ├── agent-dev.md      # Teaches "develop-maintain + publish"    ├── agent-evolution.md# Teaches "evolution"    ├── agent-use.md      # Teaches "chat usage"    ├── materials.md      # Teaches "materials library maintenance"    ├── tools.md          # Teaches "cross-avatar assist queries"    └── experts-team.md   # Teaches "WorkBuddy expert team"

Each manual follows the same structure: first write "when to use", then the flow and discipline for that scenario. For example, agent-use.md teaches "reuse session_id for follow-ups, only --new for new topics; fixed order sendpreviewresume, never resume first"; experts-team.md teaches "identify host (WorkBuddy traces), fallback to agent-use.md single session if not found" — manuals cross-reference each other.

This reveals Skill's essence: not a CLI feature catalog, but a set of "what scenario, which capability" teaching units. Two design layers stand out:

Atomic : one manual per scenario, commands stay atomic, composition happens in the Agent's orchestration layer, not inside CLI. agent-use doesn't need to know how expert team assembles; experts-team doesn't re-teach chat discipline — references when needed.

Open-ended : new scenario (e.g., expert team) adds a new reference; command tree unchanged, old manuals untouched. Capability growth and teaching growth are independent lines.

Anti-pattern tried: stuff all scenarios into one giant prompt. Every new scenario forced full reshuffle; model searched tens of thousands of tokens, error rate grew with length. Open-ended + atomic = pluggable curriculum — model reads the needed page, not the whole textbook.

Scenario Domains: One Intent, One Domain

Challenge : Same phrase "add a user" maps to three different actions — add a consumer, add a collaborator, grant org authorization. Different resources in API layer, same words from user.

Solution : Command tree expands by lifecycle domains; inside domain, atomize. For ambiguous intent, pick a default (default consumer) and announce the judgment before executing, rather than silently choosing. Org authorization is a fourth landing: search org first, confirm with user by name/path, then grant by org_id — don't treat org as a "user" and add directly.

Implementation (illustrative) :

platform-cli  agent-create   # First creation (irreversible container shape decided here)  agent-dev        # Develop, configure, publish, attach materials  agent-evolution  # Evolution diagnose, sync, push  agent-use        # Chat, sessions, usage-side tasks, instances  materials        # Materials library itself  link / whoami / setup / update ...
# Anti-pattern: mirror API spec, model guesses by literal# platform-cli agents.put_collaborators --body ...# platform-cli agents.put_consumers --body ...# Correct pattern: intent enters domain first, then atomize inside domainplatform-cli agent-dev config consumers add --user ...platform-cli agent-dev config collaborators add --user ...

Intent-to-domain routing rules are thin, cheap to maintain separately:

# Python illustrativeDEFAULT_TARGET = "usage"  # "add a user" defaults to consumerAMBIGUOUS = ("usage", "delegate", "org_grant")def route(verb: str, workspace: str) -> str:    # domain = workspace + lifecycle segment, both required    return f"agent-{workspace}:{verb}"def resolve_target(utterance: str) -> tuple[str, bool]:    hit = [t for t in AMBIGUOUS if t in utterance]    if len(hit) == 1:        return hit[0], False  # explicit, execute directly    return DEFAULT_TARGET, True  # ambiguous, default but inform user
// TypeScript illustrative// Guarantee: domain resolution fails fast, not silently fall to defaulttype Workspace = "develop" | "usage" | "evolution";type Domain = "agent-create" | "agent-dev" | "agent-evolution" | "agent-use" | "materials";function domainOf(ws: Workspace, stage: "create" | "dev" | "evolve" | "use"): Domain {    const table: Record<string, Domain> = {        "create:*": "agent-create",        "develop:dev": "agent-dev",        "evolution:evolve": "agent-evolution",        "usage:use": "agent-use",    };    const hit = table[`${ws}:${stage}`] ?? table[`${ws}:*`];    if (!hit) throw new Error(`Undefined domain combo: ${ws}/${stage}`);    return hit;}

Composite tasks must not rely on model stitching parameters. Multi-step flows like publish, evolution push, expert team go into references/, guided by Skill to read docs then execute.

Guardrails : Atomic ops CLI-first; domain count restrained — if you need an index table to find domains, you've reverted to resource tree. Update discipline: use scoped merge commands, not full-file overwrites — the minute saved by overwrite returns double when someone else's config gets clobbered.

Skill Defines Boundaries, Output Leaves Next Hop

Challenge : Host Agent must dare to operate yet not mutate production on every chit-chat; after operating it must know "what next." Former solved by Skill trigger boundaries, latter by output shape.

Solution : Skill header description explicitly lists "trigger / do-not-trigger" conditions; chat commands return one-line JSON with preview_hint and next_command; hide command details from user.

Implementation (illustrative) :

# SKILL.md header (illustrative)name: platform-clidescription: >  Only use when user explicitly wants to query / diagnose / create / publish / sync / configure permissions on platform state.  Do NOT trigger when only discussing concepts, writing proposals, changing business code, designing UI, troubleshooting non-platform issues.
// TypeScript illustrative// Guarantee: don't make model "learn the art of parsing streaming output"type SendResult = {    session_id: string;    status: "started";    preview_hint: string;    next_command: string;  // full executable line: resume / preview    workspace: "usage" | "develop" | "evolution";};async function sendAndFollow(ctx: CliCtx, res: SendResult): Promise<void> {    // host directly executes next_command, no guess, no regex    await ctx.run(res.next_command);}
# Python illustrative# Guarantee: only one line JSON on stdout, rest to stderr, no parse pollutionimport json, subprocess, sysdef send(agent: str, message: str) -> dict:    out = subprocess.run(        ["platform-cli", "agent-use", "chat", "send", "--agent", agent, "--message", message],        capture_output=True, text=True, check=True    )    res = json.loads(out.stdout.strip().splitlines()[-1])  # take last line    if "next_command" not in res:        raise RuntimeError("CLI did not provide next hop, treat as orchestration failure")    return resres = send("agent-1234", "Show me yesterday's session")print(res["preview_hint"], file=sys.stderr)  # for human eyesubprocess.run(res["next_command"], shell=True, check=True)  # for machine

High-risk actions (publish / offline, overwrite directory, push evolution, change cron) require impact explanation and confirmation before execution; read-only queries skip confirmation, else Agent asks for approval every turn. Windows JSON quoting traps: Skill must hardcode default quoting and upgrade strategy, else model enters infinite retry.

Self-check & Self-heal also codified as fixed actions: when Skill triggers and prepares to use CLI, first run whoami --json (approx every 24h, not repeated in same turn), branch on returned nextActionupdate (upgrade CLI, reinstall latest skill, ensure login), setup (complete init), login (auth), null (proceed). Even if init forgotten, first business command auto-installs and logs in; prompts go to stderr, not polluting stdout parsing. Self-heal completes silently, no user involvement.

Boundary : Skill can install into Cursor-like hosts; version update check runs "when this turn actually needs CLI" once, not before every command.

Two Acceptance Lines: One Publish, One Chat Round

Scenario A: Publish One Change

Skill judges: user wants to mutate platform state → trigger; pure strategy discussion → no trigger.

Enter agent-dev domain, confirm workspace is development.

Read publish reference, explain impact scope, wait for confirmation.

Execute publish atomic command → query status → return result.

Decision point: if model starts hand-writing curl to hit OpenAPI, domain didn't catch intent — fix Skill and commands, not prompts.

Scenario B: Chat with Published Agent

Enter agent-use: send → get one-line JSON.

Follow next_command for preview / resume. Order immutable: must send to obtain session identifier, then resume ; each preview opens new tab, doesn't replace old.

Use file params for local files, don't stuff large content into message.

Decision point: if regex needed to extract session_id from logs to continue, output is not orchestratable — CLI defect, not model's.

Scenario C: Build an Avatar Expert Team on WorkBuddy

New scenario from recent iteration: inside WorkBuddy host, assemble an "expert team whose members are avatars."

Host detection: WorkBuddy (has expert-manager) → skeleton & registration via host, skill only authors member MDs.

Core rule: members carry no domain knowledge, they are avatar shells — each member MD hardcodes its own agent_id, answers only via sendresume path.

Team lead Agent only orchestrates, never answers for members: same round parallel launch relevant members, each completes sendpreviewresume, wait all done before passing content to next phase.

Before each chat trigger, use CLI to verify expert team's system prompt is up-to-date — if updated, modify config first, then proceed.

Decision point: want unique avatars per member? Default all reuse one built-in image unless user explicitly requests custom — time saved on image generation outweighs one decent avatar.

Acceptance checklist:

Domains : newcomer finds domain by intent, not by guessing API paths.

Trigger : pure discussion no misfire; state mutations always trigger.

Workspace : every write operation can state "which workspace I'm editing".

Output : Agent continues without regexing logs.

Human talk : default state user sees no command line in chat.

Expert team : members contain no knowledge, all answers via sendresume through avatars; uid and session id separate.

What This Design Delivers

Layer leaps:

⚡ Quantified efficiency : Composite tasks from "model trial-and-error multiple rounds" to "follow reference once through"

📥 Capability sink : Teammates who can't remember API paths can safely operate via Skill

📚 Pattern upgrade : From "API's command-line shell" to "scenario-organized commands + installable Skills"

Five-Dimension Selection

Comparison across dimensions:

Primary reader : Scenario CLI + Skill = AI host + experts; API-shell CLI = script writers; Pure OpenAPI = systems; Inbound MCP = host model (single session)

Organization : Scenario CLI = by lifecycle intent; API-shell CLI = by resource path; Pure OpenAPI = by resource path; Inbound MCP = by chat verbs

Rules location : Scenario CLI = Skill / references; API-shell CLI = --help; Pure OpenAPI = doc site; Inbound MCP = tool description

Output : Scenario CLI = orchestratable JSON; API-shell CLI = text logs; Pure OpenAPI = JSON / SSE; Inbound MCP = human talk + scripts

Risk control : Scenario CLI = trigger boundaries + high-risk confirm; API-shell CLI = human caution; Pure OpenAPI = app tiering + tokens; Inbound MCP = tool count restraint

Four entry points division in one sentence: Web and IM for humans, OpenAPI for systems, MCP for host model's session, CLI for AI hosts that read Skills. Don't let any one copy another.

Define Applicability First, Then Four Pitfalls

Applicable / Not Applicable

Applicable : AI host operates platform state; cross-workspace lifecycle tasks; delivery that speaks human language to user.

Not applicable : Using CLI to replace stable contract for external promises; making every interface a command for "completeness"; unattended production changes without Skill or confirmation.

Pitfall 1: Wrap Whatever the API Has

Temptation : code generation feels great, one script yields 200 subcommands. Wrong antidote : keep auto-generating, add a mega README. Right antidote : scenario domains; composite flows into references/; atomic commands only inside domain. Back to navigation: don't hand the driver the entire street directory, give them a "find gas station" button.

Pitfall 2: Skill Only Writes "When to Use"

Fear of missing recall leads to overly broad positive descriptions — result: chit-chat triggers status queries and config changes. Fix: make "do not trigger" longer than "trigger" — list pure discussion, proposal writing, business code changes, UI work, non-platform troubleshooting explicitly. Recall didn't drop, misfires halved.

Pitfall 3: Treat Command as User-Facing Reply

Temptation : pasting commands looks professional, transparent. Wrong antidote : add --verbose for more output. Right antidote : backend runs CLI, frontend speaks business language; expose commands only when user explicitly asks for debugging. Navigation analogy: passenger wants to hear "turn right ahead", not the navigation reciting coordinates, satellite IDs, and road topology.

Pitfall 4: Chat Output Not Orchestratable

First version printed streaming text — looked intuitive. When host Agent tried to use it, continuing required regexing session ID from logs; miss → full round restart. Changed to one-line JSON with next_command, encoded sendpreviewresume into Skill, model failure rate dropped immediately. Lesson: machine output and human output must be designed separately from the start.

L1 / L2 / L3 Maturity Levels

L1 : Add Skill trigger / non-trigger boundaries; agree to hide commands from user

L2 : Restructure command tree by scenario domains; chat commands output one-line JSON + next_command L3 : Establish workspace mental model and publish/evolution closed-loop playbooks; all composite flows into references

Summary

CLI's primary reader is the Skill-reading AI host, humans second.

Slice by lifecycle scenarios, not by wrapping API paths one-to-one.

In Skill, "when not to trigger" is more valuable than "when to trigger."

Three-workspace mental model precedes commands — wrong domain = wrong disk.

Hide commands from user; high-risk actions explain impact then confirm.

Skill is atomic "scenario → capability" curriculum: new scenario adds a reference, not a mega-prompt rewrite.

Output must be orchestratable: structured result + explicit next command.

CLI scenario-designed for AI hosts: domains are the map, Skills are the traffic rules — making it an API shell just pushes the choice back to the model.

Next article will cover Tools and MCP: Where Capabilities Come From — after Agent is invoked via three usages, when it goes outbound to call tools, how registration, injection, credentials, and authorization are supplied.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AI agentsSkillsstructured outputdeveloper toolingCLI designAI host integrationscenario domainsworkspace context
James' Growth Diary
Written by

James' Growth Diary

I am James, focusing on AI Agent learning and growth. I continuously update two series: “AI Agent Mastery Path,” which systematically outlines core theories and practices of agents, and “Claude Code Design Philosophy,” which deeply analyzes the design thinking behind top AI tools. Helping you build a solid foundation in the AI era.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.