Nativa PHP Core

Article

Agent loop and sessions ... the event-sourced agent journal

Article cover illustration: Architecture, dsh-series, deepseek, agents

Agent loop ... the replaceable driver

In traditional frameworks, the agent loop is fixed. In DSH, it's a plugin. The agent-loop package is the only one in the entire harness that contains concrete loop logic. Everything else is abstract services or plugins.

# Core group
packages/core/
  scope/              # Scoped-context registration
  session/            # Event-sourced session log
  system-prompt/      # Prompt assembly
  tools/              # Tool registry
  agent/              # Agent interface
  agent-default-model/ # Default model
  agent-loop/         # THE concrete driver (replaceable!)

How agentLoop works

// Creating an agent
const agent = await ctx.agents.create({
    sessionId: 'my-session-123',
    model: 'deepseek-chat',
    cwd: '/workspace'
})

// Agent runs ... turn → step → tool call → response
await agent.followup('Analyze this file')

// Agent finished ... session log is persisted

Lifecycle

create() → setup() → enter registries → announce → start driver
    ↓
turn/step cycle (model calls, tools run, responses come back)
    ↓
dispose() → stop driver → unwind scope → detach agent → detach session

Key insight: the creator and agent-loop provider are co-owners. When one uninstalls, the agent cleans up correctly.

Sessions ... the event-sourced journal

Every session is an append-only log ... not state-based.

Session Log:
  [1] user: "Analyze this file"
  [2] agent: [tool_call: read_file, path: "src/app.ts"]
  [3] tool: [result: "import ..."]
  [4] agent: "The file has 3 imports..."
  [5] user: "Fix the imports"
  [6] agent: [tool_call: edit_file, ...]
  [7] tool: [result: "OK"]

Backends

BackendWhat it isWhen to use
JSONLAppend-only fileDevelopment, simplicity
SQLiteDatabaseProduction, full-text search

Compaction

The log can be shrunk without losing history:

Before: 1000 entries (100MB)
After compaction: 50 entries (5MB) ... summary + recent steps

Compaction preserves key decisions and removes repetitive steps.

Tool registry ... scoped tools

The tool registry in DSH is scoped ... every agent has its own tools.

// Tool registration
ctx.tools.register('read_file', {
    description: 'Read a file from the workspace',
    parameters: { path: { type: 'string' } },
    execute: async (params) => {
        return ctx.fs.read(params.path)
    }
})

// Tool execution ... model calls a tool
const result = await ctx.tools.execute('read_file', { path: 'src/app.ts' })

Tool categories

CategoryPackageExamples
Filesystemtool-fsread, write, edit
Searchtool-fs-searchglob, grep
Shelltool-shellbash
Terminaltool-terminalpersistent PTY
Webtool-websearch, fetch
Subagenttool-subagentdelegate

Parallel tool calls

An agent can call multiple tools simultaneously:

// Config
maxParallelToolCalls: 10  // default

// Agent calls 3 tools at once
await Promise.all([
    ctx.tools.execute('read_file', { path: 'a.ts' }),
    ctx.tools.execute('read_file', { path: 'b.ts' }),
    ctx.tools.execute('read_file', { path: 'c.ts' })
])

Inbox ... the message queue

An agent has an inbox ... a queue of messages waiting to be processed:

OperationWhat it does
followup()Add to next-turn FIFO, wake driver
steer()Add to next-step inbox, wake driver
inject()Add to next-step inbox, DON'T wake driver
// followup ... new turn
await agent.followup('Continue the analysis')

// steer ... change direction in current turn
await agent.steer('Use a different approach')

// inject ... silent input (waits for wake)
await agent.inject({ context: 'extra data' })

Event taxonomy

Every inbox operation publishes an event:

agent/inbox/inserted  → new message
agent/inbox/spliced   → change (insert, edit, remove)
agent/inbox/claimed   → message taken for processing
agent/inbox/discarded → message canceled
agent/pre-step        → guard (can reject)

Invariant companion

agent-loop/invariant is an optional companion that independently rebuilds request boundaries from the session log. It serves as:

  • Verification that the session log is consistent
  • Detection of duplicate requests
  • Validation of message boundaries

How it differs from traditional agent frameworks

AspectTraditionalDSH
Agent loopFixedPlugin
SessionState-basedEvent-sourced
ToolsGlobalScoped per agent
InboxRequest/ResponseFIFO + priority
ParallelNomaxParallelToolCalls
HistoryLostAppend-only log

→ DeepSeek Harness ... 50 packages: architecture overview → Cordis ... a deep dive: plugin framework → Capability seams: how DSH abstracts abilities

Sources

Comments (0)

No comments yet — be the first to react.

Reader questions (0)

No questions yet — be the first to ask.

Stuck on something in this article? Ask below. Your name is shown publicly; your email is never stored. A question appears here once a moderator approves it.