fix: default time context to system zone

This commit is contained in:
Tianyi Cui
2026-07-14 21:45:54 +08:00
parent d9d9487e0e
commit 528f9cba62
12 changed files with 189 additions and 16 deletions

View File

@@ -8,11 +8,11 @@ Opt-in dynamic system-prompt context with the current zoned time and elapsed tim
- id: time-context
name: '@deepseek-ai/dsh-time-context'
config:
timeZone: UTC # default; any IANA time-zone identifier
timeZone: Asia/Shanghai # optional IANA override; omit for the process zone
refreshIntervalMs: 60000 # default; 0 refreshes on every step
```
`timeZone` is validated at plugin load. `refreshIntervalMs` must be a non-negative safe integer. Every turn's first request refreshes; later steps reuse the reading until its age reaches the interval. `0` refreshes every step. Refresh occurs only during request assembly and creates no timer work.
When `timeZone` is omitted, the plugin resolves the Node process's system zone once at plugin load. Node honors `TZ`; without that override, the host or container supplies the zone. An explicit `timeZone` must be an IANA identifier and is validated at plugin load. `refreshIntervalMs` must be a non-negative safe integer. Every turn's first request refreshes; later steps reuse the reading until its age reaches the interval. `0` refreshes every step. Refresh occurs only during request assembly and creates no timer work.
## Message baseline
@@ -40,3 +40,4 @@ Time since previous message: <duration-or-unavailable>.
- **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.
- **Process-local default zone** — omission uses the Node process's `TZ`, host, or container zone captured at plugin load, not a remote user's zone; configure an explicit IANA zone when those differ.

View File

@@ -20,7 +20,7 @@ export const inject = ['systemPrompt']
/** Request-time clock formatting and refresh policy. Invalid values fail plugin load. */
export interface Config {
/** IANA time zone used for the rendered timestamp (default `UTC`). */
/** IANA time zone used for the rendered timestamp. Omit to resolve the Node process's system zone at plugin load. */
timeZone?: string
/** Maximum age of a reading within one turn, in milliseconds (default 60,000; `0` refreshes every step). */
refreshIntervalMs?: number
@@ -28,7 +28,7 @@ export interface Config {
/** Schemastery validation and defaults for {@link Config}. */
export const Config: z<Config> = z.object({
timeZone: z.string().default('UTC'),
timeZone: z.string(),
refreshIntervalMs: z.number().default(60_000),
})
@@ -126,7 +126,7 @@ function renderText(
* @throws when the time zone or refresh interval is invalid.
*/
export function apply(ctx: Context, config: Config): void {
const timeZone = config.timeZone as string
const timeZone = config.timeZone
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}`)
@@ -135,7 +135,7 @@ export function apply(ctx: Context, config: Config): void {
let formatter: Intl.DateTimeFormat
try {
formatter = new Intl.DateTimeFormat('en-US', {
timeZone,
...(timeZone === undefined ? {} : { timeZone }),
year: 'numeric',
month: '2-digit',
day: '2-digit',
@@ -146,7 +146,10 @@ export function apply(ctx: Context, config: Config): void {
timeZoneName: 'longOffset',
})
} catch (error: unknown) {
throw new Error(`time-context: invalid IANA timeZone ${JSON.stringify(timeZone)}`, { cause: error })
const message = timeZone === undefined
? 'time-context: failed to resolve the system time zone'
: `time-context: invalid IANA timeZone ${JSON.stringify(timeZone)}`
throw new Error(message, { cause: error })
}
const resolvedTimeZone = formatter.resolvedOptions().timeZone
const states = new WeakMap<Agent, RenderState>()

View File

@@ -0,0 +1,17 @@
# Test-only composition: keep time-context opt-in while exercising its real Loader/app path.
- id: mock-llm
name: '../../../../../examples/echo-agent/src/mock-llm.ts'
- id: bash
name: '@deepseek-ai/dsh-bash-local'
- id: time-context
name: '@deepseek-ai/dsh-time-context'
- id: stdio-agent
name: '@deepseek-ai/dsh-stdio-agent'
config:
model: mock-echo
persona: 'Test the time-context plugin.'
welcome: 'time-context e2e ready.'
persistenceRoot: './.sessions'

View File

@@ -0,0 +1,115 @@
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
import { mkdtemp, readFile, readdir, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, describe, expect, it } from 'vitest'
import { foldRequestHeader, type SessionEvent } from '@deepseek-ai/dsh-session'
const binScript = fileURLToPath(new URL('../../../ui/stdio-agent/src/bin.ts', import.meta.url))
const configPath = fileURLToPath(new URL('./fixtures/cordis.yml', import.meta.url))
const repoTsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url))
const tsxLoader = fileURLToPath(import.meta.resolve('tsx'))
const PROCESS_TIMEOUT_MS = 30_000
const TEST_TIMEOUT_MS = PROCESS_TIMEOUT_MS + 15_000
const FIRST_REPLY = 'You said: "first". Try "echo <something>" to see a tool call.'
let child: ChildProcessWithoutNullStreams | undefined
let workdir: string | undefined
afterEach(async () => {
if (child !== undefined && child.exitCode === null) child.kill('SIGKILL')
child = undefined
if (workdir !== undefined) await rm(workdir, { recursive: true, force: true })
workdir = undefined
})
async function jsonlFiles(dir: string): Promise<string[]> {
const entries = await readdir(dir, { withFileTypes: true })
const paths = await Promise.all(entries.map(async (entry) => {
const path = join(dir, entry.name)
if (entry.isDirectory()) return jsonlFiles(path)
return entry.isFile() && entry.name.endsWith('.jsonl') ? [path] : []
}))
return paths.flat()
}
async function runTwoTurns(): Promise<{ stdout: string; stderr: string }> {
workdir = await mkdtemp(join(tmpdir(), 'time-context-e2e-'))
const cwd = workdir
return new Promise((resolve, reject) => {
const proc = spawn(
process.execPath,
['--expose-internals', '--import', tsxLoader, binScript, configPath],
{
cwd,
env: {
...process.env,
TZ: 'Asia/Shanghai',
TSX_TSCONFIG_PATH: repoTsconfig,
DSH_HOME: join(cwd, '.dsh'),
DSH_AGENTS_HOME: join(cwd, '.agents'),
},
stdio: ['pipe', 'pipe', 'pipe'],
},
)
child = proc
let stdout = ''
let stderr = ''
let sentSecond = false
proc.stdout.setEncoding('utf8')
proc.stdout.on('data', (chunk: string) => {
stdout += chunk
if (!sentSecond && stdout.includes(`${FIRST_REPLY}\n> `)) {
sentSecond = true
proc.stdin.end('second\n')
}
})
proc.stderr.setEncoding('utf8')
proc.stderr.on('data', (chunk: string) => { stderr += chunk })
const timer = setTimeout(() => {
proc.kill('SIGKILL')
reject(new Error(`time-context e2e did not exit within ${PROCESS_TIMEOUT_MS / 1_000}s. stdout:\n${stdout}\nstderr:\n${stderr}`))
}, PROCESS_TIMEOUT_MS)
proc.on('exit', (code) => {
clearTimeout(timer)
if (code === 0) resolve({ stdout, stderr })
else reject(new Error(`time-context e2e exited ${code}. stdout:\n${stdout}\nstderr:\n${stderr}`))
})
proc.on('error', (error) => { clearTimeout(timer); reject(error) })
proc.stdin.write('first\n')
})
}
describe('time-context through a real cordis.yml and stdio process', () => {
it('uses the process zone and persists both first-turn and elapsed-time request context', async () => {
const { stdout, stderr } = await runTwoTurns()
expect(stderr).not.toContain('UNHANDLED')
expect(stdout).toContain('time-context e2e ready.')
expect(stdout).toContain(FIRST_REPLY)
expect(stdout).toContain('You said: "second".')
const logs = await jsonlFiles(join(workdir as string, '.sessions'))
expect(logs).toHaveLength(1)
const lines = (await readFile(logs[0] as string, 'utf8')).trimEnd().split('\n')
const events = lines.slice(1).map(line => JSON.parse(line) as SessionEvent)
expect(events.filter(event => event.type === 'turn/end')).toHaveLength(2)
const firstHeader = events.find(event => event.type === 'request/header')
if (firstHeader?.type !== 'request/header') throw new Error('missing initial request/header event')
expect(firstHeader.data.header.system).toMatch(
/Current time: \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00\[Asia\/Shanghai\]/,
)
expect(firstHeader.data.header.system).toContain(
'Time since previous message: unavailable (no earlier message in this session).',
)
const finalSystem = foldRequestHeader(events)?.system
expect(finalSystem).toContain('[Asia/Shanghai]')
expect(finalSystem).toMatch(
/Time since previous message: (?:\d+d )?(?:\d+h )?(?:\d+m )?\d+s\./,
)
}, TEST_TIMEOUT_MS)
})

