Developer guide / runtime evidence

OpenClaw 런타임을 데이터 흐름으로 읽는 분석북

입력부터 Gateway와 agent attempt, system prompt, replay history, memory search, provider payload와 관측 로그까지 하나의 실행 흐름으로 연결해 읽습니다.

  1. 01 표면 Gateway / Channel
  2. 02 실행 Attempt / Prompt / Tools
  3. 03 기억 Replay / Memory / Trace
0 chapters
0 file anchors
9ede882 snapshot
⚡ 실행 흐름 완전 해부

System map

전체 큰 지도

입력 표면에서 실행과 저장 계층으로 이동하는 기본 축이다.

OpenClaw 전체 시스템 지도 입력 표면에서 Gateway, plugin registry, agent runtime, persistence로 이어지고 다시 UI와 채널로 결과가 돌아가는 흐름. 입력 표면 CLI / Control UI Telegram / Discord API 표면 HTTP / WebSocket OpenAI-compatible 외부 이벤트 Webhook / Polling Scheduler / Task Gateway auth / scopes method router dedupe / abort broadcast Plugin Registry channels tools / providers gateway methods Agent Runtime Pi runner model / tools skills / prompt Config profiles secrets policies Session sessions.json transcript artifacts 요청 생성 capability lookup agent turn 결과/이벤트 반환

One request / one attempt

한 번의 요청이 실행되는 교차로

attempt.ts는 prompt, history, tools, provider와 관측 기록이 합류하는 중심점이다.

  1. 01 / INGRESS 질문 도착 chat.send / channel 본문, origin, route가 만들어진다.
  2. 02 / SESSION 대화 단위 해석 SessionKey + JSONL 이전 transcript와 상태를 찾는다.
  3. 03 / ATTEMPT 실행 컨텍스트 합류 run/attempt.ts prompt, replay, tools, budget을 확정한다.
  4. 04 / PROVIDER 모델 호출 instructions + tools 최종 payload로 stream을 연다.
  5. 05 / EVIDENCE 기록과 반환 trajectory / transcript 답변, usage, context 증거를 남긴다.
system-prompt.ts행동 계약
replay-history.ts보이는 과거
tool-construction-plan.ts호출 가능 도구
preemptive-compaction.tscontext budget

ALL PATHS MEET HERE

attempt.ts assemble -> preflight -> submit
Provider payloadopenai-transport-stream.ts
Compiled evidencetrajectory / cache-trace

Provider-visible context

저장된 대화가 모델 입력이 되는 과정

전체 transcript가 곧바로 모델에게 전달되지는 않는다.

  1. 01 Session load <sessionId>.jsonl의 기록을 읽는다.
  2. 02 System prompt tools, skills, memory, workspace 계약을 조립한다.
  3. 03 Sanitize thinking, images, tool call/result 형태를 정돈한다.
  4. 04 Validate + Limit provider 규칙과 최근 user turn 범위를 적용한다.
  5. 05 Context engine history와 추가 context를 최종 합성한다.
  6. 06 Budget gate overflow면 truncate 또는 compaction을 수행한다.
  7. 07 Provider payload instructions/messages/tools로 전송한다.
Disk transcript 전체 저장 기록 messages + tools + details
sanitize 호환 형태 reasoning / tool pair 정리
limit 최근 turn 정책 범위만 유지
overflow only summary compaction
Provider Visible history 현재 모델 입력

어디서 무엇을 확인하는가

저장 원문
~/.openclaw/agents/<agentId>/sessions/<sessionId>.jsonl
조립 직후
<sessionId>.trajectory.jsonlcontext.compiled
전송 직전
cache-trace.jsonlstream:context
핵심 코드
attempt.ts -> replay-history.ts -> openai-transport-stream.ts

정보가 보이지 않을 때의 검증 순서

  1. Transcript사용자 메시지나 tool result가 저장됐는지 확인
  2. Replaysanitize, validate, turn limit에서 제외됐는지 확인
  3. Contextcompaction summary 또는 memory section으로 대체됐는지 확인
  4. 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을 다시 조립할 수 있다.

