diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 650fe16d23..69fad2238e 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -787,7 +787,7 @@ Requires: `systemPrompt` ```ts config-catalog /** 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 diff --git a/docs/rfc/implemented/feature/2026-07-14-time-context-plugin.i18n.yaml b/docs/rfc/implemented/feature/2026-07-14-time-context-plugin.i18n.yaml index 10b441f03b..e70f8059f5 100644 --- a/docs/rfc/implemented/feature/2026-07-14-time-context-plugin.i18n.yaml +++ b/docs/rfc/implemented/feature/2026-07-14-time-context-plugin.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write -2026-07-14-time-context-plugin.md: 54ed3188c794eb088db47b653ea0e27db1c14ed8 -2026-07-14-time-context-plugin.zh.md: fa0de3c6460eb6ab508b53e1ca3acf99564b1926 +2026-07-14-time-context-plugin.md: 13e0eff4b9d286ee562d7a0a2c0a3a659126ba3b +2026-07-14-time-context-plugin.zh.md: 5ee50a4d49eb9a7e00a09f70b436e15d72612b1f diff --git a/docs/rfc/implemented/feature/2026-07-14-time-context-plugin.md b/docs/rfc/implemented/feature/2026-07-14-time-context-plugin.md index 54ed3188c7..13e0eff4b9 100644 --- a/docs/rfc/implemented/feature/2026-07-14-time-context-plugin.md +++ b/docs/rfc/implemented/feature/2026-07-14-time-context-plugin.md @@ -26,7 +26,7 @@ The baseline is the session event's append time, not an unlogged client timestam `refreshIntervalMs` defaults to 60,000 and must be a non-negative safe integer. Every turn's first request refreshes. Later assemblies in that turn reuse the block until its age reaches the interval; `0` refreshes every step. No timer creates work during model calls, tools, or idle time because refresh is request-bound. -`timeZone` defaults to `UTC` and is validated as an IANA identifier at plugin load. The ISO-shaped local timestamp includes the resolved zone and current numeric offset, making daylight-saving changes explicit. +When `timeZone` is omitted, `Intl.DateTimeFormat` 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 value must be an IANA identifier and is validated at load. The captured zone remains stable until plugin reload, and the ISO-shaped local timestamp includes its current numeric offset so daylight-saving changes stay explicit. This is the deployment process's zone, not a remote user's zone. ### Logging and token shape @@ -34,7 +34,7 @@ The loop records the temporal block through `request/header` and `request/header ## Testing -Unit tests pin formatting, baselines, refresh policy, validation, per-agent state, and disposal. A real agent-loop test pins the transmitted prompt and `request/header-delta`; a Loader test pins the named-export path. Default snapshot compositions omit the plugin, so their transcript fixtures contain no temporal block. +Unit tests pin formatting, baselines, refresh policy, validation, per-agent state, disposal, and load-time system-zone capture. A real agent-loop test pins the transmitted prompt and `request/header-delta`. A keyless subprocess e2e boots a test-only `cordis.yml` through the real Loader and stdio app, omits `timeZone` under a controlled `TZ`, drives two turns, and verifies the persisted request headers externally. Default snapshot compositions omit the plugin, so their transcript fixtures contain no temporal block. ## Alternatives considered @@ -43,12 +43,15 @@ Unit tests pin formatting, baselines, refresh policy, validation, per-agent stat - **Mutate requests in `agent/request`** — rejected because that seam shapes call config after the message boundary; inserted model content would bypass prompt-pressure accounting and request-header logging. - **Register separate `{{current_time}}` and `{{elapsed}}` variables** — rejected because independent providers can sample different instants and require shared caching. One section records the pair atomically without a deployment-authored template. - **Refresh from a background timer** — rejected because a new value has no consumer outside request assembly. Timer-driven `agent.inject()` would create turns and wake idle sessions merely to report time passing. +- **Keep UTC as the omitted default** — rejected because an explicitly enabled clock should follow its deployment environment unless the operator chooses UTC. `timeZone: UTC` remains available when a deployment requires it. +- **Add a time-zone detection library** — rejected because Node's `Intl` runtime already exposes the process's IANA zone. Another dependency cannot infer a remote user's zone either. - **Mount the plugin in `dsh-agent-core`** — rejected because time zone, disclosure, token budget, and freshness are deployment policy. Opt-in keeps default context stable. - **Place the package in `core/`** — rejected because `core/` owns the product API spine, while this plugin is an optional leaf with no service key. ## Consequences - Opted-in models receive a zoned clock and inter-turn duration without a tool call. The system-prompt cost is fixed per request instead of growing with the session. +- An omitted `timeZone` follows the process's `TZ`, host, or container zone as observed at plugin load. Operators must configure an explicit zone when the deployment environment does not represent the intended user. - A refresh changes the request header and can add a `request/header-delta`. `refreshIntervalMs` trades freshness against durable deltas; `0` records a new value on every step whose whole-second rendering changes. - No request exists solely to refresh time. A long-running tool leaves the prior reading until the next step assembles. - Duration reflects harness processing time at durable append boundaries, not client-network latency before logging. Preserving a client-origin timestamp requires a separate durable input contract. diff --git a/docs/rfc/implemented/feature/2026-07-14-time-context-plugin.zh.md b/docs/rfc/implemented/feature/2026-07-14-time-context-plugin.zh.md index fa0de3c646..5ee50a4d49 100644 --- a/docs/rfc/implemented/feature/2026-07-14-time-context-plugin.zh.md +++ b/docs/rfc/implemented/feature/2026-07-14-time-context-plugin.zh.md @@ -26,7 +26,7 @@ Status: implemented `refreshIntervalMs` 默认值为 60,000,并且必须是非负安全整数。每个轮次的首次请求都会刷新。同一轮次中的后续组装会复用该区块,直至其存在时间达到该间隔;设为 `0` 时每个步骤都刷新。刷新仅由请求驱动,因此在模型调用、工具运行或空闲期间,计时器不会创建任务。 -`timeZone` 默认为 `UTC`,插件加载时会校验它是否为 IANA 标识符。形似 ISO 的本地时间戳包含已解析的时区及其当前数字偏移,使夏令时变化保持显式可见。 +省略 `timeZone` 时,`Intl.DateTimeFormat` 会在插件加载时解析一次 Node 进程的系统时区。Node 会遵循 `TZ`;没有该覆盖值时,时区由主机或容器提供。显式值必须是 IANA 标识符,并在加载时接受校验。捕获的时区在插件重新加载前保持稳定,形似 ISO 的本地时间戳包含其当前数字偏移,使夏令时变化保持显式可见。该默认值代表部署进程的时区,而不是远程用户的时区。 ### 日志与 token 形态 @@ -34,7 +34,7 @@ agent loop(智能体循环)会在发送前通过 `request/header` 和 `reque ## 测试 -单元测试固定格式化、基线、刷新策略、校验、逐 agent 状态和资源释放行为。使用真实 agent loop 的测试固定实际发送的提示词和 `request/header-delta`;Loader 测试固定命名导出路径。默认快照组合不包含该插件,因此其中的 transcript(文本记录)fixture(测试前置数据)不包含时间区块。 +单元测试固定格式化、基线、刷新策略、校验、逐 agent 状态、资源释放行为,以及系统时区在加载时的捕获行为。使用真实 agent loop 的测试固定实际发送的提示词和 `request/header-delta`。无密钥子进程端到端测试通过真实 Loader 和 stdio 应用启动测试专用 `cordis.yml`,在受控 `TZ` 下省略 `timeZone`,驱动两个轮次,并从外部校验持久请求头。默认快照组合不包含该插件,因此其中的 transcript(文本记录)fixture(测试前置数据)不包含时间区块。 ## 考虑过的替代方案 @@ -43,12 +43,15 @@ agent loop(智能体循环)会在发送前通过 `request/header` 和 `reque - **在 `agent/request` 中修改请求**——不予采纳,因为该边界在消息边界之后塑造调用配置;插入模型可见内容会绕过提示词压力核算和请求头日志。 - **注册独立的 `{{current_time}}` 和 `{{elapsed}}` 变量**——不予采纳,因为独立提供方可能在不同时间点采样,并且需要共享缓存。单个区段会以原子方式记录两项信息,也不需要部署方编写时间模板。 - **通过后台计时器刷新**——不予采纳,因为请求组装之外没有消费新值的对象。由计时器驱动 `agent.inject()` 会创建轮次,并且只为报告时间流逝就唤醒空闲会话。 +- **省略配置时仍默认使用 UTC**——不予采纳,因为显式启用的时钟应跟随部署环境,除非运维方选择 UTC。需要 UTC 的部署仍可配置 `timeZone: UTC`。 +- **引入时区探测库**——不予采纳,因为 Node 的 `Intl` 运行时已经能够提供进程的 IANA 时区,而且额外依赖同样无法推断远程用户的时区。 - **在 `dsh-agent-core` 中挂载插件**——不予采纳,因为时区、信息披露、token 预算和新鲜度都属于部署策略。选择加入能保持默认上下文稳定。 - **将 package 放入 `core/`**——不予采纳,因为 `core/` 负责产品 API 主干,而该插件是没有服务键的可选叶节点。 ## 后果 - 选择加入的模型无需调用工具,即可获得分区时钟和轮次间隔时长。每个请求的系统提示词成本固定,不会随会话增长。 +- 省略 `timeZone` 时,插件采用加载时观察到的进程 `TZ`、主机或容器时区。当部署环境不能代表目标用户时,运维方必须显式配置时区。 - 刷新会改变请求头,并可能新增 `request/header-delta`。`refreshIntervalMs` 用新鲜度换取持久增量记录的数量;设为 `0` 时,每个整秒渲染结果发生变化的步骤都会记录新值。 - 系统不会仅为刷新时间而创建请求。长时间运行的工具会保留先前读数,直至下一步骤开始组装。 - 时长反映持久追加边界处的 harness 处理时间,不包含消息进入日志之前的客户端网络延迟。若要保留客户端来源时间戳,需要单独的持久输入契约。 diff --git a/docs/testing.md b/docs/testing.md index 2a571d6015..d4acdc33c4 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -23,7 +23,7 @@ An e2e assertion re-runs the command or re-reads the file externally; a keyword ## Test the real entry path -- A plugin shipped via `cordis.yml` needs at least one test through the REAL Loader path: hand-built `ctx.plugin({...})` mounts bypass `unwrapExports` and cannot catch a broken export shape ([postmortem 0001](postmortem/0001-acp-default-export-drops-inject.md); export-shape rules in [packages/AGENTS.md](../packages/AGENTS.md)). +- Product-visible plugins require a non-unit REAL-composition test. Hand-built `ctx.plugin(...)` suites are insufficient: boot test-only `cordis.yml` through Loader and app/process, mock only external/nondeterministic boundaries, and assert model-visible request/log, durable state, or user-visible output. Keep opt-ins out of shipped defaults. - A guard only guards if the regression actually fails it. For a plugin without `inject` (bundle/composition plugins), a Loader smoke stays green under a broken export shape — add an explicit `expect('default' in mod).toBe(false)` plus an `unwrapExports` round-trip assertion, and prove it: introduce the regression, watch red, revert. - "Real entry path" means the published artifact: the package `bin` points at built `lib/bin.js` under plain `node`, which tsx masks (settle races, module resolution, a swallowed load failure exiting 0). The same applies to any non-index runtime entry the built package resolves at run time (the worker-thread runtime's sibling `lib/worker.cjs`). Keep the built-artifact smokes green (`packages/ui/*/tests/built-bin.e2e.ts`, `packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts`), and assert a genuinely-missing config exits non-zero. - An e2e that spawns an example from a temp cwd sets `TSX_TSCONFIG_PATH` to the repo-root tsconfig, or it silently falls back to stale built `lib/` ([examples/AGENTS.md](../examples/AGENTS.md)). diff --git a/knip.json b/knip.json index 825980f205..5b8fc7f436 100644 --- a/knip.json +++ b/knip.json @@ -23,6 +23,10 @@ "entry": ["tests/**/*.spec.ts", "tests/**/*.e2e.ts"], "project": ["src/**/*.ts", "tests/**/*.ts"] }, + "packages/context/time-context": { + "entry": ["tests/**/*.spec.ts", "tests/**/*.e2e.ts"], + "project": ["src/**/*.ts", "tests/**/*.ts"] + }, "packages/sandbox/sandbox-local": { "entry": ["tests/**/*.spec.ts", "tests/**/*.e2e.ts"], "project": ["src/**/*.ts", "tests/**/*.ts"] diff --git a/packages/AGENTS.md b/packages/AGENTS.md index 1f92a850a9..766a188105 100644 --- a/packages/AGENTS.md +++ b/packages/AGENTS.md @@ -4,7 +4,7 @@ These package-specific rules supplement the repo-wide [conventions](../AGENTS.md - **Plugin export shape:** service packages default-export their service class; function plugins named-export `name` / `inject` / `Config` / `apply` and have no default export. Mixing the forms makes the Loader discard the function plugin's namespace ([postmortem](../docs/postmortem/0001-acp-default-export-drops-inject.md)). - **Optional services use `ctx.get(name)`.** Reserve `ctx.` for declared injections; the property proxy is topology-sensitive, while strict `ctx.get` reads the global service store ([postmortem](../docs/postmortem/0001-acp-default-export-drops-inject.md)). -- **A plugin shipped via `cordis.yml` needs at least one test through the REAL Loader/export path** — hand-built `ctx.plugin({...})` mounts bypass `unwrapExports` and cannot catch a broken export shape. Full testing policy (tiers, with-key generosity, real-entry-path guards): [docs/testing.md](../docs/testing.md). +- **Product-visible plugins require a non-unit REAL-composition test.** Hand-built `ctx.plugin(...)` suites are insufficient. Boot test-only `cordis.yml` through the Loader and app/process; mock only external/nondeterministic boundaries and assert model-visible, durable, or user-visible output. Keep opt-ins out of shipped defaults. [Policy](../docs/testing.md). - **Typed same-process service and plugin calls are contracts, not serialization boundaries.** Prefer readonly borrowed values; materialize or defensively validate only at parser/config, queued, model/tool JSON, durable/file, worker, process, or wire boundaries. - **Represent one asynchronous operation with one lifecycle controller or transaction.** Separate readiness, cancellation, disposal, reservation, or sentinel state requires an independent owner or settlement boundary; otherwise fold it while preserving rollback, callback containment, and quiescence. diff --git a/packages/context/time-context/README.md b/packages/context/time-context/README.md index 445101f4f6..b50470aef7 100644 --- a/packages/context/time-context/README.md +++ b/packages/context/time-context/README.md @@ -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: . - **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. diff --git a/packages/context/time-context/src/index.ts b/packages/context/time-context/src/index.ts index 7b087bc4de..cccd433811 100644 --- a/packages/context/time-context/src/index.ts +++ b/packages/context/time-context/src/index.ts @@ -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 = 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() diff --git a/packages/context/time-context/tests/fixtures/cordis.yml b/packages/context/time-context/tests/fixtures/cordis.yml new file mode 100644 index 0000000000..e9558abec6 --- /dev/null +++ b/packages/context/time-context/tests/fixtures/cordis.yml @@ -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' diff --git a/packages/context/time-context/tests/time-context.e2e.ts b/packages/context/time-context/tests/time-context.e2e.ts new file mode 100644 index 0000000000..daa6e9a9b8 --- /dev/null +++ b/packages/context/time-context/tests/time-context.e2e.ts @@ -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 " 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 { + 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) +}) diff --git a/packages/context/time-context/tests/time-context.spec.ts b/packages/context/time-context/tests/time-context.spec.ts index 8cf9e71f53..562b002b68 100644 --- a/packages/context/time-context/tests/time-context.spec.ts +++ b/packages/context/time-context/tests/time-context.spec.ts @@ -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'))