View File

@@ -13,14 +13,19 @@ 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')
const ORIGINAL_TIME_ZONE = process.env['TZ']
beforeEach(() => {
process.env['TZ'] = 'UTC'
vi.useFakeTimers()
vi.setSystemTime(BASE)
})
afterEach(() => {
vi.restoreAllMocks()
vi.useRealTimers()
if (ORIGINAL_TIME_ZONE === undefined) delete process.env['TZ']
else process.env['TZ'] = ORIGINAL_TIME_ZONE
})
async function mount(config: Config = {}) {
@@ -266,6 +271,18 @@ describe('refresh policy', () => {
})
describe('configuration and lifecycle', () => {
it('defaults to the process system zone and retains the zone resolved at plugin load', async () => {
process.env['TZ'] = 'Asia/Shanghai'
const { ctx } = await mount()
process.env['TZ'] = 'America/New_York'
const session = new Session(SessionId('system-zone'))
openMessageTurn(session, 1)
expect(await sectionText(ctx, sessionAgent(session))).toContain(
'Current time: 2026-07-14T08:00:00+08:00[Asia/Shanghai]',
)
})
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()
@@ -278,6 +295,16 @@ describe('configuration and lifecycle', () => {
await expect(ctx.plugin(timeContext, { timeZone: 'Not/A_Real_Zone' })).rejects.toThrow(/invalid IANA timeZone/)
})
it('fails loud when the process system zone cannot be resolved', async () => {
vi.spyOn(Intl, 'DateTimeFormat').mockImplementationOnce(() => {
throw new RangeError('system zone unavailable')
})
const ctx = new Context()
await ctx.plugin(SystemPrompt)
await expect(ctx.plugin(timeContext, {})).rejects.toThrow(/failed to resolve the system time zone/)
})
it('removes its section when the plugin fiber disposes', async () => {
const { ctx, fiber } = await mount()
const session = new Session(SessionId('dispose'))