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

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
博客园 - 三生石上(FineUI控件)
云风的 BLOG
云风的 BLOG
C
Check Point Blog
Engineering at Meta
Engineering at Meta
Y
Y Combinator Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Forbes - Security
Forbes - Security
IT之家
IT之家
L
LINUX DO - 最新话题
N
News and Events Feed by Topic
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
雷峰网
雷峰网
N
News | PayPal Newsroom
The Last Watchdog
The Last Watchdog
V
Visual Studio Blog
月光博客
月光博客
Microsoft Azure Blog
Microsoft Azure Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Webroot Blog
Webroot Blog
TaoSecurity Blog
TaoSecurity Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Schneier on Security
Schneier on Security
P
Privacy International News Feed
G
Google Developers Blog
博客园 - 聂微东
博客园 - 叶小钗
M
MIT News - Artificial intelligence
Apple Machine Learning Research
Apple Machine Learning Research
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
WordPress大学
WordPress大学
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Simon Willison's Weblog
Simon Willison's Weblog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
宝玉的分享
宝玉的分享
H
Hacker News: Front Page
Martin Fowler
Martin Fowler
L
Lohrmann on Cybersecurity
G
GRAHAM CLULEY
酷 壳 – CoolShell
酷 壳 – CoolShell
罗磊的独立博客
T
The Exploit Database - CXSecurity.com
S
Security @ Cisco Blogs
博客园_首页
AWS News Blog
AWS News Blog
P
Proofpoint News Feed
人人都是产品经理
人人都是产品经理
Help Net Security
Help Net Security
Google DeepMind News
Google DeepMind News
T
Threatpost

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
Build Your Own CLI Agent: A Step-by-Step Guide
Miodrag Vilo · 2026-05-20 · via DEV Community

Build Your Own CLI Agent — terminal chat with Ink and Mozaik

I love JavaScript. Even though I have learned several languages, JavaScript has become my first choice when building new projects. In this post I'll walk through a small terminal chat app where a language model can run shell commands for you — something you can actually run locally. At the end there's a GitHub template if you'd rather clone than copy.

Two libraries do most of the heavy lifting:

  • Ink draws the chat in the terminal — the input box, scrolling text, and key handling — using React so you are not building a TUI from scratch.
  • Mozaik connects the model, tool calls, and conversation memory. Think of it as the wiring between "the model said something," "a tool finished," and "show that in the UI," so your screen code does not have to know every detail of the API.

Ink is what the user sees; Mozaik is what coordinates the agent behind the scenes.


What we are building

One Node command that:

  1. Shows a simple chat UI in the terminal.
  2. Forwards what you type to a hosted language model.
  3. Lets the model run terminal commands through a single tool (run_command) when it needs to inspect the machine or run a build.
  4. Prints the model's replies (and optional "calling a tool…" hints) in that same UI — without pushing API calls into every component.

The goal is a clean split: the terminal view stays simple; the agent and tools stay in one place and are easier to test or swap later.


How the pieces fit together

Mozaik runs everything on a shared AgenticEnvironment: when the model speaks, asks for a tool, or a tool returns a result, every piece that has joined that environment can hear about it. For this CLI you mainly care about two kinds of participant:

Role Typical base class Responsibility
Agent BaseAgentParticipant Remembers the conversation, asks the model for the next step, and runs tools (like run_command) when the model asks for them.
Observer / UI bridge BaseObserverParticipant Listens for assistant text and tool activity from the agent and forwards it into Ink through small callbacks — so the screen updates when the model speaks or starts a tool, without owning the agent loop.

In this project, typing in Ink calls session.send, which hands your text to the agent. You could add other participant types later (for example streaming stdin), but a straight send-to-agent path keeps the tutorial easy to follow.

┌─────────────┐     session.send()      ┌──────────────────┐
│  Ink (app)  │ ──────────────────────► │  TerminalAgent   │
└─────────────┘                         │  (agent loop)    │
       ▲                                └────────┬─────────┘
       │ callbacks                            │ join()
       │                                        ▼
┌─────────────┐                         ┌──────────────────┐
│  UIUpdater  │ ◄── onExternal* ─────── │ AgenticEnvironment│
│  (observer) │                         └──────────────────┘
└─────────────┘

Enter fullscreen mode Exit fullscreen mode


Step 1 — Bootstrap the runtime (cli.tsx)

The entry file is intentionally tiny: load environment variables, maybe print a one-line usage hint, then hand off to Ink with render(<App />). Keep agent logic out of here — only bootstrapping.

#!/usr/bin/env node
import React from "react";
import { render } from "ink";
import meow from "meow";
import dotenv from "dotenv";
import path from "node:path";
import { fileURLToPath } from "node:url";
import App from "./app.js";

const here = path.dirname(fileURLToPath(import.meta.url));
dotenv.config({
  quiet: true,
  path: [
    path.resolve(process.cwd(), ".env"),
    path.resolve(here, "..", "..", ".env"),
    path.resolve(here, "..", "..", "..", ".env"),
  ],
});