Selected history 정리된 messages sanitize + limit 이후
Runtime context 이번 턴의 상태 channel / prompt cache / usage
Artifacts 추가 문맥 memory / summary / workspace

PLUGGABLE CONTRACT

contextEngine.assemble() src/context-engine/types.ts
fallback
legacy engine
hook point
attempt.ts:3033
registry
plugin slot resolution
Messages assembled.messages provider에 보낼 선택 문맥
Prompt mutation systemPromptAddition 동적 지시를 prompt 앞에 추가
Budget policy promptAuthority precheck가 어떤 양을 신뢰할지 결정
Legacy mode

legacy.ts는 기존 sanitize/validate/limit 파이프라인을 통과시키는 안전한 기본값이다.

Plugin mode

registry.ts가 등록된 engine을 해석하고 실패 시 기본 engine으로 돌아간다.

Debug point

“prompt에 있었다”가 아니라 assemble 이후 context.compiled를 확인한다.

Why the model still cannot act

Skill 본문을 읽었다고 실행 가능한 것은 아니다

모델의 지식과 provider에 전달된 호출 가능 도구는 서로 다른 조건이다.

Prompt layer

Skill instruction Skills section / SKILL.md body 무엇을 해야 하는지 모델이 이해한다.

Tool layer

Callable schema effectiveTools / toolsAllow 실제로 호출할 수 있는 수단이 남아 있다.

Outcome

수행 가능 두 조건이 모두 provider payload에 존재할 때만 성립
CASE 01 Skill 텍스트 있음 system prompt but 파일 읽기 도구 없음

참조된 문서나 로컬 리소스를 더 읽을 수 없다.

CASE 02 방법을 이해함 skillsPrompt but plugin tool 필터됨

toolsAllow 이후 schema가 없다면 호출도 없다.

CHECK 진실은 전송면에 있다 providerVisibleTools see trajectory context.compiled

prompt 문구 대신 실제 tools 목록을 비교한다.

Final wire shape

모델에게 실제로 전송되는 봉투

내부에서 존재하는 정보와 provider API에 실려 간 정보는 같다고 가정하면 안 된다.

Behavior System Prompt skills / memory / safety
Conversation Messages replay + current turn
Capability Tools providerVisibleTools
POST / provider stream openai-transport-stream.ts
instructions
system prompt text
input[]
sanitized visible messages
tools[]
callable JSON schema only
stream
response + tool calls + usage
Prompt present? instructions / system role
History present? input[] / messages[]
Tool present? tools[] schema
Evidence stream:context

Tool schema / provider adapters

도구 schema가 provider payload가 되는 실제 흐름

OpenClaw 내부 tool 계약은 공통이지만, OpenAI와 Claude로 나갈 때 wire shape가 달라진다.

INTERNAL CONTRACT

AnyAgentTool

name
모델이 호출할 tool 이름
description
모델이 선택할 때 읽는 설명
parameters
OpenClaw 내부 JSON schema
execute
runtime에서 실제 작업 수행
src/agents/tools/common.ts
  1. 01 Schema source bash-tools.schemas.ts, memory tools, plugin descriptor가 입력 계약을 만든다.
  2. 02 Tool assembly createOpenClawCodingTools, createOpenClawTools, plugin tools가 후보를 모은다.
  3. 03 Policy filter toolsAllow, sandbox, embedded mode가 이번 턴의 tool surface를 줄인다.
  4. 04 Normalize normalizeToolParameters가 provider에 안전한 JSON schema 모양으로 정리한다.
  5. 05 effectiveTools attempt.ts가 provider-visible tool 목록을 확정하고 trajectory에 남긴다.
OPENAI parameters

OpenAI function/tool calling API 계약에 맞춰 schema를 parameters로 유지한다.

openai-transport-stream.ts
CLAUDE input_schema

Anthropic Messages API의 tool 정의 계약에 맞춰 같은 schema를 input_schema로 바꾼다.

anthropic-transport-stream.ts
CHECK 01 도구가 정의됐는가

원본 tool 파일에서 parametersexecute가 같은 tool 객체에 있는지 본다.

