Developer guide / runtime evidence
OpenClaw 런타임을 데이터 흐름으로 읽는 분석북
입력부터 Gateway와 agent attempt, system prompt, replay history, memory search, provider payload와 관측 로그까지 하나의 실행 흐름으로 연결해 읽습니다.
- 01 표면 Gateway / Channel
- 02 실행 Attempt / Prompt / Tools
- 03 기억 Replay / Memory / Trace
System map
전체 큰 지도
입력 표면에서 실행과 저장 계층으로 이동하는 기본 축이다.
One request / one attempt
한 번의 요청이 실행되는 교차로
attempt.ts는 prompt, history, tools, provider와 관측 기록이 합류하는 중심점이다.
-
01 / INGRESS
질문 도착
chat.send / channel본문, origin, route가 만들어진다. -
02 / SESSION
대화 단위 해석
SessionKey + JSONL이전 transcript와 상태를 찾는다. -
03 / ATTEMPT
실행 컨텍스트 합류
run/attempt.tsprompt, replay, tools, budget을 확정한다. -
04 / PROVIDER
모델 호출
instructions + tools최종 payload로 stream을 연다. -
05 / EVIDENCE
기록과 반환
trajectory / transcript답변, usage, context 증거를 남긴다.
system-prompt.ts행동 계약replay-history.ts보이는 과거tool-construction-plan.ts호출 가능 도구preemptive-compaction.tscontext budgetALL PATHS MEET HERE
attempt.ts assemble -> preflight -> submitopenai-transport-stream.tstrajectory / cache-traceProvider-visible context
저장된 대화가 모델 입력이 되는 과정
전체 transcript가 곧바로 모델에게 전달되지는 않는다.
-
01
Session load
<sessionId>.jsonl의 기록을 읽는다. - 02 System prompt tools, skills, memory, workspace 계약을 조립한다.
- 03 Sanitize thinking, images, tool call/result 형태를 정돈한다.
- 04 Validate + Limit provider 규칙과 최근 user turn 범위를 적용한다.
- 05 Context engine history와 추가 context를 최종 합성한다.
- 06 Budget gate overflow면 truncate 또는 compaction을 수행한다.
-
07
Provider payload
instructions/messages/tools로 전송한다.
어디서 무엇을 확인하는가
- 저장 원문
~/.openclaw/agents/<agentId>/sessions/<sessionId>.jsonl- 조립 직후
<sessionId>.trajectory.jsonl의context.compiled- 전송 직전
cache-trace.jsonl의stream:context- 핵심 코드
attempt.ts->replay-history.ts->openai-transport-stream.ts
정보가 보이지 않을 때의 검증 순서
- Transcript사용자 메시지나 tool result가 저장됐는지 확인
- Replaysanitize, validate, turn limit에서 제외됐는지 확인
- Contextcompaction summary 또는 memory section으로 대체됐는지 확인
- Transportprovider payload에 prompt와 tool schema가 들어갔는지 확인
openclaw sessions --json --all-agents
openclaw logs --follow --json
openclaw memory status --deep
openclaw memory search "질문 키워드" --json
Context Engine contract
모델이 참고할 문맥을 선택하고 덧붙이는 층
History가 정리된 뒤에도 engine은 messages와 system prompt addition을 다시 조립할 수 있다.
sanitize + limit 이후
channel / prompt cache / usage
memory / summary / workspace
PLUGGABLE CONTRACT
contextEngine.assemble()src/context-engine/types.ts
- fallback
- legacy engine
- hook point
- attempt.ts:3033
- registry
- plugin slot resolution
legacy.ts는 기존 sanitize/validate/limit 파이프라인을 통과시키는 안전한 기본값이다.
registry.ts가 등록된 engine을 해석하고 실패 시 기본 engine으로 돌아간다.
“prompt에 있었다”가 아니라 assemble 이후 context.compiled를 확인한다.
Why the model still cannot act
Skill 본문을 읽었다고 실행 가능한 것은 아니다
모델의 지식과 provider에 전달된 호출 가능 도구는 서로 다른 조건이다.
Prompt layer
Skill instructionSkills section / SKILL.md body
무엇을 해야 하는지 모델이 이해한다.
Tool layer
Callable schemaeffectiveTools / toolsAllow
실제로 호출할 수 있는 수단이 남아 있다.
Outcome
수행 가능 두 조건이 모두 provider payload에 존재할 때만 성립system prompt
but
파일 읽기 도구 없음
참조된 문서나 로컬 리소스를 더 읽을 수 없다.
skillsPrompt
but
plugin tool 필터됨
toolsAllow 이후 schema가 없다면 호출도 없다.
providerVisibleTools
see
trajectory context.compiled
prompt 문구 대신 실제 tools 목록을 비교한다.
Final wire shape
모델에게 실제로 전송되는 봉투
내부에서 존재하는 정보와 provider API에 실려 간 정보는 같다고 가정하면 안 된다.
skills / memory / safety
replay + current turn
providerVisibleTools
openai-transport-stream.ts
- instructions
- system prompt text
- input[]
- sanitized visible messages
- tools[]
- callable JSON schema only
- stream
- response + tool calls + usage
instructions / system role
input[] / messages[]
tools[] schema
stream:context
Tool schema / provider adapters
도구 schema가 provider payload가 되는 실제 흐름
OpenClaw 내부 tool 계약은 공통이지만, OpenAI와 Claude로 나갈 때 wire shape가 달라진다.
AnyAgentTool
- name
- 모델이 호출할 tool 이름
- description
- 모델이 선택할 때 읽는 설명
- parameters
- OpenClaw 내부 JSON schema
- execute
- runtime에서 실제 작업 수행
src/agents/tools/common.ts
-
01
Schema source
bash-tools.schemas.ts, memory tools, plugin descriptor가 입력 계약을 만든다. -
02
Tool assembly
createOpenClawCodingTools,createOpenClawTools, plugin tools가 후보를 모은다. -
03
Policy filter
toolsAllow, sandbox, embedded mode가 이번 턴의 tool surface를 줄인다. -
04
Normalize
normalizeToolParameters가 provider에 안전한 JSON schema 모양으로 정리한다. -
05
effectiveTools
attempt.ts가 provider-visible tool 목록을 확정하고 trajectory에 남긴다.
parameters
OpenAI function/tool calling API 계약에 맞춰 schema를 parameters로 유지한다.
openai-transport-stream.ts
input_schema
Anthropic Messages API의 tool 정의 계약에 맞춰 같은 schema를 input_schema로 바꾼다.
anthropic-transport-stream.ts
원본 tool 파일에서 parameters와 execute가 같은 tool 객체에 있는지 본다.
attempt.ts의 effectiveTools와 providerVisibleTools 기록을 확인한다.
OpenAI는 parameters, Claude는 input_schema로 전송되는지 transport adapter를 본다.
tool.execute() 결과가 transcript에 들어가 다음 provider input으로 되돌아오는지 본다.
OpenAI로 나갈 때
{
"type": "function",
"name": "memory_search",
"description": "...",
"parameters": {
"type": "object",
"properties": { "query": { "type": "string" } }
}
}
Claude로 나갈 때
{
"name": "memory_search",
"description": "...",
"input_schema": {
"type": "object",
"properties": { "query": { "type": "string" } }
}
}
Memory architecture
기억은 컨텍스트, 원본, 검색 인덱스로 나뉜다
Markdown은 원본이고 index는 검색을 빠르게 만드는 파생 계층이다.
현재 Context
이번 요청에 실제로 포함된 system prompt와 replay history다. budget, limit, compaction의 영향을 받는다.
attempt.ts / replay-history.ts
Markdown Memory
사람이 읽고 수정할 수 있는 장기 기억 원본이다. 백업과 diff가 쉽고 검색 전에도 의미가 남는다.
MEMORY.md / memory/*.md
Search Manager
memory_search가 vector, FTS, qmd/builtin backend와 visibility 정책을 거쳐 관련 chunk를 찾는다.
extensions/memory-core/src/memory/
Recall retrieval path
memory_search는 어떻게 기억을 꺼내는가
Markdown 원본을 무작정 prompt에 넣지 않고 필요한 chunk를 검색해 현재 턴으로 되돌린다.
- query
- "skill 수행 실패"
- corpus
- memory / sessions / all
- limit
- maxResults + minScore
-
tools.ts입력 계약 query와 corpus를 검증한다. -
session-search-visibility.ts가시성 정책 현재 요청에 노출 가능한 session hit만 남긴다. -
search-manager.tsBackend 선택 qmd 또는 builtin fallback을 고른다. -
manager-search.ts랭킹과 결과 vector / FTS 결과 chunk를 반환한다.
MEMORY.md
memory/*.md
transcript JSONL
sync / embed / rank
Telegram data journey
질문 1건이 답장으로 돌아오기까지
채널 payload가 agent turn과 outbound delivery로 이어진다.
초기 Telegram update
- update_id
- 중복 처리와 offset 저장의 기준
- message.chat.id
- DM, group, topic 대상 식별
- message.from.id
- allowFrom, groupPolicy, pairing 판단
- text / caption / media
- RawBody, BodyForAgent, MediaPath로 정규화
- message_thread_id
- forum topic 또는 DM topic session 분리
- 01 Telegram Bot API getUpdates 또는 webhook이 update를 전달한다.
- 02 monitorTelegramProvider 계정 token, polling/webhook 모드, offset, runner를 준비한다.
- 03 createTelegramBot grammy Bot에 dedupe, sequentialize, native command, message handler를 붙인다.
- 04 bot.on("message") message, channel_post, callback_query를 표준 inbound message로 보낸다.
- 05 buildTelegramMessageContext chatId, senderId, route, SessionKey, BodyForAgent, CommandBody를 만든다.
- 06 dispatchTelegramMessage typing, reaction, streaming draft, reply fence, delivery lane을 준비한다.
- 07 runInboundReplyTurn ctxPayload와 routeSessionKey를 agent 실행/명령 처리로 넘긴다.
- 08 Agent Runtime session transcript, prompt, model, tools, plugin provider가 실행된다.
- 09 deliverReplies ReplyPayload를 Telegram chunk, HTML, media, inline button으로 변환한다.
- 10 bot.api.sendMessage message_thread_id, reply_to, parse_mode과 함께 최종 답장을 보낸다.
Evidence first debugging
모델이 “모른다”고 할 때 추적할 네 갈래
저장 여부, context 포함 여부, tool 제공 여부, memory retrieval 여부를 분리해서 조사한다.
원문 메시지와 tool result가 transcript에 있는지 본다.
<sessionId>.jsonl
sanitize, limit, compaction 뒤의 결과를 본다.
context.compiled
설명된 skill이 아니라 전송된 schema를 확인한다.
providerVisibleTools
index 상태와 검색 결과 source를 확인한다.
memory status / search
session JSONLsession:sanitizedsession:limitedcontext.compiledstream:contextOperational evidence console
어느 파일에서 어떤 사실을 확인할까
같은 요청도 metadata, transcript, compiled context, wire 직전 trace는 서로 다른 사실을 보여준다.
요약 상태
sessions.json
systemPromptReport, 상태, usage, session file 위치를 찾는다.
저장 원문
<sessionId>.jsonl
user, assistant, tool/result 이벤트가 실제로 저장됐는지 본다.
저장됨 != 현재 모델에게 보임조립 결과
context.compiled
systemPrompt, messages, tools, providerVisibleTools를 본다.
기본 활성화,OPENCLAW_TRAJECTORY=0으로 비활성
전송 직전
stream:context
session:loaded부터 history 감소를 단계별 비교한다.
설치 후 확인 루틴
- 상태
openclaw status --jsonopenclaw gateway status --deep - 세션
openclaw sessions --json --all-agents - 최종 조립
jq 'select(.type=="context.compiled") | .data' <session>.trajectory.jsonl - 기억
openclaw memory status --deepopenclaw memory search "키워드" --json - Wire 추적
OPENCLAW_CACHE_TRACE=1 OPENCLAW_CACHE_TRACE_MESSAGES=1 openclaw gateway run
Question to evidence
증상별로 어디부터 볼지 고르는 표
원인을 추측하지 말고, 관측할 수 있는 가장 가까운 경계부터 확인한다.
system-prompt.ts
tool-construction-plan.ts
providerVisibleTools
replay-history.ts
compact.ts
session:limited
tools.ts
search-manager.ts
memory status --deep
openai-transport-stream.ts
stream:context
system-prompt.ts
preemptive-compaction.ts
systemPromptReport
cache-trace.ts
trajectory/runtime.ts
context.compiled
Hands-on lab
직접 확인하며 구조를 익히는 네 가지 실습
각 실습은 원본, 변환, 최종 증거 가운데 적어도 두 경계를 비교한다.
한 턴의 최종 prompt 추적
- 짧은 메시지를 하나 보낸다.
openclaw sessions --json --all-agentscontext.compiled.data.systemPrompt와tools를 확인한다.
목표: 조립된 prompt와 tool list의 기록 위치 이해
memory_search 경로 확인
MEMORY.md에 고유 키워드를 기록한다.openclaw memory index --forceopenclaw memory search "키워드" --json
목표: Markdown 원본과 index hit의 관계 이해
Allowlist 영향 확인
toolsAllow가 걸리는 요청을 찾는다.- tool construction plan을 읽는다.
providerVisibleTools와 prompt 안내를 비교한다.
목표: 설명된 능력과 제공된 capability 구분
History가 줄어드는 위치 찾기
- 긴 session에서 cache trace를 켠다.
loaded / sanitized / limited / stream을 비교한다.replay-history.ts와compact.ts를 함께 읽는다.
목표: 저장된 기록과 visible history의 차이 확인
Deep reading roadmap
다음에 깊게 팔 모듈의 연결 지도
핵심 모듈 8개의 주경로다. Context Engine과 실습은 이어지는 전용 섹션과 챕터에서 보강한다.
- 01
attempt.ts실행의 중심 - 02
system-prompt.ts행동 계약 - 03
replay-history.ts보이는 기억 - 04
attempt-tool-construction-plan.ts도구 표면 - 05
memory-core/tools.ts검색 호출 - 06
memory/manager.ts인덱스 내부 - 07
openai-transport-stream.ts최종 전송 - 08
trajectory / cache-trace검증 증거
Input / Transform / Output
핵심 모듈을 읽을 때 반복할 질문
각 모듈은 입력을 받아 정책을 적용하고, 다음 경계에서 확인 가능한 출력을 만든다.
attempt.ts
IN session, model, tools
DO assemble, preflight, submit
OUT compiled context, result
system-prompt.ts
IN tools, skills, context files
DO section build, cache split
OUT system prompt text
replay-history.ts
IN stored transcript
DO sanitize, validate
OUT replayable messages
tool-construction-plan.ts
IN mode, allowlist, plugins
DO filter capabilities
OUT effective tools
memory-core/tools.ts
IN query, corpus, limits
DO validate, search, filter
OUT recall chunks
memory/manager.ts
IN Markdown, sessions
DO sync, rank, fallback
OUT indexed hits
openai-transport-stream.ts
IN prompt, messages, tools
DO provider conversion
OUT wire payload / stream
trajectory / cache-trace
IN runtime boundaries
DO record selected state
OUT debuggable evidence