meow(
  `
    Usage
      $ your-cli

    Starts an interactive chat with the agent.
`,
  { importMeta: import.meta },
);

render(<App />);

Enter fullscreen mode Exit fullscreen mode


Step 2 — Compose the session (session.ts)

This file is the "control room." You create the model, the conversation memory, the thing that runs tools, and the shared environment, then plug in your agent and your UI helper. Everything with awkward names (OpenAIInferenceRunner, ModelContext, and so on) lives here so the React side stays small. When you are done, the UI only needs one method: send(message), forwarded to the agent's onMessage.

import {
  AgenticEnvironment,
  Gpt54,
  ModelContext,
  OpenAIInferenceRunner,
  DefaultFunctionCallRunner,
} from "@mozaik-ai/core";
import { terminalTools } from "./terminal/tools.js";
import { TerminalAgent } from "./terminal/agent.js";
import { UIUpdater } from "./ui-updater.js";

export type AgentSession = {
  send: (message: string) => void;
};

export type AgentListeners = {
  onAssistantText: (text: string) => void;
  onFunctionCall?: (name: string) => void;
};

export function createAgentSession(listeners: AgentListeners): AgentSession {
  const functionCallRunner = new DefaultFunctionCallRunner([...terminalTools]);
  const inferenceRunner = new OpenAIInferenceRunner();

  const context = ModelContext.create("cli-agent");
  const model = new Gpt54();
  model.setTools([...terminalTools]);

  const environment = new AgenticEnvironment();
  const agent = new TerminalAgent(
    inferenceRunner,
    functionCallRunner,
    environment,
    context,
    model,
  );
  const uiUpdater = new UIUpdater(listeners);

  agent.join(environment);
  uiUpdater.join(environment);
  environment.start();

  return {
    send: (message: string) => agent.onMessage(message),
  };
}

Enter fullscreen mode Exit fullscreen mode


Step 3 — The agent loop (terminal/agent.ts)

This is the heart of the app. When someone sends a message, you record it, let the model think, and if it wants to run a tool you run it and feed the result back — then the model gets another turn until it answers in plain language.

In practice:

  • On new user text → add to conversation and ask for the next model response.
  • When the model asks for a tool → remember the call is in flight, run it, store the outcome.
  • When every outstanding tool has finished → ask the model again so it can either reply or request another step.

There is no Ink or terminal drawing in this file — only memory and orchestration — so you can change the UI later without touching the agent.

import {
  BaseAgentParticipant,
  UserMessageItem,
  FunctionCallItem,
  AgenticEnvironment,
  ModelContext,
  GenerativeModel,
  InputStream,
  InferenceRunner,
  FunctionCallRunner,
  FunctionCallOutputItem,
  DeveloperMessageItem,
} from "@mozaik-ai/core";

const programmaticAgentInputStub: InputStream = {
  async *stream() {},
};

export class TerminalAgent extends BaseAgentParticipant {
  private pendingCalls = new Set<string>();

  constructor(
    inferenceRunner: InferenceRunner,
    functionCallRunner: FunctionCallRunner,
    private readonly environment: AgenticEnvironment,
    private readonly context: ModelContext,
    private readonly model: GenerativeModel,
  ) {
    super(programmaticAgentInputStub, inferenceRunner, functionCallRunner);
  }

  override onMessage(message: string): void {
    const developerMessage = DeveloperMessageItem.create(
      `You are a terminal agent. You can run commands in the terminal to help the user with their request.`,
    );

    this.context
      .addContextItem(developerMessage)
      .addContextItem(UserMessageItem.create(message));
    this.runInference(this.environment, this.context, this.model);
  }

  override onFunctionCall(item: FunctionCallItem) {
    this.pendingCalls.add(item.callId);
    this.context.addContextItem(item);
    this.executeFunctionCall(this.environment, item);
  }

  override onFunctionCallOutput(item: FunctionCallOutputItem) {
    this.context.addContextItem(item);
    this.pendingCalls.delete(item.callId);
    if (this.pendingCalls.size === 0) {
      this.runInference(this.environment, this.context, this.model);
    }
  }
}

Enter fullscreen mode Exit fullscreen mode


Step 4 — Tools the model can use (terminal/tools.ts)

Tools are how you tell the model what it is allowed to do outside of chat text. Each tool has a name, a short description the model can read, argument shapes, and an invoke function that runs on your machine.

Here we expose one tool: run_command, which executes a shell command and returns output so the model can use it on its next turn.

import { Tool } from "@mozaik-ai/core";
import { Terminal } from "./terminal.js";

const terminal = new Terminal();

