Routines and headless
Once you trust Claude to do a task, the next move is to stop doing it by hand. If it's the same prompt on a recurring trigger, you shouldn't have to sit there and kick it off yourself every time. This lesson covers two ways to hand that work off: routines, where you build nothing, and headless mode, where you get full control from your own scripts.
Think of it as a spectrum. On one end you have routines that run on Anthropic's managed infrastructure. On the other end you have headless mode and the Agent SDK, which run Claude Code from your own code. Let's start with the end where you build the least.
한국어 대본
- 00:00Claude에게 작업을 맡길 수 있다고 확신이 들면, 다음 단계는 직접 하던 일을 멈추는 것입니다.
- 00:07가장 간단한 방법에는 스크립트나 서버가 필요하지 않습니다. 바로 루틴입니다.
- 00:10루틴은 저장된 프롬프트와 리포지터리, Connectors를 묶어 Anthropic이 관리하는
- 00:17인프라에서 트리거될 때마다 실행됩니다. 대신 완전한 제어가 필요하다면,
- 00:21헤드리스 모드와 Agent SDK를 사용해 자체 스크립트와 애플리케이션에서 Claude Code를 실행할 수 있습니다.
- 00:25직접 구축할 필요가 없는 경로부터 시작해 보겠습니다. 루틴은 프롬프트와 작업 대상 리포지터리를 묶고
- 00:32필요한 Connectors까지 묶은 다음 클라우드에서 트리거에 따라 실행합니다. 트리거는 cron 예약,
- 00:37API 엔드포인트로 보내는 HTTP POST, 또는 새로운 pull request 같은 GitHub 이벤트가 될 수 있습니다. 이 인프라는
- 00:43Anthropic이 제공하므로 밤새 켜 둘 장비도 없고, 유지 관리할 워크플로 파일도 없습니다.
- 00:47웹에서 `claude.ai/code/routines`로 만들거나 Claude Code 안에서
- 00:53`/schedule daily dependency audit at 9 a.m.`를 실행할 수 있습니다. 아침 종속성 감사나
- 00:59새 pull request가 도착할 때 실행되는 PR 분류에 사용할 수 있으며, 같은 프롬프트를 반복 트리거에서 사용하는 작업이라면
- 01:04적합합니다. 다만 의존하기 전에 알아둘 점이 세 가지 있습니다. 루틴은
- 01:07리서치 프리뷰이므로 동작과 제한이 계속 바뀔 수 있습니다. 반복 일정은 최대
- 01:12매시간 실행되며, 매 실행은 기본 브랜치의 새 clone에서 시작하고 `claude/` 접두사가 붙은 브랜치에만 push할 수 있습니다.
- 01:17저장소별 제한을 완화하지 않는 한, 이는 자율 실행이 main을 다시 쓰지 못하게 하는 안전장치입니다.
- 01:21작업에 사용자 환경이나 실행을 둘러싼 로직이 필요하다면,
- 01:28헤드리스 모드로 전환하세요. `-p` 플래그(별칭 `--print`)는 Claude Code를 대화형
- 01:33UI 없이 일회성 명령으로 실행합니다. 표준 입력을 읽고 표준 출력으로 쓰므로 다른 셸
- 01:39도구처럼 파이프할 수 있습니다. `--bare`는 hooks, Skills, Plugins, MCP 서버 및 CLAUDE.md 파일의 자동 검색을 건너뜁니다. 그러면
- 01:46명시적으로 허용한 도구만 추가된 Claude를 얻게 되고, 로컬 환경에서 우연히 로드되는 것은 아무것도 포함되지 않습니다.
- 01:51이 방식은 시작이 훨씬 빠릅니다. 이제 JSON 스키마를 `--output-format json`과 함께 지정하면
- 01:58Claude Code가 구조화된 출력을 스키마에 맞추도록 제한할 수 있습니다. 스키마에 맞는 객체는
- 02:03JSON 응답의 `structured_output` 필드에 들어오므로 `jq` 명령으로 꺼내 파이프할 수 있습니다.
- 02:08데이터베이스나 다른 스크립트에 연결해 여러 단계의 자동화에 활용하세요. JSON
- 02:15출력에서 `session_id`를 가져와 한 스크립트가 작업을 시작하고 다른 스크립트가 나중에 전체 컨텍스트와 함께 재개하도록 할 수 있습니다.
- 02:19Agent SDK는 자체 TypeScript 또는
- 02:26Python 애플리케이션에 Claude Code를 삽입할 수 있는 라이브러리를 제공합니다. 두 방식 모두 query 함수를
- 02:32노출하고 CLI와 동일한 기본 기능을 제공합니다. 프롬프트와 함께 allow tools, 시스템 프롬프트, permission mode 같은 옵션을 전달한 다음
- 02:38Claude가 스트리밍하는 메시지를 순회합니다. 루틴은 반복 작업의 기본 방식입니다. 실행은
- 02:45Anthropic의 인프라에서 이루어지므로 직접 호스팅할 것이 없습니다.
- 02:50작업에 자체 파이프라인이 필요할 때는 헤드리스 모드로 전환하세요.
- 02:52`-p`로 스크립트를 통해 데이터를 파이프하세요.
- 02:56CI에서 매번 동일한 결과가 필요할 때는 `--bare`를 사용하세요.
- 02:59작업이 자체 제품 안에 들어가야 할 때는 Agent SDK를 사용하세요.
Routines: a saved prompt that runs in the cloud
A routine is the most direct way to automate a task. There's no script and no server. It bundles three things: a prompt, the repository it works on, and any connectors it needs. Then it runs that bundle in the cloud whenever it's triggered.
The key part is that the infrastructure is Anthropic's. There's no machine of yours staying on overnight, and there's no workflow file for you to maintain. You describe the job once and it just runs.
A routine can fire on a few kinds of triggers:
- A cron schedule, like every morning at 9am.
- An HTTP POST to its API endpoint, so your own code can kick it off.
- A GitHub event, like a new pull request landing.
Anything that's the same prompt on a recurring trigger is a good fit. A morning dependency audit. A PR triager that fires when a new pull request comes in. A daily scan of your Sentry tickets to figure out what's most urgent.
Here's the mental model for what a routine ties together: a prompt, the repo, connectors, and a schedule.
Two ways to create one
You can create a routine from the web at claude.ai/code/routines. You give it a name, write the instructions describing what Claude should do in each session, pick a repository, and choose a trigger.
You can also create one from inside Claude Code without leaving your terminal. Just run the /schedule command and describe what you want in plain language, for example:
/schedule daily dependency audit at 9amSame idea, either entry point. Pick whichever fits your flow.
Three things to know before you rely on routines
Before you lean on routines for anything important, keep these three limits in mind.
- Routines are a research preview. Behavior and limits will keep moving, so don't be surprised if things change.
- A recurring schedule runs at most hourly. If you need something more frequent, routines aren't the tool.
- Each run starts from a fresh clone of your default branch and can only push to
claude/prefixed branches unless you loosen that per repo. This is the guardrail that keeps an autonomous run from rewriting main.
Headless mode: when you need your own environment
Routines are great when the work fits in the cloud. But sometimes the job needs your environment, or logic wrapped around the run. That's when you drop to headless mode.
The core of headless mode is the -p flag (short for --print). It runs Claude Code as a one-shot command with no interactive UI. It reads standard in and writes standard out, so it pipes like any other shell tool:
claude -p "summarize the changes in this diff"One thing worth knowing: -p skips auto-discovery of hooks, skills, plugins, MCP servers, and the CLAUDE.md file. You get Claude plus the tools you allow explicitly, and nothing the local environment happens to load. The upside is that startup is much faster this way.
Getting structured output back
Because headless mode pipes like any shell tool, you'll often want structured data back instead of prose. You can pair a JSON schema with the JSON output format, and Claude will constrain its output to match your schema.
The object that matches your schema lands in the structured_output field of the JSON response. So you can pull it out with a jq command and pipe it into a database or another script:
That gives you a clean array you can hand to whatever comes next.
Multi-step automation with sessions
For work that happens across multiple steps, you don't have to cram everything into one command. Capture the session's ID from the JSON output and resume it later:
claude --resume "$(jq -r .session_id /tmp/plan.json)"One script kicks off the work. Another resumes it later with full context. This is handy when the first pass produces a plan and a second pass carries it out.
Deterministic runs for CI
When CI needs the same results every single run, there's a mode built for that.
The --bare flag gives you deterministic mode. It's the right choice when you're running Claude Code inside a pipeline and you want repeatable, predictable output rather than anything that varies run to run.
The Agent SDK: Claude Code inside your own app
The last step on the spectrum is the Agent SDK. This gets you a library that embeds Claude Code inside your own TypeScript or Python applications.
Both languages expose a query function and the same primitives as the CLI. You pass a prompt plus options, like:
allowedToolsto control what Claude can do,- a system prompt,
- and a permission mode.
Then you iterate over the messages Claude streams back and handle them however your app needs. It's the same engine as the CLI, just callable from inside your product.
Which one should you reach for?
Here's the quick decision guide:
- Routines are the default for repeat work. They run on Anthropic's infrastructure with nothing for you to host.
- Headless mode with
-pis for when the job needs your pipeline and you want to pipe data through a script. --bareis for when CI needs the same results every single run.- The Agent SDK is for when the work belongs inside your own product.
Start with routines. Drop down the spectrum only when the job actually needs the extra control.