Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

DeepSeek Harness Session Logs and Turn Lifecycle

DeepSeek Harness Session Logs and Turn Lifecycle

Have you ever wondered: where exactly is the conversation history that the model sees stored?

dsh's answer is special: there's no dedicated place; it's derived from a session log.

In this chapter we'll cover session logs and the turn lifecycle: how the log acts as the single source of truth, how turns and steps are divided, and the invariant "model-visible means recorded."

In short: a session is an append-only event log, model history is derived from the log; turns and steps are execution boundaries on the log.


Session log: the single source of truth

A Session is an append-only log composed of typed SessionEvents.

It's the single source of truth for the agent's complete interaction history; the LLM message history is derived from the log and never stored separately.

Replay means re-deriving the history from the same set of events.

Each event in the log has a monotonically increasing seq(seq = log.length) and epoch-millisecond time。

Events use type for a true discriminated union, so switch (event.type) can directly narrow event.data, without type assertions.

all event.data must all be losslessly serializable to JSON,Session.append enforces this at the source.

Model-visible means recorded.Everything reaching a model request must be reconstructable from the log, and a runtime invariant asserts this.

Therefore, adding a model-visible input requires adding a session event: extend SessionEventMap and render from the log.

SDK users who need replayable transcript data should consume the session/event event stream.


deriveMessages: project model history from the log

Session.deriveMessages() Project the event log into what the model sees Message[]。

It's cached: each surface node is projected once when first seen, and rebuilt when the surface is rewritten.

It returns a frozen array of messages; modifying recorded history through projection is inexpressible at the type level.

The projection rules are straightforward:

