feat: add optional time context plugin
This commit is contained in:
7
packages/context/README.md
Normal file
7
packages/context/README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
# context/ — optional request context
|
||||
|
||||
Product plugins that add bounded model-visible request context without defining a tool or service seam. They are opt-in deployment leaves and are not part of the default `dsh-agent-core` bundle.
|
||||
|
||||
| Package | Role | ctx key |
|
||||
|---|---|---|
|
||||
| `time-context/` | Dynamic current time and elapsed-since-previous-message system-prompt section | (none) |
|
||||
42
packages/context/time-context/README.md
Normal file
42
packages/context/time-context/README.md
Normal file
@@ -0,0 +1,42 @@
|
||||
# @deepseek-ai/dsh-time-context
|
||||
|
||||
Optional temporal request context. The plugin contributes one dynamic system-prompt section with the current zoned time and the elapsed duration since the last model-visible message before the current turn. It is not mounted by `dsh-agent-core` or any shipped example; deployments opt in explicitly. Decision record: [the time-context RFC](../../../docs/rfc/implemented/feature/2026-07-14-time-context-plugin.md).
|
||||
|
||||
## Config
|
||||
|
||||
```yaml
|
||||
- id: time-context
|
||||
name: '@deepseek-ai/dsh-time-context'
|
||||
config:
|
||||
timeZone: UTC # default; any IANA time-zone identifier
|
||||
refreshIntervalMs: 60000 # default; 0 refreshes on every step
|
||||
```
|
||||
|
||||
`timeZone` is validated at plugin load. `refreshIntervalMs` must be a non-negative safe integer and is evaluated only when a request is assembled: every turn's first request gets a fresh reading, and a later step in the same turn reuses that reading until it is at least this old. Thus `0` means per-step refresh, while a positive value bounds staleness at request boundaries without creating timer-driven turns.
|
||||
|
||||
## Message baseline
|
||||
|
||||
The duration starts at the latest model-visible session event before the current `turn/start`: a user, assistant, tool-result, context, or steering message. All later refreshes in that turn retain the same baseline, so the value measures elapsed time since the preceding conversation message rather than collapsing to approximately zero after the current prompt is appended. The first turn reports that no earlier message exists. Session event append time is the durable clock source; client-side send time is not part of the session contract.
|
||||
|
||||
The plugin uses a dynamic system-prompt section rather than retained `context/message` history. The loop records the exact rendered value in `request/header` / `request/header-delta`, so requests remain reconstructable while the current request carries only one timing block.
|
||||
|
||||
## Model Experience
|
||||
|
||||
### Temporal system prompt
|
||||
|
||||
**What the model sees**: Every request in an active turn includes the two-line section below. `<timestamp>` is an ISO-shaped local timestamp with numeric offset and IANA zone; `<duration-or-unavailable>` is compact whole-second units or the first-turn fallback.
|
||||
|
||||
**Token effect**: Fixed two-line request context. A refresh replaces the section in the request header rather than retaining prior readings in conversation history.
|
||||
|
||||
#### Temporal context section
|
||||
|
||||
```markdown
|
||||
Current time: <timestamp>
|
||||
Time since previous message: <duration-or-unavailable>.
|
||||
```
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
- **Request-bound refresh only** — no clock update is emitted while the agent is waiting inside a model call or tool; the next assembled step refreshes once the configured interval has elapsed.
|
||||
- **Whole-second display** — timestamps and durations omit sub-second precision even when `refreshIntervalMs` is below 1,000.
|
||||
- **Session-event baseline** — elapsed time starts from the durable append timestamp, not a client transport's original send timestamp.
|
||||
41
packages/context/time-context/package.json
Normal file
41
packages/context/time-context/package.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-time-context",
|
||||
"description": "Optional dynamic system-prompt context with the current time and elapsed duration since the previous message",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
],
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"schemastery": "^3.18.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/dsh-agent": "^0.0.1",
|
||||
"@deepseek-ai/dsh-system-prompt": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-agent": "workspace:^",
|
||||
"@deepseek-ai/dsh-agent-loop": "workspace:^",
|
||||
"@deepseek-ai/dsh-llm": "workspace:^",
|
||||
"@deepseek-ai/dsh-session": "workspace:^",
|
||||
"@deepseek-ai/dsh-system-prompt": "workspace:^",
|
||||
"@deepseek-ai/dsh-tools": "workspace:^",
|
||||
"cordis": "^4.0.0-rc.6"
|
||||
}
|
||||
}
|
||||
189
packages/context/time-context/src/index.ts
Normal file
189
packages/context/time-context/src/index.ts
Normal file
@@ -0,0 +1,189 @@
|
||||
/**
|
||||
* Optional temporal context for model requests. The plugin contributes one
|
||||
* dynamic system-prompt section that reports the current zoned time and the
|
||||
* elapsed duration since the last model-visible message before the current
|
||||
* turn. A turn always gets a fresh reading on its first request; later steps
|
||||
* refresh only when the configured maximum age is reached.
|
||||
*
|
||||
* The section is request state, not retained conversation history. The agent
|
||||
* loop records each rendered value through its existing `request/header` or
|
||||
* `request/header-delta` event, preserving the model-visible/logged invariant
|
||||
* without accumulating stale `context/message` entries.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-time-context
|
||||
*/
|
||||
|
||||
import type { Context } from 'cordis'
|
||||
import z from 'schemastery'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import type { AssembleContext } from '@deepseek-ai/dsh-system-prompt'
|
||||
|
||||
/** Cordis plugin name used by loader diagnostics. */
|
||||
export const name = 'time-context'
|
||||
|
||||
/** The system-prompt registry that owns the dynamic request section. */
|
||||
export const inject = ['systemPrompt']
|
||||
|
||||
/** Configuration for the request-time clock section. */
|
||||
export interface Config {
|
||||
/** IANA time zone used for the rendered timestamp (default `UTC`). */
|
||||
timeZone?: string
|
||||
/** Maximum age of a reading within one turn, in milliseconds (default 60,000; `0` refreshes every step). */
|
||||
refreshIntervalMs?: number
|
||||
}
|
||||
|
||||
/** Schemastery validation and defaults for {@link Config}. */
|
||||
export const Config: z<Config> = z.object({
|
||||
timeZone: z.string().default('UTC'),
|
||||
refreshIntervalMs: z.number().default(60_000),
|
||||
})
|
||||
|
||||
/** The open turn currently being assembled, including its log boundary. */
|
||||
interface OpenTurn {
|
||||
turn: number
|
||||
startSeq: number
|
||||
}
|
||||
|
||||
/** One agent's last rendered block and its fixed previous-turn baseline. */
|
||||
interface RenderState {
|
||||
turn: number
|
||||
renderedAt: number
|
||||
previousMessageTime: number | undefined
|
||||
text: string
|
||||
}
|
||||
|
||||
/** Date-time fields required from the fixed formatter below. */
|
||||
type TimestampPart = 'day' | 'hour' | 'minute' | 'month' | 'second' | 'timeZoneName' | 'year'
|
||||
|
||||
/** Find the open turn at the tail of an agent's balanced session log. */
|
||||
function openTurn(agent: Agent): OpenTurn | undefined {
|
||||
for (const event of [...agent.session.events].reverse()) {
|
||||
switch (event.type) {
|
||||
case 'turn/end':
|
||||
return undefined
|
||||
case 'turn/start':
|
||||
return { turn: event.data.turn, startSeq: event.seq }
|
||||
default:
|
||||
// Merge-extensible session events: only turn boundaries matter here.
|
||||
break
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Timestamp of the last model-visible message before one turn opened. */
|
||||
function previousMessageTime(agent: Agent, turnStartSeq: number): number | undefined {
|
||||
for (const event of [...agent.session.events].reverse()) {
|
||||
if (event.seq >= turnStartSeq) continue
|
||||
switch (event.type) {
|
||||
case 'user/message':
|
||||
case 'assistant/message':
|
||||
case 'tool/result':
|
||||
case 'context/message':
|
||||
case 'steering/message':
|
||||
return event.time
|
||||
default:
|
||||
// Merge-extensible session events: non-surface records are not messages.
|
||||
break
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Format an epoch millisecond value as an ISO-shaped timestamp with offset and IANA zone. */
|
||||
function formatTimestamp(now: number, formatter: Intl.DateTimeFormat, timeZone: string): string {
|
||||
const parts = Object.fromEntries(
|
||||
formatter.formatToParts(now).map(part => [part.type, part.value]),
|
||||
) as Record<TimestampPart, string>
|
||||
const offset = parts.timeZoneName.replace(/^GMT$/, 'GMT+00:00').slice(3)
|
||||
return `${parts['year']}-${parts['month']}-${parts['day']}T${parts['hour']}:${parts['minute']}:${parts['second']}${offset}[${timeZone}]`
|
||||
}
|
||||
|
||||
/** Format a non-negative elapsed millisecond count as compact whole-second units. */
|
||||
function formatDuration(elapsedMs: number): string {
|
||||
let seconds = Math.floor(Math.max(0, elapsedMs) / 1000)
|
||||
const days = Math.floor(seconds / 86_400)
|
||||
seconds %= 86_400
|
||||
const hours = Math.floor(seconds / 3600)
|
||||
seconds %= 3600
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
seconds %= 60
|
||||
const parts: string[] = []
|
||||
if (days > 0) parts.push(`${days}d`)
|
||||
if (hours > 0) parts.push(`${hours}h`)
|
||||
if (minutes > 0) parts.push(`${minutes}m`)
|
||||
parts.push(`${seconds}s`)
|
||||
return parts.join(' ')
|
||||
}
|
||||
|
||||
/** Build the exact two-line model-facing section. */
|
||||
function renderText(
|
||||
now: number,
|
||||
previous: number | undefined,
|
||||
formatter: Intl.DateTimeFormat,
|
||||
timeZone: string,
|
||||
): string {
|
||||
const elapsed = previous === undefined
|
||||
? 'unavailable (no earlier message in this session)'
|
||||
: formatDuration(now - previous)
|
||||
return `Current time: ${formatTimestamp(now, formatter, timeZone)}\nTime since previous message: ${elapsed}.`
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the dynamic temporal system-prompt section.
|
||||
* @param ctx - plugin context; the section registration is disposed with it.
|
||||
* @param config - validated time zone and intra-turn refresh interval.
|
||||
*/
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
const timeZone = config.timeZone as string
|
||||
const refreshIntervalMs = config.refreshIntervalMs as number
|
||||
if (!Number.isSafeInteger(refreshIntervalMs) || refreshIntervalMs < 0) {
|
||||
throw new Error(`time-context: refreshIntervalMs must be a non-negative safe integer, got ${refreshIntervalMs}`)
|
||||
}
|
||||
|
||||
let formatter: Intl.DateTimeFormat
|
||||
try {
|
||||
formatter = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone,
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hourCycle: 'h23',
|
||||
timeZoneName: 'longOffset',
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
throw new Error(`time-context: invalid IANA timeZone ${JSON.stringify(timeZone)}`, { cause: error })
|
||||
}
|
||||
const resolvedTimeZone = formatter.resolvedOptions().timeZone
|
||||
const states = new WeakMap<Agent, RenderState>()
|
||||
|
||||
ctx.systemPrompt.section({
|
||||
name: 'context:time',
|
||||
order: 10,
|
||||
text(context: AssembleContext): string {
|
||||
const agent = context.agent
|
||||
if (agent === undefined) return ''
|
||||
const currentTurn = openTurn(agent)
|
||||
if (currentTurn === undefined) return ''
|
||||
|
||||
const now = Date.now()
|
||||
const prior = states.get(agent)
|
||||
if (prior !== undefined
|
||||
&& prior.turn === currentTurn.turn
|
||||
&& now >= prior.renderedAt
|
||||
&& now - prior.renderedAt < refreshIntervalMs) {
|
||||
return prior.text
|
||||
}
|
||||
|
||||
const previous = prior?.turn === currentTurn.turn
|
||||
? prior.previousMessageTime
|
||||
: previousMessageTime(agent, currentTurn.startSeq)
|
||||
const text = renderText(now, previous, formatter, resolvedTimeZone)
|
||||
states.set(agent, { turn: currentTurn.turn, renderedAt: now, previousMessageTime: previous, text })
|
||||
return text
|
||||
},
|
||||
})
|
||||
}
|
||||
354
packages/context/time-context/tests/time-context.spec.ts
Normal file
354
packages/context/time-context/tests/time-context.spec.ts
Normal file
@@ -0,0 +1,354 @@
|
||||
/** Unit, loop-integration, lifecycle, and real-Loader coverage for dsh-time-context. */
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import Loader from '@cordisjs/plugin-loader'
|
||||
import LlmService, { CallId, LlmAdapter } from '@deepseek-ai/dsh-llm'
|
||||
import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
|
||||
import SessionStore, { Session, SessionId, foldRequestHeader } from '@deepseek-ai/dsh-session'
|
||||
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
||||
import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
|
||||
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
|
||||
import * as timeContext from '@deepseek-ai/dsh-time-context'
|
||||
import type { Config } from '@deepseek-ai/dsh-time-context'
|
||||
|
||||
const BASE = Date.parse('2026-07-14T00:00:00.000Z')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(BASE)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
/** Mount the system-prompt service and the optional plugin. */
|
||||
async function mount(config: Config = {}) {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SystemPrompt)
|
||||
const fiber = await ctx.plugin(timeContext, config)
|
||||
return { ctx, fiber }
|
||||
}
|
||||
|
||||
/** Minimal agent-shaped holder over a real append-only Session. */
|
||||
function sessionAgent(session: Session, id = 'agent'): Agent {
|
||||
return { id: AgentId(id), session } as unknown as Agent
|
||||
}
|
||||
|
||||
/** Resolve only this plugin's assembled section text. */
|
||||
async function sectionText(ctx: Context, agent?: Agent): Promise<string | undefined> {
|
||||
const assembly = await ctx.systemPrompt.assemble(agent === undefined ? {} : { agent })
|
||||
return assembly.sections.find(section => section.name === 'context:time')?.text
|
||||
}
|
||||
|
||||
/** Append the prompt side of an open message turn. */
|
||||
function openMessageTurn(session: Session, turn: number): void {
|
||||
session.append('turn/start', { turn, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
session.append('user/message', {
|
||||
content: [{ type: 'text', text: `turn ${turn}` }],
|
||||
source: { kind: 'user' },
|
||||
}, { surfaceOp: 'append' })
|
||||
}
|
||||
|
||||
/** Script helper for a text-only model response. */
|
||||
function textResponse(text: string): StreamChunk[] {
|
||||
return [
|
||||
{ type: 'block-start', index: 0, blockType: 'text' },
|
||||
{ type: 'block-end', index: 0, block: { type: 'text', text } },
|
||||
{ type: 'finish', reason: { kind: 'stop' } },
|
||||
]
|
||||
}
|
||||
|
||||
/** Script helper for one tool-call response. */
|
||||
function toolCallResponse(): StreamChunk[] {
|
||||
return [
|
||||
{ type: 'block-start', index: 0, blockType: 'tool-call' },
|
||||
{
|
||||
type: 'block-end',
|
||||
index: 0,
|
||||
block: { type: 'tool-call', id: CallId('tick-1'), name: 'tick', arguments: '{}' },
|
||||
},
|
||||
{ type: 'finish', reason: { kind: 'tool-calls' } },
|
||||
]
|
||||
}
|
||||
|
||||
/** Deterministic adapter that records each request and consumes one chunk script. */
|
||||
class ScriptedAdapter extends LlmAdapter {
|
||||
readonly requests: GenerateOptions[] = []
|
||||
|
||||
constructor(private readonly script: StreamChunk[][]) {
|
||||
super()
|
||||
}
|
||||
|
||||
override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
|
||||
this.requests.push(options)
|
||||
const chunks = this.script.shift()
|
||||
if (chunks === undefined) throw new Error('ScriptedAdapter: script exhausted')
|
||||
for (const chunk of chunks) yield chunk
|
||||
}
|
||||
}
|
||||
|
||||
/** Mount the real loop spine plus this optional plugin. */
|
||||
async function loopHarness(adapter: ScriptedAdapter, config: Config = {}): Promise<Context> {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(LlmService)
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SystemPrompt)
|
||||
await ctx.plugin(ToolRegistry)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
await ctx.plugin(AgentLoop, { agents: [] })
|
||||
await ctx.plugin(timeContext, config)
|
||||
ctx.llm.registerAdapter(['mock'], adapter)
|
||||
return ctx
|
||||
}
|
||||
|
||||
describe('temporal section rendering', () => {
|
||||
it('renders the first turn in UTC with the explicit no-previous-message fallback', async () => {
|
||||
const { ctx } = await mount()
|
||||
const session = new Session(SessionId('first'))
|
||||
openMessageTurn(session, 1)
|
||||
|
||||
expect(await sectionText(ctx, sessionAgent(session))).toBe(
|
||||
'Current time: 2026-07-14T00:00:00+00:00[UTC]\n'
|
||||
+ 'Time since previous message: unavailable (no earlier message in this session).',
|
||||
)
|
||||
})
|
||||
|
||||
it('renders a non-UTC numeric offset and all compact duration units', async () => {
|
||||
const { ctx } = await mount({ timeZone: 'Asia/Shanghai' })
|
||||
const session = new Session(SessionId('offset'))
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
session.append('assistant/message', {
|
||||
turn: 1,
|
||||
step: 1,
|
||||
content: [{ type: 'text', text: 'previous' }],
|
||||
}, { surfaceOp: 'append' })
|
||||
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
vi.setSystemTime(BASE + 90_061_000)
|
||||
openMessageTurn(session, 2)
|
||||
|
||||
expect(await sectionText(ctx, sessionAgent(session))).toBe(
|
||||
'Current time: 2026-07-15T09:01:01+08:00[Asia/Shanghai]\n'
|
||||
+ 'Time since previous message: 1d 1h 1m 1s.',
|
||||
)
|
||||
})
|
||||
|
||||
it('clamps a backward wall-clock adjustment to a zero duration', async () => {
|
||||
const { ctx } = await mount()
|
||||
const session = new Session(SessionId('backward-duration'))
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
session.append('assistant/message', {
|
||||
turn: 1,
|
||||
step: 1,
|
||||
content: [{ type: 'text', text: 'future by adjusted clock' }],
|
||||
}, { surfaceOp: 'append' })
|
||||
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
vi.setSystemTime(BASE - 5_000)
|
||||
openMessageTurn(session, 2)
|
||||
|
||||
expect(await sectionText(ctx, sessionAgent(session))).toContain('Time since previous message: 0s.')
|
||||
})
|
||||
|
||||
const previousMessageCases = [
|
||||
['user/message', (session: Session): void => {
|
||||
session.append('user/message', { content: [{ type: 'text', text: 'u' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
|
||||
}],
|
||||
['assistant/message', (session: Session): void => {
|
||||
session.append('assistant/message', { turn: 1, step: 1, content: [{ type: 'text', text: 'a' }] }, { surfaceOp: 'append' })
|
||||
}],
|
||||
['tool/result', (session: Session): void => {
|
||||
session.append('tool/result', {
|
||||
turn: 1,
|
||||
step: 1,
|
||||
callId: CallId('previous'),
|
||||
content: [{ type: 'text', text: 'r' }],
|
||||
isError: false,
|
||||
}, { surfaceOp: 'append' })
|
||||
}],
|
||||
['context/message', (session: Session): void => {
|
||||
session.append('context/message', {
|
||||
content: [{ type: 'text', text: 'c' }],
|
||||
source: { kind: 'plugin', plugin: 'test' },
|
||||
}, { surfaceOp: 'append' })
|
||||
}],
|
||||
['steering/message', (session: Session): void => {
|
||||
session.append('steering/message', {
|
||||
turn: 1,
|
||||
content: [{ type: 'text', text: 's' }],
|
||||
source: { kind: 'user' },
|
||||
}, { surfaceOp: 'append' })
|
||||
}],
|
||||
] as const
|
||||
|
||||
it.each(previousMessageCases)('uses a prior %s as the duration baseline', async (_name, appendPrevious) => {
|
||||
const { ctx } = await mount()
|
||||
const session = new Session(SessionId(`previous-${_name}`))
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
appendPrevious(session)
|
||||
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
vi.setSystemTime(BASE + 5_000)
|
||||
openMessageTurn(session, 2)
|
||||
|
||||
expect(await sectionText(ctx, sessionAgent(session))).toContain('Time since previous message: 5s.')
|
||||
})
|
||||
|
||||
it('contributes empty text without an active agent turn', async () => {
|
||||
const { ctx } = await mount()
|
||||
expect(await sectionText(ctx)).toBe('')
|
||||
|
||||
const empty = sessionAgent(new Session(SessionId('empty')))
|
||||
expect(await sectionText(ctx, empty)).toBe('')
|
||||
|
||||
const closedSession = new Session(SessionId('closed'))
|
||||
openMessageTurn(closedSession, 1)
|
||||
closedSession.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
expect(await sectionText(ctx, sessionAgent(closedSession))).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('refresh policy', () => {
|
||||
it('reuses within the interval, refreshes at expiry, and refreshes after a backward clock jump', async () => {
|
||||
const { ctx } = await mount({ refreshIntervalMs: 60_000 })
|
||||
const session = new Session(SessionId('interval'))
|
||||
const agent = sessionAgent(session)
|
||||
openMessageTurn(session, 1)
|
||||
|
||||
const first = await sectionText(ctx, agent)
|
||||
vi.setSystemTime(BASE + 30_000)
|
||||
expect(await sectionText(ctx, agent)).toBe(first)
|
||||
vi.setSystemTime(BASE + 60_000)
|
||||
const expired = await sectionText(ctx, agent)
|
||||
expect(expired).toContain('2026-07-14T00:01:00+00:00[UTC]')
|
||||
vi.setSystemTime(BASE + 59_000)
|
||||
expect(await sectionText(ctx, agent)).toContain('2026-07-14T00:00:59+00:00[UTC]')
|
||||
})
|
||||
|
||||
it('refreshes every assembly when refreshIntervalMs is zero', async () => {
|
||||
const { ctx } = await mount({ refreshIntervalMs: 0 })
|
||||
const session = new Session(SessionId('every-step'))
|
||||
const agent = sessionAgent(session)
|
||||
openMessageTurn(session, 1)
|
||||
const first = await sectionText(ctx, agent)
|
||||
vi.setSystemTime(BASE + 1_000)
|
||||
expect(await sectionText(ctx, agent)).not.toBe(first)
|
||||
})
|
||||
|
||||
it('always refreshes for a new turn and keeps the preceding message baseline', async () => {
|
||||
const { ctx } = await mount({ refreshIntervalMs: 60_000 })
|
||||
const session = new Session(SessionId('turn-refresh'))
|
||||
const agent = sessionAgent(session)
|
||||
openMessageTurn(session, 1)
|
||||
const first = await sectionText(ctx, agent)
|
||||
vi.setSystemTime(BASE + 1_000)
|
||||
session.append('assistant/message', {
|
||||
turn: 1,
|
||||
step: 1,
|
||||
content: [{ type: 'text', text: 'done' }],
|
||||
}, { surfaceOp: 'append' })
|
||||
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
vi.setSystemTime(BASE + 2_000)
|
||||
openMessageTurn(session, 2)
|
||||
|
||||
const second = await sectionText(ctx, agent)
|
||||
expect(second).not.toBe(first)
|
||||
expect(second).toContain('Time since previous message: 1s.')
|
||||
})
|
||||
|
||||
it('keeps refresh caches independent per agent', async () => {
|
||||
const { ctx } = await mount({ refreshIntervalMs: 60_000 })
|
||||
const sessionA = new Session(SessionId('agent-a'))
|
||||
const sessionB = new Session(SessionId('agent-b'))
|
||||
const agentA = sessionAgent(sessionA, 'a')
|
||||
const agentB = sessionAgent(sessionB, 'b')
|
||||
openMessageTurn(sessionA, 1)
|
||||
openMessageTurn(sessionB, 1)
|
||||
const aFirst = await sectionText(ctx, agentA)
|
||||
vi.setSystemTime(BASE + 30_000)
|
||||
const bFirst = await sectionText(ctx, agentB)
|
||||
vi.setSystemTime(BASE + 40_000)
|
||||
|
||||
expect(await sectionText(ctx, agentA)).toBe(aFirst)
|
||||
expect(bFirst).toContain('2026-07-14T00:00:30+00:00[UTC]')
|
||||
})
|
||||
})
|
||||
|
||||
describe('configuration and lifecycle', () => {
|
||||
it('fails loud for negative, fractional, unsafe, and invalid-zone config', async () => {
|
||||
for (const refreshIntervalMs of [-1, 1.5, Number.MAX_SAFE_INTEGER + 1]) {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SystemPrompt)
|
||||
await expect(ctx.plugin(timeContext, { refreshIntervalMs })).rejects.toThrow(/non-negative safe integer/)
|
||||
}
|
||||
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SystemPrompt)
|
||||
await expect(ctx.plugin(timeContext, { timeZone: 'Not/A_Real_Zone' })).rejects.toThrow(/invalid IANA timeZone/)
|
||||
})
|
||||
|
||||
it('removes its section when the plugin fiber disposes', async () => {
|
||||
const { ctx, fiber } = await mount()
|
||||
const session = new Session(SessionId('dispose'))
|
||||
const agent = sessionAgent(session)
|
||||
openMessageTurn(session, 1)
|
||||
expect(await sectionText(ctx, agent)).toContain('Current time:')
|
||||
|
||||
await fiber.dispose()
|
||||
expect(await sectionText(ctx, agent)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('real agent-loop request logging', () => {
|
||||
it('refreshes a long turn in the system prompt and records the header delta without context history', async () => {
|
||||
const adapter = new ScriptedAdapter([toolCallResponse(), textResponse('done'), textResponse('next turn')])
|
||||
const ctx = await loopHarness(adapter, { refreshIntervalMs: 60_000 })
|
||||
ctx.tools.register(defineTool({
|
||||
name: 'tick',
|
||||
description: 'advance fake time',
|
||||
parameters: {},
|
||||
async execute() {
|
||||
vi.setSystemTime(BASE + 61_000)
|
||||
return [{ type: 'text' as const, text: 'advanced' }]
|
||||
},
|
||||
}))
|
||||
const agent = ctx.agentLoop.create(AgentId('loop'), { model: 'mock' })
|
||||
|
||||
agent.send([{ type: 'text', text: 'start' }])
|
||||
await agent.whenIdle()
|
||||
expect(adapter.requests).toHaveLength(2)
|
||||
expect(adapter.requests[0]!.system).toContain('2026-07-14T00:00:00+00:00[UTC]')
|
||||
expect(adapter.requests[1]!.system).toContain('2026-07-14T00:01:01+00:00[UTC]')
|
||||
expect(agent.session.events.some(event => event.type === 'context/message')).toBe(false)
|
||||
expect(agent.session.events.filter(event => event.type === 'request/header-delta')).toHaveLength(1)
|
||||
expect(foldRequestHeader(agent.session.events)?.system).toBe(adapter.requests[1]!.system)
|
||||
|
||||
vi.setSystemTime(BASE + 361_000)
|
||||
agent.send([{ type: 'text', text: 'again' }])
|
||||
await agent.whenIdle()
|
||||
expect(adapter.requests[2]!.system).toContain('Time since previous message: 5m 0s.')
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('real Loader export path', () => {
|
||||
it('keeps the namespace metadata and boots through unwrapExports', async () => {
|
||||
expect('default' in timeContext).toBe(false)
|
||||
const loader = Object.create(Loader.prototype) as Loader
|
||||
const unwrapped = loader.unwrapExports(timeContext) as Record<string, unknown>
|
||||
expect(unwrapped).toBe(timeContext)
|
||||
expect(unwrapped.name).toBe('time-context')
|
||||
expect(unwrapped.inject).toEqual(['systemPrompt'])
|
||||
expect(unwrapped.Config).toBeDefined()
|
||||
expect(typeof unwrapped.apply).toBe('function')
|
||||
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SystemPrompt)
|
||||
const plugin = loader.unwrapExports(timeContext) as Parameters<Context['plugin']>[0]
|
||||
await ctx.plugin(plugin)
|
||||
const session = new Session(SessionId('loader'))
|
||||
openMessageTurn(session, 1)
|
||||
expect(await sectionText(ctx, sessionAgent(session))).toContain('Current time:')
|
||||
})
|
||||
})
|
||||
15
packages/context/time-context/tsconfig.json
Normal file
15
packages/context/time-context/tsconfig.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types"
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [
|
||||
{ "path": "../../../vendor/cosmokit" },
|
||||
{ "path": "../../../vendor/cordis" },
|
||||
{ "path": "../../../vendor/schemastery" },
|
||||
{ "path": "../../core/system-prompt" },
|
||||
{ "path": "../../core/agent" }
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user