CHECK 02 이번 턴에 남았는가

attempt.tseffectiveToolsproviderVisibleTools 기록을 확인한다.

CHECK 03 provider 형식으로 바뀌었는가

OpenAI는 parameters, Claude는 input_schema로 전송되는지 transport adapter를 본다.

CHECK 04 실행 결과가 replay됐는가

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는 검색을 빠르게 만드는 파생 계층이다.

Short term

현재 Context

이번 요청에 실제로 포함된 system prompt와 replay history다. budget, limit, compaction의 영향을 받는다.

attempt.ts / replay-history.ts
Durable source

Markdown Memory

사람이 읽고 수정할 수 있는 장기 기억 원본이다. 백업과 diff가 쉽고 검색 전에도 의미가 남는다.

MEMORY.md / memory/*.md
Recall index

Search Manager

memory_search가 vector, FTS, qmd/builtin backend와 visibility 정책을 거쳐 관련 chunk를 찾는다.

extensions/memory-core/src/memory/

Recall retrieval path

memory_search는 어떻게 기억을 꺼내는가

Markdown 원본을 무작정 prompt에 넣지 않고 필요한 chunk를 검색해 현재 턴으로 되돌린다.

MODEL TOOL CALL memory_search
query
"skill 수행 실패"
corpus
memory / sessions / all
limit
maxResults + minScore
  1. tools.ts 입력 계약 query와 corpus를 검증한다.
  2. session-search-visibility.ts 가시성 정책 현재 요청에 노출 가능한 session hit만 남긴다.
  3. search-manager.ts Backend 선택 qmd 또는 builtin fallback을 고른다.
  4. manager-search.ts 랭킹과 결과 vector / FTS 결과 chunk를 반환한다.
SOURCE OF TRUTH Markdown MEMORY.md
memory/*.md
OPTIONAL CORPUS Sessions transcript JSONL
DERIVED INDEX Vector + FTS 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 분리
  1. 01 Telegram Bot API getUpdates 또는 webhook이 update를 전달한다.
  2. 02 monitorTelegramProvider 계정 token, polling/webhook 모드, offset, runner를 준비한다.
  3. 03 createTelegramBot grammy Bot에 dedupe, sequentialize, native command, message handler를 붙인다.
  4. 04 bot.on("message") message, channel_post, callback_query를 표준 inbound message로 보낸다.
  5. 05 buildTelegramMessageContext chatId, senderId, route, SessionKey, BodyForAgent, CommandBody를 만든다.
  6. 06 dispatchTelegramMessage typing, reaction, streaming draft, reply fence, delivery lane을 준비한다.
  7. 07 runInboundReplyTurn ctxPayload와 routeSessionKey를 agent 실행/명령 처리로 넘긴다.
  8. 08 Agent Runtime session transcript, prompt, model, tools, plugin provider가 실행된다.
  9. 09 deliverReplies ReplyPayload를 Telegram chunk, HTML, media, inline button으로 변환한다.
  10. 10 bot.api.sendMessage message_thread_id, reply_to, parse_mode과 함께 최종 답장을 보낸다.

Evidence first debugging

모델이 “모른다”고 할 때 추적할 네 갈래

저장 여부, context 포함 여부, tool 제공 여부, memory retrieval 여부를 분리해서 조사한다.

왜 system prompt에 있던 skill 또는 이전 대화를 모델이 활용하지 못했을까?
01 / STORED? 기록은 남았는가

원문 메시지와 tool result가 transcript에 있는지 본다.

<sessionId>.jsonl
02 / VISIBLE? 현재 context에 남았는가

sanitize, limit, compaction 뒤의 결과를 본다.

context.compiled
03 / CALLABLE? 실행 tool이 있었는가

설명된 skill이 아니라 전송된 schema를 확인한다.

providerVisibleTools
04 / RETRIEVED? 장기 기억이 검색됐는가

index 상태와 검색 결과 source를 확인한다.

memory status / search
Disksession JSONL
Replaysession:sanitized
Limitsession:limited
Assemblecontext.compiled
Wirestream:context

Operational evidence console

어느 파일에서 어떤 사실을 확인할까

같은 요청도 metadata, transcript, compiled context, wire 직전 trace는 서로 다른 사실을 보여준다.

SESSION INDEX

요약 상태

sessions.json

systemPromptReport, 상태, usage, session file 위치를 찾는다.

Prompt 본문 자체가 아니라 계측 요약
TRANSCRIPT

저장 원문

<sessionId>.jsonl

user, assistant, tool/result 이벤트가 실제로 저장됐는지 본다.

저장됨 != 현재 모델에게 보임
TRAJECTORY

조립 결과

context.compiled

systemPrompt, messages, tools, providerVisibleTools를 본다.

기본 활성화, OPENCLAW_TRAJECTORY=0으로 비활성
CACHE TRACE

전송 직전

stream:context

session:loaded부터 history 감소를 단계별 비교한다.

명시적으로 켜야 하며 민감 내용 주의

설치 후 확인 루틴

  1. 상태openclaw status --jsonopenclaw gateway status --deep
  2. 세션openclaw sessions --json --all-agents
  3. 최종 조립jq 'select(.type=="context.compiled") | .data' <session>.trajectory.jsonl
  4. 기억openclaw memory status --deepopenclaw memory search "키워드" --json
  5. Wire 추적OPENCLAW_CACHE_TRACE=1 OPENCLAW_CACHE_TRACE_MESSAGES=1 openclaw gateway run

Question to evidence

증상별로 어디부터 볼지 고르는 표

원인을 추측하지 말고, 관측할 수 있는 가장 가까운 경계부터 확인한다.

질문 먼저 볼 모듈 증거
Skill이 있는데 모른다 system-prompt.ts
tool-construction-plan.ts
providerVisibleTools
이전 대화를 잊었다 replay-history.ts
compact.ts
session:limited
Memory 검색이 없다 tools.ts
search-manager.ts
memory status --deep
Provider마다 다르다 openai-transport-stream.ts stream:context
Prompt가 너무 크다 system-prompt.ts
preemptive-compaction.ts
systemPromptReport
최종 payload가 궁금하다 cache-trace.ts
trajectory/runtime.ts
context.compiled

Hands-on lab

직접 확인하며 구조를 익히는 네 가지 실습

각 실습은 원본, 변환, 최종 증거 가운데 적어도 두 경계를 비교한다.

LAB 01 / PROMPT

한 턴의 최종 prompt 추적

  1. 짧은 메시지를 하나 보낸다.
  2. openclaw sessions --json --all-agents
  3. context.compiled.data.systemPrompttools를 확인한다.

목표: 조립된 prompt와 tool list의 기록 위치 이해

LAB 02 / MEMORY

memory_search 경로 확인

  1. MEMORY.md에 고유 키워드를 기록한다.
  2. openclaw memory index --force
  3. openclaw memory search "키워드" --json

목표: Markdown 원본과 index hit의 관계 이해

LAB 03 / TOOLS

Allowlist 영향 확인

  1. toolsAllow가 걸리는 요청을 찾는다.
  2. tool construction plan을 읽는다.
  3. providerVisibleTools와 prompt 안내를 비교한다.

목표: 설명된 능력과 제공된 capability 구분

LAB 04 / HISTORY

History가 줄어드는 위치 찾기

  1. 긴 session에서 cache trace를 켠다.
  2. loaded / sanitized / limited / stream을 비교한다.
  3. replay-history.tscompact.ts를 함께 읽는다.

목표: 저장된 기록과 visible history의 차이 확인

Deep reading roadmap

다음에 깊게 팔 모듈의 연결 지도

핵심 모듈 8개의 주경로다. Context Engine과 실습은 이어지는 전용 섹션과 챕터에서 보강한다.

  1. 01attempt.ts실행의 중심
  2. 02system-prompt.ts행동 계약
  3. 03replay-history.ts보이는 기억
  4. 04attempt-tool-construction-plan.ts도구 표면
  5. 05memory-core/tools.ts검색 호출
  6. 06memory/manager.ts인덱스 내부
  7. 07openai-transport-stream.ts최종 전송
  8. 08trajectory / 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