<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Juniarto Samsudin on Medium]]></title>
        <description><![CDATA[Stories by Juniarto Samsudin on Medium]]></description>
        <link>https://medium.com/@juniarto-samsudin?source=rss-99a5a2e5cc91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8CxIbgGinGkm12VHwpMxcw.jpeg</url>
            <title>Stories by Juniarto Samsudin on Medium</title>
            <link>https://medium.com/@juniarto-samsudin?source=rss-99a5a2e5cc91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:00:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@juniarto-samsudin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Stagehand Agent to Fill a Google Form Tutorial: Basic Browser Agent Automation]]></title>
            <link>https://juniarto-samsudin.medium.com/using-stagehand-agent-to-fill-a-google-form-tutorial-basic-browser-agent-automation-efa84cb068ed?source=rss-99a5a2e5cc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/efa84cb068ed</guid>
            <category><![CDATA[browser-automation]]></category>
            <category><![CDATA[stagehand]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-browser-automation]]></category>
            <dc:creator><![CDATA[Juniarto Samsudin]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 09:09:49 GMT</pubDate>
            <atom:updated>2026-06-22T09:09:49.483Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MaENvXNEUG-M8XaO5KrSiQ.png" /></figure><p>There is a very specific kind of task that feels harmless at first and then slowly becomes annoying: entering the same sample data into the same form over and over again.</p><p>Google Forms is a great example. It looks simple, but automating it with traditional browser scripts can turn into a pile of brittle selectors, awkward waits, and weird page-state issues. One small layout change and suddenly your “simple” script is no longer simple.</p><p>That is where Stagehand starts to feel useful.</p><p>Stagehand sits on top of Playwright, but instead of forcing you to handcraft every interaction, it lets you describe what you want in natural language. For pages like Google Forms, that is often a better match for the problem you are actually trying to solve.</p><p>In this post, I will walk through the script in <em>[index.ts]</em>, which fills and submits a Google Form with multiple fake records. More importantly, I will explain why the script is structured the way it is, what Stagehand is really helping with, and where you still want ordinary engineering guardrails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*4Gfz8QHzZnqZ4sgOSV0mdw.jpeg" /></figure><h4><strong>Why Stagehand is a good fit for this</strong></h4><p>Stagehand gives you a few different ways to interact with a page:</p><p>- act() for one focused action<br>- observe() to discover likely actions before choosing one<br>- extract() to pull information out of the page<br>- agent() for multi-step tasks that need some judgment</p><blockquote><em>Filling a form is not really one action. It is a sequence of little decisions.</em></blockquote><p>The browser has to find the right fields, connect each field to the right value, type the content, scroll when necessary, and then submit everything in the right order. That is exactly the kind of workflow where an agent can be more pleasant than a giant collection of selectors.</p><h4><strong>What this script actually does</strong></h4><p>The script submits a Google Form multiple times using realistic fake data.</p><pre>const records: Array&lt;{<br>  name: string;<br>  email: string;<br>  address: string;<br>  phone: string;<br>  comments: string;<br>}&gt; = [<br>  {<br>    name: &quot;Alice Johnson&quot;,<br>    email: &quot;alice.johnson@example.com&quot;,<br>    address: &quot;1428 Elm Street, Springfield, IL 62704&quot;,<br>    phone: &quot;217-555-0142&quot;,<br>    comments: &quot;Looking forward to the upcoming event!&quot;,<br>  },<br>  {<br>    name: &quot;Brian Martinez&quot;,<br>    email: &quot;brian.martinez@example.com&quot;,<br>    address: &quot;753 Maple Avenue, Austin, TX 78701&quot;,<br>    phone: &quot;512-555-0198&quot;,<br>    comments: &quot;Please add me to the mailing list.&quot;,<br>  },<br>  {<br>    name: &quot;Carla Nguyen&quot;,<br>    email: &quot;carla.nguyen@example.com&quot;,<br>    address: &quot;910 Sunset Blvd, Seattle, WA 98101&quot;,<br>    phone: &quot;206-555-0173&quot;,<br>    comments: &quot;Interested in the volunteer program.&quot;,<br>  },<br>  {<br>    name: &quot;David O&#39;Connor&quot;,<br>    email: &quot;david.oconnor@example.com&quot;,<br>    address: &quot;422 Oakwood Drive, Boston, MA 02108&quot;,<br>    phone: &quot;617-555-0124&quot;,<br>    comments: &quot;Can someone call me about my registration?&quot;,<br>  },<br>  {<br>    name: &quot;Emily Patel&quot;,<br>    email: &quot;emily.patel@example.com&quot;,<br>    address: &quot;1188 Cedar Lane, Denver, CO 80202&quot;,<br>    phone: &quot;303-555-0167&quot;,<br>    comments: &quot;Vegetarian meal preference for the dinner.&quot;,<br>  },<br>  {<br>    name: &quot;Felix Romano&quot;,<br>    email: &quot;felix.romano@example.com&quot;,<br>    address: &quot;67 Riverside Way, Portland, OR 97201&quot;,<br>    phone: &quot;503-555-0185&quot;,<br>    comments: &quot;Will arrive late on the first day.&quot;,<br>  },<br>  {<br>    name: &quot;Grace Kim&quot;,<br>    email: &quot;grace.kim@example.com&quot;,<br>    address: &quot;239 Birch Street, Atlanta, GA 30303&quot;,<br>    phone: &quot;404-555-0119&quot;,<br>    comments: &quot;Requesting accessibility accommodations.&quot;,<br>  },<br>  {<br>    name: &quot;Hassan Ali&quot;,<br>    email: &quot;hassan.ali@example.com&quot;,<br>    address: &quot;814 Pine Hollow Rd, Chicago, IL 60601&quot;,<br>    phone: &quot;312-555-0156&quot;,<br>    comments: &quot;Bringing a plus-one to the reception.&quot;,<br>  },<br>  {<br>    name: &quot;Isabella Rossi&quot;,<br>    email: &quot;isabella.rossi@example.com&quot;,<br>    address: &quot;57 Willow Court, San Diego, CA 92101&quot;,<br>    phone: &quot;619-555-0138&quot;,<br>    comments: &quot;Preferred contact time: weekday evenings.&quot;,<br>  },<br>  {<br>    name: &quot;James Thompson&quot;,<br>    email: &quot;james.thompson@example.com&quot;,<br>    address: &quot;1205 Aspen Circle, Nashville, TN 37201&quot;,<br>    phone: &quot;615-555-0102&quot;,<br>    comments: &quot;Thank you for organizing this!&quot;,<br>  },<br>];</pre><p>Each record includes:<br>- name<br>- email<br>- address<br>- phone<br>- comments</p><p>That makes it handy for a few common situations:<br>- testing a form before sharing it<br>- generating sample submissions for demos<br>- checking whether a browser agent can map human field labels to the correct inputs</p><p>It is not meant for spamming forms or dodging restrictions. Use it on forms you own or forms you are allowed to test.</p><p><strong>Before you write code, check the form settings</strong></p><p>This is the part people tend to skip, and it is often the real source of failure.</p><p>If you want a batch-submission script to behave nicely, the Google Form itself needs to allow that workflow. The easiest setup is:<br>- the form opens directly from the link<br>- sign-in is not required<br>- more than one response is allowed</p><p>If the form requires a Google account or limits users to one response, the script has to work around that. At that point, the problem is not really “how do I automate a form?” It is “what rules did the form owner choose?”</p><p>So before you touch the prompt, selectors, or model choice, check the settings.</p><p><strong>## Where to get Stagehand</strong></p><p>If you want to try this yourself, Stagehand is available as an npm package:</p><pre>npm install @browserbasehq/stagehand</pre><p>The package used in this project is `@browserbasehq/stagehand`.</p><p>If you want the official places to start, here they are:<br>- Website: <a href="https://stagehand.dev/">stagehand.dev</a><br>- Docs: <a href="https://docs.stagehand.dev/">docs.stagehand.dev</a><br>- GitHub: <a href="https://github.com/browserbase/stagehand">github.com/browserbase/stagehand</a></p><p><strong><em>If you are the kind of person who likes to read the docs before touching the code, start with the website or docs. </em></strong>They give a much clearer picture of how act(), observe(), extract(), and agent() are meant to be used, and the GitHub repo is there when you want source code, examples, or release history.</p><p>In this project, the import looks like this:</p><pre>import { Stagehand } from &quot;@browserbasehq/stagehand&quot;;</pre><p><strong>The overall flow of the script</strong></p><p>One thing I like about the current script is that it has a clean lifecycle:</p><p>1. Start Stagehand in a visible local browser.<br>2. Open the Google Form.<br>3. Confirm the form is reachable.<br>4. Create one reusable Stagehand agent.<br>5. Loop through a batch of records.<br>6. Fill the form.<br>7. Submit it.<br>8. Verify that Google actually recorded the response.<br>9. Reload the form and repeat.</p><p>That shape matters more than it might look. A lot of flaky automation comes from skipping straight to “type into the field” without first controlling the page lifecycle.</p><p><strong>Step 1: Start Stagehand in a visible browser<br></strong>The script begins like this:</p><pre>import &quot;dotenv/config&quot;;<br>import { Stagehand } from &quot;@browserbasehq/stagehand&quot;;<br>const stagehand = new Stagehand({<br>env: &quot;LOCAL&quot;,<br>localBrowserLaunchOptions: {<br>headless: false,<br>},<br>});<br>await stagehand.init();<br>const page = stagehand.context.pages()[0];</pre><p>Two choices here are especially practical.</p><p><strong><em>env: “LOCAL”</em> </strong>keeps the browser on your own machine, which is ideal while you are still shaping the workflow.</p><p><strong><em>headless: false</em></strong> means you can actually see what the browser is doing. That sounds minor until the first time the page redirects, scrolls oddly, or hangs on a confirmation screen. A visible browser is often the fastest debugging tool you have.</p><p><strong>Step 2: Open the form and make sure the setup matches your expectations</strong></p><p>The form is opened with plain Playwright:</p><pre>const FORM_URL = &quot;https://docs.google.com/forms/d/.../viewform&quot;;<br>await page.goto(FORM_URL, { waitUntil: &quot;domcontentloaded&quot; });</pre><p>This is one of the things I like about Stagehand. You are not trapped inside a magical abstraction. When direct browser control is the simplest answer, you can just use it.</p><p>In the ideal case, the form opens and the fields are ready.</p><p>The current script also includes a sign-in detection branch:</p><pre>const needsSignIn = async (): Promise&lt;boolean&gt; =&gt; {<br>const url = page.url();<br>if (url.includes(&quot;accounts.google.com&quot;)) return true;<br>try {<br>  const visible = await page<br>      .locator(&quot;text=Sign in to continue&quot;)<br>      .first()<br>      .isVisible()<br>      .catch(() =&gt; false);<br>  return Boolean(visible);<br>      } <br>catch {<br>      return false;<br>  }<br>};</pre><p>I would think of this as a backup plan, not the happy path.</p><p>If you control the form, it is cleaner to make the form accessible enough for the workflow you want to test. But if you cannot change the settings, the script handles the interruption honestly by pausing for manual sign-in:</p><pre>if (await needsSignIn()) {<br>  console.log(&quot;Google sign-in required. Please sign in manually.&quot;);<br>  await waitForEnter(<br>      &quot;After signing in and seeing the form, press Enter here to continue…&quot;<br>  );<br>  await page.goto(FORM_URL, { waitUntil: &quot;domcontentloaded&quot; });<br>}</pre><p>That may not sound glamorous, but it is a perfectly reasonable engineering choice. Good automation does not have to pretend every obstacle can be solved elegantly.</p><p><strong>Step 3: Wait for the form before asking the agent to work</strong></p><p>Before the agent starts filling anything, the script waits for text inputs and textareas:</p><pre>await page<br>  .waitForSelector(&#39;input[type=&quot;text&quot;], textarea&#39;, { timeout: 20000 })<br>  .catch(() =&gt; {<br>      console.warn(&quot;Warning: form inputs not detected within 20s.&quot;);<br>});</pre><p>This is not the exciting part of the script, but it is the kind of line that saves you from annoying failures later.</p><p>AI agents still operate inside a real browser. If the page is only half ready, the agent starts from a bad position. A short wait here is much cheaper than debugging a misleading error after the fact.</p><p><strong>Step 4: Create one agent and let it handle the whole form</strong></p><p>Here is the core of the automation:</p><pre>const agent = stagehand.agent({<br>  mode: &quot;hybrid&quot;,<br>  model: &quot;openai/gpt-5.1&quot;,<br>  systemPrompt:<br>    &quot;You fill out Google Forms accurately. Fill every field exactly as given. After filling all fields, click the Submit button. Do not ask questions.&quot;,<br>});</pre><p>This works well for three reasons.</p><p>First, the script is using an agent for a genuinely multi-step task. That is a strong use case for Stagehand.</p><p>Second, the agent is created once and reused across the whole batch, which keeps the workflow simple.</p><p>Third, the system prompt is clear without being wordy. It tells the agent what success looks like, what it should do next, and what it should avoid.</p><p>That is usually the right tone for browser agents. Specific beats clever.</p><p><strong>Step 5: Pass structured data into a natural-language task</strong></p><p>For each record, the script builds a variables object:</p><pre>const variables = {<br>  name: record.name,<br>  email: record.email,<br>  address: record.address,<br>  phone: record.phone,<br>  comments: record.comments,<br>};</pre><p>Then it passes that data into the instruction:</p><pre>const result = await agent.execute({<br>  instruction:<br>    &quot;Fill out this Google Form with these values and click Submit: &quot; +<br>    &quot;name=%name%, email=%email%, address=%address%, phone number=%phone%, comments=%comments%. &quot; +<br>    &quot;After filling all 5 fields, click the Submit button at the bottom.&quot;,<br>    variables,<br>    maxSteps: 15,<br>    highlightCursor: true,<br>});</pre><p>This is one of the nicest parts of the design.</p><p>The task is written in plain language, but the data is still structured. That gives you a useful balance:</p><ul><li>the agent gets flexibility in how it understands the page</li><li>your code keeps full control over the values being submitted</li></ul><p>On a third-party interface like Google Forms, that is often much less fragile than trying to wire every field manually.</p><p><strong>Why Google Forms is a good stress test</strong></p><p>Google Forms looks clean in the browser, but the markup is not always pleasant to automate directly.</p><ul><li>labels are not always mapped in the cleanest way</li><li>field positions can change</li><li>validation can appear dynamically</li><li>some inputs only become obvious after scrolling</li></ul><p>Humans do fine with that. Traditional automation often does not.</p><p>Stagehand helps because it lets the browser agent reason about what the page means, not just what the DOM happens to look like at that moment.</p><p>That does not mean you should trust it blindly. It means you can spend less effort fighting selectors and more effort designing a workflow that is easy to verify.</p><p><strong>Step 6: Verify the result instead of trusting intent</strong></p><p>This is the part I would keep even if everything else changed.</p><p>After <em>agent.execute() </em>returns, the script still checks the page for Google’s confirmation message:</p><pre>const confirmed = await page<br>  .waitForSelector(&quot;text=Your response has been recorded&quot;, {<br>      timeout: 15000,<br>  })<br>  .then(() =&gt; true)<br>  .catch(() =&gt; false);</pre><p>Then it combines that with the agent result:</p><pre>if (result.success &amp;&amp; result.completed &amp;&amp; confirmed) {<br>  console.log(&quot;Submitted successfully.&quot;);<br>  successCount++;<br>} else {<br>  console.log(<br>    `Submission may not have completed. agent.success=${result.success}, completed=${result.completed}, confirmed=${confirmed}`<br>  );<br>}</pre><p>That is the right mindset.</p><p>An agent saying “I think I finished” is useful. The page itself saying “Your response has been recorded” is better. Whenever you can, let the browser state be the final judge.</p><p><strong>Step 7: Reset the form between responses</strong></p><p>After a submission, Google Forms usually shows a confirmation page instead of a fresh blank form. So before the next record, the script navigates back to the original form URL:</p><pre>if (i &gt; 0) {<br>  await page.goto(FORM_URL, { waitUntil: &quot;domcontentloaded&quot; });<br>  await page<br>    .waitForSelector(&#39;input[type=&quot;text&quot;], textarea&#39;, { timeout: 15000 })<br>  .catch(() =&gt; {});<br>}</pre><p>You could try to click “Submit another response,” but reloading the canonical URL is simpler and usually easier to reason about.</p><p>Of course, this only works if the form actually allows multiple responses. If Google Forms is configured to allow one response per user, the script is not broken. The form is simply enforcing the rule it was given.</p><p><strong>Step 8: Slow the script down on purpose</strong></p><p>The script waits five seconds between submissions:</p><pre>const REST_MS = 5000;<br>await new Promise((r) =&gt; setTimeout(r, REST_MS));</pre><p>I like this choice more than I would have a few years ago.</p><p>When people automate forms, there is a natural temptation to make everything fast. In practice, a slightly slower script is often the one that behaves better. A short pause gives the page, browser, and network a moment to settle.</p><p>Fast is satisfying. Predictable is better.</p><p><strong>A simplified version of the approach</strong></p><p>Here is a trimmed version of the same idea:</p><pre>import &quot;dotenv/config&quot;;<br>import { Stagehand } from &quot;@browserbasehq/stagehand&quot;;<br>const FORM_URL = &quot;https://docs.google.com/forms/d/.../viewform&quot;;<br>const records = [<br>  {<br>    name: &quot;Alice Johnson&quot;,<br>    email: &quot;alice.johnson@example.com&quot;,<br>    address: &quot;1428 Elm Street, Springfield, IL 62704&quot;,<br>    phone: &quot;217–555–0142&quot;,<br>    comments: &quot;Looking forward to the upcoming event!&quot;,<br>  },<br>];<br>async function main() {<br>  const stagehand = new Stagehand({<br>      env: &quot;LOCAL&quot;,<br>      localBrowserLaunchOptions: { headless: false },<br>  });<br>  await stagehand.init();<br>  const page = stagehand.context.pages()[0];<br>  await page.goto(FORM_URL, { waitUntil: &quot;domcontentloaded&quot; });<br>  await page.waitForSelector(&#39;input[type=&quot;text&quot;], textarea&#39;, {<br>  timeout: 20000,<br>  });<br><br>  const agent = stagehand.agent({<br>    mode: &quot;hybrid&quot;,<br>    model: &quot;openai/gpt-5.1&quot;,<br>    systemPrompt:<br>      &quot;You fill out Google Forms accurately. Fill every field exactly as given. After filling all fields, click the Submit button. Do not ask questions.&quot;,<br>  });<br><br>for (const record of records) {<br>  const result = await agent.execute({<br>      instruction:<br>        &quot;Fill out this Google Form with these values and click Submit: &quot; +<br>        &quot;name=%name%, email=%email%, address=%address%, phone number=%phone%, comments=%comments%. &quot; +<br>        &quot;After filling all 5 fields, click the Submit button at the bottom.&quot;,<br>      variables: record,<br>      maxSteps: 15,<br>      highlightCursor: true,<br>  });<br>  const confirmed = await page<br>        .waitForSelector(&quot;text=Your response has been recorded&quot;, { timeout: 15000 })<br>        .then(() =&gt; true)<br>    .catch(() =&gt; false);<br>    console.log({<br>        success: result.success,<br>        completed: result.completed,<br>        confirmed,<br>    });<br>  }<br>    await stagehand.close();<br>  }<br>  main().catch(console.error);</pre><p><strong>When </strong>agent()<strong> is not the best tool</strong></p><p>This example uses agent() because filling a form is naturally multi-step.</p><p>But not every Stagehand workflow needs a full agent. If you want tighter control over a single interaction, observe() plus act() can be easier to debug. For example, if your task is just “find the submit button and click exactly the best candidate,” that smaller pattern may be a better fit.</p><p>The rough rule is simple:</p><ul><li>use agent() when the browser needs to interpret a sequence of actions</li><li>use observe() and act() when you want more precise control over one action</li></ul><p><strong>Final recap</strong></p><p>We used Stagehand to automate a Google Form by:</p><ul><li>launching a local visible browser</li><li>making sure the Google Form settings allow open access and repeated responses</li><li>keeping a manual sign-in fallback only for restricted forms</li><li>creating one reusable browser agent</li><li>passing structured data into a natural-language instruction</li><li>verifying the confirmation message after submission</li><li>repeating the flow for multiple test records</li></ul><p>If you are learning Stagehand, this is a strong example to study because it shows the unglamorous part of browser automation: waiting, reloading, checking state, and making sure the page really did what you expected. That is usually where reliability comes from.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efa84cb068ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Vibe Coding: Build a Terminal File Browser with Spec Kit, Ink and Spec-Driven Development…]]></title>
            <link>https://juniarto-samsudin.medium.com/practical-vibe-coding-build-a-terminal-file-browser-with-spec-kit-ink-and-spec-driven-development-f6f74feb48a6?source=rss-99a5a2e5cc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6f74feb48a6</guid>
            <category><![CDATA[spec-kit]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[spec-driven-development]]></category>
            <dc:creator><![CDATA[Juniarto Samsudin]]></dc:creator>
            <pubDate>Sun, 31 May 2026 09:33:31 GMT</pubDate>
            <atom:updated>2026-05-31T09:33:31.716Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Practical Vibe Coding: Build a Terminal File Browser with Spec Kit, Ink and Spec-Driven Development in VSCode</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*orHDzUqpc28plcJAIPy6KA.png" /></figure><p>Most AI coding workflows still start with code. You describe a feature, the agent jumps into implementation, and only later realize that half the important decisions were never written down.</p><p>Spec Kit flips that around.</p><p>Instead of treating specs as throwaway notes, it turns them into the backbone of the build. You define the product behavior first, clarify ambiguity early, then let the AI generate a technical plan, task list, and implementation from that shared source of truth.</p><p>In this tutorial, we will build a small terminal file browser with GitHub Copilot, Spec Kit, and Ink. The goal is not just to get a working app. The goal is to learn a beginner-friendly workflow for spec-driven development that you can reuse on your next project.</p><p><strong>What is Spec-Driven Development?</strong></p><p>Spec-driven development means you describe what the product should do before deciding how to build it.</p><p>Spec Kit organizes that into a repeatable flow:</p><p>1.<strong> /constitution</strong> defines project principles.<br>2. <strong>/specify</strong> defines user-facing behavior.<br>3. <strong>/clarify</strong> resolves ambiguity.<br>4.<strong> /plan</strong> chooses the technical approach.<br>5. <strong>/tasks</strong> breaks the work into small steps.<br>6. <strong>/analyze</strong> checks consistency across artifacts.<br>7. <strong>/implement</strong> executes the plan.</p><p>That sequence matters. The earlier files answer product questions. The later files answer engineering questions.</p><p><strong>What We Are Building</strong></p><p>We will build a read-only terminal dashboard that lets a user browse the local filesystem.</p><p>The first version supports:</p><p>- viewing the current directory<br>- moving selection with the keyboard<br>- entering folders<br>- going back to the parent folder<br>- refreshing the listing<br>- showing loading, empty, and error states<br>- staying read-only and safe</p><p>The final dashboard looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*OMQIa7vID_2aP0N8RwAyIQ.png" /><figcaption>Text Dashboard</figcaption></figure><p>It has four visible regions:</p><p>- a header<br>- a left sidebar for navigation context<br>- a right content panel for directory entries<br>- a footer with keyboard hints</p><p><strong>Step 1: Install Spec Kit</strong></p><p>Spec Kit is distributed through the `specify` CLI.</p><pre>uv tool install specify-cli - from git+https://github.com/github/spec-kit.git<br>specify - version</pre><p>Then initialize a project that targets GitHub Copilot:</p><pre>specify init my-project - ai copilot</pre><p>If you already have a project folder, you can initialize in place:</p><pre>specify init . - ai copilot</pre><p>According to the Spec Kit docs, this gives your AI agent a structured set of slash commands for the full workflow, from constitution to implementation.</p><p><strong>Step 2: Add Ink Knowledge to the Project</strong></p><p>Our app is a terminal UI, so we also want the agent to know Ink patterns.</p><p>Add the Ink skill:</p><pre>npx skills add juniarto-samsudin/ink-tui-skill</pre><p>Why do this? Because Ink apps have a few recurring patterns that are easy to get wrong when you are new:</p><p>- keep argument parsing in <em>cli.tsx</em><br>- render the main app from <em>App.tsx</em><br>- model layout with <em>Box</em> and <em>Text</em> first<br>- add keyboard handling early with <em>useInput()</em><br>- keep global keys at the top level<br>- guard panel-specific input with focus state</p><p>That guidance is simple, but it prevents a lot of messy TUI code.</p><p><strong>Step 3: Start with the Constitution</strong></p><p>The constitution is not the feature spec. Think of it as the project DNA.</p><p>It defines rules that every future feature should follow. For this tutorial, the important principles are:</p><p>- tutorial-first development<br>- specification-first workflow<br>- safe local filesystem interaction<br>- keyboard-first terminal UX<br>- testable core logic<br>- incremental implementation<br>- cross-platform awareness</p><p>Prompt example on speckig.constitution agent:</p><pre>/speckit.constitution<br>Create a project constitution for a learning-focused terminal application project.<br>Use these principles:<br>- tutorial-first development<br>- specification-first workflow<br>- safe local filesystem interaction<br>- keyboard-first terminal user experience<br>- testable core logic<br>- incremental implementation<br>- cross-platform awareness</pre><p>This is a good beginner checkpoint: if you cannot state the project</p><p><strong>Step 4: Write the Product Spec</strong></p><p>Now describe the product behavior without leaking technical implementation details.</p><p>This is where many beginners slip. They write something like, “Use Ink and TypeScript to create a sidebar with React hooks.” That belongs in the plan, not the spec.</p><p>The spec should answer questions like these:</p><p>- what should the user see?<br>- what should the user be able to do?<br>- what should happen on errors?<br>- what is intentionally out of scope?</p><p>Prompt example on speckit.specify agent:</p><pre>/speckit.specify Build a terminal-based file browser for learning purposes.<br>The application should let a user browse the local filesystem from inside a<br>text-based terminal interface.<br>Core user experience:<br>- show a header area<br>- show a left navigation context area<br>- show a right directory contents area<br>- start in the current working directory by default<br>- support keyboard controls for moving, entering folders, going to parent,<br>refreshing, and quitting<br>- remain read-only<br>- show loading, empty, and error states<br>Non-goals for version 1:<br>- file preview<br>- file editing<br>- file deletion<br>- mouse support<br>- recursive tree view</pre><p>Notice the tone here. We are describing behavior and boundaries, not code.</p><p><strong>Step 5: Clarify the Ambiguous Parts</strong></p><p>Good specs still have gaps. <em>/speckit.clarify</em> is where you resolve them before implementation starts.</p><p>For this file browser, useful clarifications included:</p><p>- default starting path is the current working directory<br>- one optional path argument is allowed<br>- invalid paths should show a clear message and fall back predictably<br>- pressing Enter on a file should show a “not implemented” status message<br>- hidden files are shown by default<br>- symlinks should be visible but not handled with complicated traversal rules<br>- the left panel should show breadcrumbs, not a full recursive tree</p><p>Prompt example on <em>/speckit.clarify</em> agent:</p><pre>/speckit.clarify<br>Clarify the feature specification for the terminal file browser.<br>Resolve these areas:<br>1. Starting path behavior<br>2. Enter on files<br>3. Left panel scope<br>4. Hidden files<br>5. Symbolic links<br>6. Large directories<br>7. Cross-platform path handling</pre><p>This step saves time. It is much cheaper to settle ambiguity here than after the agent has written the wrong code in ten files.</p><p><strong>Step 6: Plan the Technical Design</strong></p><p>Only after the behavior is stable should you choose the stack and structure.</p><p>For this project, the plan uses:</p><p>- Node.js<br>- TypeScript<br>- Ink<br>- React functional components<br>- Vitest<br>- `fs/promises` and `path`</p><p>Prompt example:</p><pre>/speckit.plan Use Node.js, TypeScript, and the Ink framework to implement the<br>terminal file browser. Use agent skill [ink-tui-skill].<br>Architecture:<br>- separate filesystem logic from UI rendering<br>- separate navigation state from presentational components<br>- create a filesystem service for reading directories<br>- create a browser state layer for selection, loading, errors, and navigation<br>- keep components focused on rendering<br>- test filesystem and navigation logic outside the UI</pre><p>This is where implementation details belong. In our project, that led to a clean structure like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*y4c0EWTmvCatqdFN9EVvyA.png" /></figure><p>One of the most useful design choices here is separating three layers:</p><p><em>fileSystemService -&gt; reads the filesystem<br>browserStateHelpers -&gt; pure state transitions<br>useFileBrowser -&gt; React state wrapper</em></p><p>That makes the core logic easier to test and easier to explain.</p><p><strong>Step 7: Generate Tasks Before Code</strong></p><p>Once the plan is ready, let Spec Kit turn it into an ordered task list.</p><pre>/speckit.tasks<br>Generate tutorial-friendly implementation tasks.<br>Requirements:<br>- keep each task small and explainable<br>- include exact file paths<br>- group tasks by phase<br>- include tests for utilities and services<br>- include README documentation tasks</pre><p>This matters more than it looks. A good `tasks.md` prevents the agent from skipping invisible but important work like tests, empty states, and docs.</p><p><strong>Step 8: Analyze Before Implementing</strong></p><p>Before you let the AI write code, run a consistency check.</p><pre>/speckit.analyze<br>Check the constitution, specification, plan, and tasks for consistency.<br>Pay attention to:<br>- read-only filesystem safety<br>- keyboard coverage<br>- error states<br>- test coverage for navigation and filesystem behavior<br>- avoiding recursive scanning in version 1</pre><p>This is the quality gate. If the plan says “read-only” but the tasks quietly introduce file operations, this is where you catch it.</p><p><strong>## Step 9: Implement in Small, Controlled Rounds</strong></p><p>Now run implementation.</p><pre>/speckit.implement<br>Implement the feature according to the generated tasks.<br>Constraints:<br>- keep the implementation read-only<br>- keep dependencies minimal<br>- run tests after implementation<br>- update README.md</pre><p>In practice, implementation often takes more than one pass. That is normal.</p><p>For example, after the first round the dashboard may work, but the three panels might not be visually separated. That is a perfect time for a focused follow-up prompt:</p><pre>/speckit.implement<br>The current layout is missing the proper three-region dashboard structure.<br>Please implement:<br>- a Header panel at the top<br>- a LeftPanel sidebar on the left<br>- a RightPanel content area on the right<br>- a Footer at the bottom<br>The regions should be visually separated with borders.</pre><p>Then, if you want fixed dimensions and keyboard focus between panels, you can iterate again:</p><pre>/speckit.implement<br>sidebar, header and content should be fixed width and height.<br>user can move among them using tab.</pre><p>This is another good beginner lesson: spec-driven development is structured, not rigid. You still refine the product, but you do it with explicit prompts and traceable intent.</p><p><strong>Step 10: Understand the Ink-Specific Pieces</strong></p><p>From the Ink skill, a few patterns are especially useful for this app:</p><p>1. Keep CLI parsing in `cli.tsx` and render the UI from `App.tsx`.<br>2. Use `Box` and `Text` to model the dashboard before adding complexity.<br>3. Add `useInput()` early so keyboard handling is explicit.<br>4. Keep global keys like quit and tab focus in the top-level app.<br>5. Route panel-specific keys based on which panel is focused.</p><p>A simple layout sketch in Ink looks like this:</p><pre>&lt;Box flexDirection=&quot;column&quot;&gt;<br>&lt;Header /&gt;<br>&lt;Box flexDirection=&quot;row&quot;&gt;<br>&lt;LeftPanel /&gt;<br>&lt;RightPanel /&gt;<br>&lt;/Box&gt;<br>&lt;Footer /&gt;<br>&lt;/Box&gt;</pre><p>That sounds small, but it reflects the whole dashboard structure from the spec.</p><p><strong>Why This Workflow Works for Beginners</strong></p><p>If you are new to AI-assisted development, this workflow gives you something very valuable: separation of concerns for thinking.</p><p>- The constitution answers, “What kind of project are we building?”<br>- The spec answers, “What should the product do?”<br>- Clarification answers, “What did we forget to decide?”<br>- The plan answers, “How should we build it?”<br>- Tasks answer, “In what order should we do the work?”<br>- Analyze answers, “Does it still make sense as a whole?”<br>- Implement answers, “Now write the code.”</p><p>That structure makes it easier to collaborate with AI because each stage narrows the problem.</p><p><strong>Final Takeaway</strong></p><p>The biggest mindset shift is this: do not ask the AI to “build the app” too early.</p><p>Ask it to help you define the rules, the behavior, the open questions, the architecture, and the task sequence first. Once those are solid, implementation becomes much more predictable.</p><p>For a small project like a terminal file browser, the payoff is immediate. You get a cleaner architecture, safer behavior, better tests, and a tutorial that stays understandable from beginning to end.</p><p>If you want to try this yourself, start small:</p><p>1. pick a feature with clear user interaction<br>2. write the spec before the stack<br>3. clarify the ambiguous parts<br>4. keep the first version intentionally narrow<br>5. let the agent implement only after the artifacts agree</p><p>That is spec-driven development in practice: slower at the start, usually much faster once the code begins.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6f74feb48a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Terminal UI with Ink: A Beginner-Friendly Tutorial]]></title>
            <link>https://juniarto-samsudin.medium.com/building-a-terminal-ui-with-ink-a-beginner-friendly-tutorial-1581041c7168?source=rss-99a5a2e5cc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/1581041c7168</guid>
            <category><![CDATA[tui]]></category>
            <category><![CDATA[ink]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[linux-terminal]]></category>
            <dc:creator><![CDATA[Juniarto Samsudin]]></dc:creator>
            <pubDate>Mon, 25 May 2026 02:14:11 GMT</pubDate>
            <atom:updated>2026-05-25T02:14:11.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hb3Nj2Qy0jkuVzeyCQGmsA.png" /></figure><p>If you already know React, Ink feels surprisingly familiar. If you do not know React, that is still fine. Ink lets you build terminal applications using components instead of manually printing lines with `console.log()`.</p><p>This tutorial walks from the very beginning: project setup, directory structure, how Ink renders a terminal user interface, how keyboard input works, why the app stays open, how to switch focus between panels, how to open a popup detail box, and how commands like `npm link` and `npx` make your CLI runnable.</p><p>This guide uses the current `my-ink-cli` project as the example. It is written for people who are completely new to Ink.</p><p><strong>What Ink Is</strong></p><blockquote>Ink is a library for building Terminal User Interfaces, or TUIs, with React.</blockquote><p>A TUI is not a web page. It runs inside the terminal. That means there is no normal browser mouse interaction by default. Beginners often expect clickable panels, hover states, and pointer movement. Ink does not work like that out of the box. Most Ink apps are controlled by the keyboard.</p><p><strong>So when you build an Ink app, think like this:</strong></p><p>- The terminal is your screen.<br>- React components are your UI building blocks.<br>- Keyboard input is your main interaction model.<br>-Layout is made with Ink components like `Box` and `Text`.</p><p><strong>What We Will Build</strong></p><p>The example app has:</p><p>- a header<br>- a left navigation panel<br>- a content panel<br>- a popup detail box that opens on top of the content panel<br>- keyboard navigation with arrow keys, `Tab`, `Enter`, `x`, `Esc`, and `q`</p><p><strong>Prerequisites</strong></p><p>Before starting, make sure you have:</p><p>- Node.js installed<br>- npm installed<br>- a terminal you can run Node commands in<br>- basic familiarity with JavaScript or TypeScript</p><p>You can check your versions with:</p><pre>node -v<br>npm -v</pre><p><strong>Step 1: Create a New Ink Project</strong></p><p>The easiest way to start is with Ink’s starter tool:</p><pre>npx create-ink-app my-ink-cli<br>cd my-ink-cli<br>npm install</pre><p>This scaffolds a working Ink project. The starter already gives you a minimal CLI and a simple component.</p><p><strong>Step 2: Understand the Directory Structure<br></strong>At the point covered in this tutorial, the project looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*4WWH_iK-4jUGxCxjIYPC9Q.png" /><figcaption>Directory Structure</figcaption></figure><p>What each file does:</p><p>- `package.json` defines the package name, scripts, dependencies, and the executable CLI entry.<br>- `readme.md` is the starter documentation.<br>- `test.tsx` contains tests for the Ink UI.<br>- `tsconfig.json` configures TypeScript.<br>- `source/cli.tsx` is the CLI entry point.<br>- `source/app.tsx` is the actual terminal UI.<br>- `tutorial.md` is this tutorial.</p><p>After you build the project, TypeScript outputs compiled files into `dist/`. The most important generated file is `dist/cli.js`.</p><p><strong>## Step 3: Install the Main Dependencies</strong></p><p>This project uses these main runtime dependencies:</p><pre>{&quot;dependencies&quot;: {<br>  &quot;ink&quot;: &quot;^4.1.0&quot;,<br>  &quot;meow&quot;: &quot;^11.0.0&quot;,<br>  &quot;react&quot;: &quot;^18.2.0&quot;<br>  }<br>}</pre><p>What they do:</p><ul><li>`ink` renders React components in the terminal.<br>- `react` gives you the component model and hooks.<br>- `meow` parses command-line flags like ` — name=Jane`.</li></ul><p><strong>## Step 4: Understand the CLI Entry Point</strong></p><p>The first important file is `source/cli.tsx`:</p><pre>#!/usr/bin/env node<br>import React from &#39;react&#39;;<br>import {render} from &#39;ink&#39;;<br>import meow from &#39;meow&#39;;<br>import App from &#39;./app.js&#39;;<br>const cli = meow(<br>`<br>Usage<br>$ my-ink-cli<br>Options<br> - name Your name<br>Examples<br>$ my-ink-cli - name=Jane<br>Hello, Jane<br>`,<br>{<br>importMeta: import.meta,<br>flags: {<br>name: {<br>type: &#39;string&#39;,<br>},<br>},<br>},<br>);<br>render(&lt;App name={cli.flags.name} /&gt;);</pre><p>This file does four jobs.</p><p><strong>First</strong>, the shebang line tells the operating system to run the file with Node:</p><pre>#!/usr/bin/env node</pre><p><strong>Second</strong>, `meow` reads terminal flags. In this project, it reads ` — name`.</p><p><strong>Third</strong>, `render()` from Ink starts the TUI.</p><p><strong>Fourth</strong>, the `App` component receives the parsed flag and renders the UI.</p><p>A useful mental model is:</p><p><strong><em>terminal command -&gt; meow parses arguments -&gt; Ink renders &lt;App /&gt;</em></strong></p><p><strong>## Step 5: Build the UI in </strong>`app.tsx`</p><p>Here is the current application code:</p><pre>import React, {useEffect, useState} from &#39;react&#39;;<br>import {Box, Text, useApp, useInput} from &#39;ink&#39;;<br><br>type Props = {<br>  name: string | undefined;<br>};<br><br>type SidebarProps = {<br>  selectedIndex: number;<br>  setSelectedIndex: React.Dispatch&lt;React.SetStateAction&lt;number&gt;&gt;;<br>  focused: boolean;<br>};<br><br>type ContentProps = {<br>  name: string;<br>  selectedItem: (typeof navItems)[number];<br>  focused: boolean;<br>  isDetailOpen: boolean;<br>  onOpenDetail: () =&gt; void;<br>  onCloseDetail: () =&gt; void;<br>};<br><br>const navItems = [&#39;Home&#39;, &#39;About&#39;, &#39;Settings&#39;, &#39;Help&#39;] as const;<br><br>const itemDetails: Record&lt;(typeof navItems)[number], string&gt; = {<br>  Home: &#39;This is the home view. Use it as the main overview area of the dashboard.&#39;,<br>  About: &#39;This page explains what this dashboard is for and who it is built for.&#39;,<br>  Settings: &#39;Configure preferences, themes, and other app-level options here.&#39;,<br>  Help: &#39;Quick reference for keyboard shortcuts and navigation hints.&#39;,<br>};<br><br>function Sidebar({selectedIndex, setSelectedIndex, focused}: SidebarProps) {<br>  useInput((input, key) =&gt; {<br>    if (!focused || input) {<br>      return;<br>    }<br>    if (key.upArrow) {<br>      setSelectedIndex(index =&gt; Math.max(0, index - 1));<br>    }<br>    if (key.downArrow) {<br>      setSelectedIndex(index =&gt; Math.min(navItems.length - 1, index + 1));<br>    }<br>  });<br>  return (<br>    &lt;Box borderStyle=&quot;single&quot; width={20} flexDirection=&quot;column&quot; paddingX={1}&gt;<br>      &lt;Text bold underline color={focused ? &#39;yellow&#39; : undefined}&gt;<br>        Navigation<br>      &lt;/Text&gt;<br>        {navItems.map((item, index) =&gt; (<br>          &lt;Text key={item} color={index === selectedIndex ? &#39;cyan&#39; : undefined}&gt;<br>              {index === selectedIndex ? &#39;▶&#39; : &#39;•&#39;} {item}<br>          &lt;/Text&gt;<br>         ))}<br>    &lt;/Box&gt;<br>  );<br>}<br><br>function Content({<br>  name,<br>  selectedItem,<br>  focused,<br>  isDetailOpen,<br>  onOpenDetail,<br>  onCloseDetail,<br>}: ContentProps) {<br>  useInput((input, key) =&gt; {<br>      if (!focused) {<br>        return;<br>      }<br>      <br>      if (isDetailOpen) {<br>        if (input === &#39;x&#39;) {<br>            onCloseDetail();<br>        }<br>      return;<br>      }<br><br>      if (key.return) {<br>        onOpenDetail();<br>      }<br> });<br><br>return (<br>    &lt;Box borderStyle=&quot;single&quot; flexGrow={1} flexDirection=&quot;column&quot; paddingX={1}&gt;<br>    &lt;Text bold underline color={focused ? &#39;yellow&#39; : undefined}&gt;<br>        {selectedItem}<br>    &lt;/Text&gt;<br>    &lt;Text dimColor={isDetailOpen}&gt;<br>        Hello, &lt;Text color={isDetailOpen ? undefined : &#39;green&#39;}&gt;{name}&lt;/Text&gt;!<br>    &lt;/Text&gt;<br>    &lt;Text dimColor&gt;<br>        {isDetailOpen ? &#39;Press x to close the panel&#39; : &#39;Press Enter to open details&#39;}<br>    &lt;/Text&gt;<br>    {isDetailOpen &amp;&amp; (<br>          &lt;Box<br>              borderStyle=&quot;double&quot;<br>              borderColor=&quot;magenta&quot;<br>              flexDirection=&quot;column&quot;<br>              paddingX={1}<br>              marginTop={1}<br>              width=&quot;90%&quot;<br>              alignSelf=&quot;center&quot;<br>          &gt;<br>            &lt;Text bold color=&quot;magenta&quot;&gt;{selectedItem}&lt;/Text&gt;<br>            &lt;Text&gt;{itemDetails[selectedItem]}&lt;/Text&gt;<br>            &lt;Text dimColor&gt;── Press x to close ──&lt;/Text&gt;<br>          &lt;/Box&gt;<br>  )}<br>  &lt;/Box&gt;<br>);<br>}<br><br>export default function App({name = &#39;Stranger&#39;}: Props) {<br>    const {exit} = useApp();<br>    const [selectedIndex, setSelectedIndex] = useState(0);<br>    const [focusedPanel, setFocusedPanel] = useState&lt;&#39;sidebar&#39; | &#39;content&#39;&gt;(&#39;sidebar&#39;);<br>    const [isDetailOpen, setIsDetailOpen] = useState(false);<br>    const selectedItem = navItems[selectedIndex] ?? navItems[0];<br><br>    useEffect(() =&gt; {<br>        setIsDetailOpen(false);<br>    }, [selectedIndex]);<br><br>    useInput((input, key) =&gt; {<br>        if (input === &#39;q&#39; || key.escape) {<br>        if (isDetailOpen) {<br>            setIsDetailOpen(false);<br>            return;<br>        }<br>        exit();<br>      }<br><br>    if (!isDetailOpen &amp;&amp; key.tab) {<br>        setFocusedPanel(panel =&gt;<br>          panel === &#39;sidebar&#39; ? &#39;content&#39; : &#39;sidebar&#39;,<br>        );<br>    }<br>    });<br><br>    return (<br>        &lt;Box flexDirection=&quot;column&quot;&gt;<br>        &lt;Box borderStyle=&quot;single&quot; paddingX={1} justifyContent=&quot;space-between&quot;&gt;<br>          &lt;Text bold color=&quot;cyan&quot;&gt;My Dashboard&lt;/Text&gt;<br>          &lt;Text&gt;Tab to switch focus • q to quit&lt;/Text&gt;<br>        &lt;/Box&gt;<br>        &lt;Box flexDirection=&quot;row&quot;&gt;<br>        &lt;Sidebar<br>            selectedIndex={selectedIndex}<br>            setSelectedIndex={setSelectedIndex}<br>            focused={focusedPanel === &#39;sidebar&#39; &amp;&amp; !isDetailOpen}<br>        /&gt;<br>        &lt;Content<br>            name={name}<br>            selectedItem={selectedItem}<br>            focused={focusedPanel === &#39;content&#39;}<br>            isDetailOpen={isDetailOpen}<br>            onOpenDetail={() =&gt; {<br>                setIsDetailOpen(true);<br>            }}<br>            onCloseDetail={() =&gt; {<br>                setIsDetailOpen(false);<br>            }}<br>        /&gt;<br>        &lt;/Box&gt;<br>&lt;/Box&gt;<br>);<br>}</pre><p>That may look like a lot at first, but it is built from a few simple ideas.</p><p><strong>Step 6: Learn Ink’s Basic Components</strong></p><p><strong><em>`render()`</em></strong></p><p>`render(&lt;App /&gt;)` starts the Ink application. In a browser, React renders to the DOM. In Ink, React renders to the terminal.</p><p><strong><em>`Box`</em></strong></p><p>`Box` is the layout component. If you know CSS flexbox, this will feel familiar.</p><p>Example:</p><pre>&lt;Box flexDirection=&quot;row&quot;&gt;<br>&lt;Box width={20}&gt;Sidebar&lt;/Box&gt;<br>&lt;Box flexGrow={1}&gt;Content&lt;/Box&gt;<br>&lt;/Box&gt;</pre><p>This creates two side-by-side areas.</p><p><strong><em>`Text`</em></strong></p><p>`Text` prints terminal text. It can also style that text using props such as `color`, `bold`, `underline`, and `dimColor`.</p><p>Example:</p><pre>&lt;Text bold color=&quot;cyan&quot;&gt;My Dashboard&lt;/Text&gt;</pre><p><strong>Step 7: Understand </strong>`useState`</p><p>The app stores interactive values in React state.</p><pre>const [selectedIndex, setSelectedIndex] = useState(0);<br>const [focusedPanel, setFocusedPanel] = useState&lt;&#39;sidebar&#39; | &#39;content&#39;&gt;(&#39;sidebar&#39;);<br>const [isDetailOpen, setIsDetailOpen] = useState(false);</pre><p>These mean:</p><p><strong>- `selectedIndex`</strong> tells us which menu item is active.<br>- <strong>`focusedPanel`</strong> tells us whether the sidebar or content is currently handling input.<br>- <strong>`isDetailOpen`</strong> tells us whether the popup detail box is visible.</p><p><strong>Step 8: Understand </strong>`navItems[selectedIndex]`</p><p>This line is important:</p><pre>const selectedItem = navItems[selectedIndex] ?? navItems[0];</pre><p>`navItems` is an array-like constant:</p><pre>const navItems = [&#39;Home&#39;, &#39;About&#39;, &#39;Settings&#39;, &#39;Help&#39;] as const;</pre><p>You can still read items from it by index.</p><p>- navItems[0] is ’Home’`<br>- navItems[1] is ’About’<br>- navItems[2] is ’Settings’<br>- navItems[3] is ’Help’</p><p>So `navtems[selectedIndex]` means: get the item at the current selected position.</p><p>The `?? navItems[0]` part is a safety fallback. If the current index is invalid and returns `undefined`, use the first item instead.</p><p>A simple analogy is:</p><p>- `navItems` is a row of labeled boxes<br>- `selectedIndex` is the box number<br>- `navItems[selectedIndex]` gives you the label inside that box</p><p><strong>Step 9: Understand </strong>`useInput`</p><p>`useInput()` is Ink’s keyboard listener.</p><pre>useInput((input, key) =&gt; {<br>     // handle user input<br>});</pre><p>Ink gives you two things:</p><p>- `input`: the literal typed character, like `q`, `r`, or `x`<br>- `key`: information about special keys, like arrow keys, `Tab`, `Enter`, and `Escape`</p><p>Examples from this project:</p><pre>if (input === &#39;q&#39; || key.escape) {<br>exit();<br>}</pre><p>This means: if the user presses `q` or `Esc`, close the app.</p><pre>if (key.upArrow) {<br>     setSelectedIndex(index =&gt; Math.max(0, index - 1));<br>}</pre><p>This means: if the user presses the up arrow, move the selection upward.</p><p><strong>Why the app stays open</strong></p><p>A common beginner question is: why does the app exit immediately sometimes?</p><p>A normal Node CLI prints something and ends. An Ink app stays alive when it still has work to do, such as listening for input. `useInput()` is one of the reasons the program remains interactive instead of exiting right away.</p><p><strong>Step 10: Can You Have More Than One </strong>`useInput()`<strong>?</strong></p><p>Yes, you can.<br>This project uses more than one `useInput()`:</p><p>- one inside `Sidebar`<br>- one inside `Content`<br>- one inside `App`</p><p>That does not mean each `Box` automatically owns keyboard focus. A `Box` is only a layout element. Ink does not automatically say, “this panel owns the keyboard now.”</p><p>That is why the project has a `focusedPanel` state. Each section checks whether it is allowed to react.</p><p>For example, the sidebar only handles arrow keys when `focused` is true:</p><pre>if (!focused || input) {<br>    return;<br>}</pre><p>The content panel only reacts to `Enter` and `x` when it is focused.<br>This is how you build panel-specific keyboard behavior in Ink: you manage the focus logic yourself.</p><p><strong>Step 11: Understand </strong>`useApp()`</p><p>`useApp()` gives your component access to the running Ink app.</p><p>In this project:</p><pre>const {exit} = useApp();</pre><p>This extracts the `exit()` function from Ink.</p><p>When you later call:</p><pre>exit();</pre><p>Ink closes the terminal UI and returns control to the shell.</p><p>A simple mental model is:</p><p>- `useInput()` listens for keys<br>- `useState()` stores changing values<br>- `useApp()` controls the app itself</p><p><strong>Step 12: Understand </strong>`useEffect()`<strong> in This App</strong></p><p>This project uses `useEffect()` here:</p><pre>useEffect(() =&gt; {<br>    setIsDetailOpen(false);<br>}, [selectedIndex]);</pre><p>This means: whenever the selected menu item changes, automatically close the popup.</p><p>Without this effect, you could open the detail panel for `Home`, then move to `About`, and the old popup might stay open in a confusing state.</p><p><strong>## Step 13: Keyboard-First Thinking in Ink</strong></p><p>If you come from web development, you may expect mouse movement and clickable panels. That is usually not how terminal apps work.</p><p>In this app, the keyboard model is:</p><p>- `Tab` switches focus between panels<br>- `↑` and `↓` move in the sidebar<br>- `Enter` opens the detail popup<br>- `x` closes the popup<br>- `Esc` closes the popup first, then exits the app if no popup is open<br>- `q` quits the app</p><p>This is the normal TUI mindset. The keyboard is the primary interface.</p><p><strong>## Step 14: Screen Capture of the Base TUI</strong></p><p>This is a captured terminal frame from the running app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*BHYcpoN0ICcR6snRxnLM6Q.png" /><figcaption>Base TUI</figcaption></figure><p>Notice the layout:</p><p>- the top line is the header<br>- the left panel is the navigation sidebar<br>- the right panel is the content frame</p><p><strong>Step 15: Screen Capture of the Popup State</strong></p><p>When the content frame is focused and the user presses `Enter`, the app opens a popup detail box on top of the content area.</p><p>A simplified capture of that state looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*mhektngm-wt29xR5ma_74Q.png" /></figure><p>The popup is not a browser modal. It is still terminal output. But visually, it behaves like an overlay on top of the current content frame.</p><p><strong>## Step 16: Running the Project</strong></p><p>Build the TypeScript source into `dist/`:</p><pre>npm run build</pre><p>Then run the compiled CLI directly:</p><pre>node dist/cli.js - name=Jane</pre><p><strong>Step 17: Why the CLI Command Name Works</strong></p><p>In `package.json`, this project has:</p><pre>{<br>   &quot;name&quot;: &quot;my-ink-cli&quot;,<br>   &quot;bin&quot;: &quot;dist/cli.js&quot;<br>}</pre><p>These two fields are important.</p><p>- `name` is the package name<br>- `bin` tells npm which file should be run as the command-line executable</p><p>The file itself also begins with:</p><pre>#!/usr/bin/env node</pre><p>That tells the system to run the file with Node.</p><p><strong>Step 18: What </strong>`npm link`<strong> Does</strong></p><p>`npm link` creates a global symbolic link from your machine’s global npm area to your local project.</p><p>From your project folder:</p><pre>npm run build<br>npm link</pre><p>After that, you can run:</p><pre>my-ink-cli - name=Jane</pre><p>Why does that work?</p><p>Because npm registers the CLI command based on the `name` and `bin` fields. In simple terms, it connects the command `my-ink-cli` to your local `dist/cli.js`.</p><p>You can think of the flow like this:</p><pre>npm link<br>-&gt; create global symlink<br>-&gt; command my-ink-cli becomes available in your PATH<br>-&gt; running my-ink-cli executes dist/cli.js</pre><p>This is very useful during local development because you can test your CLI as if it were installed globally.</p><p>To remove the link later:</p><pre>npm unlink</pre><p><strong>Step 19: What </strong>`npx`<strong> Does</strong></p><p>`npx` lets you run a package without installing it globally in the normal way.</p><p><strong>### Local project usage</strong></p><p>Inside the project folder, after building, you can run:</p><pre>npx . - name=Jane</pre><p>The `.` means: use the current package in this folder.</p><p><strong>### Published package usage</strong></p><p>After publishing your package to npm, users can run:</p><pre>npx my-ink-cli - name=Jane</pre><p>In that case, `npx` downloads the package temporarily, runs it, and then discards it.</p><p><strong>### </strong>`npm link`<strong> vs </strong>`npx`</p><p>Use `npm link` when you are actively developing the CLI and want a stable global command on your own machine.</p><p>Use `npx .` when you want to quickly test the local package without creating a global symlink.</p><p>Use `npx my-ink-cli` after publishing, when you want other people to try the tool without asking them to install it globally.</p><p><strong>## Step 20: Testing</strong></p><p>This project also has tests.</p><p>npm testRun them with:</p><pre>npm test</pre><p>The `test.tsx` file uses `ava` and `ink-testing-library` to render the component and verify what appears in the terminal.</p><p>This is useful because terminal UIs should still be testable, especially when the interaction logic grows.</p><p><strong>Step 21: A Simpler Way to Think About the Whole App</strong></p><p>If everything above feels like a lot, reduce it to this simple model:</p><p>1. `cli.tsx` reads command-line flags and starts Ink.</p><p>2. `app.tsx` renders a header, sidebar, and content area.</p><p>3. `useState()` stores which item is selected, which panel is focused, and whether the popup is open.</p><p>4. `useInput()` listens to keyboard events.</p><p>5. `useApp()` lets the app exit cleanly.</p><p>6. `Box` handles layout.</p><p>7. `Text` prints styled text.</p><p>That is already enough to build a useful interactive terminal app.</p><p><strong>## Final Thoughts</strong></p><p>Ink is a good fit when you want a terminal application that feels more structured than a plain script. Instead of manually printing lines and handling raw terminal behavior yourself, you describe the UI with components and let Ink manage rendering.</p><p>The most important shift for beginners is this: do not think of it as a web page inside the terminal. Think of it as a keyboard-driven application with layout primitives.</p><p>Once you are comfortable with `Box`, `Text`, `useInput()`, `useState()`, and `useApp()`, you can build dashboards, menus, prompts, status views, and multi-panel terminal tools with a much cleaner mental model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1581041c7168" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Full-Stack App with AI Agents: A Practical Guide]]></title>
            <link>https://juniarto-samsudin.medium.com/building-a-full-stack-app-with-ai-agents-a-practical-guide-801977e35348?source=rss-99a5a2e5cc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/801977e35348</guid>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[full-stack-developer]]></category>
            <dc:creator><![CDATA[Juniarto Samsudin]]></dc:creator>
            <pubDate>Fri, 08 May 2026 10:26:35 GMT</pubDate>
            <atom:updated>2026-05-08T10:26:35.814Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcZbA07DkhiNrn8Z3E2LXA.jpeg" /></figure><p>Modern software development is evolving rapidly with AI assistance. In this article, I’ll walk you through a real-world project called <strong>salary-app</strong> — a full-stack salary management application — and show you how to leverage AI agents to build and maintain it efficiently.</p><h3>What We’re Building</h3><p>The salary-app is a monorepo project with:</p><ul><li><strong>Backend</strong>: FastAPI + SQLAlchemy (Python 3.12+)</li><li><strong>Frontend</strong>: Next.js 16 with App Router + React 19 + shadcn/ui</li><li><strong>Shared packages</strong>: TypeScript types and API client</li></ul><p>Here’s the project structure:</p><pre>salary-app/<br>├── backend/              # FastAPI backend<br>├── frontend/             # Next.js frontend<br>├── packages/<br>│   ├── shared/           # Shared TypeScript types<br>│   └── api-client/       # Generated API client<br>├── docker-compose.yml    # PostgreSQL setup<br>├── AGENTS.md             # Main agent guidelines<br>└── .agents/              # Agent configurations</pre><h3>Why Use AI Agents?</h3><p>Instead of having one AI assistant trying to handle everything, we split responsibilities:</p><ol><li><strong>Backend API Agent</strong> — Handles all server-side code</li><li><strong>Frontend UI Agent</strong> — Manages all client-side code</li><li><strong>Shared API Contract</strong> — The “agreement” between them</li></ol><p>This separation prevents conflicts and ensures each agent stays in its lane.</p><h3>The Agent System in Action</h3><h3>Backend API Agent</h3><p>The Backend API agent is specialized for server-side work. Here’s what its configuration looks like:</p><pre>---<br>description: &quot;Use when implementing API endpoints, writing backend tests, maintaining OpenAPI schema, or updating the API contract.&quot;<br>name: &quot;Backend API&quot;<br>tools: [read, edit, search, execute, todo]<br>---</pre><p>This agent:</p><ul><li>Only touches backend/ and packages/shared/api-contract.md</li><li>Never edits frontend code</li><li>Uses uv (not pip) for Python package management</li><li>Generates OpenAPI schemas after changes</li></ul><p>Here’s a typical backend endpoint it might create:</p><pre># backend/app/api/v1/employees.py<br>from fastapi import APIRouter, Depends<br>from sqlalchemy.ext.asyncio import AsyncSession<br>from app.core.database import get_db<br>from app.models.employee import Employee<br>from app.schemas.employee import EmployeeCreate, EmployeeListResponse</pre><pre>router = APIRouter(prefix=&quot;/employees&quot;, tags=[&quot;employees&quot;])</pre><pre>@router.get(&quot;&quot;, response_model=EmployeeListResponse)<br>async def list_employees(<br>    db: AsyncSession = Depends(get_db),<br>    _: str = Depends(get_current_user),<br>) -&gt; EmployeeListResponse:<br>    result = await db.execute(select(Employee))<br>    employees = result.scalars().all()<br>    return EmployeeListResponse(<br>        data=[EmployeeResponse.model_validate(e) for e in employees]<br>    )</pre><h3>Frontend UI Agent</h3><p>The Frontend UI agent handles everything in the browser. Its configuration:</p><pre>---<br>description: &quot;Use when building UI pages, components, or frontend features.&quot;<br>name: &quot;Frontend UI&quot;<br>tools: [read, edit, search, todo]<br>---</pre><p>This agent:</p><ul><li>Only works in frontend/ and packages/api-client/</li><li>Reads api-contract.md before building features</li><li>Uses shadcn/ui components with base-nova preset</li><li>Never touches backend code</li></ul><p>Here’s how it consumes the API:</p><pre>// frontend/src/app/page.tsx<br>&quot;use client&quot;</pre><pre>import { listEmployees, type EmployeeResponse } from &quot;@salary-app/api-client&quot;<br>import { useEffect, useState } from &quot;react&quot;</pre><pre>export default function EmployeesPage() {<br>  const [employees, setEmployees] = useState&lt;EmployeeResponse[]&gt;([])<br>  <br>  useEffect(() =&gt; {<br>    const token = getToken()<br>    listEmployees(token)<br>      .then((res) =&gt; setEmployees(res.data))<br>      .catch((err) =&gt; console.error(err))<br>  }, [])<br>  <br>  // ... render UI<br>}</pre><h3>The Secret Sauce: API Contract</h3><p>The magic happens in packages/shared/api-contract.md. This file is the <strong>single source of truth</strong> for API shapes:</p><pre># API Contract</pre><pre>This file is the single source of truth for backend API shapes consumed by the frontend.<br>The **Frontend UI** agent reads this file before building any data-fetching logic.</pre><pre>---</pre><pre>## Endpoints</pre><pre>### Employees</pre><pre>#### `GET /api/v1/employees`</pre><pre>Requires: `Authorization: Bearer &lt;token&gt;` header</pre><pre>**Response 200 OK**<br>```json<br>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;id&quot;: &quot;uuid-string&quot;,<br>      &quot;name&quot;: &quot;John Doe&quot;,<br>      &quot;date_of_birth&quot;: &quot;1990-01-15&quot;,<br>      &quot;salary&quot;: 75000.00<br>    }<br>  ]<br>}</pre><pre>When the Backend Agent adds an endpoint:<br>1. It updates `api-contract.md`<br>2. It exports `openapi.json`<br>3. The Frontend Agent regenerates the API client</pre><pre>## Understanding openapi.json: The Bridge Between Backend and Frontend</pre><pre>You might wonder: &quot;What exactly is `openapi.json` and why do we need it?&quot;</pre><pre>### What is openapi.json?</pre><pre>OpenAPI (formerly Swagger) is a specification for describing REST APIs. FastAPI **automatically generates** this specification from your Python code. When the Backend Agent creates endpoints, FastAPI builds a complete JSON description of every route, including:</pre><pre>- Endpoint paths and HTTP methods<br>- Request parameters and body schemas<br>- Response schemas and status codes<br>- Authentication requirements</pre><pre>Here&#39;s a snippet of what `packages/shared/openapi.json` looks like:</pre><pre>```json<br>{<br>  &quot;openapi&quot;: &quot;3.1.0&quot;,<br>  &quot;info&quot;: {<br>    &quot;title&quot;: &quot;Salary App&quot;,<br>    &quot;version&quot;: &quot;1.0.0&quot;<br>  },<br>  &quot;paths&quot;: {<br>    &quot;/api/v1/employees&quot;: {<br>      &quot;get&quot;: {<br>        &quot;summary&quot;: &quot;List Employees&quot;,<br>        &quot;responses&quot;: {<br>          &quot;200&quot;: {<br>            &quot;content&quot;: {<br>              &quot;application/json&quot;: {<br>                &quot;schema&quot;: {<br>                  &quot;$ref&quot;: &quot;#/components/schemas/EmployeeListResponse&quot;<br>                }<br>              }<br>            }<br>          }<br>        }<br>      }<br>    }<br>  },<br>  &quot;components&quot;: {<br>    &quot;schemas&quot;: {<br>      &quot;EmployeeResponse&quot;: {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>          &quot;id&quot;: { &quot;type&quot;: &quot;string&quot; },<br>          &quot;name&quot;: { &quot;type&quot;: &quot;string&quot; },<br>          &quot;date_of_birth&quot;: { &quot;type&quot;: &quot;string&quot;, &quot;format&quot;: &quot;date&quot; },<br>          &quot;salary&quot;: { &quot;type&quot;: &quot;number&quot; }<br>        }<br>      }<br>    }<br>  }<br>}</pre><h3>Who Creates openapi.json?</h3><p>The <strong>Backend API Agent</strong> exports it after implementing endpoints. Here’s the workflow:</p><p><strong>Step 1: Backend Agent implements the endpoint</strong></p><pre># backend/app/api/v1/employees.py<br>@router.post(&quot;&quot;, response_model=EmployeeResponse, status_code=201)<br>async def create_employee(<br>    payload: EmployeeCreate,<br>    db: AsyncSession = Depends(get_db),<br>    _: str = Depends(get_current_user),<br>) -&gt; EmployeeResponse:<br>    employee = Employee(<br>        name=payload.name,<br>        date_of_birth=payload.date_of_birth,<br>        salary=payload.salary,<br>    )<br>    db.add(employee)<br>    await db.commit()<br>    await db.refresh(employee)<br>    return EmployeeResponse.model_validate(employee)</pre><p><strong>Step 2: Backend Agent exports openapi.json</strong></p><p>The agent runs this command (as defined in its workflow):</p><pre>cd backend &amp;&amp; uv run python -c &quot;<br>import json<br>from app.main import app<br>with open(&#39;../packages/shared/openapi.json&#39;, &#39;w&#39;) as f:<br>    json.dump(app.openapi(), f, indent=2)<br>print(&#39;openapi.json written to packages/shared/openapi.json&#39;)<br>&quot;</pre><p>FastAPI’s app.openapi() method generates the complete specification automatically — no manual writing needed!</p><h3>How Frontend Agent Uses openapi.json to Create API Client</h3><p>Now comes the magic. The <strong>Frontend UI Agent</strong> reads openapi.json and generates a fully-typed TypeScript API client.</p><p><strong>Step 1: Frontend Agent checks if openapi.json was updated</strong></p><p>The agent’s workflow includes:</p><blockquote><em>“Check whether </em><em>packages/shared/openapi.json has been updated since the last client generation. If so, regenerate </em><em>packages/api-client/.&quot;</em></blockquote><p><strong>Step 2: Generate TypeScript types from openapi.json</strong></p><p>Using openapi-typescript tool:</p><pre>npx openapi-typescript packages/shared/openapi.json -o packages/api-client/src/schema.d.ts</pre><p>This creates TypeScript types that match your backend schemas exactly:</p><pre>// packages/api-client/src/schema.d.ts (generated)<br>export interface EmployeeResponse {<br>  id: string<br>  name: string<br>  date_of_birth: string<br>  salary: number<br>}</pre><pre>export interface EmployeeListResponse {<br>  data: EmployeeResponse[]<br>}</pre><pre>export interface paths {<br>  &quot;/api/v1/employees&quot;: {<br>    get: {<br>      responses: {<br>        200: {<br>          content: {<br>            &quot;application/json&quot;: EmployeeListResponse<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p><strong>Step 3: Create the API client wrapper</strong></p><p>The Frontend Agent creates packages/api-client/src/index.ts with typed fetch helpers:</p><pre>// packages/api-client/src/index.ts<br>const BASE_URL = process.env.NEXT_PUBLIC_API_URL ?? &quot;http://localhost:8000&quot;</pre><pre>export class ApiError extends Error {<br>  constructor(<br>    public readonly status: number,<br>    public readonly detail?: string,<br>  ) {<br>    super(detail ?? `HTTP error ${status}`)<br>  }<br>}</pre><pre>export async function listEmployees(token: string): Promise&lt;EmployeeListResponse&gt; {<br>  const res = await fetch(`${BASE_URL}/api/v1/employees`, {<br>    headers: { Authorization: `Bearer ${token}` },<br>  })</pre><pre>  if (!res.ok) {<br>    const body = await res.json().catch(() =&gt; null)<br>    throw new ApiError(res.status, body?.detail ?? res.statusText)<br>  }</pre><pre>  return res.json() as Promise&lt;EmployeeListResponse&gt;<br>}</pre><pre>export async function createEmployee(<br>  data: EmployeeCreate,<br>  token: string,<br>): Promise&lt;EmployeeResponse&gt; {<br>  const res = await fetch(`${BASE_URL}/api/v1/employees`, {<br>    method: &quot;POST&quot;,<br>    headers: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      Authorization: `Bearer ${token}`,<br>    },<br>    body: JSON.stringify(data),<br>  })</pre><pre>  if (!res.ok) {<br>    throw new ApiError(res.status, `Failed to create employee`)<br>  }</pre><pre>  return res.json()<br>}</pre><h3>How UI Code Uses the API Client</h3><p>Now your frontend components can import and use these typed functions:</p><pre>// frontend/src/app/page.tsx<br>&quot;use client&quot;</pre><pre>import { listEmployees, createEmployee, type EmployeeResponse } from &quot;@salary-app/api-client&quot;<br>import { useState, useEffect } from &quot;react&quot;<br>import { Button } from &quot;@/components/ui/button&quot;<br>import { Card, CardContent, CardHeader, CardTitle } from &quot;@/components/ui/card&quot;</pre><pre>export default function EmployeesPage() {<br>  const [employees, setEmployees] = useState&lt;EmployeeResponse[]&gt;([])<br>  <br>  useEffect(() =&gt; {<br>    const token = getToken()<br>    if (!token) {<br>      router.push(&quot;/login&quot;)<br>      return<br>    }<br>    <br>    listEmployees(token)<br>      .then((res) =&gt; setEmployees(res.data))<br>      .catch((err) =&gt; console.error(&quot;Failed to load:&quot;, err))<br>  }, [])</pre><pre>  async function handleCreate(formData: EmployeeCreate) {<br>    const token = getToken()<br>    try {<br>      const newEmployee = await createEmployee(formData, token)<br>      setEmployees([...employees, newEmployee])<br>    } catch (err) {<br>      console.error(&quot;Failed to create:&quot;, err)<br>    }<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Employees&lt;/h1&gt;<br>      {employees.map(emp =&gt; (<br>        &lt;Card key={emp.id}&gt;<br>          &lt;CardHeader&gt;<br>            &lt;CardTitle&gt;{emp.name}&lt;/CardTitle&gt;<br>          &lt;/CardHeader&gt;<br>          &lt;CardContent&gt;<br>            &lt;p&gt;Salary: ${emp.salary}&lt;/p&gt;<br>          &lt;/CardContent&gt;<br>        &lt;/Card&gt;<br>      ))}<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>The Complete Flow</h3><p>Here’s the full picture of how backend and frontend stay in sync:</p><pre>1. Backend Agent writes Python endpoint<br>   ↓<br>2. FastAPI automatically generates OpenAPI spec<br>   ↓<br>3. Backend Agent exports openapi.json to packages/shared/<br>   ↓<br>4. Frontend Agent detects updated openapi.json<br>   ↓<br>5. Frontend Agent runs openapi-typescript to generate TypeScript types<br>   ↓<br>6. Frontend Agent creates/updates API client functions<br>   ↓<br>7. UI components import and use typed API client<br>   ↓<br>8. Type safety from backend to frontend! ✓</pre><p>This approach ensures:</p><ul><li><strong>Type safety</strong>: If you change a field in the backend, TypeScript will catch it in the frontend</li><li><strong>No manual sync</strong>: The OpenAPI spec is generated, not written by hand</li><li><strong>Single source of truth</strong>: The backend code IS the specification</li></ul><h3>Setting Up Your Own Agent-Driven Project</h3><h3>Step 1: Initialize with /init</h3><p>Start by creating the AGENTS.md file. In VS Code with Copilot, use:</p><pre>/init</pre><p>This generates a base AGENTS.md file. For our project, it looks like:</p><pre># Salary App — Agent Guidelines</pre><pre>Full-stack salary management application: **FastAPI backend + Next.js frontend**, connected to PostgreSQL.</pre><pre>## Repository Structure</pre><p>backend/ # FastAPI + SQLAlchemy async (Python 3.12+, uv) frontend/ # Next.js 16 App Router + React 19 + shadcn/ui packages/shared/ # @salary-app/shared — shared TypeScript types</p><pre>## Local Dev Setup</pre><pre>**Start PostgreSQL:**<br>```bash<br>docker-compose up -d</pre><p><strong>Backend:</strong></p><pre>cd backend<br>uv run uvicorn app.main:app --reload</pre><pre>### Step 2: Link copilot-instructions.md to AGENTS.md</pre><pre>Create `.agents/copilot-instructions.md` with a reference to your main file:</pre><pre>```markdown<br>Refer to [AGENTS.md](../AGENTS.md) for more information about how to use this file.</pre><p>This keeps instructions modular and maintainable.</p><h3>Step 3: Install Skills</h3><p>Skills add specialized knowledge to your agents. Check skills-lock.json to see what&#39;s installed:</p><pre>{<br>  &quot;version&quot;: 1,<br>  &quot;skills&quot;: {<br>    &quot;fastapi-python&quot;: {<br>      &quot;source&quot;: &quot;mindrally/skills&quot;,<br>      &quot;sourceType&quot;: &quot;github&quot;,<br>      &quot;skillPath&quot;: &quot;fastapi-python/SKILL.md&quot;<br>    },<br>    &quot;nextjs&quot;: {<br>      &quot;source&quot;: &quot;vercel-labs/vercel-plugin&quot;,<br>      &quot;sourceType&quot;: &quot;github&quot;,<br>      &quot;skillPath&quot;: &quot;skills/nextjs/SKILL.md&quot;<br>    },<br>    &quot;shadcn&quot;: {<br>      &quot;source&quot;: &quot;shadcn/ui&quot;,<br>      &quot;sourceType&quot;: &quot;github&quot;,<br>      &quot;skillPath&quot;: &quot;skills/shadcn/SKILL.md&quot;<br>    }<br>  }<br>}</pre><p>Skills are stored in .agents/skills/ and provide domain-specific guidance. For example, the fastapi-python skill teaches the agent about async patterns, dependency injection, and SQLAlchemy best practices.</p><h3>Step 4: Create Custom Agents with /create-agent</h3><p>To create specialized agents, use the /create-agent command and define their scope:</p><p><strong>Backend API Agent</strong> (.github/agents/backend-api.agent.md):</p><pre>---<br>name: &quot;Backend API&quot;<br>description: &quot;Use when implementing API endpoints, writing backend tests, maintaining OpenAPI schema, or updating the API contract.&quot;<br>tools: [read, edit, search, execute, todo]<br>---</pre><pre>## Scope<br>You may ONLY read or edit files under:<br>- `backend/`<br>- `packages/shared/api-contract.md`</pre><pre>Do NOT read, edit, or suggest changes to `frontend/`.</pre><pre>## Workflow<br>1. Read the Contract First<br>2. Implement Endpoints<br>3. Generate Migration<br>4. Write Tests<br>5. Export openapi.json<br>6. Update the API Contract</pre><p><strong>Frontend UI Agent</strong> (.github/agents/frontend-ui.agent.md):</p><pre>---<br>name: &quot;Frontend UI&quot;<br>description: &quot;Use when building UI pages, components, or frontend features.&quot;<br>tools: [read, edit, search, todo]<br>---</pre><pre>## Scope<br>You may ONLY read or edit files under:<br>- `frontend/`<br>- `packages/api-client/`<br>- `packages/shared/api-contract.md`</pre><pre>## API Client Generation<br>`packages/api-client/` is generated from `packages/shared/openapi.json`.<br>Whenever openapi.json is updated, regenerate the client:</pre><pre>```bash<br>npx openapi-typescript packages/shared/openapi.json -o packages/api-client/src/schema.d.ts</pre><pre>### Step 5: Add Custom Prompts</pre><pre>Customize agent behavior with specific instructions. For example, in `frontend/AGENTS.md`:</pre><pre>```markdown<br>## Frontend Conventions</pre><pre>- **Next.js 16 App Router** with React 19 — use Server Components by default<br>- **Tailwind CSS v4** — no `tailwind.config.ts`<br>- **shadcn/ui** with `base-nova` preset<br>- **Path alias**: `@/` → `src/`<br>- **Shared types**: import from `@salary-app/shared`</pre><pre>&lt;!-- BEGIN:nextjs-agent-rules --&gt;<br># This is NOT the Next.js you know<br>This version has breaking changes — read the docs before writing code.<br>&lt;!-- END:nextjs-agent-rules --&gt;</pre><h3>The Workflow in Practice</h3><p>Here’s how a typical feature flows:</p><ol><li><strong>You</strong>: “Add a feature to create employees”</li><li><strong>Backend Agent</strong> (automatically invoked):</li></ol><ul><li>Reads api-contract.md</li><li>Implements POST /api/v1/employees in backend/app/api/v1/employees.py</li></ul><pre>class EmployeeCreate(BaseModel):<br>         name: str<br>         date_of_birth: date<br>         salary: float = Field(..., gt=0)</pre><ul><li>Writes tests in backend/tests/test_employees.py</li><li>Exports openapi.json</li></ul><p><strong>3. Frontend Agent</strong> (automatically invoked):</p><ul><li>Regenerates packages/api-client/</li><li>Reads the updated contract</li><li>Builds the UI in frontend/src/app/page.tsx using shadcn/ui components</li><li>Uses the typed API client:</li></ul><pre>import { createEmployee } from &quot;@salary-app/api-client&quot;<br>     <br>     const handleSubmit = async (data: EmployeeCreate) =&gt; {<br>       const token = getToken()<br>       const response = await createEmployee(data, token)<br>       // Handle response<br>     }</pre><h3>How to Use Custom Agents to Initiate Code</h3><p>Now that you have your agents configured, here’s how to actually <strong>invoke them</strong> to start building your backend and frontend.</p><h3>Understanding Agent Invocation</h3><p>Agents are triggered by <strong>matching your request to their description</strong>. When you ask Copilot something, it routes your request to the appropriate agent based on the description field in their configuration.</p><h3>Backend API Agent: How to Invoke</h3><p>The Backend API agent has this description:</p><pre>description: &quot;Use when implementing API endpoints, writing backend tests, maintaining OpenAPI schema, or updating the API contract.&quot;</pre><p><strong>To trigger the Backend Agent</strong>, use prompts like:</p><pre>✅ &quot;Implement the employees API endpoint&quot;<br>✅ &quot;Create a POST /api/v1/employees endpoint&quot;<br>✅ &quot;Add authentication to the app&quot;<br>✅ &quot;Write tests for the employee endpoints&quot;<br>✅ &quot;Update the API contract with a new endpoint&quot;<br>✅ &quot;Generate the OpenAPI schema&quot;</pre><p><strong>Example: Initiating Backend Code</strong></p><p>You type in Copilot chat:</p><pre>&quot;Implement the employee management API with GET and POST endpoints&quot;</pre><p>The Backend Agent then:</p><ol><li>Reads packages/shared/api-contract.md to see what&#39;s needed</li><li>Creates the route handler in backend/app/api/v1/employees.py:</li></ol><pre>from fastapi import APIRouter, Depends <br>from app.core.database import get_db <br>from app.models.employee import Employee  <br>router = APIRouter(prefix=&quot;/employees&quot;, tags=[&quot;employees&quot;])  <br>@router.get(&quot;&quot;, response_model=EmployeeListResponse) <br>async def list_employees(db: AsyncSession = Depends(get_db)):     <br>      result = await db.execute(select(Employee))     <br>      employees = result.scalars().all()     <br>      return EmployeeListResponse(data=employees)</pre><p>3. Creates pydantic schemas in backend/app/schemas/employee.py<br>4.Writes tests in backend/tests/test_employees.py<br>5. Exports openapi.json to packages/shared/</p><h3>Frontend UI Agent: How to Invoke</h3><p>The Frontend UI agent has this description:</p><pre>description: &quot;Use when building UI pages, components, or frontend features.&quot;</pre><p><strong>To trigger the Frontend Agent</strong>, use prompts like:</p><pre>✅ &quot;Create the employee list page&quot;<br>✅ &quot;Build a form to create new employees&quot;<br>✅ &quot;Add a login page with shadcn/ui components&quot;<br>✅ &quot;Create a reusable Button component&quot;<br>✅ &quot;Style the employees page with Tailwind&quot;<br>✅ &quot;Regenerate the API client from openapi.json&quot;</pre><p><strong>Example: Initiating Frontend Code</strong></p><p>You type in Copilot chat:</p><pre>&quot;Create the employee list page that displays all employees in cards&quot;</pre><p>The Frontend Agent then:</p><ol><li>Checks if packages/shared/openapi.json was updated</li><li>Regenerates the API client if needed:</li></ol><pre>npx openapi-typescript packages/shared/openapi.json -o packages/api-client/src/schema</pre><p>3. Reads packages/shared/api-contract.md to understand the data shapes</p><p>4. Creates the page in frontend/src/app/page.tsx:</p><pre>&quot;use client&quot; <br>import { listEmployees, type EmployeeResponse } from &quot;@salary-app/api-client&quot; <br>import { useEffect, useState } from &quot;react&quot; <br>import { Card, CardContent, CardHeader, CardTitle } from &quot;@/components/ui/card&quot;  <br>export default function EmployeesPage() {   <br>    const [employees, setEmployees] = useState&lt;EmployeeResponse[]&gt;([])      <br>    useEffect(() =&gt; {     <br>         const token = getToken()     <br>         listEmployees(token)       <br>                  .then((res) =&gt; setEmployees(res.data))       <br>                  .catch((err) =&gt; console.error(err))   }, [])      <br>         return (     &lt;div className=&quot;grid grid-cols-3 gap-4&quot;&gt;       <br>                           {employees.map(emp =&gt; (         <br>                               &lt;Card key={emp.id}&gt;           <br>                                  &lt;CardHeader&gt;             <br>                                    &lt;CardTitle&gt;{emp.name}&lt;/CardTitle&gt;<br>                                  &lt;/CardHeader&gt;           <br>                                  &lt;CardContent&gt;             <br>                                     &lt;p&gt;Salary: ${emp.salary}&lt;/p&gt;           <br>                                  &lt;/CardContent&gt;         <br>                                &lt;/Card&gt;       ))}     <br>                        &lt;/div&gt;   <br>                                ) }</pre><h3>Explicit Agent Selection</h3><p>If you want to <strong>explicitly use a specific agent</strong>, you can use the runSubagent tool (if available) or simply phrase your request to match that agent&#39;s description more precisely.</p><p><strong>Example: Explicitly requesting Backend Agent</strong></p><pre>&quot;Use the Backend API agent to implement JWT authentication&quot;</pre><p><strong>Example: Explicitly requesting Frontend Agent</strong></p><pre>&quot;Use the Frontend UI agent to create a responsive navbar&quot;</pre><h3>Starting the Entire Project from Scratch</h3><p>When you have a new monorepo and want to initiate both backend and frontend:</p><p><strong>Step 1: Initialize the project structure</strong></p><pre>/init</pre><p>This creates AGENTS.md with project-wide guidelines.</p><p><strong>Step 2: Set up the backend (trigger Backend Agent)</strong></p><pre>&quot;Set up the FastAPI backend with PostgreSQL connection, <br>create the database models for employees, and implement <br>GET and POST endpoints for /api/v1/employees&quot;</pre><p>The Backend Agent will:</p><ul><li>Create backend/app/main.py with FastAPI setup</li><li>Set up backend/app/core/database.py for PostgreSQL connection</li><li>Create backend/app/models/employee.py with SQLAlchemy model</li><li>Implement endpoints in backend/app/api/v1/employees.py</li><li>Generate the first openapi.json</li></ul><p><strong>Step 3: Set up the frontend (trigger Frontend Agent)</strong></p><pre>&quot;Create the Next.js frontend with shadcn/ui, set up the <br>employee list page, and create a form to add new employees&quot;</pre><p>The Frontend Agent will:</p><ul><li>Set up frontend/src/app/layout.tsx and page.tsx</li><li>Create components in frontend/src/components/ui/ using shadcn</li><li>Generate packages/api-client/ from openapi.json</li><li>Build the employee list and create form pages</li><li>Use the typed API client for data fetching</li></ul><h3>Pro Tips for Working with Agents</h3><ol><li><strong>Be specific in your requests</strong> — “Create a login page with email/password fields using shadcn Card component” works better than just “Create a login page”</li><li><strong>Let agents work sequentially</strong> — Backend first, then frontend. The frontend agent needs the openapi.json from the backend agent.</li><li><strong>Check the outputs</strong> — After the Backend Agent runs, verify openapi.json was created. After the Frontend Agent runs, verify the UI works.</li><li><strong>Use the API contract</strong> — Both agents refer to api-contract.md. Keep it updated!</li><li><strong>Agents respect their scope</strong> — The Backend Agent won’t touch frontend/, and the Frontend Agent won&#39;t touch backend/. This prevents conflicts.</li></ol><h3>Why Bother With All This?</h3><p>You might wonder: “This seems like a lot of setup. Why not just code normally?”</p><p>Here’s why this approach rocks:</p><ol><li><strong>Clear Boundaries</strong> — Agents don’t step on each other’s toes</li><li><strong>Consistent Code</strong> — Skills enforce best practices (like using uv instead of pip)</li><li><strong>Living Documentation</strong> — api-contract.md stays in sync with code</li><li><strong>Type Safety</strong> — Shared types flow from backend → OpenAPI → frontend</li><li><strong>Scalability</strong> — New team members (human or AI) know exactly what to do</li></ol><h3>Monorepo Benefits</h3><p>The npm workspaces setup in package.json:</p><pre>{<br>  &quot;workspaces&quot;: [<br>    &quot;frontend&quot;,<br>    &quot;packages/shared&quot;,<br>    &quot;packages/api-client&quot;<br>  ]<br>}</pre><p>This means:</p><ul><li>Shared types are imported via @salary-app/shared</li><li>API client is imported via @salary-app/api-client</li><li>Changes propagate instantly across packages</li></ul><h3>Conclusion</h3><p>AI agents aren’t just fancy chatbots — they’re specialized assistants that can maintain complex project structures when given clear guidelines. By setting up:</p><ul><li>✅ AGENTS.md with project-wide rules</li><li>✅ Custom agents with scoped responsibilities</li><li>✅ Skills for domain expertise</li><li>✅ API contract as the source of truth</li></ul><p>You create a development environment where AI can be truly helpful without creating chaos.</p><p>The salary-app project shows this in action: a full-stack app where backend and frontend agents collaborate through a shared contract, each staying in their lane while delivering working code.</p><p>Give it a try in your next project — start with /init, add some skills, and watch your AI assistant become a specialized team member!</p><p><em>Have you tried AI agents in your development workflow? Share your experiences in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=801977e35348" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Learned to Stop Worrying and Love NPM Monorepos]]></title>
            <link>https://juniarto-samsudin.medium.com/how-i-learned-to-stop-worrying-and-love-npm-monorepos-f04b50b1e13c?source=rss-99a5a2e5cc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/f04b50b1e13c</guid>
            <category><![CDATA[monorepo-npm]]></category>
            <category><![CDATA[npm-workspaces]]></category>
            <dc:creator><![CDATA[Juniarto Samsudin]]></dc:creator>
            <pubDate>Fri, 08 May 2026 09:09:24 GMT</pubDate>
            <atom:updated>2026-05-08T09:09:24.572Z</atom:updated>
            <content:encoded><![CDATA[<p>So you’ve got multiple packages that need to work together, and you’re tired of publishing to npm every time you make a small change. Or maybe you’re just trying to organize your codebase better. Either way, npm workspaces (monorepos) might be exactly what you need.</p><p>In this article, I’ll walk you through setting up an npm monorepo using a simple project I built. Nothing fancy, just practical stuff you can actually use.</p><h3>What’s a Monorepo Anyway?</h3><p>Before we dive in, let’s keep it simple. A monorepo is just a single repository that contains multiple packages or projects. Instead of having separate repos for every little thing, you put them all in one place.</p><p>Think of it like a toolbox. Sure, you could have a separate box for hammers, another for screwdrivers, and another for wrenches. Or you could just have one big toolbox with compartments for everything. That’s basically what a monorepo is.</p><h3>Why Would You Want This?</h3><p>Here are a few reasons:</p><ul><li><strong>Shared code made easy</strong>: Your packages can use each other without publishing to npm</li><li><strong>Atomic changes</strong>: Update multiple packages in a single commit</li><li><strong>Simplified dependency management</strong>: Install shared dependencies once, use everywhere</li><li><strong>Better developer experience</strong>: One git clone, one npm install, and you&#39;re ready to go</li></ul><h3>Let’s Build Something: A Real Example</h3><p>I created a super simple project to demonstrate how this works. It has two packages:</p><ol><li><strong>very-simple-server</strong>: A package that exports a function to log “Hello from Server!”</li><li><strong>very-simple-client</strong>: A package that imports and uses the server package</li></ol><p>Here’s the project structure:</p><pre>npm-monorepo-learn/<br>├── package.json          # Root package.json with workspaces config<br>└── packages/<br>    ├── very-simple-server/<br>    │   ├── package.json<br>    │   └── index.js<br>    └── very-simple-client/<br>        ├── package.json<br>        └── index.js</pre><h3>Step 1: Initialize Your Monorepo</h3><p>First, create your project folder and initialize npm:</p><pre>mkdir npm-monorepo-learn<br>cd npm-monorepo-learn<br>npm init -y</pre><p>This creates your root package.json. Now here&#39;s the magic part — you need to tell npm that this is a monorepo by adding workspaces to your package.json:</p><pre>{<br>  &quot;name&quot;: &quot;npm-monorepo-learn&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;workspaces&quot;: [<br>    &quot;packages/very-simple-server&quot;,<br>    &quot;packages/very-simple-client&quot;<br>  ]<br>}</pre><h3>Step 2: Create Your Workspaces</h3><p>Now create your packages. You can do this manually, or use npm’s built-in workspace flag:</p><pre>npm init -y -w packages/very-simple-server -w packages/very-simple-client</pre><p>The -w flag tells npm to initialize those folders as workspaces. It creates the package.json files for each workspace automatically.</p><h3>Step 3: Write Some Code</h3><p>Let’s make the server package do something. In packages/very-simple-server/index.js:</p><pre>module.exports = () =&gt; console.log(&#39;Hello from Server!&#39;);</pre><p>Now the client package can use it. In packages/very-simple-client/index.js:</p><pre>console.log(&quot;Inside in Client!&quot;);<br>const server = require(&quot;very-simple-server&quot;);<br>server();</pre><p>Notice how the client requires very-simple-server by name? That&#39;s the beauty of workspaces — npm links them automatically. No need to run npm link or publish to a registry.</p><h3>Step 4: Run Your Code</h3><p>To run the client code:</p><pre>node packages/very-simple-client/index.js</pre><p>You should see:</p><pre>Inside in Client!<br>Hello from Server!</pre><p>Pretty cool, right? The client found the server package without any extra configuration.</p><h3>Managing Dependencies in a Monorepo</h3><p>Here’s where things get interesting. You can install packages in different ways:</p><h3>Install a Package for All Workspaces</h3><p>Want to use Jest for testing across all your packages?</p><pre>npm install jest</pre><p>This installs Jest in the root node_modules, and all workspaces can access it. It&#39;s like a shared toolbox.</p><h3>Install a Package for a Specific Workspace</h3><p>What if you want Mocha only for the server package?</p><pre>npm install mocha -w packages/very-simple-server</pre><p>The -w flag specifies which workspace gets the dependency. In our project, the server&#39;s package.json now has Mocha, but the client doesn&#39;t.</p><h3>Running Scripts Across Workspaces</h3><p>You can run npm scripts in different ways:</p><p><strong>Run test from the root (uses root’s test script):</strong></p><pre>npm test</pre><p><strong>Run tests in ALL workspaces:</strong></p><pre>npm test -ws</pre><p><strong>Run test in a specific workspace:</strong></p><pre>npm test -w packages/very-simple-client</pre><p>The -ws flag is your friend when you want to do something across all packages.</p><h3>Keeping Dependencies Up to Date</h3><p>Worried about outdated packages? Just run:</p><pre>npm outdated</pre><p>It’ll show you what’s old and needs updating across your entire monorepo.</p><h3>The Root package.json</h3><p>Here’s what the root package.json looks like in our project:</p><pre>{<br>  &quot;name&quot;: &quot;npm-monorepo-learn&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;type&quot;: &quot;commonjs&quot;,<br>  &quot;workspaces&quot;: [<br>    &quot;packages/very-simple-server&quot;,<br>    &quot;packages/very-simple-client&quot;<br>  ],<br>  &quot;dependencies&quot;: {<br>    &quot;jest&quot;: &quot;^30.3.0&quot;<br>  }<br>}</pre><p>And here’s a workspace package.json (the server one):</p><pre>{<br>  &quot;name&quot;: &quot;very-simple-server&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified in server\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;mocha&quot;: &quot;^11.7.5&quot;<br>  }<br>}</pre><h3>When Should You Use a Monorepo?</h3><p>Monorepos aren’t for everyone. Here’s when they make sense:</p><p><strong>Use a monorepo when:</strong></p><ul><li>You have related packages that depend on each other</li><li>You want to share code between projects</li><li>You’re building a component library with multiple components</li><li>You want simpler local development</li></ul><p><strong>Maybe skip it when:</strong></p><ul><li>Your packages are completely unrelated</li><li>You have a tiny project (just use a single package)</li><li>Your team isn’t comfortable with the concept yet</li></ul><h3>Common Gotchas</h3><ol><li><strong>Package names matter</strong>: Workspaces reference each other by their name field in package.json, not by folder name.</li><li><strong>Dependencies in workspaces</strong>: If workspace A depends on workspace B, make sure B’s name in its package.json matches what A is requiring.</li><li><strong>Hoisting</strong>: By default, npm tries to “hoist” dependencies to the root node_modules. This is usually what you want, but can cause issues if you have conflicting versions.</li></ol><h3>Wrapping Up</h3><p>Npm workspaces are a game-changer for managing multiple related packages. They’re built into npm (no extra tools needed), they’re easy to set up, and they make local development so much smoother.</p><p>The example project we walked through is intentionally simple, but the same concepts apply to real-world projects. Whether you’re building a component library, a full-stack app with shared types, or just trying to organize your code better, monorepos can help.</p><p>Give it a try! Start small, maybe with two packages that do something simple. Once you get the hang of it, you’ll wonder how you ever lived without it.</p><p>Happy coding! 🚀</p><p><em>Have you tried npm workspaces? What’s your experience been like? Let me know in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f04b50b1e13c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastra Agent Workflow: Human In The Loop, Suspend and Resume in Next.JS [Part 4]]]></title>
            <link>https://juniarto-samsudin.medium.com/mastra-agent-workflow-human-in-the-loop-suspend-and-resume-in-next-js-part-4-13e97265a8a6?source=rss-99a5a2e5cc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/13e97265a8a6</guid>
            <category><![CDATA[mastra-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[human-in-the-loop]]></category>
            <dc:creator><![CDATA[Juniarto Samsudin]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 04:06:35 GMT</pubDate>
            <atom:updated>2025-08-25T04:06:35.876Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“An agent workflow is like a relay — every step passes the baton. Miss a handoff, and the whole race stumbles. But when it flows right… everything moves at super speed.” </em>– The Flash</p><p>This is the fourth part of our exploration into the Mastra framework’s Workflow feature.<br><strong>Part 1:</strong> <a href="https://medium.com/@juniarto-samsudin/rain-or-shine-weve-got-you-covered-introducing-mastra-s-smart-activity-workflow-agent-%EF%B8%8F-40767909fd5c">Rain or Shine, We’ve Got You Covered! Introducing Mastra’s Smart Activity Workflow Agent!</a><br><strong>Part 2:</strong> <a href="https://juniarto-samsudin.medium.com/rain-or-shine-weve-got-you-covered-introducing-mastra-s-smart-activity-workflow-agent-part-2-41b8aaa4ad37">Introducing Mastra’s Smart Activity Workflow Agent in Next.JS</a><br><strong>Part 3</strong>: <a href="https://juniarto-samsudin.medium.com/mastra-agent-workflow-human-in-the-loop-suspend-and-resume-97f99bd443a6">Mastra Agent Workflow: Human In The Loop, Suspend and Resume</a><br><strong>Part 4</strong>: [This Article]</p><p>We’ve already talked about how “Human In The Loop” functions within the Local Dev Playground. Now, let’s take a look at how this same concept is put into practice with Next.js. While the implementation might not be identical, the underlying idea remains the same.</p><p>From this point forward, we’ll be sticking to the directory structures that we set up in [<a href="https://juniarto-samsudin.medium.com/rain-or-shine-weve-got-you-covered-introducing-mastra-s-smart-activity-workflow-agent-part-2-41b8aaa4ad37">Part 2</a>].</p><ol><li><strong>Workflow<br></strong>[src/mastra/workflows/<a href="http://approval-workflow.ts/">approval-workflow.ts</a>]</li></ol><pre>import { createWorkflow, createStep } from &quot;@mastra/core/workflows&quot;;<br>import { z } from &quot;zod&quot;;<br><br>const approvalStep = createStep({<br>  id: &quot;approval-step&quot;,<br>  description: &quot;Wait for manager approval&quot;,<br>  inputSchema: z.object({<br>    requestId: z.string(),<br>    amount: z.number()<br>  }),<br>  outputSchema: z.object({<br>    approved: z.boolean(),<br>    approverName: z.string()<br>  }),<br>  suspendSchema: z.object({<br>    requestId: z.string(),<br>    pendingSince: z.string()<br>  }),<br>  resumeSchema: z.object({<br>    approved: z.boolean(),<br>    approverName: z.string()<br>  }),<br>  execute: async ({ inputData, resumeData, suspend }) =&gt; {<br>    // If we don&#39;t have approval data yet, suspend the workflow<br>    if (!resumeData) {<br>      await suspend({<br>        requestId: inputData.requestId,<br>        pendingSince: new Date().toISOString()<br>      });<br>      // This return won&#39;t be reached when suspended<br>      return { approved: false, approverName: &quot;&quot; };<br>    }<br><br><br>    // We have resume data, so the approval came through<br>    return {<br>      approved: resumeData.approved,<br>      approverName: resumeData.approverName<br>    };<br>  }<br>});<br><br>export const approvalWorkflow = createWorkflow({<br>  id: &quot;approval-workflow&quot;,<br>  inputSchema: z.object({<br>    requestId: z.string(),<br>    amount: z.number()<br>  }),<br>  outputSchema: z.object({<br>    approved: z.boolean(),<br>    approverName: z.string()<br>  })<br>})<br>  .then(approvalStep)<br>  .commit();</pre><p><strong>2. Create Tools to access Workflow<br></strong>[src/mastra/tools/<a href="http://approval-tool.ts/">approval-tool.ts</a>]</p><pre>import { createTool } from &#39;@mastra/core/tools&#39;;<br>import { z } from &#39;zod&#39;;<br>import { mastra } from &#39;@/mastra&#39;;<br><br>export const startApprovalTool = createTool({<br>    id: &#39;start-approval-tool&#39;,<br>    description: &#39;Start an approval process for a request&#39;,<br>    inputSchema: z.object({<br>        requestId: z.string().describe(&#39;Unique identifier for the request&#39;),<br>        amount: z.number().describe(&#39;Amount to be approved&#39;),<br>    }),<br>    outputSchema: z.object({<br>        runId: z.string().describe(&#39;Run ID of the approval workflow&#39;),<br>    }),<br>    execute: async ({ context }) =&gt; {<br>        const { requestId, amount } = context;<br><br>        const MyWorkflow = mastra.getWorkflow(&#39;approvalWorkflow&#39;);<br><br>        // Start the approval workflow<br>        const run = await MyWorkflow.createRunAsync();<br>        await run.start({<br>            inputData: {<br>                requestId,<br>                amount,<br>            },<br>        });<br><br>        return {<br>            runId: run.runId<br>        };<br>    }<br>});<br><br>export const resumeApprovalTool = createTool({<br>    id: &#39;resume-approval-tool&#39;,<br>    description: &#39;Resume an approval process with the decision and approver name&#39;,<br>    inputSchema: z.object({<br>        runId: z.string().describe(&#39;Run ID of the approval workflow&#39;),<br>        approved: z.boolean().describe(&#39;Approval decision&#39;),<br>        approverName: z.string().describe(&#39;Name of the approver&#39;),<br>    }),<br>    outputSchema: z.object({<br>        result: z.string().describe(&#39;Result of the approval process&#39;),<br>    }),<br>    execute: async ({ context }) =&gt; {<br>        const { runId, approved, approverName } = context;<br><br>        const MyWorkflow = mastra.getWorkflow(&#39;approvalWorkflow&#39;);<br>        const run = await MyWorkflow.createRunAsync({<br>            runId: context.runId    <br>        });<br><br>        const result = await run.resume({<br>            step: &#39;approval-step&#39;,<br>            resumeData: {<br>                approved,<br>                approverName<br>            }       <br>        });<br><br>        return {<br>            result: JSON.stringify(result)<br>        };<br><br>    }<br>});</pre><p><strong>3. Create Agent.<br></strong>[src/mastra/agents/<a href="http://approva-agent.ts/">approval-agent.ts</a>]</p><pre>import { Agent } from &quot;@mastra/core&quot;;<br>import { openai } from &quot;@ai-sdk/openai&quot;;<br>import { startApprovalTool, resumeApprovalTool } from &quot;@/mastra/tools/approval-tool&quot;;<br>import { Memory } from &quot;@mastra/memory&quot;;<br>import { LibSQLStore } from &quot;@mastra/libsql&quot;;<br><br><br>export const approvalAgent = new Agent({<br>  name: &quot;approvalAgent&quot;,<br>  model: openai(&quot;gpt-4o&quot;), // No LLM model is directly associated with this agent<br>  instructions: <br>  &quot;You are a helpful workflow agent that assists with approver activity.&quot; + <br>  &quot;Use the startApprovalTool to start an approval process. This will start and then suspend the workflow and return a runId.&quot; +<br>  &quot;Use the resumeApprovalTool to resume the approval process. This takes the runId returned from the startApprovalTool and the decision (approved or not) and the approver name entered by the user.&quot; +<br>  &quot;It will resume the workflow and then return the result of the approval process.&quot;,<br>  tools: {<br>    startApprovalTool,<br>    resumeApprovalTool,<br>  },<br>  memory: new Memory({<br>    storage: new LibSQLStore({<br>      url: &quot;file:../mastra.db&quot;, // path is relative to the .mastra/output directory<br>    }),<br>  }),<br>});</pre><p><strong>4. Update Masra Index to include newly created workflows, tools and agent.<br></strong>[src/mastra/<a href="http://index.ts/">index.ts</a>]</p><pre>import { Mastra } from &#39;@mastra/core/mastra&#39;;<br>import { PinoLogger } from &#39;@mastra/loggers&#39;;<br>import { LibSQLStore } from &#39;@mastra/libsql&#39;;<br>import { approvalAgent} from &#39;./agents/approval-agent&#39;;<br>import { approvalWorkflow } from &#39;./workflows/approval-workflow&#39;;<br><br>export const mastra = new Mastra({<br>  workflows: { approvalWorkflow },<br>  agents: { approvalAgent },<br>  storage: new LibSQLStore({<br>    // stores telemetry, evals, ... into memory storage, if it needs to persist, change to file:../mastra.db<br>    url: &quot;:memory:&quot;,<br>  }),<br>  logger: new PinoLogger({<br>    name: &#39;Mastra&#39;,<br>    level: &#39;info&#39;,<br>  }),<br>});</pre><p>Good, We have agent, workflow, and tool ready. Time to setup <a href="http://next.js/">Next.Js</a>.</p><ol><li><strong>Route<br></strong>[src/app/api/chatapproval/<a href="http://route.ts/">route.ts</a>]</li></ol><pre>import { mastra } from &quot;@/mastra&quot;;<br>import { Agent } from &quot;@mastra/core&quot;;<br>import { openai } from &quot;@ai-sdk/openai&quot;;<br>import { startApprovalTool, resumeApprovalTool } from &quot;@/mastra/tools/approval-tool&quot;;<br><br>// Using Agent<br>export async function POST(req: Request) {<br>  try {<br>      const { messages } = await req.json();<br>      console.log(&#39;Received messages:&#39;, messages);<br><br> <br>      const myAgent = mastra.getAgent(&quot;approvalAgent&quot;);<br><br>      const stream = await myAgent.stream(messages);<br>      const dataStreamResponse = stream.toDataStreamResponse({<br>        getErrorMessage: error =&gt; {<br>          if (error == null) {<br>            return &#39;unknown error&#39;;<br>          }<br><br>          if (typeof error === &#39;string&#39;) {<br>            return error;<br>          }<br><br>          if (error instanceof Error) {<br>            return error.message;<br>          }<br><br>          return JSON.stringify(error);<br>        },<br>      });<br><br>      return dataStreamResponse;<br><br>      <br>  } catch (error) {<br>      console.error(&#39;Error during agent streaming:&#39;, error);<br>      return new Response(&#39;Error during agent streaming&#39;, { status: 500 });<br>  }<br>}</pre><p><strong>2. Layout<br></strong>[src/app/activityplanner/layout.tsx]</p><pre>import type { Metadata } from &quot;next&quot;;<br>import { Geist, Geist_Mono } from &quot;next/font/google&quot;;<br>//import &quot;./globals.css&quot;;<br>import FloatingChatApproval from &quot;@/components/FloatingChatApproval&quot;;<br><br>const geistSans = Geist({<br>  variable: &quot;--font-geist-sans&quot;,<br>  subsets: [&quot;latin&quot;],<br>});<br><br>const geistMono = Geist_Mono({<br>  variable: &quot;--font-geist-mono&quot;,<br>  subsets: [&quot;latin&quot;],<br>});<br><br>export const metadata: Metadata = {<br>  title: &quot;Create Next App&quot;,<br>  description: &quot;Generated by create next app&quot;,<br>};<br><br>export default function RootLayout({<br>  children,<br>}: Readonly&lt;{<br>  children: React.ReactNode;<br>}&gt;) {<br>  return (<br>    &lt;&gt;<br>        {children}<br>        &lt;FloatingChatApproval /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p><strong>3. Page<br></strong>[src/app/approval/page.tsx]</p><pre>import Image from &quot;next/image&quot;;<br><br>export default function Home() {<br>  return (<br>    &lt;div className=&quot;flex items-center justify-center h-screen&quot;&gt;<br>      &lt;h1&gt;Hello Chat Bot Approval&lt;/h1&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>4. Component<br></strong>[src/components/FloatingChatApproval.tsx]</p><pre>&#39;use client&#39;;<br><br>import { useChat } from &#39;@ai-sdk/react&#39;;<br>import { useState } from &#39;react&#39;;<br><br>export default function FloatingChatApproval() {<br>  const { messages, input, handleInputChange, handleSubmit } = useChat({<br>    maxSteps: 5,<br>    api:&#39;/api/chatapproval&#39;<br>  });<br>  const [open, setOpen] = useState(false);<br>    <br>  return (<br>    &lt;div className=&quot;fixed bottom-4 right-4 z-50&quot;&gt;<br>      &lt;button<br>        onClick={() =&gt; setOpen(!open)}<br>        className=&quot;mb-2 bg-blue-600 text-white px-4 py-2 rounded-full shadow&quot;<br>      &gt;<br>        {open ? &#39;Close Chat&#39; : &#39;Open Chat&#39;}<br>      &lt;/button&gt;<br><br>      {open &amp;&amp; (<br>        &lt;div className=&quot;fixed bottom-35 right-20 w-[350px] max-h-[500px] bg-white shadow-xl border rounded-xl overflow-y-auto p-5&quot;&gt;<br>          &lt;button<br>            onClick={() =&gt; setOpen(false)}<br>            className=&quot;absolute top-2 right-2 text-gray-500 hover:text-gray-700&quot;<br>          &gt;<br>            &amp;times;<br>          &lt;/button&gt;<br>          &lt;div className=&quot;flex flex-col w-full max-w-md py-24 mx-auto stretch text-gray-700 &quot;&gt;<br>            {messages.map(message =&gt; (<br>              &lt;div key={message.id} className=&quot;whitespace-pre-wrap&quot;&gt;<br>                {message.role === &#39;user&#39; ? &#39;User: &#39; : &#39;AI: &#39;}<br>                {message.parts.map((part, i) =&gt; {<br>                  switch (part.type) {<br>                    case &#39;text&#39;:<br>                      return &lt;div key={`${message.id}-${i}`}&gt;{part.text}&lt;/div&gt;;<br>                  }<br>                })}<br>              &lt;/div&gt;<br>            ))}<br>          &lt;/div&gt;<br>          &lt;form onSubmit={handleSubmit}&gt;<br>            &lt;input<br>              className=&quot;fixed dark:bg-zinc-900 bottom-10 w-[330px] max-w-md p-2 mb-8 border border-zinc-300 dark:border-zinc-800 rounded shadow-xl text-gray-700 dark:text-gray-200&quot;<br>              value={input}<br>              placeholder=&quot;Say something...&quot;<br>              onChange={handleInputChange}<br>            /&gt;<br>          &lt;/form&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>It’s all done! The user interface should now appear as show below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LkxRvmevzesMbbMQoS15Ew.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13e97265a8a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rain or Shine, We’ve Got You Covered! Introducing Mastra’s Smart Activity Workflow Agent! [Part -2]]]></title>
            <link>https://juniarto-samsudin.medium.com/rain-or-shine-weve-got-you-covered-introducing-mastra-s-smart-activity-workflow-agent-part-2-41b8aaa4ad37?source=rss-99a5a2e5cc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/41b8aaa4ad37</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[mastra-ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[ai-workflow]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Juniarto Samsudin]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 07:29:12 GMT</pubDate>
            <atom:updated>2025-08-05T07:29:12.240Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“A good agent knows when to act. A great one knows when to wait.” — Nick Fury, on suspend-and-resume in AI agentic workflows</em></p><p>In the <a href="https://medium.com/@juniarto-samsudin/rain-or-shine-weve-got-you-covered-introducing-mastra-s-smart-activity-workflow-agent-%EF%B8%8F-40767909fd5c">first part </a>of this series, we set up our planning agent and workflow on a local development server. This allowed us to test everything out in a playful environment, specifically at <a href="http://localhost:4111/">http://localhost:4111/.</a> Now, we’re ready to take the next step and deploy them within a Next.js application. Before we dive into that, it’s important that we first get Mastra set up in Next.js. If you need more details on how to do that, you can check out this article: “<a href="https://juniarto-samsudin.medium.com/building-chatbox-ui-on-next-js-using-vercel-ai-sdk-part-1-86cec0889bf4">Building Chatbox UI on Next.js using Vercel AI SDK [part 1]</a>”.</p><p><strong>So, where exactly do our agent and workflows reside?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/0*sIdYhzXfNr6Bdblv" /></figure><p><strong>[agents]: This is where our agents live.<br>[workflows]: This is where our workflows live.</strong></p><ol><li><strong>Planning Agent [src/mastra/agents/</strong><a href="http://planning-agent.ts/"><strong>planning-agent.ts</strong></a><strong>]</strong></li></ol><pre>import { Agent } from &quot;@mastra/core/agent&quot;;<br>import { openai } from &quot;@ai-sdk/openai&quot;;<br> <br>const llm = openai(&quot;gpt-4o&quot;);<br> <br>// Define the planning agent that generates activity recommendations<br>// based on weather conditions and location<br>const planningAgent = new Agent({<br>  name: &quot;planningAgent&quot;,<br>  model: llm,<br>  instructions: `<br>        You are a local activities and travel expert who excels at weather-based planning. Analyze the weather data and provide practical activity recommendations.<br> <br>        📅 [Day, Month Date, Year]<br>        ═══════════════════════════<br> <br>        🌡️ WEATHER SUMMARY<br>        • Conditions: [brief description]<br>        • Temperature: [X°C/Y°F to A°C/B°F]<br>        • Precipitation: [X% chance]<br> <br>        🌅 MORNING ACTIVITIES<br>        Outdoor:<br>        • [Activity Name] - [Brief description including specific location/route]<br>          Best timing: [specific time range]<br>          Note: [relevant weather consideration]<br> <br>        🌞 AFTERNOON ACTIVITIES<br>        Outdoor:<br>        • [Activity Name] - [Brief description including specific location/route]<br>          Best timing: [specific time range]<br>          Note: [relevant weather consideration]<br> <br>        🏠 INDOOR ALTERNATIVES<br>        • [Activity Name] - [Brief description including specific venue]<br>          Ideal for: [weather condition that would trigger this alternative]<br> <br>        ⚠️ SPECIAL CONSIDERATIONS<br>        • [Any relevant weather warnings, UV index, wind conditions, etc.]<br> <br>        Guidelines:<br>        - Suggest 2-3 time-specific outdoor activities per day<br>        - Include 1-2 indoor backup options<br>        - For precipitation &gt;50%, lead with indoor activities<br>        - All activities must be specific to the location<br>        - Include specific venues, trails, or locations<br>        - Consider activity intensity based on temperature<br>        - Keep descriptions concise but informative<br> <br>        Maintain this exact formatting for consistency, using the emoji and section headers as shown.<br>      `,<br>});<br> <br>export { planningAgent };</pre><p>2. <strong>Activity Planning Workflow [src/mastra/workflows/</strong><a href="http://activity-planner-workflow.ts/"><strong>activity-planner-workflow.ts</strong></a><strong>]</strong></p><pre>import { z } from &quot;zod&quot;;<br>import { createWorkflow, createStep } from &quot;@mastra/core/workflows&quot;;<br>//import { mastra } from &quot;@/mastra&quot;;<br> <br>// Helper function to convert weather codes to human-readable conditions<br>function getWeatherCondition(code: number): string {<br>  const conditions: Record&lt;number, string&gt; = {<br>    0: &quot;Clear sky&quot;,<br>    1: &quot;Mainly clear&quot;,<br>    2: &quot;Partly cloudy&quot;,<br>    3: &quot;Overcast&quot;,<br>    45: &quot;Foggy&quot;,<br>    48: &quot;Depositing rime fog&quot;,<br>    51: &quot;Light drizzle&quot;,<br>    53: &quot;Moderate drizzle&quot;,<br>    55: &quot;Dense drizzle&quot;,<br>    61: &quot;Slight rain&quot;,<br>    63: &quot;Moderate rain&quot;,<br>    65: &quot;Heavy rain&quot;,<br>    71: &quot;Slight snow fall&quot;,<br>    73: &quot;Moderate snow fall&quot;,<br>    75: &quot;Heavy snow fall&quot;,<br>    95: &quot;Thunderstorm&quot;,<br>  };<br>  return conditions[code] || &quot;Unknown&quot;;<br>}<br> <br>const forecastSchema = z.object({<br>  date: z.string(),<br>  maxTemp: z.number(),<br>  minTemp: z.number(),<br>  precipitationChance: z.number(),<br>  condition: z.string(),<br>  location: z.string(),<br>});<br><br>const fetchWeather = createStep({<br>  id: &quot;fetch-weather&quot;,<br>  description: &quot;Fetches weather forecast for a given city&quot;,<br>  inputSchema: z.object({<br>    city: z.string(),<br>  }),<br>  outputSchema: forecastSchema,<br>  execute: async ({ inputData }) =&gt; {<br>    if (!inputData) {<br>      throw new Error(&quot;Trigger data not found&quot;);<br>    }<br> <br>    const geocodingUrl = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(inputData.city)}&amp;count=1`;<br>    const geocodingResponse = await fetch(geocodingUrl);<br>    const geocodingData = (await geocodingResponse.json()) as {<br>      results: { latitude: number; longitude: number; name: string }[];<br>    };<br> <br>    if (!geocodingData.results?.[0]) {<br>      throw new Error(`Location &#39;${inputData.city}&#39; not found`);<br>    }<br> <br>    const { latitude, longitude, name } = geocodingData.results[0];<br> <br>    const weatherUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&amp;longitude=${longitude}&amp;current=precipitation,weathercode&amp;timezone=auto,&amp;hourly=precipitation_probability,temperature_2m`;<br>    const response = await fetch(weatherUrl);<br>    const data = (await response.json()) as {<br>      current: {<br>        time: string;<br>        precipitation: number;<br>        weathercode: number;<br>      };<br>      hourly: {<br>        precipitation_probability: number[];<br>        temperature_2m: number[];<br>      };<br>    };<br> <br>    const forecast = {<br>      date: new Date().toISOString(),<br>      maxTemp: Math.max(...data.hourly.temperature_2m),<br>      minTemp: Math.min(...data.hourly.temperature_2m),<br>      condition: getWeatherCondition(data.current.weathercode),<br>      location: name,<br>      precipitationChance: data.hourly.precipitation_probability.reduce(<br>        (acc, curr) =&gt; Math.max(acc, curr),<br>        0,<br>      ),<br>    };<br> <br>    return forecast;<br>  },<br>});<br><br>const planActivities = createStep({<br>  id: &quot;plan-activities&quot;,<br>  description: &quot;Suggests activities based on weather conditions&quot;,<br>  inputSchema: forecastSchema,<br>  outputSchema: z.object({<br>    activities: z.string(),<br>  }),<br>  execute: async ({ inputData, mastra }) =&gt; {<br>    const forecast = inputData;<br> <br>    if (!forecast) {<br>      throw new Error(&quot;Forecast data not found&quot;);<br>    }<br> <br>    const prompt = `Based on the following weather forecast for ${forecast.location}, suggest appropriate activities:<br>      ${JSON.stringify(forecast, null, 2)}<br>      `;<br> <br>    const agent = mastra?.getAgent(&quot;planningAgent&quot;);<br>    if (!agent) {<br>      throw new Error(&quot;Planning agent not found&quot;);<br>    }<br> <br>    const response = await agent.stream([<br>      {<br>        role: &quot;user&quot;,<br>        content: prompt,<br>      },<br>    ]);<br> <br>    let activitiesText = &quot;&quot;;<br> <br>    for await (const chunk of response.textStream) {<br>      process.stdout.write(chunk);<br>      activitiesText += chunk;<br>    }<br>    console.log(&quot;Activities planned:&quot;, activitiesText);<br> <br>    return {<br>      activities: activitiesText,<br>    };<br>  },<br>});<br><br>const planIndoorActivities = createStep({<br>  id: &quot;plan-indoor-activities&quot;,<br>  description: &quot;Suggests indoor activities based on weather conditions&quot;,<br>  inputSchema: forecastSchema,<br>  outputSchema: z.object({<br>    activities: z.string(),<br>  }),<br>  execute: async ({ inputData, mastra }) =&gt; {<br>    const forecast = inputData;<br> <br>    if (!forecast) {<br>      throw new Error(&quot;Forecast data not found&quot;);<br>    }<br> <br>    const prompt = `In case it rains, plan indoor activities for ${forecast.location} on ${forecast.date}`;<br> <br>    const agent = mastra?.getAgent(&quot;planningAgent&quot;);<br>    if (!agent) {<br>      throw new Error(&quot;Planning agent not found&quot;);<br>    }<br> <br>    const response = await agent.stream([<br>      {<br>        role: &quot;user&quot;,<br>        content: prompt,<br>      },<br>    ]);<br> <br>    let activitiesText = &quot;&quot;;<br> <br>    for await (const chunk of response.textStream) {<br>      process.stdout.write(chunk);<br>      activitiesText += chunk;<br>    }<br><br>    console.log(&quot;Indoor activities planned:&quot;, activitiesText);<br> <br>    return {<br>      activities: activitiesText,<br>    };<br>  },<br>});<br><br>const activityPlanningWorkflow = createWorkflow({<br>  id: &quot;activity-planning-workflow-step2-if-else&quot;,<br>  inputSchema: z.object({<br>    city: z.string().describe(&quot;The city to get the weather for&quot;),<br>  }),<br>  outputSchema: z.object({<br>    activities: z.string(),<br>  }),<br>})<br>  .then(fetchWeather)<br>  .branch([<br>    // Branch for high precipitation (indoor activities)<br>    [<br>      async ({ inputData }) =&gt; {<br>        return inputData?.precipitationChance &gt; 50;<br>      },<br>      planIndoorActivities,<br>    ],<br>    // Branch for low precipitation (outdoor activities)<br>    [<br>      async ({ inputData }) =&gt; {<br>        return inputData?.precipitationChance &lt;= 50;<br>      },<br>      planActivities,<br>    ],<br>  ]);<br> <br>activityPlanningWorkflow.commit();<br> <br>export { activityPlanningWorkflow };</pre><p><strong>3. index.ts [src/mastra/index.ts]</strong></p><pre>import { Mastra } from &#39;@mastra/core/mastra&#39;;<br>import { PinoLogger } from &#39;@mastra/loggers&#39;;<br>import { LibSQLStore } from &#39;@mastra/libsql&#39;;<br>import { activityPlanningWorkflow } from &#39;./workflows/activity-planner-workflow&#39;;<br>import { planningAgent} from &#39;./agents/planning-agent&#39;;<br><br><br>export const mastra = new Mastra({<br>  workflows: { activityPlanningWorkflow },<br>  agents: { planningAgent },<br>  storage: new LibSQLStore({<br>    // stores telemetry, evals, ... into memory storage, if it needs to persist, change to file:../mastra.db<br>    url: &quot;:memory:&quot;,<br>  }),<br>  logger: new PinoLogger({<br>    name: &#39;Mastra&#39;,<br>    level: &#39;info&#39;,<br>  }),<br>});</pre><p>So, that’s pretty much all there is to our agent and workflow. Now, we can move on to the fun part: coding up our user interface!</p><p><strong>User Interface and API:</strong></p><p><strong>Directory structure:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*ADzFSkfk-K4qe6_GR1_Qrw.png" /></figure><p><strong>[src/app/api/chatactivityplanner/</strong><a href="http://route.ts/"><strong>route.ts</strong></a><strong>]</strong></p><p>Perhaps this is the most important part. We wrapped our workflow inside the agent.</p><pre>import { mastra } from &quot;@/mastra&quot;;<br>import { Agent } from &quot;@mastra/core&quot;;<br>import { openai } from &quot;@ai-sdk/openai&quot;;<br><br>// Using Agent<br>export async function POST(req: Request) {<br>  try {<br>      const { messages } = await req.json();<br>      console.log(&#39;Received messages:&#39;, messages);<br><br>      const myAgent = new Agent({<br>        name: &quot;workflowAgent&quot;,<br>        model: openai(&quot;gpt-4o&quot;),<br>        instructions: &quot;You are a helpful workflow agent that assists with activity planning. Use the provided workflow to generate activity recommendations based on user input on a city.&quot;,<br>        workflows: {<br>          activityPlanningWorkflow: mastra.getWorkflow(&quot;activityPlanningWorkflow&quot;),<br>        },<br>      })<br><br>      const stream = await myAgent.stream(messages);<br>      const dataStreamResponse = stream.toDataStreamResponse({<br>        getErrorMessage: error =&gt; {<br>          if (error == null) {<br>            return &#39;unknown error&#39;;<br>          }<br><br>          if (typeof error === &#39;string&#39;) {<br>            return error;<br>          }<br><br>          if (error instanceof Error) {<br>            return error.message;<br>          }<br><br>          return JSON.stringify(error);<br>        },<br>      });<br><br>      return dataStreamResponse;<br>      <br>  } catch (error) {<br>      console.error(&#39;Error during agent streaming:&#39;, error);<br>      return new Response(&#39;Error during agent streaming&#39;, { status: 500 });<br>  }<br>}</pre><p><strong>[src/app/activityplanner/layout.tsx]</strong></p><pre>import type { Metadata } from &quot;next&quot;;<br>import { Geist, Geist_Mono } from &quot;next/font/google&quot;;<br>//import &quot;./globals.css&quot;;<br>import FloatingChatActivityPlanner from &quot;@/components/FloatingChatActivityPlanner&quot;;<br><br>const geistSans = Geist({<br>  variable: &quot;--font-geist-sans&quot;,<br>  subsets: [&quot;latin&quot;],<br>});<br><br>const geistMono = Geist_Mono({<br>  variable: &quot;--font-geist-mono&quot;,<br>  subsets: [&quot;latin&quot;],<br>});<br><br>export const metadata: Metadata = {<br>  title: &quot;Create Next App&quot;,<br>  description: &quot;Generated by create next app&quot;,<br>};<br><br>export default function RootLayout({<br>  children,<br>}: Readonly&lt;{<br>  children: React.ReactNode;<br>}&gt;) {<br>  return (<br>    &lt;&gt;<br>        {children}<br>        &lt;FloatingChatActivityPlanner /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p><strong>[src/app/activityplanner/page.tsx]</strong></p><pre>import Image from &quot;next/image&quot;;<br><br>export default function Home() {<br>  return (<br>    &lt;div className=&quot;flex items-center justify-center h-screen&quot;&gt;<br>      &lt;h1&gt;Hello Chat Bot Activity Planner&lt;/h1&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>[src/components/FloatingChatActivityPlanner.tsx]</strong></p><pre>&#39;use client&#39;;<br><br>import { useChat } from &#39;@ai-sdk/react&#39;;<br>import { useState } from &#39;react&#39;;<br><br>export default function FloatingChatActivityPlanner() {<br>  const { messages, input, handleInputChange, handleSubmit } = useChat({<br>    maxSteps: 5,<br>    api:&#39;/api/chatactivityplanner&#39;<br>  });<br>  const [open, setOpen] = useState(false);<br>    <br>  return (<br>    &lt;div className=&quot;fixed bottom-4 right-4 z-50&quot;&gt;<br>      &lt;button<br>        onClick={() =&gt; setOpen(!open)}<br>        className=&quot;mb-2 bg-blue-600 text-white px-4 py-2 rounded-full shadow&quot;<br>      &gt;<br>        {open ? &#39;Close Chat&#39; : &#39;Open Chat&#39;}<br>      &lt;/button&gt;<br><br>      {open &amp;&amp; (<br>        &lt;div className=&quot;fixed bottom-35 right-20 w-[350px] max-h-[500px] bg-white shadow-xl border rounded-xl overflow-y-auto p-5&quot;&gt;<br>          &lt;button<br>            onClick={() =&gt; setOpen(false)}<br>            className=&quot;absolute top-2 right-2 text-gray-500 hover:text-gray-700&quot;<br>          &gt;<br>            &amp;times;<br>          &lt;/button&gt;<br>          &lt;div className=&quot;flex flex-col w-full max-w-md py-24 mx-auto stretch text-gray-700 &quot;&gt;<br>            {messages.map(message =&gt; (<br>              &lt;div key={message.id} className=&quot;whitespace-pre-wrap&quot;&gt;<br>                {message.role === &#39;user&#39; ? &#39;User: &#39; : &#39;AI: &#39;}<br>                {message.parts.map((part, i) =&gt; {<br>                  switch (part.type) {<br>                    case &#39;text&#39;:<br>                      return &lt;div key={`${message.id}-${i}`}&gt;{part.text}&lt;/div&gt;;<br>                  }<br>                })}<br>              &lt;/div&gt;<br>            ))}<br>          &lt;/div&gt;<br>          &lt;form onSubmit={handleSubmit}&gt;<br>            &lt;input<br>              className=&quot;fixed dark:bg-zinc-900 bottom-10 w-[330px] max-w-md p-2 mb-8 border border-zinc-300 dark:border-zinc-800 rounded shadow-xl text-gray-700 dark:text-gray-200&quot;<br>              value={input}<br>              placeholder=&quot;Say something...&quot;<br>              onChange={handleInputChange}<br>            /&gt;<br>          &lt;/form&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>It’s all done! The user interface should now appear as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*Yv8qPMImlsjbut0cxHM0UQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41b8aaa4ad37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastra Agent Workflow: Human In The Loop, Suspend and Resume]]></title>
            <link>https://juniarto-samsudin.medium.com/mastra-agent-workflow-human-in-the-loop-suspend-and-resume-97f99bd443a6?source=rss-99a5a2e5cc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/97f99bd443a6</guid>
            <category><![CDATA[mastra-ai]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Juniarto Samsudin]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 06:43:15 GMT</pubDate>
            <atom:updated>2025-08-25T00:27:36.385Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“Even the sharpest mind needs time to reassess the plan. Suspend the workflow — not because it’s failing, but because precision demands patience. Then resume… with purpose.”</em></p><p><em>— Batman, in the Batcave during a systems update</em></p><p>This is the third part of our exploration into the Mastra framework’s Workflow feature.</p><p>Part 1:<a href="https://juniarto-samsudin.medium.com/rain-or-shine-weve-got-you-covered-introducing-mastra-s-smart-activity-workflow-agent-%EF%B8%8F-40767909fd5c"> Rain or Shine, We’ve Got You Covered! Introducing Mastra’s Smart Activity Workflow Agent!</a> <br>Part 2: <a href="https://juniarto-samsudin.medium.com/rain-or-shine-weve-got-you-covered-introducing-mastra-s-smart-activity-workflow-agent-part-2-41b8aaa4ad37">Introducing Mastra’s Smart Activity Workflow Agent in Next.JS </a><br>Part 3: [This article]</p><p>This is the third part of our exploration into the Mastra framework’s Workflow feature. If you haven’t read the first part, you can find it <a href="https://juniarto-samsudin.medium.com/rain-or-shine-weve-got-you-covered-introducing-mastra-s-smart-activity-workflow-agent-%EF%B8%8F-40767909fd5c">here</a>.</p><p>Workflows in Mastra have a cool ability: they can be paused and then picked up right where they left off. A common reason for pausing a workflow is when it needs human involvement, like waiting for someone to approve something or provide specific information.</p><p>Let’s look at an example. Imagine a user wants to request approval for a certain amount of cash. The workflow would kick off with the requestId and amount as its initial input. Then, it would basically hit the “pause” button, waiting for someone to give their official approval and also provide their name (which we’ll call approvalName). Once that approval comes through, the workflow can resume its operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*iS1SPgxPHHnchlFZARsvqA.png" /></figure><p><strong>[src/mastra/workflows/</strong><a href="http://approval-workflow.ts/"><strong>approval-workflow.ts</strong></a><strong>]</strong></p><pre>import { createWorkflow, createStep } from &quot;@mastra/core/workflows&quot;;<br>import { z } from &quot;zod&quot;;<br><br>const approvalStep = createStep({<br>  id: &quot;approval-step&quot;,<br>  description: &quot;Wait for manager approval&quot;,<br>  inputSchema: z.object({<br>    requestId: z.string(),<br>    amount: z.number()<br>  }),<br>  outputSchema: z.object({<br>    approved: z.boolean(),<br>    approverName: z.string()<br>  }),<br>  suspendSchema: z.object({<br>    requestId: z.string(),<br>    pendingSince: z.string()<br>  }),<br>  resumeSchema: z.object({<br>    approved: z.boolean(),<br>    approverName: z.string()<br>  }),<br>  execute: async ({ inputData, resumeData, suspend }) =&gt; {<br>    // If we don&#39;t have approval data [resumeSchema] yet, suspend the workflow<br>    if (!resumeData) {<br>      // Create suspendSchema<br>      await suspend({<br>        requestId: inputData.requestId,<br>        pendingSince: new Date().toISOString()<br>      });<br>      // This return won&#39;t be reached when suspended<br>      return { approved: false, approverName: &quot;&quot; };<br>    }<br><br>    // We have resume data, so the approval came through<br>    return {<br>      approved: resumeData.approved,<br>      approverName: resumeData.approverName<br>    };<br>  }<br>});<br><br>export const approvalWorkflow = createWorkflow({<br>  id: &quot;approval-workflow&quot;,<br>  inputSchema: z.object({<br>    requestId: z.string(),<br>    amount: z.number()<br>  }),<br>  outputSchema: z.object({<br>    approved: z.boolean(),<br>    approverName: z.string()<br>  })<br>})<br>  .then(approvalStep)<br>  .commit();</pre><p>To test ‘approval-workflow’ above, we launch our Local Dev Playground</p><pre>mastra dev</pre><p>at <a href="http://localhost:4111/">http://localhost:4111</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*JBlVwv2A7Y_7o5CVSUW48A.png" /></figure><p>Okay, so first off, we need to get the workflow started. We’ll kick it off with some initial information, like a “Request ID,” let’s say “R-1,” and an “Amount,” for example, “1250.”</p><p>Once we do that, the workflow will basically hit a pause button. It’ll get “suspended” because we don’t have all the necessary information to keep it going right away. Think of it like waiting for a crucial piece of data. While it’s suspended, some specific data, which we call “suspendData,” will be generated. This data is structured according to something called “suspendSchema.”</p><p>Now, this is where human interaction comes into play. Someone needs to step in and provide the missing details. Specifically, they’ll need to input whether the request has been “approved” and also the “approverName.” This information will fulfill what we call the “resumeSchema,” which tells the system it’s okay to pick up where it left off.</p><p>Once those details are entered, the workflow can finally continue, and ultimately, it will be completed!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*Wg520QMCBvHaViYFZtHwjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*N3CUS1_7Egc70p3mBZcwzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*lwvMmck2hc3ThPxf5RNZ5Q.png" /></figure><p>We’ve successfully run, paused, and restarted the workflow using the graphical interface in our Local Development Playground. That’s great! But the real question is, how do we access or test this workflow from a separate client, like a Node.js script using MastraClient library?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*jYM7MVqDG3GfezOc0SaT9A.png" /></figure><p><strong>Mastra Client Script</strong></p><pre>import { MastraClient } from &quot;@mastra/client-js&quot;;<br> <br>const client = new MastraClient({<br>    // Default Mastra development server port<br>    baseUrl: &quot;http://localhost:4111&quot;, <br>});<br><br>const main = async () =&gt; {<br> <br>    let result = null;<br>    let run = null;<br>    let myWorkflow = null;<br>    try {<br>        myWorkflow = await client.getWorkflow(&quot;approvalWorkflow&quot;);<br>        <br>        run = await myWorkflow.createRun();<br><br>        myWorkflow.watch({ runId: run.runId }, (record) =&gt; {<br>            console.log(record);<br>        });<br><br>        result = await myWorkflow.startAsync({<br>            runId: run.runId,<br>            inputData: {<br>                requestId: &quot;R-12345&quot;,<br>                amount: 1250<br>            },<br>        });<br>       <br>    } catch (error) {<br>        console.error(&quot;Error:&quot;, error);<br>    }<br><br>    await sleep(3000); <br>   // Wait for 3 seconds to allow the workflow to complete<br>    console.log(&quot;Workflow execution completed.&quot;);<br><br>    if (result?.status === &quot;suspended&quot; &amp;&amp; run) {<br>        console.log(&quot;Workflow is suspended. Steps:&quot;, result.steps);<br>/*        <br>  Workflow is suspended. Steps: <br>  {<br>       input: { requestId: &#39;R-12345&#39;, amount: 1250 },<br>       &#39;approval-step&#39;: {<br>             payload: { requestId: &#39;R-12345&#39;, amount: 1250 },<br>             startedAt: 1754028180224,<br>             status: &#39;suspended&#39;,<br>             suspendPayload: {<br>                       requestId: &#39;R-12345&#39;, <br>                       pendingSince: &#39;2025-08-01T06:03:00.225Z&#39;<br>              },<br>             suspendedAt: 1754028180225<br>        }<br>   }<br>*/<br><br><br><br><br>        myWorkflow?.watch({ runId: run.runId }, (record) =&gt; {<br>            console.log(&quot;Resume Watch Record:&quot;, JSON.stringify(record, null, 2));<br>        });<br><br>        const resumeResult = await myWorkflow?.resume({<br>            step: &#39;approval-step&#39;,<br>            runId: run.runId,<br>            resumeData: {<br>                approved: true,<br>                approverName: &quot;John Doe&quot;,<br>            }<br>        });<br><br>        const finalresult = await myWorkflow?.runExecutionResult(run.runId);<br>        console.log(&quot;Resume Result:&quot;, JSON.stringify(finalresult, null, 2));<br>        <br>    }<br>}<br><br>(async () =&gt; {<br>    await main();<br>})().catch(console.error);<br><br>function sleep(ms: number): Promise&lt;void&gt; {<br>    return new Promise(resolve =&gt; setTimeout(resolve, ms));<br>}</pre><p>Resume Result:</p><pre>{<br>  &quot;status&quot;: &quot;success&quot;,<br>  &quot;result&quot;: {<br>    &quot;approved&quot;: true,<br>    &quot;approverName&quot;: &quot;John Doe&quot;<br>  },<br>  &quot;payload&quot;: {<br>    &quot;requestId&quot;: &quot;R-12345&quot;,<br>    &quot;amount&quot;: 1250<br>  },<br>  &quot;steps&quot;: {<br>    &quot;input&quot;: {<br>      &quot;requestId&quot;: &quot;R-12345&quot;,<br>      &quot;amount&quot;: 1250<br>    },<br>    &quot;approval-step&quot;: {<br>      &quot;payload&quot;: {<br>        &quot;requestId&quot;: &quot;R-12345&quot;,<br>        &quot;amount&quot;: 1250<br>      },<br>      &quot;startedAt&quot;: 1754028983001,<br>      &quot;status&quot;: &quot;success&quot;,<br>      &quot;suspendPayload&quot;: {<br>        &quot;requestId&quot;: &quot;R-12345&quot;,<br>        &quot;pendingSince&quot;: &quot;2025-08-01T06:16:23.001Z&quot;<br>      },<br>      &quot;suspendedAt&quot;: 1754028983001,<br>      &quot;resumePayload&quot;: {<br>        &quot;approved&quot;: true,<br>        &quot;approverName&quot;: &quot;John Doe&quot;<br>      },<br>      &quot;resumedAt&quot;: 1754028986013,<br>      &quot;output&quot;: {<br>        &quot;approved&quot;: true,<br>        &quot;approverName&quot;: &quot;John Doe&quot;<br>      },<br>      &quot;endedAt&quot;: 1754028986014<br>    }<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97f99bd443a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rain or Shine, We’ve Got You Covered! Introducing Mastra’s Smart Activity Workflow Agent! ☀️☔]]></title>
            <link>https://juniarto-samsudin.medium.com/rain-or-shine-weve-got-you-covered-introducing-mastra-s-smart-activity-workflow-agent-%EF%B8%8F-40767909fd5c?source=rss-99a5a2e5cc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/40767909fd5c</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[mastra-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-agent-workflow]]></category>
            <dc:creator><![CDATA[Juniarto Samsudin]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 00:17:06 GMT</pubDate>
            <atom:updated>2025-08-05T07:30:55.982Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rain or Shine, We’ve Got You Covered! Introducing Mastra’s Smart Activity Workflow Agent! [Part-1]☀️☔</h3><p><em>“I used to build suits of armor. Now I build workflows — autonomous agents that think faster than any human. It’s not magic. It’s just advanced orchestration.” — Tony Stark, Iron Man</em></p><p>Part 1: This Article<br>Part 2: <a href="https://juniarto-samsudin.medium.com/rain-or-shine-weve-got-you-covered-introducing-mastra-s-smart-activity-workflow-agent-part-2-41b8aaa4ad37">Introducing Mastra’s Smart Activity Workflow Agent in Next.JS </a><br>Part 3: <a href="https://juniarto-samsudin.medium.com/mastra-agent-workflow-human-in-the-loop-suspend-and-resume-97f99bd443a6">Mastra Agent Workflow: Human In The Loop, Suspend and Resume</a></p><p>Let’s dive into the idea of Agent Workflow! If you’re completely new to this, don’t sweat it — this article is designed to guide you through everything you need to know and get you comfortable with the topic.</p><p><strong><em>A user tells us a city. Our app then checks the weather forecast for that city. Based on the forecast, we’ll suggest activities. If there’s more than a 50% chance of rain, we’ll recommend indoor activities. Otherwise, outdoor or general activities are fair game!</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*5ofLd1Xj3wdJqdZnOYqBug.png" /></figure><p>This instruction is about developing Mastra locally. For information on setting up your local development environment, please visit<a href="https://mastra.ai/en/docs/server-db/local-dev-playground"> https://mastra.ai/en/docs/server-db/local-dev-playground</a>.</p><p><strong>Workflow — Step 1 [get weather forecast]</strong></p><p><strong>[workflow/</strong><a href="http://conditional-workflow.ts/"><strong>conditional-workflow.ts</strong></a><strong>]</strong></p><pre>import { z } from &quot;zod&quot;;<br>import { createWorkflow, createStep } from &quot;@mastra/core/workflows&quot;;<br> <br>// Helper function to convert weather codes to human-readable conditions<br>function getWeatherCondition(code: number): string {<br>  const conditions: Record&lt;number, string&gt; = {<br>    0: &quot;Clear sky&quot;,<br>    1: &quot;Mainly clear&quot;,<br>    2: &quot;Partly cloudy&quot;,<br>    3: &quot;Overcast&quot;,<br>    45: &quot;Foggy&quot;,<br>    48: &quot;Depositing rime fog&quot;,<br>    51: &quot;Light drizzle&quot;,<br>    53: &quot;Moderate drizzle&quot;,<br>    55: &quot;Dense drizzle&quot;,<br>    61: &quot;Slight rain&quot;,<br>    63: &quot;Moderate rain&quot;,<br>    65: &quot;Heavy rain&quot;,<br>    71: &quot;Slight snow fall&quot;,<br>    73: &quot;Moderate snow fall&quot;,<br>    75: &quot;Heavy snow fall&quot;,<br>    95: &quot;Thunderstorm&quot;,<br>  };<br>  return conditions[code] || &quot;Unknown&quot;;<br>}<br> <br>const forecastSchema = z.object({<br>  date: z.string(),<br>  maxTemp: z.number(),<br>  minTemp: z.number(),<br>  precipitationChance: z.number(),<br>  condition: z.string(),<br>  location: z.string(),<br>});<br><br>const fetchWeather = createStep({<br>  id: &quot;fetch-weather&quot;,<br>  description: &quot;Fetches weather forecast for a given city&quot;,<br>  inputSchema: z.object({<br>    city: z.string(),<br>  }),<br>  outputSchema: forecastSchema,<br>  execute: async ({ inputData }) =&gt; {<br>    if (!inputData) {<br>      throw new Error(&quot;Trigger data not found&quot;);<br>    }<br> <br>    const geocodingUrl = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(inputData.city)}&amp;count=1`;<br>    const geocodingResponse = await fetch(geocodingUrl);<br>    const geocodingData = (await geocodingResponse.json()) as {<br>      results: { latitude: number; longitude: number; name: string }[];<br>    };<br> <br>    if (!geocodingData.results?.[0]) {<br>      throw new Error(`Location &#39;${inputData.city}&#39; not found`);<br>    }<br> <br>    const { latitude, longitude, name } = geocodingData.results[0];<br> <br>    const weatherUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&amp;longitude=${longitude}&amp;current=precipitation,weathercode&amp;timezone=auto,&amp;hourly=precipitation_probability,temperature_2m`;<br>    const response = await fetch(weatherUrl);<br>    const data = (await response.json()) as {<br>      current: {<br>        time: string;<br>        precipitation: number;<br>        weathercode: number;<br>      };<br>      hourly: {<br>        precipitation_probability: number[];<br>        temperature_2m: number[];<br>      };<br>    };<br><br>    const forecast = {<br>      date: new Date().toISOString(),<br>      maxTemp: Math.max(...data.hourly.temperature_2m),<br>      minTemp: Math.min(...data.hourly.temperature_2m),<br>      condition: getWeatherCondition(data.current.weathercode),<br>      location: name,<br>      precipitationChance: data.hourly.precipitation_probability.reduce(<br>        (acc, curr) =&gt; Math.max(acc, curr),<br>        0,<br>      ),<br>    };<br> <br>    return forecast;<br>  },<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*lElwisyZ9FwwlO2IhbWTnw.png" /></figure><p>Step 1 might seem a bit long and complicated, but it’s really just what you see in the picture. You give me a city, like Singapore, and I’ll give you a weather forecastSchema. That forecastSchema will include the date, highest and lowest temperatures, chance of rain, weather conditions, and the location itself.</p><p>We haven’t set up the Agent or LLM yet for Step 1. It’s not needed. No intelligence is required.</p><p>Okay, so for Step 2, you have two choices: if there’s more than a 50% chance of rain, you’ll go with “plantIndoorActivities.” But if the chance of rain is less than 50%, then you’ll opt for “planActivities.” Now, before we dive into Step 2, it’s important to note that both of these options involve an “Agent.” This Agent’s job is to come up with different activities. So, let’s get that Agent sorted out first!</p><p><strong>[agents/</strong><a href="http://planning-agent.ts/"><strong>planning-agent.ts</strong></a><strong>]</strong></p><pre>import { Agent } from &quot;@mastra/core/agent&quot;;<br>import { openai } from &quot;@ai-sdk/openai&quot;;<br> <br>const llm = openai(&quot;gpt-4o&quot;);<br> <br>// Define the planning agent that generates activity recommendations<br>// based on weather conditions and location<br>const planningAgent = new Agent({<br>  name: &quot;planningAgent&quot;,<br>  model: llm,<br>  instructions: `<br>        You are a local activities and travel expert who excels at<br>        weather-based planning. Analyze the weather data and provide practical activity recommendations.<br> <br>        📅 [Day, Month Date, Year]<br>        ═══════════════════════════<br> <br>        🌡️ WEATHER SUMMARY<br>        • Conditions: [brief description]<br>        • Temperature: [X°C/Y°F to A°C/B°F]<br>        • Precipitation: [X% chance]<br> <br>        🌅 MORNING ACTIVITIES<br>        Outdoor:<br>        • [Activity Name] - [Brief description including specific location/route]<br>          Best timing: [specific time range]<br>          Note: [relevant weather consideration]<br> <br>        🌞 AFTERNOON ACTIVITIES<br>        Outdoor:<br>        • [Activity Name] - [Brief description including specific location/route]<br>          Best timing: [specific time range]<br>          Note: [relevant weather consideration]<br> <br>        🏠 INDOOR ALTERNATIVES<br>        • [Activity Name] - [Brief description including specific venue]<br>          Ideal for: [weather condition that would trigger this alternative]<br> <br>        ⚠️ SPECIAL CONSIDERATIONS<br>        • [Any relevant weather warnings, UV index, wind conditions, etc.]<br> <br>        Guidelines:<br>        - Suggest 2-3 time-specific outdoor activities per day<br>        - Include 1-2 indoor backup options<br>        - For precipitation &gt;50%, lead with indoor activities<br>        - All activities must be specific to the location<br>        - Include specific venues, trails, or locations<br>        - Consider activity intensity based on temperature<br>        - Keep descriptions concise but informative<br> <br>        Maintain this exact formatting for consistency, using the emoji and  <br>        section headers as shown.`,<br> });<br> <br>export { planningAgent };</pre><p>Okay, the agent has finished its work. Now, we’re ready to move on to the next part, step 2, which is planning out all the activities when the weather is good or bad.</p><p>We will continue to work on [workflow/<a href="http://conditional-workflow.ts/">conditional-workflow.ts</a>]</p><pre>const planActivities = createStep({<br>  id: &quot;plan-activities&quot;,<br>  description: &quot;Suggests activities based on weather conditions&quot;,<br>  inputSchema: forecastSchema,<br>  outputSchema: z.object({<br>    activities: z.string(),<br>  }),<br>  execute: async ({ inputData, mastra }) =&gt; {<br>    const forecast = inputData;<br> <br>    if (!forecast) {<br>      throw new Error(&quot;Forecast data not found&quot;);<br>    }<br> <br>    const prompt = `Based on the following weather forecast for ${forecast.location}, suggest appropriate activities:<br>      ${JSON.stringify(forecast, null, 2)}<br>      `;<br> <br>    const agent = mastra?.getAgent(&quot;planningAgent&quot;);<br>    if (!agent) {<br>      throw new Error(&quot;Planning agent not found&quot;);<br>    }<br> <br>    const response = await agent.stream([<br>      {<br>        role: &quot;user&quot;,<br>        content: prompt,<br>      },<br>    ]);<br><br>  let activitiesText = &quot;&quot;;<br> <br>    for await (const chunk of response.textStream) {<br>      process.stdout.write(chunk);<br>      activitiesText += chunk;<br>    }<br> <br>    return {<br>      activities: activitiesText,<br>    };<br>  },<br>});<br><br>const planIndoorActivities = createStep({<br>  id: &quot;plan-indoor-activities&quot;,<br>  description: &quot;Suggests indoor activities based on weather conditions&quot;,<br>  inputSchema: forecastSchema,<br>  outputSchema: z.object({<br>    activities: z.string(),<br>  }),<br>  execute: async ({ inputData, mastra }) =&gt; {<br>    const forecast = inputData;<br> <br>    if (!forecast) {<br>      throw new Error(&quot;Forecast data not found&quot;);<br>    }<br> <br>    const prompt = `In case it rains, plan indoor activities for ${forecast.location} on ${forecast.date}`;<br> <br>    const agent = mastra?.getAgent(&quot;planningAgent&quot;);<br>    if (!agent) {<br>      throw new Error(&quot;Planning agent not found&quot;);<br>    }<br> <br>    const response = await agent.stream([<br>      {<br>        role: &quot;user&quot;,<br>        content: prompt,<br>      },<br>    ]);<br><br>let activitiesText = &quot;&quot;;<br> <br>    for await (const chunk of response.textStream) {<br>      process.stdout.write(chunk);<br>      activitiesText += chunk;<br>    }<br> <br>    return {<br>      activities: activitiesText,<br>    };<br>  },<br>});<br><br>const activityPlanningWorkflow = createWorkflow({<br>  id: &quot;activity-planning-workflow-step2-if-else&quot;,<br>  inputSchema: z.object({<br>    city: z.string().describe(&quot;The city to get the weather for&quot;),<br>  }),<br>  outputSchema: z.object({<br>    activities: z.string(),<br>  }),<br>})<br>  .then(fetchWeather)<br>  .branch([<br>    // Branch for high precipitation (indoor activities)<br>    [<br>      async ({ inputData }) =&gt; {<br>        return inputData?.precipitationChance &gt; 50;<br>      },<br>      planIndoorActivities,<br>    ],<br>    // Branch for low precipitation (outdoor activities)<br>    [<br>      async ({ inputData }) =&gt; {<br>        return inputData?.precipitationChance &lt;= 50;<br>      },<br>      planActivities,<br>    ],<br>  ]);<br> <br>activityPlanningWorkflow.commit();<br> <br>export { activityPlanningWorkflow };</pre><p>Great! We’ve finished building our workflow, so now it’s time to update our `index.ts` file with all the new changes we’ve made to the workflow and the agent.</p><pre>import { Mastra } from &#39;@mastra/core/mastra&#39;;<br>import { PinoLogger } from &#39;@mastra/loggers&#39;;<br>import { LibSQLStore } from &#39;@mastra/libsql&#39;;<br>import { planningAgent } from &#39;./agents/planning-agent&#39;;<br>import { activityPlanningWorkflow } from &#39;./workflows/conditional-workflow&#39;;<br><br><br>export const mastra = new Mastra({<br>  workflows: { activityPlanningWorkflow},<br>  agents: { planningAgent },<br>  storage: new LibSQLStore({<br>    url: &quot;:memory:&quot;,<br>  }),<br>  logger: new PinoLogger({<br>    name: &#39;Mastra&#39;,<br>    level: &#39;info&#39;,<br>  }),<br>  server: {<br>    port: 4111, // Default port for the Mastra server<br>    timeout:10000<br>  }<br>});</pre><p>You can check out our workflow by visiting `http://localhost:4111`. Once you’re there, you can run the workflow and then take a look at the results.</p><p>The images below will give you a clear picture of the workflow itself, how it runs, and what the final outcome looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/0*OE58N8x8BN6aJrDK" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/0*weBUKGxRgwToQwL2" /></figure><p>📅 Thursday, July 24, 2025</p><p>═══════════════════════════</p><p>🌡️ WEATHER SUMMARY</p><p>• Conditions: Overcast with potential rain</p><p>• Temperature: 28°C/82°F to 32°C/90°F</p><p>• Precipitation: 60% chance</p><p>🏠 INDOOR ALTERNATIVES</p><p>• ArtScience Museum — Explore interactive exhibits and stunning art installations at Marina Bay Sands. Ideal for: Rainy weather with high precipitation.</p><p>• National Gallery Singapore — Discover Southeast Asian art in a beautifully restored historic building. Ideal for: Overcast and rainy conditions.</p><p>• Gardens by the Bay Conservatories — Visit the Flower Dome and Cloud Forest for a climate-controlled botanical experience. Ideal for: Rainy and humid weather.</p><p>⚠️ SPECIAL CONSIDERATIONS</p><p>• Be prepared for sudden rain showers; carry an umbrella.</p><p>• Check for any weather advisories or updates before heading out.</p><p>• Consider indoor venues with air conditioning due to high humidity and warm temperatures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40767909fd5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agent and MPC Server — Stand-Alone Mastra Server — [Part 5]]]></title>
            <link>https://juniarto-samsudin.medium.com/agent-and-mpc-server-stand-alone-mastra-server-part-5-de3571a032a8?source=rss-99a5a2e5cc91------2</link>
            <guid isPermaLink="false">https://medium.com/p/de3571a032a8</guid>
            <category><![CDATA[vercel-ai-sdk]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mastra-ai]]></category>
            <dc:creator><![CDATA[Juniarto Samsudin]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 10:00:53 GMT</pubDate>
            <atom:updated>2025-07-13T10:00:53.137Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Agent and MPC Server — Stand-Alone Mastra Server — [Part 5]</strong></h3><p><strong><em>“With great power comes great responsibility.” — Spider-Man. Just like our agent, now with its own server, it’s got a whole new level of responsibility!</em></strong></p><p>Hold on a sec, Part 5, you say? You might be thinking, “Didn’t we just do this?” And you’d be right! This part is basically a clone of <a href="https://medium.com/@juniarto-samsudin/agent-and-mpc-server-part-4-7e9af94096c5">Part 4</a>, but with a twist — a different way of getting things set up. Instead of our agent buddy chilling in the Next.js application server, this time they’ve got their own pad in the Mastra Server. Talk about moving up in the world, eh? Pretty neat, if I do say so myself!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KpVudT2tfJVvHBxBAQwglw.png" /></figure><p>The pool is ready. Let’s jump in!</p><ol><li>Setup Mastra Stand-Alone Server</li></ol><pre>npm create mastra@latest</pre><p>Add Open API Key in .env</p><pre>OPENAI_API_KEY=&lt;your-api-key&gt;</pre><p>2. Now we’ll see the exact similar directory structure as we have seen before in Part 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/0*ZCU741Kb1veN7oRm" /></figure><p><strong>[agents] : This is where our agents live.</strong></p><p><strong>[mcps]: This is where our MCP clients live.</strong></p><p><strong>[</strong><a href="http://index.ts/"><strong>index.ts</strong></a><strong>]: This is where we define our agents and mcp clients</strong></p><p>Simply copy all agent-related files created in Part 4 to their respective directories.</p><ol><li><strong>MCP Client: [mpcs/</strong><a href="http://jphmcpclient.ts/"><strong>jphmcpclient.ts</strong></a><strong>]</strong></li><li><strong>Agent:[agents/</strong><a href="http://jph-agent.ts/"><strong>jph-agent.ts</strong></a><strong>]</strong></li><li><strong>[</strong><a href="http://index.ts/"><strong>index.ts</strong></a><strong>]</strong></li></ol><p>3. Build and Deploy</p><p>Build</p><pre>mastra build</pre><p>Deploy</p><pre>node --import=./.mastra/output/instrumentation.mjs .mastra/output/index.mjs</pre><p>Fantastic! Our server is now up and running on port 4111.</p><p><strong>User Interface and API:</strong></p><p>Following the directory structure from<a href="https://medium.com/@juniarto-samsudin/agent-and-mpc-server-part-4-7e9af94096c5"> Part 4</a>, make sure all the necessary folders are set up and the right files are moved into them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*N57uMZjUxrWy3pZsuxd7zA.png" /></figure><p>You only need to make a small change to `<a href="http://route.ts/">route.ts</a>`.</p><p><strong>[src/app/api/chatinternal/</strong><a href="http://route.ts/"><strong>route.ts</strong></a><strong>]</strong></p><pre>import { openai } from &#39;@ai-sdk/openai&#39;;<br>import { streamText} from &#39;ai&#39;;<br>import { z } from &#39;zod&#39;;<br>import { createOllama, ollama } from &#39;ollama-ai-provider&#39;;<br>import { mastra } from &quot;@/mastra&quot;;<br>import { MastraClient } from &#39;@mastra/client-js&#39;;<br><br><br>// Allow streaming responses up to 30 seconds<br>export const maxDuration = 30;<br><br><br>// Initialize the client<br>const client = new MastraClient({<br>  baseUrl: &#39;http://localhost:4111&#39;, //  Our Mastra Stand Alone Server Address and PORT<br>});<br><br><br><br>// Using Agent<br>export async function POST(req: Request) {<br>  try {<br>      const { messages } = await req.json();<br>      console.log(&#39;Received messages:&#39;, messages);<br><br>      const myAgent = client.getAgent(&quot;jphAgent&quot;); // Use the MastraClient to get the agent<br>      const response = await myAgent.stream({<br>        messages: messages,<br>      });<br><br>    return response<br>      <br>  } catch (error) {<br>      console.error(&#39;Error during agent streaming:&#39;, error);<br>      return new Response(&#39;Error during agent streaming&#39;, { status: 500 });<br>  }<br>}</pre><p>Whew, we made it! You can check out the awesome results in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yQBJt1GbJM5M5qMo" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de3571a032a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>