Events projected as Description
user/message a user message carrying the exact content; the optional envelope is only log display metadata
assistant/message an assistant message including provider, model, and optional replay status
assistant/chunk Skip belongs to replay/UI data; the assembled messages are authoritative
tool/result a user message with a tool-result block tool results return to the model under the user role
turn/*、step/* Skip structural information, not projected as messages

One detail: empty-content assistant/message will also be skipped.

Steps truncated by max-tokens with no content still record an assistant/message to save usage, provider and model, but assistant turns with no content must not enter the provider transcript.


Three Event Domains

Choosing the right event domain is the first decision for most changes.

The official docs divide events into three domains, each with its own purpose:

Event Domain Representative Event Feature When to Use
Session Events turn/start、step/start、user/message、assistant/*、tool/call、tool/result Appended to the log and broadcast, persistent facts A fact must still exist after reload
Agent Events agent/pre-step、agent/request、agent/status、agent/turn-stopping Carry the active Agent, real-time control and state Observe or intercept work in progress
Capability Events tools/*、fs/*、llm/stream Attach policies to seams without import cycles Attach policies and adapters to capability seams

where agent/pre-step、agent/request、llm/stream and the three tools/* events are waterfall; listeners must call next() to delegate onward.

agent/turn-stopping is a serial event, with no next()。


definition of turns and steps

A step is one model request plus the tools it calls.

A turn contains zero or more steps: it opens before the first input is claimed and closes when no more work is owed.

Note: a turn encloses one model loop execution, not the entire session log.

The official sequence diagram shows the complete flow as:turn/start → agent/pre-step → step/start → llm/stream → 工具 → step/end → turn/end。

Turn sequence diagram

Input reaches the driver through the same inbox.

Some messages wake the driver immediately; injected context stays in the inbox until another message wakes it.

agent/pre-step Decides what the model sees: listeners can rewrite claimed messages or reject them outright.

When the first claim is rejected or rewritten to empty, a persistent turn with no steps is still closed, so the log records the attempt.


Key Events for turn and step

Every boundary in the log has a corresponding event; the most commonly used ones are listed below.

Events Data Carried Description
turn/start { turn } Opens a turn before the loop claims queued input or runs pre-step
turn/end { turn, reason } Closes a turn with a TurnEndReason (completed / aborted / blocked / error / max-tokens / interrupted)
step/start { turn, step } Opens a step within a turn
step/end { turn, step } Closes that step
user/message UserMessage An identified value shared by direct prompts, injected context, steering and real-time inbox events
assistant/chunk { turn, step, chunk } Raw streaming chunks, token-level replay fidelity
assistant/message { turn, step, message, usage? } Assembled assistant message (used by derived history)
tool/call { turn, step, callId, name, arguments } A tool call from a model request; arguments is the raw JSON string produced by the model
tool/result { turn, step, message, error?, meta? } The model-visible result of a completed tool call

A useful semantics:assistant/message Events record every successful provider call, including those that return empty content or end with max-tokens.

Empty content does not enter derived history, but the persistent event still retains usage.

It passes the question through sourceEventSeqs Precisely list the corresponding assistant/chunk events, including an explicit empty list.


Hands-on example: parsing a JSONL session log

Below is a short session log (canonical packed-line layout of JSONL) from a task to 'fix a typo in the runoob repo'.

Each line is a SessionEvent with type, seq, time and data.



{"type":"turn/start","seq":0,"time":1755000000000,"data":{"turn":1}}

{"type":"step/start","seq":1,"time":1755000000010,"data":{"turn":1,"step":1}}

{"type":"user/message","seq":2,"time":1755000000020,"data":{"role":"user","content":[{"type":"text","text":"Fix the typo in the runoob README."}]},"surfaceOp":"append","sourceEventSeqs":[0]}

{"type":"assistant/chunk","seq":3,"time":1755000000030,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","text":"I'll "}}}

{"type":"assistant/chunk","seq":4,"time":1755000000040,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","name":"bash","arguments":"{\"command\":\"grep runoob README.md\"}"}}}

{"type":"assistant/message","seq":5,"time":1755000000050,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"I'll search"},{"type":"tool_use","id":"call_1","name":"bash","input":{"command":"grep runoob README.md"}}]},"usage":{"inputTokens":12,"outputTokens":4}},"surfaceOp":"append","sourceEventSeqs":[3,4]}

{"type":"tool/call","seq":6,"time":1755000000060,"data":{"turn":1,"step":1,"callId":"call_1","name":"bash","arguments":"{\"command\":\"grep runoob README.md\"}"}}

{"type":"tool/result","seq":7,"time":1755000000070,"data":{"turn":1,"step":1,"message":{"role":"tool","toolName":"bash","content":"runoob","isError":false}},"surfaceOp":"append","sourceEventSeqs":[6]}

{"type":"step/end","seq":8,"time":1755000000080,"data":{"turn":1,"step":1}}

{"type":"turn/end","seq":9,"time":1755000000090,"data":{"turn":1,"reason":{"kind":"completed"}}}

Note user/message、assistant/message、tool/result The three surface event types carry surfaceOp markers indicating how they join the derived surface.

turn/start、step/start and other boundary events do not carry surfaceOp and are not projected into model messages.

Below we replay this log in Python, rebuild the conversation and mark the turn/step boundaries.

Example

File path: examples/parse_session_log.py

Parse a JSONL session log, rebuild the model-visible conversation and mark the turn/step boundaries.

This is a simplified teaching model of Session.deriveMessages(); the real implementation is cached and returns frozen messages.

import

json

import

sys

def

derive_messages

(

events

)

:

   

"""Only project surface events, simulating the projection rules of deriveMessages.

    user/message -> user message
    assistant/message -> assistant message
    tool/result -> user message carrying a tool-result block
    turn/, step/, assistant/chunk, tool/call are not projected as messages
    """

    messages

=

[

]

   

for

ev

in

events:

        t

=

ev

[

"type"

]

        d

=

ev

[

"data"

]

       

if

t

==

"user/message"

:

            messages.

append

(

{

"role"

:

"user"

,

"content"

: d

[

"content"

]

}

)

       

elif

t

==

"assistant/message"

:

            messages.

append

(

{

"role"

:

"assistant"

,

"content"

: d

[

"message"

]

[

"content"

]

}

)

       

elif

t

==

"tool/result"

:

            messages.

append

(

{

"role"

:

"tool"

,

"name"

: d

[

"message"

]

[

"toolName"

]

,

"content"

: d

[

"message"

]

[

"content"

]

}

)

   

return

messages

def

main

(

path

)

:

   

with

open

(

path

,

encoding

=

"utf-8"

)

as

f:

        events

=

[

json.

loads

(

line

)

for

line

in

f

if

line.

strip

(

)

]

   

First pass: print execution boundaries to understand the nesting of turn and step.

   

for

ev

in

events:

        d

=

ev

[

"data"

]

       

if

ev

[

"type"

]

==

"turn/start"

:

           

print

(

f

"[turn/start] turn={d['turn']}"

)

       

elif

ev

[

"type"

]

==

"turn/end"

:

           

print

(

f

"[turn/end]   turn={d['turn']} reason={d['reason']}"

)

       

elif

ev

[

"type"

]

==

"step/start"

:

           

print

(

f

"  [step/start] turn={d['turn']} step={d['step']}"

)

       

elif

ev

[

"type"

]

==

"step/end"

:

           

print

(

f

"  [step/end]   turn={d['turn']} step={d['step']}"

)

       

elif

ev

[

"type"

]

==

"assistant/chunk"

:

           

print

(

f

"    chunk: {d['chunk']['type']}"

)

       

elif

ev

[

"type"

]

==

"tool/call"

:

           

print

(

f

"    tool/call: {d['name']} args={d['arguments']}"

)

   

Second pass: rebuild the model-visible derived history.

   

print

(

"\nModel-visible derived messages:"

)

   

for

m

in

derive_messages

(

events

)

:

       

if

m

[

"role"

]

==

"tool"

:

           

print

(

f

"  [tool] {m['name']}: {m['content']}"

)

       

else

:

           

print

(

f

"  [{m['role']}] {m['content']}"

)

if

name

==

"main"

:

    main

(

sys

.

argv

[

1

]

)

Running this log produces roughly:



[turn/start] turn=1

  [step/start] turn=1 step=1

    chunk: text-delta

    chunk: tool-call-delta

    tool/call: bash args={"command":"grep runoob README.md"}

  [step/end]   turn=1 step=1

[turn/end]   turn=1 reason={'kind': 'completed'}



Model-visible derived messages:

  [user] [{'type': 'text', 'text': 'Fix the typo in the runoob README.'}]

  [assistant] [{'type': 'text', 'text': 'I'll search'}, {'type': 'tool_use', ...}]

  [tool] bash: runoob

Original assistant/chunk skipped during derivation; the assembled assistant/message is authoritative.

This is 'what the model sees is recorded': every message the model sees can be reconstructed verbatim from this log.


Summary and self-test

The session log is the sole source of context the model sees, turns and steps are execution boundaries on the log, and the three event domains help you choose the right extension point.

Self-test questions:

Problem Reference
To store a fact that 'still exists after reload', which event type should you use? Session events (persistent, appended to the log)
Where does the history the model sees come from? Session.deriveMessages() Derived from the log, never stored separately
How many steps can a turn contain? Zero or more; opens before the first input is claimed and closes when no more work is owed