export const terminalTools: Tool[] = [
  {
    name: "run_command",
    description: "Run a command in the terminal.",
    parameters: {
      type: "object",
      properties: {
        command: {
          type: "string",
          description: "The command to run in the terminal.",
        },
        cwd: { type: "string", description: "The current working directory." },
      },
      required: ["command", "cwd"],
    },
    strict: true,
    type: "function",
    invoke: async (args: { command: string; cwd: string }) => {
      const result = await terminal.runCommand(args.command, args.cwd);
      return result;
    },
  },
];

Enter fullscreen mode Exit fullscreen mode


Step 5 — Feed the terminal UI (ui-updater.ts)

The observer sits between Mozaik and Ink. When the agent produces text the user should see, this class forwards it through a callback; when a tool starts, it can add a small status line (for example "calling run_command").

You stay subscribed to external events so you hear what the agent is doing, not duplicate the agent's own work — one clear owner of the loop and one clear owner of the display.

import {
  Participant,
  FunctionCallItem,
  ModelMessageItem,
  BaseObserverParticipant,
} from "@mozaik-ai/core";

type Listeners = {
  onAssistantText: (text: string) => void;
  onFunctionCall?: (name: string) => void;
};

export class UIUpdater extends BaseObserverParticipant {
  constructor(private readonly listeners: Listeners) {
    super();
  }

  override onFunctionCall(item: FunctionCallItem) {
    this.listeners.onFunctionCall?.(item.toJSON()?.name ?? "tool");
  }

  override onExternalFunctionCall(
    _source: Participant,
    item: FunctionCallItem,
  ) {
    this.listeners.onFunctionCall?.(item.toJSON()?.name ?? "tool");
  }

  override onExternalModelMessage(_source: Participant, item: ModelMessageItem) {
    const text = item.content?.text ?? "";
    if (text) this.listeners.onAssistantText(text);
  }
}

Enter fullscreen mode Exit fullscreen mode


Step 6 — Wire Ink (app.tsx)

The Ink layer holds chat history in normal React state, builds the session once so you do not reconnect on every render, and on submit appends the user message then calls session.send. Anything the observer hears arrives through the callbacks you passed in when creating the session.

import React, { useMemo, useRef, useState } from "react";
import { useApp } from "ink";
import { createAgentSession } from "./session.js";

type ChatMessage = {
  id: number;
  role: "user" | "assistant" | "system";
  content: string;
};

export default function App() {
  const { exit } = useApp();
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const nextId = useRef(0);

  const appendMessage = (role: ChatMessage["role"], content: string) => {
    setMessages((previous) => [
      ...previous,
      { id: nextId.current++, role, content },
    ]);
  };

  const session = useMemo(
    () =>
      createAgentSession({
        onAssistantText: (text: string) => {
          appendMessage("assistant", text);
        },
        onFunctionCall: (name: string) => {
          appendMessage("system", `calling tool: ${name}`);
        },
      }),
    [],
  );

  const handleSubmit = (value: string) => {
    const trimmed = value.trim();
    if (!trimmed) return;
    appendMessage("user", trimmed);
    session.send(trimmed);
  };

  // …render messages + <TextInput onSubmit={handleSubmit} /> …
}

Enter fullscreen mode Exit fullscreen mode


Step 7 — Credentials and build

Put your API key in .env (the template expects OPENAI_API_KEY; check Mozaik if you change model or provider). Then install, build, and run the compiled CLI (or npm link if you want a global command).

cp .env.example .env
# add OPENAI_API_KEY=sk-...

npm install
npm run build
npm start

Enter fullscreen mode Exit fullscreen mode


Starter repository

Prefer a working tree over copy-paste? There is a template repo with the same layout this article walks through — agent, observer, tools, and Ink UI already split into files.

Scaffold a fresh project without copying the template's full git history:

npx degit jigjoy-ai/cli-agent-starter my-cli-agent
cd my-cli-agent
git init
git add .
git commit -m "Initial commit"
npm install

Enter fullscreen mode Exit fullscreen mode

Replace jigjoy-ai/cli-agent-starter with your fork or canonical URL if it moves; replace my-cli-agent with your package name. Then edit package.json (name, bin), tweak source/cli.tsx / source/app.tsx branding, and start adding participants and tools.

GitHub alternative: enable Template repository in the repo settings and use Use this template — you get a first commit snapshot with a clean history for a new repo.

Starter template: github.com/jigjoy-ai/cli-agent-starter


Where to go next

  • Add BaseHumanParticipant if you want stdin streaming as first-class InputStream input.
  • Add a second BaseAgentParticipant and use onExternal* handlers to log or aggregate multi-agent chatter.
  • Swap Gpt54 / runners for other models supported by Mozaik as the ecosystem grows.

You now have a concise path from "blank Node project" to Ink front end + Mozaik event bus + tool-running agent — with a degit-friendly repo to hit the ground running.


Learn more

Mozaik: github.com/jigjoy-ai/mozaik

Related: Reactive Agents in Mozaik · Mozaik 3.0 — Agentic Environment

Read the full article on JigJoy: jigjoy.ai/blog/build-your-own-cli-agent