refactor(agent-loop): separate injected context from turns
This commit is contained in:
@@ -64,7 +64,7 @@ Providers stream token-sized deltas, so a raw log stores hundreds of `assistant/
|
||||
|
||||
`request/header` records a full canonical snapshot of the non-history request envelope with reason `initial`, `resume`, or `change`. `foldRequestHeader()` selects the latest snapshot; legacy delta events and the removed `fallback` reason are rejected. `messagePrefix` remains separate from derived history. See the [reconstructable-requests Agent Note](../../../.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md).
|
||||
|
||||
A `user/message` renders its `content` verbatim as a user-role message whether it is a direct human prompt, a synthetic injection, or an admitted goal round; its typed `source` is the only channel that tells them apart and carries any domain-specific durable facts. A `user/message` or `steering/message` with prompt-prefix context keeps the exact combined model bytes in `content` and stores a model-hidden `envelope` containing the direct `displayContent` and prefix context sources. `displayPromptContent()` selects the human-facing prompt without changing derived history.
|
||||
A `user/message` renders its `content` verbatim as a user-role message whether it is a direct human prompt, a synthetic injection, or an admitted goal round; its typed `source` is the only channel that tells them apart and carries any domain-specific durable facts. Turn execution remains enclosed by `turn/start` and `turn/end`, while an idle injection may append and flush a `user/message` between turns without running the model.
|
||||
|
||||
`tool/result` persists the model-facing content, optional internal failure identity, and optional presentation metadata. A tool's successful canonical `value` and human-readable canonical failure message remain execution-local; rendered error content is the replay-authoritative message. This preserves the existing event shape and does not change `SESSION_FORMAT_VERSION`.
|
||||
|
||||
|
||||
@@ -11,9 +11,9 @@ import { isAbsolute } from 'node:path'
|
||||
import { deepFreeze } from '@deepseek-ai/dsh-llm'
|
||||
import { scopeOf, scopeTarget } from '@deepseek-ai/dsh-scope'
|
||||
import type { Scoped } from '@deepseek-ai/dsh-scope'
|
||||
import type { ContentBlock, Message } from '@deepseek-ai/dsh-llm'
|
||||
import type { Message } from '@deepseek-ai/dsh-llm'
|
||||
import { SESSION_FORMAT_VERSION, SessionId } from './types.ts'
|
||||
import type { CreateSessionOptions, EpochHeader, OutOfBandSessionEventType, PromptMessageData, SessionEvent, SessionEventMap, SessionEventType, SessionHeader, SurfaceIntent, SurfaceEventType, TurnTrigger } from './types.ts'
|
||||
import type { CreateSessionOptions, EpochHeader, OutOfBandSessionEventType, SessionEvent, SessionEventMap, SessionEventType, SessionHeader, SurfaceIntent, SurfaceEventType, TurnTrigger } from './types.ts'
|
||||
import { snapshotJsonValue } from './json.ts'
|
||||
import { SurfaceManager } from './surface.ts'
|
||||
import type { SessionSurface } from './surface.ts'
|
||||
@@ -29,15 +29,6 @@ export type { SessionSurface, SurfaceFoldReplacement, SurfaceFoldResult } from '
|
||||
export { foldSurface, isSurfaceEvent, isSurfaceEligibleType } from './surface.ts'
|
||||
export { canonicalHeader, foldRequestHeader, headerEquals } from './request-header.ts'
|
||||
|
||||
/**
|
||||
* Return the human-facing prompt blocks from a durable prompt message.
|
||||
* @param data - ordinary or steering prompt event data.
|
||||
* @returns the effective direct prompt, excluding baked prefix context.
|
||||
*/
|
||||
export function displayPromptContent(data: PromptMessageData): ContentBlock[] {
|
||||
return data.envelope?.displayContent ?? data.content
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the latest closed message-triggered turn, excluding injection and
|
||||
* plugin-owned zero-step turns.
|
||||
@@ -534,9 +525,7 @@ export class Session {
|
||||
switch (event.type) {
|
||||
// Ordinary prompts, injected context, and mid-turn steering project
|
||||
// identically in user role: the event's model-facing content stays
|
||||
// verbatim. A prompt envelope is model-hidden display metadata; its
|
||||
// prefix bytes are already present in content. The message's `source`/`meta`
|
||||
// and steering's `turn` are also log-only. Do NOT
|
||||
// verbatim. The message's `source` and steering's `turn` are log-only. Do NOT
|
||||
// re-add per-type framing (e.g. `<context>`/`<steering>`) here: framing is
|
||||
// caller-owned — a producer bakes it into `content`, as workspace-context
|
||||
// does with `<system-reminder>` — or, if reintroduced, must be driven by
|
||||
|
||||
@@ -66,8 +66,8 @@ function validateEvent(
|
||||
let nextStep = trace.nextStep
|
||||
let pendingCalls: SessionTraceTransition['pendingCalls'] = { kind: 'none' }
|
||||
|
||||
// SessionEventMap is merge-extensible, so the default enforces turn
|
||||
// enclosure for package-added events as well as the built-in variants.
|
||||
// Model input may be appended between turns without running the model.
|
||||
// Merge-extensible package events remain turn-enclosed by default.
|
||||
switch (event.type) {
|
||||
case 'turn/start': {
|
||||
if (trace.openTurn !== null) {
|
||||
@@ -141,6 +141,8 @@ function validateEvent(
|
||||
pendingCalls = { kind: 'delete', callId: event.data.callId }
|
||||
break
|
||||
}
|
||||
case 'user/message':
|
||||
break
|
||||
default: {
|
||||
if (trace.openTurn === null) {
|
||||
fail(`${event.type} appended outside any open turn (every event must be turn-enclosed)`)
|
||||
|
||||
@@ -183,25 +183,6 @@ export interface EpochHeader {
|
||||
*/
|
||||
export type RequestHeaderReason = 'initial' | 'resume' | 'change'
|
||||
|
||||
/** Durable model-hidden annotation for one context baked into a prompt message. */
|
||||
export interface PromptPrefixContext {
|
||||
/** Producer provenance retained for transcript presentation and inspection. */
|
||||
source: MessageSource
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-facing view of a prompt whose exact model content includes prefixed
|
||||
* context. `content` on the owning event remains the reconstructable model
|
||||
* input; this envelope prevents transcript, title, and re-reference consumers
|
||||
* from treating the baked context as direct human text.
|
||||
*/
|
||||
export interface PromptMessageEnvelope {
|
||||
/** Effective user prompt after interception rewrites, without baked context. */
|
||||
displayContent: ContentBlock[]
|
||||
/** Ordered descriptors for contexts already baked into the event content. */
|
||||
prefixContexts: PromptPrefixContext[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared payload for user, injected-context, and steering prompt messages. A
|
||||
* direct human prompt, a synthetic `agent.inject()` context, and mid-turn
|
||||
@@ -210,12 +191,10 @@ export interface PromptMessageEnvelope {
|
||||
* not by event type.
|
||||
*/
|
||||
export interface PromptMessageData {
|
||||
/** Exact model-facing blocks, including any baked prompt-prefix contexts. */
|
||||
/** Exact model-facing blocks. */
|
||||
content: ContentBlock[]
|
||||
/** Producer provenance for the direct prompt. */
|
||||
/** Producer provenance. */
|
||||
source: MessageSource
|
||||
/** Present only when prompt-prefix contexts were baked into `content`. */
|
||||
envelope?: PromptMessageEnvelope
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -226,10 +205,7 @@ export interface PromptMessageData {
|
||||
*/
|
||||
export interface SessionEventMap {
|
||||
/**
|
||||
* Opens turn `turn`. `trigger` records what started it — one claimed queued
|
||||
* message or an idle-time injection. The turn is the durability/replay
|
||||
* boundary: every event sits between a `turn/start` and its matching
|
||||
* `turn/end` (the turn-enclosure invariant).
|
||||
* Opens turn `turn`. `trigger` records what started the model loop.
|
||||
*/
|
||||
'turn/start': { turn: number; trigger: TurnTrigger }
|
||||
/**
|
||||
@@ -248,9 +224,8 @@ export interface SessionEventMap {
|
||||
* (the queued message claimed for this turn), a synthetic `agent.inject()`
|
||||
* context (file-change notices, subdir AGENTS.md, skill content, cron
|
||||
* notifications, …), or an admitted goal continuation round. All three
|
||||
* project their `content` verbatim; `source` (with a non-`user` kind marking
|
||||
* injected context) is the only channel that tells them apart. An idle
|
||||
* injection wraps this event in a one-shot turn so the log stays turn-enclosed.
|
||||
* project their `content` verbatim; `source` tells them apart. An idle
|
||||
* injection may append this event between turns without running the model.
|
||||
*/
|
||||
'user/message': PromptMessageData
|
||||
/**
|
||||
|
||||
@@ -102,7 +102,7 @@ describe('session-log invariants', () => {
|
||||
} as never) }).toThrow(/seq must strictly increase/)
|
||||
})
|
||||
|
||||
it('enforces turn numbering and enclosure', async () => {
|
||||
it('enforces turn numbering and encloses events other than idle context', async () => {
|
||||
const first = await setup()
|
||||
const open = first.ctx.sessions.create()
|
||||
open.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
@@ -119,9 +119,9 @@ describe('session-log invariants', () => {
|
||||
|
||||
const outside = (await setup()).ctx.sessions.create()
|
||||
expect(() => outside.append('user/message', {
|
||||
content: [{ type: 'text', text: 'hi' }],
|
||||
source: { kind: 'user' },
|
||||
}, { surfaceOp: 'append' })).toThrow(/outside any open turn/)
|
||||
content: [{ type: 'text', text: 'idle context' }],
|
||||
source: { kind: 'plugin', plugin: 'test' },
|
||||
}, { surfaceOp: 'append' })).not.toThrow()
|
||||
expect(() => outside.append('steering/message', {
|
||||
turn: 1,
|
||||
content: [{ type: 'text', text: 'go' }],
|
||||
|
||||
@@ -2,7 +2,6 @@ import { describe, expect, expectTypeOf, it, vi } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import { CallId } from '@deepseek-ai/dsh-llm'
|
||||
import SessionStore, {
|
||||
displayPromptContent,
|
||||
findLastMessageTurnEnd,
|
||||
SESSION_FORMAT_VERSION,
|
||||
Session,
|
||||
@@ -136,35 +135,6 @@ describe('Session', () => {
|
||||
expect(steeringMessage!.content).toEqual([{ type: 'text', text: 'focus on tests' }])
|
||||
})
|
||||
|
||||
it('derives baked prompt context while exposing only the direct prompt for display', () => {
|
||||
const session = new Session(SessionId('prompt-envelope'))
|
||||
const event = session.append('user/message', {
|
||||
content: [
|
||||
{ type: 'text', text: 'background' },
|
||||
{ type: 'text', text: '\n\n## My request:\n' },
|
||||
{ type: 'text', text: 'question' },
|
||||
],
|
||||
source: { kind: 'user' },
|
||||
envelope: {
|
||||
displayContent: [{ type: 'text', text: 'question' }],
|
||||
prefixContexts: [{ source: { kind: 'plugin', plugin: 'reference' } }],
|
||||
},
|
||||
}, { surfaceOp: 'append' })
|
||||
|
||||
expect(session.deriveMessages()).toEqual([{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: 'background' },
|
||||
{ type: 'text', text: '\n\n## My request:\n' },
|
||||
{ type: 'text', text: 'question' },
|
||||
],
|
||||
}])
|
||||
expect(displayPromptContent(event.data)).toEqual([{ type: 'text', text: 'question' }])
|
||||
expect(Object.isFrozen(event.data.envelope?.displayContent)).toBe(true)
|
||||
expect(new Session(SessionId('prompt-envelope-replay'), session.events).deriveMessages())
|
||||
.toEqual(session.deriveMessages())
|
||||
})
|
||||
|
||||
it('keeps context source durable in the event while hiding it from the projection', () => {
|
||||
const session = new Session(SessionId('s2-raw'))
|
||||
session.append('user/message', {
|
||||
|
||||
Reference in New Issue
Block a user