refactor(schedule): make absolute times explicit

This commit is contained in:
Tianyi Cui
2026-08-09 16:30:11 +08:00
parent 3d6498e91b
commit b7ec8429a9
109 changed files with 1248 additions and 3219 deletions

View File

@@ -11,10 +11,7 @@ import type { HostFrame, MuxFrame, RpcMessage, RpcRequest } from '../src/client/
import { FixtureApiClient, createFixtureApi } from '../src/client/fixture.ts'
const sid = (id: string): SessionId => id as SessionId
const req = <P>(payload: P): RpcRequest<P> => ({
rpcId: RpcId(`t-${Math.abs(Math.sin(reqCount++)).toString(36).slice(2, 10)}`),
payload: { timeZone: 'UTC', clientTimeZone: 'UTC', ...payload },
})
const req = <P>(payload: P): RpcRequest<P> => ({ rpcId: RpcId(`t-${Math.abs(Math.sin(reqCount++)).toString(36).slice(2, 10)}`), payload })
let reqCount = 0
interface TimingHooks {
@@ -758,82 +755,6 @@ describe('createFixtureApi', () => {
})
})
it('mirrors canonical Session and message-bound client zone handling', async () => {
const api = createFixtureApi({ empty: true })
const sessionId = sid('fx-zone')
const alias = 'US/Eastern'
const canonical = new Intl.DateTimeFormat('en-US', { timeZone: alias })
.resolvedOptions().timeZone
await expect(api.sessions.create(req({ sessionId, timeZone: alias }))).resolves.toMatchObject({
result: { ok: true, value: { sessionId } },
})
await expect(api.sessions.create(req({ sessionId, timeZone: canonical }))).resolves.toMatchObject({
result: { ok: true, value: { sessionId } },
})
const conflict = await api.sessions.create(req({ sessionId, timeZone: 'Asia/Shanghai' }))
expect(conflict.result).toMatchObject({
ok: false,
error: {
code: 'session-conflict',
details: {
sessionId,
requestedTimeZone: 'Asia/Shanghai',
existingTimeZone: canonical,
},
},
})
const prompted = await api.sessions.prompt(req({
sessionId,
mode: 'queue',
content: [{ type: 'text', text: 'zone-bound' }],
clientTimeZone: alias,
}))
expect(prompted.result).toMatchObject({ ok: true })
const history = await api.sessions.history(req({ sessionId }))
if (!history.result.ok) throw new Error('fixture history failed')
const user = history.result.value.events.find(entry => entry.event.type === 'user/message')
expect(user?.event).toMatchObject({
type: 'user/message',
data: { source: { kind: 'user', clientTimeZone: canonical } },
})
})
it.each([
['timeZone', undefined],
['timeZone', 'CST'],
['timeZone', 'Not/A_Real_Zone'],
['clientTimeZone', undefined],
['clientTimeZone', 'CST'],
['clientTimeZone', 'Not/A_Real_Zone'],
] as const)('rejects invalid fixture %s input %j', async (field, value) => {
const api = createFixtureApi({ empty: true })
if (field === 'timeZone') {
const invalidRequest = req({})
Object.assign(invalidRequest.payload, { timeZone: value })
const created = await api.sessions.create(invalidRequest)
expect(created.result).toMatchObject({
ok: false,
error: { code: 'invalid-time-zone', details: { field, value: value ?? null } },
})
return
}
const created = await api.sessions.create(req({ timeZone: 'UTC' }))
if (!created.result.ok) throw new Error('fixture create failed')
const invalidRequest = req({
sessionId: created.result.value.sessionId,
mode: 'queue' as const,
content: [{ type: 'text' as const, text: 'rejected' }],
})
Object.assign(invalidRequest.payload, { clientTimeZone: value })
const prompted = await api.sessions.prompt(invalidRequest)
expect(prompted.result).toMatchObject({
ok: false,
error: { code: 'invalid-time-zone', details: { field, value: value ?? null } },
})
})
it('attaches an existing ungrouped Session to a matching Workspace', async () => {
const api = createFixtureApi()
const sessionId = sid('fx-existing-ungrouped')
@@ -865,12 +786,7 @@ describe('createFixtureApi', () => {
error: {
code: 'session-conflict',
message: `session ${existing.sessionId} already uses no cwd`,
details: {
sessionId: existing.sessionId,
requestedCwd: '/tmp/fixture',
requestedTimeZone: 'UTC',
existingTimeZone: 'UTC',
},
details: { sessionId: existing.sessionId, requestedCwd: '/tmp/fixture' },
},
})
})
@@ -1067,16 +983,11 @@ describe('FixtureApiClient (protocol-level fake carrier)', () => {
{ query: 'fixture' },
new AbortController().signal,
)).result.ok).toBe(true)
const created = await client.sessions.create({ timeZone: 'UTC' })
const created = await client.sessions.create({})
if (!created.result.ok) throw new Error('create failed')
const id = created.result.value.sessionId
expect((await client.sessions.history({ sessionId: id })).result.ok).toBe(true)
expect((await client.sessions.prompt({
sessionId: id,
mode: 'queue',
content: [{ type: 'text', text: '嗨' }],
clientTimeZone: 'UTC',
})).result.ok).toBe(true)
expect((await client.sessions.prompt({ sessionId: id, mode: 'queue', content: [{ type: 'text', text: '嗨' }] })).result.ok).toBe(true)
expect((await client.sessions.cancel({ sessionId: id })).result.ok).toBe(true)
expect((await client.host.describe({})).result.ok).toBe(true)
expect((await client.workspace.list({})).result.ok).toBe(true)
@@ -1087,7 +998,7 @@ describe('FixtureApiClient (protocol-level fake carrier)', () => {
const renamed = await client.workspace.rename({ workspaceId: wsid, title: 'via-client-2' })
if (!renamed.result.ok) throw new Error('workspace rename failed')
expect(renamed.result.value.workspace.title).toBe('via-client-2')
const attached = await client.sessions.create({ workspaceId: wsid, timeZone: 'UTC' })
const attached = await client.sessions.create({ workspaceId: wsid })
if (!attached.result.ok) throw new Error('attached create failed')
const moved = await client.workspace.insertSessionBefore({ workspaceId: wsid, sessionId: attached.result.value.sessionId })
if (!moved.result.ok) throw new Error('workspace move failed')
@@ -1147,7 +1058,6 @@ describe('FixtureApiClient (protocol-level fake carrier)', () => {
const created = await client.sessions.create({
workspaceId: made.result.value.workspace.workspaceId,
sessionId,
timeZone: 'UTC',
})
expect(created.result).toMatchObject({ ok: true, value: { sessionId } })
const frames = await framesPromise
@@ -1156,7 +1066,6 @@ describe('FixtureApiClient (protocol-level fake carrier)', () => {
sessionId,
mode: 'queue',
content: [{ type: 'text', text: 'retain' }],
clientTimeZone: 'UTC',
})
expect(rejected.result).toMatchObject({ ok: false, error: { code: 'agent-busy' } })
})
@@ -1167,7 +1076,6 @@ describe('FixtureApiClient (protocol-level fake carrier)', () => {
const partialResult = await partial.sessions.create({
workspaceId: 'fx-ws-fixture' as WorkspaceId,
sessionId: sid('fx-query-partial'),
timeZone: 'UTC',
})
expect(partialResult.result).toMatchObject({
ok: false,
@@ -1179,7 +1087,6 @@ describe('FixtureApiClient (protocol-level fake carrier)', () => {
await expect(dropped.sessions.create({
workspaceId: 'fx-ws-fixture' as WorkspaceId,
sessionId: sid('fx-query-dropped'),
timeZone: 'UTC',
})).rejects.toThrow(/dropped session\.create response/)
})

View File

@@ -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 packages/client/runtime/README.md
README.md: bd8528e97b04d5b4b28922266306969e8f19295a
README.zh.md: 9aea486fb17c5a170ee8c1195435d220b495b615
README.md: 42fb7642cbf4f122a3c9517fb22a291eb6debe87
README.zh.md: c798634b875570dfd49d6240ed85f6895d2dece4

View File

@@ -4,6 +4,8 @@ English | [中文](README.zh.md)
Client cordis boot and React-free object services: SlotsService wraps SlotCore and supplies renderer data sources; SessionsService owns Session objects and the Chat-facing list, scope, and event-window state; SessionHistoryService lazily owns independent raw-history ledgers for inspection consumers, loading the current tail first and prepending one older page only when its consumer requests it. Each history snapshot exposes the raw window's absolute base sequence so a consumer detects a prepend even when the page adds no surface-visible node. WorkspacesService depends on SessionsService and owns Workspace objects, list/actions, default-target derivation, and the New Session blank-reuse entry (`connectWorkspace`). The runtime fans the shared Host stream into the Session, Workspace, and activated history owners without routing inspection state through Session or SessionManager, and bridges the registry-invalidation frames to typed ctx events (`commands/changed`, `settings/changed`, `credentials/changed`, `models/changed`) so surface caches refetch without touching the stream. Client sessions are always Host-born (Session+Agent+cwd in one `session.create`); the client holds no pre-entity session state — a session's Agent scope (the client mirror of host dsh-scope, keyed by the shared agent/session id) is born when its row enters the list mirror and dies with the prune. Contract: api-contracts v3 §4. Each `Session` holds a generic `ProjectionValueStore` seeded from the history-tail `projections` block and updated by `session/projection` frames under higher-seq-wins; domain keys (including `todos`) are read via `projections.faceOf` / `useProjection`, not via `ConversationSnapshot`. The store also publishes one reference-stable whole-value map through `SessionSummary.projectionValues`, allowing global list consumers to reuse the same projections without creating per-session subscriptions.
For each ordinary local `Session.prompt()`, the runtime samples the browser's current `Intl.DateTimeFormat().resolvedOptions().timeZone` and attaches it to that one prompt RPC. It is neither cached nor included in Session creation or fork state, so travel and concurrent tabs keep message-local provenance. A browser that cannot provide a non-empty zone fails the prompt locally instead of silently substituting deployment state.
## Slot declaration injection
`ctx.slots.inject(name, callback)` makes a full `SlotMap` key the dependency for a contribution whose plugin can activate independently from the declaring entry. It runs `callback` synchronously when the declaration exists, otherwise waits; declaration collapse disposes the callback effect, and redeclaration reruns it. The controller belongs to the caller's plugin fiber, so unloading the contributor cancels either the wait or its active registrations. A direct `slots.register()` into an undeclared slot still throws.

View File

@@ -4,6 +4,8 @@
客户端 cordis 启动与不依赖 React 的对象服务SlotsService 包装 SlotCore 并提供 renderer 数据源SessionsService 拥有 Session 对象以及 Chat 所需的列表、scope 和事件窗口状态SessionHistoryService 为检查类消费方惰性拥有彼此独立的原始历史账本,先加载当前尾部,并仅在消费方请求时向前补入一页更早历史。每份历史快照都会公开原始窗口的绝对基准序号,因此即使该页没有新增任何 surface 可见节点消费方仍能检测到向前补页。WorkspacesService 依赖 SessionsService拥有 Workspace 对象、列表/操作、默认目标派生,以及 New Session 空会话复用入口(`connectWorkspace`)。运行时把共享 Host 流分发给 Session、Workspace 和已激活的历史数据所有者,不让检查状态经过 Session 或 SessionManager并把注册表失效帧桥接为类型化 ctx 事件(`commands/changed``settings/changed``credentials/changed``models/changed`),使各表面缓存无需触碰流即可重拉。客户端会话一律由 Host 创建(一次 `session.create` 同时产生 Session、agent智能体和 cwd客户端不持有任何实体化之前的会话状态——agent scopehost dsh-scope 的客户端镜像,以 agent/session 共用 id 为键)在会话行进入列表镜像时创建,并随 prune 销毁。约定api-contracts v3 §4。每个 `Session` 持有一个通用的 `ProjectionValueStore`,由历史记录尾部的 `projections` 块播种,并经 `session/projection` 帧按 seq 高者胜更新;领域键(含 `todos`)经 `projections.faceOf``useProjection` 读取,不经 `ConversationSnapshot`。该 store 还会通过 `SessionSummary.projectionValues` 发布一份引用稳定的完整值映射,使全局列表消费方无需为每个会话创建订阅,即可复用同一组投影。
每次调用普通本地 `Session.prompt()` 时,运行时都会采样浏览器当前的 `Intl.DateTimeFormat().resolvedOptions().timeZone`,并只把该值附加到这一次提示词 RPC。该值既不缓存也不包含在 Session 创建或 fork 状态中,因此旅行与并发标签页都能保留消息本地的来源信息。浏览器若无法提供非空时区,会在本地拒绝该提示词,而不会悄然使用部署状态代替。
## Slot 声明注入
`ctx.slots.inject(name, callback)` 将完整的 `SlotMap` key 作为贡献项的依赖,适用于贡献方插件可独立于声明条目激活的情形。声明存在时,它会同步运行 `callback`,否则等待;声明折叠会 dispose资源释放回调 effect重新声明则会再次运行回调。控制器归调用方的插件 fiber 所有,因此卸载贡献方会取消等待或移除其活跃注册项。直接调用 `slots.register()` 向未声明 slot 注册仍会抛出异常。

View File

@@ -10,7 +10,6 @@ import type {
// plugin-to-plugin value imports are a bundle purity error.
import { transportError } from '@deepseek-ai/dsh-host-apiproxy/api'
import { mergeOrderedBaseline } from '../ordered-baseline.ts'
import { resolvedClientTimeZone } from '../time-zone.ts'
import type { SessionListEntry, TitledSessionSummary } from './lineage.ts'
import { flattenLineage } from './lineage.ts'
import type { PendingInteractionStatus } from './pending.ts'
@@ -515,10 +514,7 @@ export class SessionManager {
opts: { workspaceId?: WorkspaceId; cwd?: string; sessionId?: SessionId } = {},
): Promise<RpcResult<{ sessionId: SessionId }>> {
try {
const shared = {
timeZone: resolvedClientTimeZone(),
...(opts.sessionId === undefined ? {} : { sessionId: opts.sessionId }),
}
const shared = opts.sessionId === undefined ? {} : { sessionId: opts.sessionId }
const payload = opts.workspaceId !== undefined
? { workspaceId: opts.workspaceId, ...shared }
: { ...(opts.cwd === undefined ? {} : { cwd: opts.cwd }), ...shared }

View File

@@ -1,4 +1,4 @@
/** Browser-owned time-zone sampling for Session and prompt RPC provenance. */
/** Browser-owned time-zone sampling for prompt RPC provenance. */
/**
* Resolve the current browser IANA zone for one outbound operation.

View File

@@ -12,11 +12,8 @@ import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
import * as RuntimeClient from '../src/client/index.ts'
import type { SessionsService } from '../src/client/sessions/service.ts'
import type { WorkspacesService } from '../src/client/workspaces/service.ts'
import { resolvedClientTimeZone } from '../src/client/time-zone.ts'
import { FakeApiClient, ok } from './fake-api.ts'
const CLIENT_TIME_ZONE = resolvedClientTimeZone()
interface Bench {
ctx: Context
api: FakeApiClient
@@ -105,10 +102,7 @@ describe('runtime client apply', () => {
const sessions = bench.ctx.get('sessions') as SessionsService
const workspaces = bench.ctx.get('workspaces') as WorkspacesService
expect(bench.api.callsOf('session.create')).toEqual([{
workspaceId: 'w-recent',
timeZone: CLIENT_TIME_ZONE,
}])
expect(bench.api.callsOf('session.create')).toEqual([{ workspaceId: 'w-recent' }])
expect(sessions.list.getSnapshot().current).toBe('fk-new')
sessions.clear()

View File

@@ -6,13 +6,11 @@
import { describe, expect, it, vi } from 'vitest'
import type { SessionId } from '@deepseek-ai/dsh-client-connection/client'
import { SessionManager } from '../src/client/sessions/manager.ts'
import { resolvedClientTimeZone } from '../src/client/time-zone.ts'
import { FakeApiClient, deferred, err, ok } from './fake-api.ts'
import { entries, plainTurn } from './event-script.ts'
const S1 = 'fk-m1' as SessionId
const S2 = 'fk-m2' as SessionId
const CLIENT_TIME_ZONE = resolvedClientTimeZone()
type SummaryOver = Partial<{
updatedAt: number
@@ -710,11 +708,7 @@ describe('remaining branches', () => {
api.onCreate = () => Promise.resolve(ok({ sessionId: S1 }))
const manager = new SessionManager(api)
await manager.create({ cwd: '/tmp/w', sessionId: S1 })
expect(api.callsOf('session.create')).toEqual([{
cwd: '/tmp/w',
sessionId: S1,
timeZone: CLIENT_TIME_ZONE,
}])
expect(api.callsOf('session.create')).toEqual([{ cwd: '/tmp/w', sessionId: S1 }])
expect(manager.getListSnapshot().items[0]).toMatchObject({ sessionId: S1, cwd: '/tmp/w' })
await manager.create({ cwd: '/tmp/w' }) // same id returned: no duplicate row
expect(manager.getListSnapshot().items).toHaveLength(1)

View File

@@ -11,7 +11,6 @@ import type { SessionEvent } from '@deepseek-ai/dsh-session/types'
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
import type { SessionId } from '@deepseek-ai/dsh-client-connection/client'
import { Session } from '../src/client/sessions/session.ts'
import { resolvedClientTimeZone } from '../src/client/time-zone.ts'
import { FakeApiClient, deferred, err, ok } from './fake-api.ts'
import { entries, ev, plainTurn } from './event-script.ts'
@@ -20,7 +19,6 @@ const at = (seq: number, e: Record<string, unknown>): SessionEvent =>
const SID = 'fk-s1' as SessionId
const PARENT = 'fk-parent' as SessionId
const CLIENT_TIME_ZONE = resolvedClientTimeZone()
afterEach(() => {
vi.unstubAllGlobals()
@@ -724,11 +722,11 @@ describe('prompt and cancel errors', () => {
expect(result.ok).toBe(true)
// Monotone: settlement alone does not step the phase anywhere.
expect(session.getSnapshot().composerPhase).toBe('engaging')
expect(api.callsOf('session.prompt')).toEqual([{
expect(api.callsOf('session.prompt')).toMatchObject([{
sessionId: SID,
mode: 'queue',
content: [{ type: 'text', text: '要发的' }],
clientTimeZone: CLIENT_TIME_ZONE,
clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
}])
// First content lands (running turn): engaging → active.
session.handleRunning(true)

View File

@@ -10,11 +10,9 @@ import { Context } from 'cordis'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { SessionId } from '@deepseek-ai/dsh-client-connection/client'
import { SessionCreateError, SessionsService, scopeOf } from '../src/client/sessions/service.ts'
import { resolvedClientTimeZone } from '../src/client/time-zone.ts'
import { FakeApiClient, deferred, err, ok } from './fake-api.ts'
const sid = (s: string): SessionId => s as SessionId
const CLIENT_TIME_ZONE = resolvedClientTimeZone()
interface Bench {
ctx: Context
@@ -454,11 +452,7 @@ describe('create', () => {
const b = bench()
b.api.onCreate = () => Promise.resolve(ok({ sessionId: sid('fresh') }))
await expect(b.svc.create({ cwd: '/w', sessionId: sid('fresh') })).resolves.toBe('fresh')
expect(b.api.callsOf('session.create')).toEqual([{
cwd: '/w',
sessionId: 'fresh',
timeZone: CLIENT_TIME_ZONE,
}])
expect(b.api.callsOf('session.create')).toEqual([{ cwd: '/w', sessionId: 'fresh' }])
b.api.onCreate = () => Promise.resolve({
rpcId: 'e' as never,
result: { ok: false as const, error: { code: 'internal' as const, message: '爆了', details: {} } },

View File

@@ -12,11 +12,11 @@ describe('browser time zone', () => {
)
})
it('fails loud when the runtime exposes no zone', () => {
it.each([undefined, ''])('fails loud when the runtime exposes no zone %#', (timeZone) => {
const options = new Intl.DateTimeFormat().resolvedOptions()
vi.spyOn(Intl.DateTimeFormat.prototype, 'resolvedOptions').mockReturnValue({
...options,
timeZone: '',
timeZone: timeZone as string,
})
expect(() => resolvedClientTimeZone()).toThrow('browser time zone is unavailable')

View File

@@ -2,14 +2,12 @@ import { Context } from 'cordis'
import { describe, expect, it } from 'vitest'
import type { SessionId, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-connection/client'
import { SessionsService } from '../src/client/sessions/service.ts'
import { resolvedClientTimeZone } from '../src/client/time-zone.ts'
import { WorkspaceManager } from '../src/client/workspaces/manager.ts'
import { DirectoryBrowseError, WorkspaceCreateError, WorkspacesService } from '../src/client/workspaces/service.ts'
import { FakeApiClient, deferred, err, ok } from './fake-api.ts'
const sid = (id: string): SessionId => id as SessionId
const wid = (id: string): WorkspaceId => id as WorkspaceId
const CLIENT_TIME_ZONE = resolvedClientTimeZone()
function workspace(id: string, sessionIds: SessionId[] = [], createdAt = '2026-01-01T00:00:00.000Z'): WorkspaceView {
return {
@@ -190,10 +188,7 @@ describe('WorkspacesService', () => {
// Miss: beta has only a non-blank session → host create with workspaceId.
api.onCreate = () => Promise.resolve(ok({ sessionId: sid('s-fresh') }))
await expect(workspaces.connectWorkspace(wid('beta'))).resolves.toBe('s-fresh')
expect(api.callsOf('session.create')).toEqual([{
workspaceId: 'beta',
timeZone: CLIENT_TIME_ZONE,
}])
expect(api.callsOf('session.create')).toEqual([{ workspaceId: 'beta' }])
// Same guarantee on the create arm (draft hand-off writes the machine pre-open).
expect(sessions.binding(sid('s-fresh'))).toBeDefined()
@@ -201,10 +196,7 @@ describe('WorkspacesService', () => {
// never reused, a fresh accounted session is created instead.
api.onCreate = () => Promise.resolve(ok({ sessionId: sid('s-fresh-3') }))
await expect(workspaces.connectWorkspace(wid('gamma'))).resolves.toBe('s-fresh-3')
expect(api.callsOf('session.create')).toEqual([
{ workspaceId: 'beta', timeZone: CLIENT_TIME_ZONE },
{ workspaceId: 'gamma', timeZone: CLIENT_TIME_ZONE },
])
expect(api.callsOf('session.create')).toEqual([{ workspaceId: 'beta' }, { workspaceId: 'gamma' }])
// Unknown workspace fails loud instead of silently creating in nowhere.
await expect(workspaces.connectWorkspace(wid('ghost'))).rejects.toThrow(/unknown workspace ghost/)
@@ -419,10 +411,7 @@ describe('startInitialSelection', () => {
await b.sessions.refresh()
// Store notifications and the connect round trip are microtask-batched.
await new Promise(resolve => setTimeout(resolve, 0))
expect(b.api.callsOf('session.create')).toEqual([{
workspaceId: 'recent',
timeZone: CLIENT_TIME_ZONE,
}])
expect(b.api.callsOf('session.create')).toEqual([{ workspaceId: 'recent' }])
expect(b.sessions.list.getSnapshot().current).toBe('s-new')
stop()
})

View File

@@ -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 packages/context/time-context/README.md
README.md: 9956918c63b49de8ec5e739bc3d9887e269930a8
README.zh.md: 3a9bb1012fc0639d9c3f6b104cea5a64d4b187d6
README.md: 0bdb0d463362427d6a7050c2d7d6d55f96779f9c
README.zh.md: 92eb0b3f43162279ac7e0f728e685863d75a28b6

View File

@@ -2,7 +2,7 @@
English | [中文](README.zh.md)
Opt-in durable context with the current zoned time, immutable Session zone, request-bound browser zones, and elapsed time sampled during model-request preparation. Default compositions do not mount it; the opt-in Schedule Web overlay does. Decision record: [the durable time-context Agent Note](../../../.agents/notes/implemented/feature/2026-07-16-durable-per-step-time-context.md).
Opt-in durable context with the current zoned time, the browser zone attached to the open request, and elapsed time sampled during model-request preparation. Default compositions leave it disabled; the Schedule Web overlay mounts it so the model can interpret otherwise-unqualified dates and times in the user's browser zone. Decision record: [the durable time-context Agent Note](../../../.agents/notes/implemented/feature/2026-07-16-durable-per-step-time-context.md).
## Config
@@ -10,31 +10,31 @@ Opt-in durable context with the current zoned time, immutable Session zone, requ
- id: time-context
name: '@deepseek-ai/dsh-time-context'
config:
timeZone: Asia/Shanghai # optional fallback for headerless Sessions; omit for the process zone
refreshIntervalMs: 60000 # optional; omit or set to 0 for every non-empty entered request batch
timeZone: Asia/Shanghai # optional fallback when the request has no unique browser zone
refreshIntervalMs: 60000 # optional; omit or set to 0 for every eligible attempt
```
When a Session has `SessionHeader.timeZone`, that immutable IANA zone formats its readings. A headerless Session instead uses the configured fallback; 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 fallback. An explicit `timeZone` is validated at plugin load but does not override a Session-owned zone.
When the open turn contains one Host-validated browser zone, that request-local zone formats the timestamp. With missing or mixed browser provenance, `timeZone` supplies the display fallback; omitting it resolves the Node process zone once at plugin load. Node honors `TZ`, and every explicit fallback is validated through `Intl.DateTimeFormat`.
`refreshIntervalMs` must be a non-negative safe integer. Omission or `0` adds context to every non-empty entered request batch whose signal is not already aborted. A positive value adds it only when the session has no earlier time-context injection, wall time moved backward, or at least that many milliseconds have elapsed since the latest injection.
`refreshIntervalMs` must be a non-negative safe integer. Omission or `0` adds context to every eligible entering pre-step whose signal is not already aborted. A positive value adds it only when the Session has no earlier time-context injection, wall time moved backward, or at least that many milliseconds elapsed since the latest injection.
## Request-zone ownership
The browser samples `Intl.DateTimeFormat().resolvedOptions().timeZone` for each prompt. The Host validates and canonicalizes that value before binding it to the exact durable `user-rpc` message source. Time-context examines only those sources in the open turn: one unique zone resolves the request, multiple zones are `mixed`, and none are `unavailable`. It does not read or mutate Session headers, connection state, or Schedule records.
The resolved instruction tells the model to interpret otherwise-unqualified dates and times in that browser zone. Mixed or unavailable provenance tells the model to ask the user to clarify. This is natural-language context, not an input default at another package boundary: a tool that accepts local calendar fields still owns its explicit zone requirement.
## Timing semantics
The plugin prepends an `agent/pre-step` listener and delegates first. When the downstream decision enters a non-empty message batch, time-context derives client zones from those final messages plus user-rpc messages already entered in the open turn, then appends one reading to that decision. Schedule later derives the same facts directly from the immutable Session header and those durable user-rpc sources; the reading is not a second machine authority.
The plugin prepends an `agent/pre-step` listener and delegates first. When an injection is due and the downstream decision enters, it appends one sourced `UserMessage` to the returned batch. AgentLoop records the final batch after `step/start` and before request derivation. Rejection, listener failure, or an already-aborted signal records nothing.
An entering non-empty batch records its downstream messages followed by exactly one time-context `UserMessage` after `step/start`. Its source is the exact snapshot marker `{ kind: 'plugin', plugin: 'time-context', form: 'snapshot', sections: [{ name: 'time-context', text: <same rendered text> }] }`; the invariant companion and Schedule consumer both fail closed if that shape or text equality drifts. The Session header and original user-rpc sources remain the only machine-readable zone owners. A decision rewritten to empty never gains a reading: it opens no initial step, and an empty tool continuation may still enter a later step using existing history.
Each reading uses the exact snapshot source `{ kind: 'plugin', plugin: 'time-context', form: 'snapshot', sections: [{ name: 'time-context', text: <same text> }] }`. The `./invariant` companion validates that shape, re-derives the current-turn browser policy from the original `user-rpc` messages, and checks the timestamp zone and elapsed baseline.
Reject, cancellation, and listener failure before `step/start` add no reading. A plugin disposal that wins while the listener awaits downstream work also prevents the in-flight listener from contributing. Steering inserted after AgentLoop has claimed the current batch retains ordinary next-step ownership and receives fresh context when that later step enters; time-context adds no inbox state or AgentLoop lifecycle path.
Positive-interval scheduling scans raw durable Session events for the latest plugin-attributed message, including a reading shadowed by compaction. It therefore survives resume without a process-local cache. A positive interval can intentionally let a later request reuse existing history without a fresh reading; the Schedule Web overlay omits the interval.
Positive-interval scheduling scans the raw durable session events for the latest `user/message` with that source, including a reading shadowed by compaction. The schedule therefore applies across turns and resumed processes without process-local cache state. It reduces append frequency and history growth but never removes an existing reading, and sessions schedule independently.
Step 1 measures from the latest preceding durable user, assistant, or tool-result message. The prompt proposed for that step has not been appended yet. Later steps measure from the preceding time-context event in the same turn. Missing baselines report `unavailable`, and backward wall-clock movement clamps elapsed time to zero.
Step 1 measures from the latest durable model-visible message before the current proposal; the prompt entering that same step has not been appended yet. Later steps measure from the preceding time-context event in the same turn. Both baselines use durable session-event timestamps; backward wall-clock movement clamps elapsed time to zero. A missing first-step baseline, or a later step with no earlier same-turn reading because interval suppression skipped it, reports `unavailable`.
A time reading records an entered request step, not a completed or successfully transmitted request. A later request-preparation failure can therefore leave the reading in history, while a failure before `step/start` cannot.
The separately published `./invariant` companion checks the simple plugin source, open turn and step, elapsed baseline, and durable event time. It also re-derives Session and client zones from the Session header and current turn's original user-rpc messages, so duplicated source authority or mismatched rendered policy fails. The rendered timestamp must parse and cannot postdate the event; process suspension between sampling and append does not invalidate the reading.
The time reading stays in derived conversation history until a later compaction shadows it. Request headers contain no time-context state. Request reconstruction uses the complete durable surface prefix after each `step/start`, so transmitted requests need not map one-to-one to readings: request preparation can fail after step entry, while an empty continuation or interval suppression can let a request reuse existing history without adding one.
A reading records an entered step, not a completed or transmitted request. A later preparation failure can leave it in history. The message remains in derived conversation history until compaction shadows it; `request/header` contains no time-context state, and request reconstruction uses the complete durable surface prefix after each `step/start`.
## Model Experience
@@ -42,14 +42,13 @@ The time reading stays in derived conversation history until a later compaction
#### What the model sees
On each non-empty entered batch that injects, one source-tagged context message contains the four lines below. `<timestamp>` is an ISO-shaped local timestamp with numeric offset and IANA zone; durations use compact whole-second units. The Session line reports the immutable Session zone or `unavailable`, and the client line reports one resolved zone, a sorted mixed set, or `missing`. An empty continuation or positive interval can let an entered step reuse prior history without a new reading.
Each injected message contains three lines. `<timestamp>` is an ISO-shaped timestamp with numeric offset and IANA zone; durations use compact whole-second units.
##### First step
```markdown
Time sampled while preparing turn <turn>, step 1: <timestamp>
Session time zone: <iana-zone-or-unavailable>.
Client time zone for this request: <iana-zone-or-mixed-set-or-missing>.
Browser time zone for this request: <iana-zone-or-mixed-or-unavailable-policy>.
Elapsed since the preceding model-visible message: <duration-or-unavailable>.
```
@@ -57,14 +56,13 @@ Elapsed since the preceding model-visible message: <duration-or-unavailable>.
```markdown
Time sampled while preparing turn <turn>, step <step>: <timestamp>
Session time zone: <iana-zone-or-unavailable>.
Client time zone for this request: <iana-zone-or-mixed-set-or-missing>.
Browser time zone for this request: <iana-zone-or-mixed-or-unavailable-policy>.
Elapsed since the preceding step context: <duration-or-unavailable>.
```
#### Token effect
Each injected four-line message accumulates until compaction shadows it. A positive interval reduces additions; omission or `0` adds one for every non-empty entered request batch.
Each reading accumulates until compaction shadows it. A positive interval reduces additions; omission or `0` adds one at every eligible preparation attempt.
#### KV Cache effect
@@ -72,8 +70,8 @@ Append-only; newly visible content follows the reusable request prefix and does
## Known Limitations and Deferred Work
- **Prompt provenance only** — browser-zone context guides natural-language interpretation but does not silently supply another tool's required zone field.
- **Mixed turns ask** — if one open turn contains prompts from different browser zones, the model is told to clarify rather than guess which one owns an unqualified time.
- **Fallback is not user authority** — the configured or process zone formats the clock when browser provenance is missing or mixed, but the model-facing policy still says to clarify.
- **Whole-second display** — timestamps and durations omit sub-second precision even though durable event times retain milliseconds.
- **Session-event baseline** — elapsed time starts from durable append timestamps, not a client transport's original send timestamp.
- **Headerless fallback zone** — a Session without `SessionHeader.timeZone` renders through the configured or process fallback but reports its Session zone as `unavailable`; consumers that require unambiguous local-time interpretation must request an explicit zone.
- **Immutable Session zone** — a Session zone does not change when another browser resumes it. The request-bound browser sources expose disagreement instead of silently changing the displayed default.
- **History cost between compactions** — omission or `0` retains one reading for every non-empty entered request batch, including batches whose later request preparation fails; empty continuations reuse prior history, while a positive interval reduces but does not eliminate this cost.
- **History cost between compactions** — omission or `0` retains one reading for every eligible attempt; a positive interval reduces but does not eliminate this cost and may leave a later request without fresh browser-zone guidance.

View File

@@ -2,7 +2,7 @@
[English](README.md) | 中文
可选的持久上下文,包含模型请求准备期间采样的带时区的当前时间与经过时长。`dsh-agent-spine-demo` 与随附示例不挂载该插件。决策记录:[持久 time-context Agent Note](../../../.agents/notes/implemented/feature/2026-07-16-durable-per-step-time-context.md)。
可选的持久上下文,包含当前带时区时间、附加到当前开放请求的浏览器时区以及在模型请求准备期间采样的经过时长。默认组合不启用它Schedule Web overlay 会挂载它,使模型可以按用户的浏览器时区解释未明确限定时区的日期和时间。决策记录:[持久 time-context Agent Note](../../../.agents/notes/implemented/feature/2026-07-16-durable-per-step-time-context.md)。
## 配置
@@ -10,27 +10,31 @@
- id: time-context
name: '@deepseek-ai/dsh-time-context'
config:
timeZone: Asia/Shanghai # optional IANA override; omit for the process zone
timeZone: Asia/Shanghai # optional fallback when the request has no unique browser zone
refreshIntervalMs: 60000 # optional; omit or set to 0 for every eligible attempt
```
省略 `timeZone` 时,插件会在加载时解析一次 Node 进程的系统时区。Node 遵循 `TZ`;如果没有该覆盖,时区由宿主或容器提供。显式 `timeZone` 必须是 IANA 标识符,并在插件加载时验证
当当前开放轮次只包含一个经 Host 校验的浏览器时区时,使用该请求本地时区格式化时间戳。浏览器来源信息缺失或混杂时,`timeZone` 提供显示回退;省略它则会在插件加载时解析一次 Node 进程时区。Node 遵循 `TZ`,每个显式回退值都经 `Intl.DateTimeFormat` 校验
`refreshIntervalMs` 必须是非负安全整数。省略或设为 `0` 时,会为每信号尚未中止且进入步骤的合格步骤前处理添加上下文。正数值只会在会话没有早先 time-context 注入、挂钟时间倒退,或自最新注入起已经过至少相应毫秒数时添加上下文。
`refreshIntervalMs` 必须是非负安全整数。省略或设为 `0` 时,会为每信号尚未中止且进入步骤的合格 pre-step 添加上下文。正数值只会在会话没有更早的 time-context 注入、挂钟时间倒退,或自最新注入起已经过至少相应毫秒数时添加上下文。
## 请求时区归属
浏览器会为每条提示词采样 `Intl.DateTimeFormat().resolvedOptions().timeZone`。Host 校验并规范化该值,再将其绑定到确切的持久 `user-rpc` 消息来源。Time-context 只检查当前开放轮次中的这些来源:唯一一个时区可解析请求,多个时区记为 `mixed`,没有时区则记为 `unavailable`。它不会读取或修改会话标头、连接状态或 Schedule 记录。
解析后的指令告诉模型,把未明确限定时区的日期和时间解释为该浏览器时区。来源信息为 mixed 或 unavailable 时,模型会收到要求用户澄清的指令。这是自然语言上下文,并非另一个包边界上的输入默认值:接受本地日历字段的工具仍自行负责其显式时区要求。
## 时序语义
该插件会前置一个 `agent/pre-step` 监听器。需要注入且下游决策进入拟议步骤时,它会返回批次中添加一条带来源的 `UserMessage`。AgentLoop `step/start` 之后、普通自动压缩compaction之前记录该上下文其来源为 `{ kind: 'plugin', plugin: 'time-context' }`。被抑制、拒绝或失败的步骤前处理不会记录任何内容。
该插件会前置一个 `agent/pre-step` 监听器,并先行委托下游。需要注入且下游决策进入步骤时,它会返回批次加一条带来源的 `UserMessage`。AgentLoop 在 `step/start` 之后、请求派生之前记录最终批次。决策被拒绝、监听器失败或信号已经中止时,不会记录任何内容。
正间隔调度会扫描原始持久会话事件,查找最新的上述源 `user/message`,包括已被压缩遮蔽的时间读数。因此,调度可以跨轮次以及进程恢复持续生效,不需要进程本地缓存状态。它会降低追加频率与历史增长,但绝不移除现有时间读数,且每个会话独立调度
每个读数都使用确切的快照来源 `{ kind: 'plugin', plugin: 'time-context', form: 'snapshot', sections: [{ name: 'time-context', text: <same text> }] }``./invariant` 配套模块会校验该形状,根据原始 `user-rpc` 消息重新派生当前轮次的浏览器策略,并检查时间戳时区与经过时长基线
第 1 步从前一条模型可见消息起测量,包括开启轮次的提示词。后续步骤从同一轮次中前一个 time-context 事件起测量。两种基线都使用持久会话事件时间戳;挂钟时间倒退时,经过时长限制为零。如果第一步缺少基线,或者后续步骤因间隔抑制而没有较早的同轮次时间读数,则报告 `unavailable`
正数间隔调度会扫描原始持久会话事件查找最新一条归因于插件的消息其中包括已被压缩compaction遮蔽的读数。因此它无需进程本地缓存也能在恢复后继续生效。正数间隔可以有意让后续请求复用现有历史而不添加新读数Schedule Web overlay 会省略该间隔
时间读数记录的是一个已进入步骤的步骤前批次,不是已完成步骤或已传输请求。后续请求准备失败时,该读数可能已留在历史中;但下游步骤前监听器拒绝或失败时,该读数不会被记录
第 1 步从最新一条在其之前持久化的用户、助手或工具结果消息起测量。为该步骤拟议的提示词尚未追加。后续步骤从同一轮次中前一个 time-context 事件起测量。缺少基线时报告 `unavailable`,挂钟时间倒退时将经过时长限制为零
单独发布的 `./invariant` 配套模块会根据当前未结束的轮次、下一个步骤前位置、经过时长基线与持久事件时间检查每个归因于插件的时间读数。其渲染时间戳必须可解析,且不能晚于该事件;采样与追加之间的进程挂起不会使时间读数失效
时间读数会保留在派生会话历史中,直到后续压缩遮蔽它。请求标头不含 time-context 状态。请求重建会在每个 `step/start` 之后使用完整持久表层前缀,因此已传输请求无需与时间读数一一对应:请求准备可能在进入步骤后失败,而间隔抑制可让请求复用现有历史,无需添加时间读数。
读数记录的是已进入的步骤,不是已完成或已传输的请求。后续准备失败时,该读数可能留在历史中。消息会保留在派生会话历史中,直到压缩将其遮蔽;`request/header` 不含 time-context 状态,请求重建会使用每个 `step/start` 之后的完整持久表层前缀
## 模型体验
@@ -38,12 +42,13 @@
#### 模型看到的内容
次执行注入的准备尝试都会生成一条带源标记的上下文消息包含下方两行。`<timestamp>` 是带数字偏移 IANA 时区、形如 ISO 的本地时间戳;持续时间使用紧凑的整秒单位。正间隔可能使某次步骤尝试没有新时间读数。
条注入消息包含行。`<timestamp>` 是带数字偏移 IANA 时区、形如 ISO 的时间戳;持续时间使用紧凑的整秒单位。
##### 第一步
```markdown
Time sampled while preparing turn <turn>, step 1: <timestamp>
Browser time zone for this request: <iana-zone-or-mixed-or-unavailable-policy>.
Elapsed since the preceding model-visible message: <duration-or-unavailable>.
```
@@ -51,12 +56,13 @@ Elapsed since the preceding model-visible message: <duration-or-unavailable>.
```markdown
Time sampled while preparing turn <turn>, step <step>: <timestamp>
Browser time zone for this request: <iana-zone-or-mixed-or-unavailable-policy>.
Elapsed since the preceding step context: <duration-or-unavailable>.
```
#### Token 影响
条注入的两行消息都会累积,直到压缩遮蔽。正间隔会减少添加;省略或设为 `0` 则会为每次合格准备尝试添加一条。
个读数都会累积,直到压缩将其遮蔽。正间隔会减少新增读数;省略或设为 `0` 时,每次合格准备尝试都会添加一条。
#### KV Cache 影响
@@ -64,7 +70,8 @@ Elapsed since the preceding step context: <duration-or-unavailable>.
## 已知限制与暂缓事项
- **仅限提示词来源信息**:浏览器时区上下文用于指导自然语言解释,但不会悄然填入另一工具所要求的时区字段。
- **混合轮次会询问**:如果同一个开放轮次包含来自不同浏览器时区的提示词,模型会收到要求澄清的指令,而不会猜测哪个时区拥有未限定的时间。
- **回退值不代表用户权威**:浏览器来源信息缺失或混杂时,配置或进程时区用于格式化时钟,但面向模型的策略仍要求澄清。
- **整秒显示**:时间戳与持续时间省略亚秒精度,尽管持久事件时间保留毫秒。
- **会话事件基线**:经过时长从持久追加时间戳起计算,而非客户端传输的原始发送时间戳。
- **进程本地默认时区**:省略设置时,使用插件加载时捕获的 Node 进程 `TZ`、宿主或容器时区,而非远程用户的时区;两者不同时,请配置显式 IANA 时区。
- **压缩之间的历史成本**:省略设置或设为 `0` 会为每次合格准备尝试保留一条时间读数,包括后续取消或失败的尝试;正间隔可以降低但无法消除该成本。
- **压缩之间的历史成本**:省略或设为 `0` 时,每次合格尝试都会保留一条读数;正数间隔可以降低但无法消除该成本,也可能使后续请求缺少新鲜的浏览器时区指导。

View File

@@ -11,14 +11,11 @@ import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import type { UserMessage } from '@deepseek-ai/dsh-llm'
import {
deriveClientTimeZoneContext,
renderTimeZoneContext,
deriveBrowserTimeZoneContext,
renderBrowserTimeZoneContext,
} from './request-zone.ts'
import { createTimestampFormatter, formatTimestamp } from './timestamp.ts'
export type { ClientTimeZoneContext } from './request-zone.ts'
export { deriveClientTimeZoneContext } from './request-zone.ts'
/** Cordis plugin name used by loader diagnostics. */
export const name = 'time-context'
@@ -27,7 +24,7 @@ export const inject = ['agents']
/** Request-preparation clock formatting and append scheduling. Invalid values fail plugin load. */
export interface Config {
/** Fallback display zone for headerless Sessions. Omit to use the process zone. */
/** Fallback display zone when the open turn has no unique browser zone. Omit to use the process zone. */
timeZone?: string
/** Minimum milliseconds between durable injections in one session. Omit or set to 0 to inject at every eligible step. */
refreshIntervalMs?: number
@@ -56,7 +53,7 @@ function formatDuration(elapsedMs: number): string {
return parts.join(' ')
}
/** Find the latest model-visible event before the current proposal. */
/** Find the latest model-visible event, excluding this plugin's pending append. */
function precedingMessageTime(agent: Agent): number | undefined {
for (const event of [...agent.session.events].reverse()) {
switch (event.type) {
@@ -97,33 +94,32 @@ function latestInjectionTime(agent: Agent): number | undefined {
return undefined
}
/** Collect already-entered and proposed messages belonging to one open turn. */
/** Collect already-entered and proposed user messages belonging to one open turn. */
function requestMessages(agent: Agent, turn: number, proposed: readonly UserMessage[]): UserMessage[] {
const start = agent.session.events.findLastIndex(
event => event.type === 'turn/start' && event.data.turn === turn,
)
const entered = start < 0
? []
: agent.session.events.slice(start + 1).flatMap(event => event.type === 'user/message' ? [event.data] : [])
: agent.session.events.slice(start + 1)
.flatMap(event => event.type === 'user/message' ? [event.data] : [])
return [...entered, ...proposed]
}
/** Render one durable time reading. */
function renderText(
now: number,
turn: number,
step: number,
previous: number | undefined,
formatter: Intl.DateTimeFormat,
displayTimeZone: string,
sessionTimeZone: string | undefined,
timeZone: string,
messages: readonly UserMessage[],
): string {
const elapsed = previous === undefined ? 'unavailable' : formatDuration(now - previous)
const baseline = step === 1 ? 'model-visible message' : 'step context'
const client = deriveClientTimeZoneContext(messages)
return `Time sampled while preparing turn ${turn}, step ${step}: ${formatTimestamp(now, formatter, displayTimeZone)}\n`
+ `${renderTimeZoneContext(sessionTimeZone, client)}\n`
const browserContext = renderBrowserTimeZoneContext(deriveBrowserTimeZoneContext(messages))
return `Time sampled while preparing turn ${turn}, step ${step}: ${formatTimestamp(now, formatter, timeZone)}\n`
+ `${browserContext}\n`
+ `Elapsed since the preceding ${baseline}: ${elapsed}.`
}
@@ -141,12 +137,11 @@ function validateRefreshInterval(refreshIntervalMs: number | undefined): void {
/**
* Register a prepended pre-step listener for the lifetime of `ctx`.
* @param ctx - Plugin context; the listener is disposed with it.
* @param config - Time zone and durable refresh scheduling configuration.
* @returns A disposer that prevents an in-flight listener from contributing.
* @throws When the refresh interval or configured/process time zone is invalid.
* @param ctx - plugin context; the listener is disposed with it.
* @param config - time zone and durable refresh scheduling configuration.
* @throws when the refresh interval is invalid or the configured or process time zone cannot be resolved.
*/
export function apply(ctx: Context, config: Config): () => void {
export function apply(ctx: Context, config: Config): void {
const timeZone = config.timeZone
const refreshIntervalMs = config.refreshIntervalMs
validateRefreshInterval(refreshIntervalMs)
@@ -161,66 +156,22 @@ export function apply(ctx: Context, config: Config): () => void {
}
const fallbackTimeZone = fallbackFormatter.resolvedOptions().timeZone
const formatters = new Map<string, Intl.DateTimeFormat>([[fallbackTimeZone, fallbackFormatter]])
let disposed = false
/** Resolve one Session-owned formatter without making the process zone authoritative. */
/** Resolve and cache one request-local timestamp formatter. */
const formatterFor = (selectedTimeZone: string): Intl.DateTimeFormat => {
const existing = formatters.get(selectedTimeZone)
if (existing !== undefined) return existing
let created: Intl.DateTimeFormat
try {
created = createTimestampFormatter(selectedTimeZone)
} catch (error: unknown) {
throw new Error(`time-context: invalid Session time zone ${JSON.stringify(selectedTimeZone)}`, { cause: error })
}
const created = createTimestampFormatter(selectedTimeZone)
formatters.set(selectedTimeZone, created)
return created
}
/** Build one current reading after downstream pre-step transforms settle. */
const readingFor = (
agent: Agent,
turn: number,
step: number,
messages: readonly UserMessage[],
): UserMessage => {
const now = Date.now()
const previous = step === 1
? precedingMessageTime(agent)
: precedingStepContextTime(agent, turn)
const sessionTimeZone = agent.session.header.timeZone
const displayTimeZone = sessionTimeZone ?? fallbackTimeZone
const formatter = sessionTimeZone === undefined
? fallbackFormatter
: formatterFor(sessionTimeZone)
const text = renderText(
now,
turn,
step,
previous,
formatter,
displayTimeZone,
sessionTimeZone,
requestMessages(agent, turn, messages),
)
return createUserMessage({
content: [{ type: 'text', text }],
source: { kind: 'plugin', plugin: name, form: 'snapshot', sections: [{ name, text }] },
})
}
ctx.on('agent/pre-step', async (
{ agent, turn, step, signal },
next,
): Promise<PreStepDecision> => {
const wasDisposed = (): boolean => disposed
const wasAborted = (): boolean => signal.aborted
if (wasDisposed()) return next()
const decision = await next()
if (wasDisposed() || wasAborted() || decision.kind === 'reject'
|| decision.messages.length === 0) {
return decision
}
if (decision.kind === 'reject' || signal.aborted) return decision
const now = Date.now()
if (refreshIntervalMs !== undefined && refreshIntervalMs > 0) {
const lastInjection = latestInjectionTime(agent)
@@ -228,16 +179,30 @@ export function apply(ctx: Context, config: Config): () => void {
&& now >= lastInjection
&& now - lastInjection < refreshIntervalMs) return decision
}
const previous = step === 1
? precedingMessageTime(agent)
: precedingStepContextTime(agent, turn)
const messages = requestMessages(agent, turn, decision.messages)
const browser = deriveBrowserTimeZoneContext(messages)
const selectedTimeZone = browser.kind === 'resolved' ? browser.timeZone : fallbackTimeZone
const text = renderText(
now,
turn,
step,
previous,
formatterFor(selectedTimeZone),
selectedTimeZone,
messages,
)
return {
kind: 'enter',
messages: [
...decision.messages,
readingFor(agent, turn, step, decision.messages),
createUserMessage({
content: [{ type: 'text', text }],
source: { kind: 'plugin', plugin: name, form: 'snapshot', sections: [{ name, text }] },
}),
],
}
}, { prepend: true })
return () => {
disposed = true
}
}

View File

@@ -3,7 +3,10 @@
import type { Context } from 'cordis'
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import { deriveClientTimeZoneContext, renderTimeZoneContext } from './request-zone.ts'
import {
deriveBrowserTimeZoneContext,
renderBrowserTimeZoneContext,
} from './request-zone.ts'
import { createTimestampFormatter, formatTimestamp } from './timestamp.ts'
const PACKAGE_NAME = '@deepseek-ai/dsh-time-context'
@@ -11,8 +14,7 @@ const SOURCE_NAME = 'time-context'
const READING = new RegExp(
'^Time sampled while preparing turn (\\d+), step (\\d+): '
+ '(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:Z|[+-]\\d{2}:\\d{2})\\[[^\\]]+\\])\\n'
+ 'Session time zone: ([^.]+)\\.\\n'
+ 'Client time zone for this request: (.+)\\.\\n'
+ '(Browser time zone for this request: .+)\\n'
+ 'Elapsed since the preceding (model-visible message|step context): '
+ '(?:unavailable|(?:(?:\\d+d )?(?:\\d+h )?(?:\\d+m )?\\d+s))\\.$',
)
@@ -22,7 +24,7 @@ export const name = 'time-context-invariant'
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/** Derive the open step owned by a time-context reading. */
/** Derive the open step boundary at which a time-context reading may append. */
function preparationPosition(history: readonly SessionEvent[], fail: InvariantFailure): { turn: number; step: number } {
let openTurn: number | undefined
let openStep: number | undefined
@@ -68,12 +70,12 @@ function preparationPosition(history: readonly SessionEvent[], fail: InvariantFa
/** Collect the entered user messages belonging to one open turn. */
function requestMessages(history: readonly SessionEvent[], turn: number) {
const start = history.findLastIndex(event => event.type === 'turn/start' && event.data.turn === turn)
return history.slice(start + 1).flatMap(event => event.type === 'user/message' ? [event.data] : [])
return history.slice(start + 1)
.flatMap(event => event.type === 'user/message' ? [event.data] : [])
}
/** Validate one plugin-attributed time reading against its session position and timestamp. */
function validateReading(
session: Session,
history: readonly SessionEvent[],
event: SessionEvent<'user/message'>,
fail: InvariantFailure,
@@ -121,15 +123,13 @@ function validateReading(
|| section.text !== blockText) {
fail('time-context source must carry only the exact snapshot text, not request authority')
}
const renderedAuthority = `Session time zone: ${match[4]}.\nClient time zone for this request: ${match[5]}.`
const expectedAuthority = renderTimeZoneContext(
session.header.timeZone,
deriveClientTimeZoneContext(requestMessages(history, turn)),
)
if (renderedAuthority !== expectedAuthority) {
fail('time-context text does not match the Session and current request zones')
const renderedBrowserContext = match[4]
const browserContext = deriveBrowserTimeZoneContext(requestMessages(history, turn))
const expectedBrowserContext = renderBrowserTimeZoneContext(browserContext)
if (renderedBrowserContext !== expectedBrowserContext) {
fail('time-context browser-zone text does not match current-turn user messages')
}
const baseline = match[6]
const baseline = match[5]
if ((step === 1) !== (baseline === 'model-visible message')) {
fail(`time-context step ${step} uses the wrong elapsed-time baseline ${JSON.stringify(baseline)}`)
}
@@ -141,20 +141,19 @@ function validateReading(
|| event.time < renderedTime) {
fail('time-context rendered timestamp must parse and not postdate its durable event')
}
const sessionTimeZone = session.header.timeZone
if (sessionTimeZone !== undefined) {
if (browserContext.kind === 'resolved') {
let expectedTimestamp: string
try {
expectedTimestamp = formatTimestamp(
renderedTime,
createTimestampFormatter(sessionTimeZone),
sessionTimeZone,
createTimestampFormatter(browserContext.timeZone),
browserContext.timeZone,
)
} catch (error: unknown) {
fail(`time-context Session time zone cannot format its durable timestamp: ${String(error)}`)
fail(`time-context browser zone cannot format its durable timestamp: ${String(error)}`)
}
if (rendered !== expectedTimestamp) {
fail('time-context rendered timestamp does not match the Session time zone')
fail('time-context rendered timestamp does not match the unique browser zone')
}
}
}
@@ -166,7 +165,7 @@ function validateSession(session: Session, fail: InvariantFailure): void {
if (event.type !== 'user/message'
|| event.data.source.kind !== 'plugin'
|| event.data.source.plugin !== SOURCE_NAME) continue
validateReading(session, session.events.slice(0, index), event, fail)
validateReading(session.events.slice(0, index), event, fail)
}
}
@@ -180,7 +179,7 @@ const install: InvariantInstaller = Object.assign((ctx: Context, fail: Invariant
if (event.type !== 'user/message'
|| event.data.source.kind !== 'plugin'
|| event.data.source.plugin !== SOURCE_NAME) return
validateReading(session, session.events, event, fail)
validateReading(session.events, event, fail)
}, { global: true })
}, { inject: ['sessions'] })
/* jscpd:ignore-end */

View File

@@ -1,15 +1,16 @@
/** Request-zone derivation shared by time-context rendering and Schedule tools. */
/** Browser-zone derivation and model-facing policy text for one open request turn. */
import { assertNever } from '@deepseek-ai/dsh-llm'
import type { UserMessage } from '@deepseek-ai/dsh-llm'
/** Client-zone facts derived from the user-rpc messages in one open turn. */
export type ClientTimeZoneContext =
/** Browser-zone facts derived from user-rpc messages in one open turn. */
export type BrowserTimeZoneContext =
| { readonly kind: 'resolved'; readonly timeZone: string }
| { readonly kind: 'mixed'; readonly timeZones: string[] }
| { readonly kind: 'mixed'; readonly timeZones: readonly string[] }
| { readonly kind: 'missing' }
/** Read the Host-validated client zone from one ordinary user-rpc message. */
function clientTimeZone(message: UserMessage): string | undefined {
/** Read a Host-validated browser zone from one ordinary user-rpc message. */
function browserTimeZone(message: UserMessage): string | undefined {
const source = message.source
return source.kind === 'user'
&& 'rpcId' in source
@@ -21,13 +22,15 @@ function clientTimeZone(message: UserMessage): string | undefined {
}
/**
* Derive the unique, mixed, or missing client zone from entered request input.
* @param messages - User messages belonging to the current open turn.
* @returns A sorted, duplicate-free request-zone context.
* Derive the unique, mixed, or missing browser zone for one open turn.
* @param messages - Entered and proposed user messages belonging to the turn.
* @returns Sorted, duplicate-free browser-zone facts.
*/
export function deriveClientTimeZoneContext(messages: readonly UserMessage[]): ClientTimeZoneContext {
export function deriveBrowserTimeZoneContext(
messages: readonly UserMessage[],
): BrowserTimeZoneContext {
const timeZones = [...new Set(messages.flatMap((message) => {
const timeZone = clientTimeZone(message)
const timeZone = browserTimeZone(message)
return timeZone === undefined ? [] : [timeZone]
}))].sort()
const [timeZone, ...remaining] = timeZones
@@ -37,20 +40,23 @@ export function deriveClientTimeZoneContext(messages: readonly UserMessage[]): C
}
/**
* Render Session and request-zone facts for the model-visible time reading.
* @param sessionTimeZone - Immutable Session zone, or `undefined` for legacy Sessions.
* @param client - Client zones derived from the current open turn.
* @returns The two policy lines appended to a time-context reading.
* Render the model instruction for one browser-zone context.
* @param context - Browser-zone facts for the open turn.
* @returns One durable policy line.
*/
export function renderTimeZoneContext(
sessionTimeZone: string | undefined,
client: ClientTimeZoneContext,
): string {
const session = sessionTimeZone ?? 'unavailable'
const request = client.kind === 'resolved'
? client.timeZone
: client.kind === 'mixed'
? `mixed ${JSON.stringify(client.timeZones)}`
: 'missing'
return `Session time zone: ${session}.\nClient time zone for this request: ${request}.`
export function renderBrowserTimeZoneContext(context: BrowserTimeZoneContext): string {
switch (context.kind) {
case 'resolved':
return `Browser time zone for this request: ${context.timeZone}. `
+ 'Interpret otherwise-unqualified dates and times in this zone.'
case 'mixed':
return `Browser time zone for this request: mixed ${JSON.stringify(context.timeZones)}. `
+ 'Ask the user to clarify otherwise-unqualified dates and times.'
case 'missing':
return 'Browser time zone for this request: unavailable. '
+ 'Ask the user to clarify otherwise-unqualified dates and times.'
/* v8 ignore next 2 -- the closed BrowserTimeZoneContext union is exhausted above. */
default:
return assertNever(context, 'BrowserTimeZoneContext')
}
}

View File

@@ -45,16 +45,14 @@ function reading(
step = '1',
baseline = 'model-visible message',
timestamp = '2026-07-14T00:00:00+00:00[UTC]',
sessionTimeZone = 'unavailable',
clientTimeZone = 'missing',
browser = 'Browser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.',
): string {
return `Time sampled while preparing turn ${turn}, step ${step}: ${timestamp}\n`
+ `Session time zone: ${sessionTimeZone}.\n`
+ `Client time zone for this request: ${clientTimeZone}.\n`
+ `${browser}\n`
+ `Elapsed since the preceding ${baseline}: unavailable.`
}
function preparing(turn: number, step: number): Session {
function preparing(turn: number, step: number, clientTimeZone?: string): Session {
const session = Session.create(SessionId(`time-invariant-${turn}-${step}`))
for (let priorTurn = 1; priorTurn < turn; priorTurn += 1) {
session.append('turn/start', { turn: priorTurn })
@@ -63,7 +61,9 @@ function preparing(turn: number, step: number): Session {
session.append('turn/start', { turn })
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: `turn ${turn}` }],
source: { kind: 'user' },
source: clientTimeZone === undefined
? { kind: 'user' }
: { kind: 'user', rpcId: `turn-${String(turn)}`, clientTimeZone } as never,
}), { surfaceOp: 'append' })
for (let priorStep = 1; priorStep < step; priorStep += 1) {
session.append('step/start', { turn, step: priorStep })
@@ -89,8 +89,7 @@ describe('time-context invariants', () => {
it('accepts a reading whose turn, step, baseline, and timestamp agree', async () => {
const ctx = await setup()
const text = 'Time sampled while preparing turn 2, step 3: 2026-07-14T00:00:00+00:00[UTC]\n'
+ 'Session time zone: unavailable.\n'
+ 'Client time zone for this request: missing.\n'
+ 'Browser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\n'
+ 'Elapsed since the preceding step context: 4m 2s.'
expect(() => { ctx.emit('session/event', preparing(2, 3), event(text)) }).not.toThrow()
})
@@ -102,231 +101,47 @@ describe('time-context invariants', () => {
}).not.toThrow()
})
it('rejects a reading appended after request execution starts', async () => {
it('requires browser-zone policy and timestamp to match current-turn request provenance', async () => {
const ctx = await setup()
const session = preparing(1, 1)
session.append('request/header', {
header: { config: { provider: 'mock', model: 'mock' } },
reason: 'initial',
})
const policy = 'Browser time zone for this request: Asia/Shanghai. '
+ 'Interpret otherwise-unqualified dates and times in this zone.'
expect(() => {
ctx.emit('session/event', session, event(reading()))
}).toThrow(/must precede request\/header/)
})
it('derives Session and client zones from their original durable owners', async () => {
const ctx = await setup()
const id = SessionId('time-invariant-zones')
const session = Session.create(id, [], {
version: 0,
id,
createdAt: SECOND,
timeZone: 'Asia/Shanghai',
})
session.append('turn/start', { turn: 1 })
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'travel request' }],
source: { kind: 'user', rpcId: 'travel-request', clientTimeZone: 'America/New_York' } as never,
}), { surfaceOp: 'append' })
session.append('step/start', { turn: 1, step: 1 })
expect(() => {
ctx.emit('session/event', session, event(reading(
ctx.emit('session/event', preparing(1, 1, 'Asia/Shanghai'), event(reading(
'1',
'1',
'model-visible message',
'2026-07-14T08:00:00+08:00[Asia/Shanghai]',
'Asia/Shanghai',
'America/New_York',
)))
policy,
), SECOND + 456))
}).not.toThrow()
expect(() => {
ctx.emit('session/event', session, event(reading(
'1',
'1',
'model-visible message',
'2026-07-14T08:00:00+08:00[Asia/Shanghai]',
'Asia/Shanghai',
'Asia/Shanghai',
)))
}).toThrow(/does not match the Session and current request zones/)
ctx.emit('session/event', preparing(1, 1, 'Asia/Shanghai'), event(reading()))
}).toThrow(/browser-zone text/)
expect(() => {
ctx.emit('session/event', session, event(reading(
ctx.emit('session/event', preparing(1, 1, 'Asia/Shanghai'), event(reading(
'1',
'1',
'model-visible message',
'2026-07-14T00:00:00+00:00[UTC]',
'Asia/Shanghai',
'America/New_York',
policy,
)))
}).toThrow(/rendered timestamp does not match the Session time zone/)
}).toThrow(/rendered timestamp does not match the unique browser zone/)
})
it('rejects a durable reading whose Session zone cannot format the timestamp', async () => {
it('rejects invalid browser provenance loaded across the durable boundary', async () => {
const ctx = await setup()
const id = SessionId('time-invariant-invalid-zone')
const session = Session.create(id, [], {
version: 0,
id,
createdAt: SECOND,
timeZone: 'Invalid/Zone',
})
session.append('turn/start', { turn: 1 })
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'invalid zone request' }],
source: { kind: 'user' },
}), { surfaceOp: 'append' })
session.append('step/start', { turn: 1, step: 1 })
const timeZone = 'Not/A_Real_Zone'
const policy = `Browser time zone for this request: ${timeZone}. `
+ 'Interpret otherwise-unqualified dates and times in this zone.'
expect(() => {
ctx.emit('session/event', session, event(reading(
ctx.emit('session/event', preparing(1, 1, timeZone), event(reading(
'1',
'1',
'model-visible message',
'2026-07-14T00:00:00+00:00[UTC]',
'Invalid/Zone',
`2026-07-14T00:00:00+00:00[${timeZone}]`,
policy,
)))
}).toThrow(/Session time zone cannot format its durable timestamp/)
})
it('rejects a malformed reading seeded after companion setup', async () => {
const ctx = await setup()
const id = SessionId('time-invariant-future-seed')
const text = reading(
'1',
'1',
'model-visible message',
'2026-07-14T00:00:00+00:00[UTC]',
'Asia/Shanghai',
'Asia/Shanghai',
)
expect(() => ctx.sessions.create(id, {
meta: { timeZone: 'Asia/Shanghai' },
seed: [
{ type: 'turn/start', seq: 0, time: SECOND, data: { turn: 1 } },
{
type: 'user/message',
seq: 1,
time: SECOND,
surfaceOp: 'append',
data: createUserMessage({
content: [{ type: 'text', text: 'seeded request' }],
source: { kind: 'user', rpcId: 'seeded-request', clientTimeZone: 'Asia/Shanghai' } as never,
}),
},
{ type: 'step/start', seq: 2, time: SECOND, data: { turn: 1, step: 1 } },
{ ...event(text), seq: 3, surfaceOp: 'append' },
],
})).toThrow(/rendered timestamp does not match the Session time zone/)
expect(ctx.sessions.get(id)).toBeUndefined()
})
it('rejects a time-context source that duplicates request authority', async () => {
const ctx = await setup()
const base = event(reading())
const duplicate: SessionEvent<'user/message'> = {
...base,
data: {
...base.data,
source: { ...base.data.source, authority: {} } as never,
},
}
expect(() => {
ctx.emit('session/event', preparing(1, 1), duplicate)
}).toThrow(/must carry only the exact snapshot text/)
})
it('rejects snapshot provenance whose section differs from the model-visible text', async () => {
const ctx = await setup()
const base = event(reading())
const mismatched: SessionEvent<'user/message'> = {
...base,
data: {
...base.data,
source: {
kind: 'plugin',
plugin: 'time-context',
form: 'snapshot',
sections: [{ name: 'time-context', text: 'different' }],
},
},
}
expect(() => {
ctx.emit('session/event', preparing(1, 1), mismatched)
}).toThrow(/must carry only the exact snapshot text/)
})
it('rejects snapshot provenance whose sections are only array-like', async () => {
const ctx = await setup()
const base = event(reading())
const arrayLike: SessionEvent<'user/message'> = {
...base,
data: {
...base.data,
source: {
kind: 'plugin',
plugin: 'time-context',
form: 'snapshot',
sections: { 0: { name: 'time-context', text: reading() }, length: 1 },
} as never,
},
}
expect(() => {
ctx.emit('session/event', preparing(1, 1), arrayLike)
}).toThrow(/must carry only the exact snapshot text/)
})
it.each([
[
'matched non-string text',
{ type: 'text', text: 7 },
[{ name: 'time-context', text: 7 }],
/must contain exactly one text block/,
],
[
'an extra text-block field',
{ type: 'text', text: reading(), extra: true },
[{ name: 'time-context', text: reading() }],
/must contain exactly one text block/,
],
[
'an extra section field',
{ type: 'text', text: reading() },
[{ name: 'time-context', text: reading(), extra: true }],
/must carry only the exact snapshot text/,
],
] as const)(
'rejects snapshot provenance with %s',
async (_name, block, sections, diagnostic) => {
const ctx = await setup()
const base = event(reading())
const malformed: SessionEvent<'user/message'> = {
...base,
data: {
...base.data,
content: [block as never],
source: { kind: 'plugin', plugin: 'time-context', form: 'snapshot', sections } as never,
},
}
expect(() => {
ctx.emit('session/event', preparing(1, 1), malformed)
}).toThrow(diagnostic)
},
)
it('rejects package-owned provenance without snapshot sections', async () => {
const ctx = await setup()
const base = event(reading())
const unformed: SessionEvent<'user/message'> = {
...base,
data: {
...base.data,
source: { kind: 'plugin', plugin: 'time-context' },
},
}
expect(() => {
ctx.emit('session/event', preparing(1, 1), unformed)
}).toThrow(/must carry only the exact snapshot text/)
}).toThrow(/browser zone cannot format/)
})
it('validates each existing reading against its preceding durable prefix', async () => {
@@ -377,22 +192,23 @@ describe('time-context invariants', () => {
.toThrow(/inside an open turn/)
})
it('rejects a reading before step/start', async () => {
const ctx = await setup()
const session = Session.create(SessionId('time-invariant-turn-only'))
session.append('turn/start', { turn: 1 })
expect(() => { ctx.emit('session/event', session, event(reading())) }).toThrow(/follow step\/start/)
})
it('rejects a reading outside its open preparation', async () => {
it('rejects a reading outside a prompt boundary', async () => {
const ctx = await setup()
const ended = preparing(1, 1)
ended.append('step/end', { turn: 1, step: 1 })
expect(() => { ctx.emit('session/event', ended, event(reading())) })
.toThrow(/follow step\/start/)
expect(() => { ctx.emit('session/event', ended, event(reading())) }).toThrow(/follow step\/start/)
const notEntered = Session.create(SessionId('time-invariant-turn-only'))
notEntered.append('turn/start', { turn: 1 })
expect(() => { ctx.emit('session/event', notEntered, event(reading())) }).toThrow(/follow step\/start/)
expect(() => {
ctx.emit('session/event', Session.create(SessionId('time-invariant-empty')), event(reading()))
}).toThrow(/inside an open turn/)
const requested = preparing(1, 1)
requested.append('request/header', {
header: { config: { provider: 'mock', model: 'model' } },
reason: 'initial',
})
expect(() => { ctx.emit('session/event', requested, event(reading())) }).toThrow(/precede request\/header/)
})
it.each([
@@ -409,6 +225,7 @@ describe('time-context invariants', () => {
['ignored', SECOND, [], /exactly one text block/],
['ignored', SECOND, [{ type: 'image', data: 'x', mimeType: 'image/png' }], /exactly one text block/],
['ignored', SECOND, [{ type: 'text', text: 'one' }, { type: 'text', text: 'two' }], /exactly one text block/],
[reading(), SECOND, [{ type: 'text', text: reading(), extra: true }], /exactly one text block/],
] as const)('rejects an incoherent durable reading', async (text, time, content, message) => {
const ctx = await setup()
const preparationStep = text.includes('turn 1, step 2:') ? 2 : 1
@@ -421,6 +238,55 @@ describe('time-context invariants', () => {
}).toThrow(message)
})
it('requires exact snapshot provenance without copied request authority', async () => {
const ctx = await setup()
const base = event(reading())
for (const source of [
{ kind: 'plugin', plugin: 'time-context' },
{ ...base.data.source, authority: {} },
{
kind: 'plugin',
plugin: 'time-context',
form: 'snapshot',
sections: [{ name: 'time-context', text: 'different' }],
},
{
kind: 'plugin',
plugin: 'time-context',
form: 'snapshot',
sections: { 0: { name: 'time-context', text: reading() }, length: 1 },
},
{
kind: 'plugin',
plugin: 'time-context',
form: 'snapshot',
sections: [{ name: 'time-context', text: reading(), extra: true }],
},
]) {
const malformed: SessionEvent<'user/message'> = {
...base,
data: { ...base.data, source: source as never },
}
expect(() => { ctx.emit('session/event', preparing(1, 1), malformed) })
.toThrow(/must carry only the exact snapshot text/)
}
})
it('validates a seeded Session created after invariant registration', async () => {
const ctx = await setup()
const text = reading('1', '2', 'step context')
expect(() => {
ctx.sessions.create(SessionId('time-invariant-created-invalid'), {
seed: [
{ type: 'turn/start', seq: 0, time: SECOND, data: { turn: 1 } },
{ type: 'step/start', seq: 1, time: SECOND, data: { turn: 1, step: 1 } },
{ ...event(text), seq: 2, surfaceOp: 'append' },
],
})
}).toThrow(/expected turn 1\/step 1/)
expect(ctx.sessions.get(SessionId('time-invariant-created-invalid'))).toBeUndefined()
})
it('ignores context messages owned by another package', async () => {
const ctx = await setup()
const other = event('unrelated', SECOND + 456, undefined, 'other')

View File

@@ -1,64 +1,44 @@
import { describe, expect, it } from 'vitest'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import * as timeContext from '@deepseek-ai/dsh-time-context'
import type { UserMessage } from '@deepseek-ai/dsh-llm'
import {
deriveClientTimeZoneContext,
} from '@deepseek-ai/dsh-time-context'
import { renderTimeZoneContext } from '../src/request-zone.ts'
deriveBrowserTimeZoneContext,
renderBrowserTimeZoneContext,
} from '../src/request-zone.ts'
function request(clientTimeZone?: unknown) {
function browserMessage(timeZone: string): UserMessage {
return createUserMessage({
content: [{ type: 'text', text: 'request' }],
source: clientTimeZone === undefined
? { kind: 'user' }
: { kind: 'user', rpcId: 'request-zone', clientTimeZone } as never,
content: [{ type: 'text', text: timeZone }],
source: { kind: 'user', rpcId: `rpc-${timeZone}`, clientTimeZone: timeZone } as never,
})
}
describe('request-zone derivation', () => {
it('publishes derivation without exposing the internal renderer', () => {
expect(timeContext.deriveClientTimeZoneContext).toBe(deriveClientTimeZoneContext)
expect('renderTimeZoneContext' in timeContext).toBe(false)
})
it('derives missing, one resolved zone, and sorted unique mixed zones', () => {
describe('browser request-zone context', () => {
it('derives missing, unique, and sorted mixed zones from user-rpc messages only', () => {
const plugin = createUserMessage({
content: [],
source: { kind: 'plugin', plugin: 'fixture' },
content: [{ type: 'text', text: 'plugin' }],
source: { kind: 'plugin', plugin: 'test' },
})
expect(deriveClientTimeZoneContext([plugin, request(), request(1)])).toEqual({ kind: 'missing' })
expect(deriveClientTimeZoneContext([createUserMessage({
content: [],
source: { kind: 'user', clientTimeZone: 'Asia/Shanghai' } as never,
})])).toEqual({ kind: 'missing' })
expect(deriveClientTimeZoneContext([
request('Asia/Shanghai'),
request('Asia/Shanghai'),
expect(deriveBrowserTimeZoneContext([plugin])).toEqual({ kind: 'missing' })
expect(deriveBrowserTimeZoneContext([
browserMessage('Asia/Shanghai'),
browserMessage('Asia/Shanghai'),
])).toEqual({ kind: 'resolved', timeZone: 'Asia/Shanghai' })
expect(deriveClientTimeZoneContext([
request('Asia/Shanghai'),
request('America/New_York'),
expect(deriveBrowserTimeZoneContext([
browserMessage('Asia/Shanghai'),
browserMessage('America/New_York'),
])).toEqual({
kind: 'mixed',
timeZones: ['America/New_York', 'Asia/Shanghai'],
})
})
it('renders resolved, mixed, and unavailable policy lines', () => {
expect(renderTimeZoneContext('Asia/Shanghai', {
kind: 'resolved',
timeZone: 'Asia/Shanghai',
})).toBe(
'Session time zone: Asia/Shanghai.\nClient time zone for this request: Asia/Shanghai.',
)
expect(renderTimeZoneContext('UTC', {
kind: 'mixed',
timeZones: ['America/New_York', 'UTC'],
})).toBe(
'Session time zone: UTC.\nClient time zone for this request: mixed ["America/New_York","UTC"].',
)
expect(renderTimeZoneContext(undefined, { kind: 'missing' })).toBe(
'Session time zone: unavailable.\nClient time zone for this request: missing.',
)
it('renders one explicit model policy for every context', () => {
expect(renderBrowserTimeZoneContext({ kind: 'resolved', timeZone: 'Asia/Shanghai' }))
.toContain('Interpret otherwise-unqualified dates and times in this zone.')
expect(renderBrowserTimeZoneContext({
kind: 'mixed', timeZones: ['America/New_York', 'Asia/Shanghai'],
})).toContain('mixed ["America/New_York","Asia/Shanghai"]')
expect(renderBrowserTimeZoneContext({ kind: 'missing' })).toContain('unavailable')
})
})

View File

@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Context } from 'cordis'
import Loader from '@cordisjs/plugin-loader'
import { createUserMessage, CallId, LlmAdapter } from '@deepseek-ai/dsh-llm'
import type { GenerateOptions, StreamChunk, UserMessage } from '@deepseek-ai/dsh-llm'
import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
import { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
import AgentRegistry, { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent'
import { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
@@ -53,11 +53,13 @@ function sessionAgent(session: Session, id = 'agent'): Agent {
}
}
function openMessageTurn(session: Session, turn: number): void {
function openMessageTurn(session: Session, turn: number, clientTimeZone?: string): void {
session.append('turn/start', { turn })
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: `turn ${turn}` }],
source: { kind: 'user' },
source: clientTimeZone === undefined
? { kind: 'user' }
: { kind: 'user', rpcId: `turn-${String(turn)}`, clientTimeZone } as never,
}), { surfaceOp: 'append' })
}
@@ -79,35 +81,24 @@ async function fire(
turn: number,
step: number,
signal: AbortSignal = SIGNAL,
messages: UserMessage[] = [],
): Promise<void> {
const fallback = messages.length === 0
? createUserMessage({
content: [],
source: { kind: 'plugin', plugin: 'time-context-test-proposal' },
})
: undefined
const proposal = fallback === undefined ? messages : [fallback]
const proposed = createUserMessage({
content: [{ type: 'text', text: 'request proposal' }],
source: { kind: 'plugin', plugin: 'time-context-test' },
})
const decision = await agentEvents(ctx, agent).waterfall(
'agent/pre-step',
{ messages: proposal, turn, step, signal },
() => Promise.resolve({ kind: 'enter' as const, messages: proposal }),
{ messages: [proposed], turn, step, signal },
() => Promise.resolve({ kind: 'enter' as const, messages: [proposed] }),
)
if (decision.kind === 'enter') {
for (const message of decision.messages) {
if (message.id === fallback?.id) continue
if (message === proposed) continue
agent.session.append('user/message', message, { surfaceOp: 'append' })
}
}
}
function rpcMessage(text: string, clientTimeZone: string): UserMessage {
return createUserMessage({
content: [{ type: 'text', text }],
source: { kind: 'user', rpcId: `rpc-${text}`, clientTimeZone } as never,
})
}
function textResponse(text: string): StreamChunk[] {
return [
{ type: 'block-start', index: 0, blockType: 'text' },
@@ -161,84 +152,22 @@ function requestText(request: GenerateOptions): string {
}
describe('durable step context', () => {
it('uses the immutable Session zone and the current request message zone', async () => {
const { ctx } = await mount()
const id = SessionId('session-zone')
const session = Session.create(id, [], {
version: 0,
id,
createdAt: BASE,
timeZone: 'Asia/Shanghai',
})
session.append('turn/start', { turn: 1 })
const agent = sessionAgent(session)
await fire(ctx, agent, 1, 1, SIGNAL, [
rpcMessage('local request', 'Asia/Shanghai'),
])
expect(contextTexts(session)[0]).toContain(
'2026-07-14T08:00:00+08:00[Asia/Shanghai]',
)
expect(contextTexts(session)[0]).toContain('Session time zone: Asia/Shanghai.')
expect(contextTexts(session)[0]).toContain('Client time zone for this request: Asia/Shanghai.')
const reading = session.events.at(-1)
expect(reading).toMatchObject({
type: 'user/message',
data: {
source: { kind: 'plugin', plugin: 'time-context' },
},
})
await fire(ctx, agent, 1, 2, SIGNAL, [
rpcMessage('same zone again', 'Asia/Shanghai'),
])
expect(contextTexts(session)).toHaveLength(2)
})
it('reports sorted mixed zones from the current request chain without changing the Session zone', async () => {
const { ctx } = await mount()
const id = SessionId('mixed-zone')
const session = Session.create(id, [], {
version: 0,
id,
createdAt: BASE,
timeZone: 'Asia/Shanghai',
})
session.append('turn/start', { turn: 1 })
session.append('user/message', rpcMessage('first tab', 'Asia/Shanghai'), {
surfaceOp: 'append',
})
await fire(ctx, sessionAgent(session), 1, 1, SIGNAL, [
rpcMessage('second tab', 'America/New_York'),
])
expect(contextTexts(session)[0]).toContain('Session time zone: Asia/Shanghai.')
expect(contextTexts(session)[0]).toContain(
'Client time zone for this request: mixed ["America/New_York","Asia/Shanghai"].',
)
})
it('records turn, step, zoned time, and the preceding model-visible message baseline', async () => {
const { ctx } = await mount({ timeZone: 'Asia/Shanghai' })
const session = Session.create(SessionId('first'))
openMessageTurn(session, 1)
openMessageTurn(session, 1, 'Asia/Shanghai')
vi.setSystemTime(BASE + 90_061_000)
await fire(ctx, sessionAgent(session), 1, 1)
expect(contextTexts(session)).toEqual([
'Time sampled while preparing turn 1, step 1: 2026-07-15T09:01:01+08:00[Asia/Shanghai]\n'
+ 'Session time zone: unavailable.\n'
+ 'Client time zone for this request: missing.\n'
+ 'Browser time zone for this request: Asia/Shanghai. Interpret otherwise-unqualified dates and times in this zone.\n'
+ 'Elapsed since the preceding model-visible message: 1d 1h 1m 1s.',
])
const event = session.events.at(-1)
expect(event?.type).toBe('user/message')
if (event?.type !== 'user/message') throw new Error('missing time context')
const text = event.data.content.find(block => block.type === 'text')?.text
if (text === undefined) throw new Error('missing time-context text')
// The reading is a `snapshot`-form context: one named contribution whose
// text is exactly what the model read, so a consumer attributes it without
// re-splitting prose.
@@ -248,7 +177,9 @@ describe('durable step context', () => {
form: 'snapshot',
sections: [{
name: 'time-context',
text,
text: 'Time sampled while preparing turn 1, step 1: 2026-07-15T09:01:01+08:00[Asia/Shanghai]\n'
+ 'Browser time zone for this request: Asia/Shanghai. Interpret otherwise-unqualified dates and times in this zone.\n'
+ 'Elapsed since the preceding model-visible message: 1d 1h 1m 1s.',
}],
})
expect(event.surfaceOp).toBe('append')
@@ -281,12 +212,40 @@ describe('durable step context', () => {
expect(contextTexts(session)[1]).toBe(
'Time sampled while preparing turn 3, step 2: 2026-07-14T00:01:01+00:00[UTC]\n'
+ 'Session time zone: unavailable.\n'
+ 'Client time zone for this request: missing.\n'
+ 'Browser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\n'
+ 'Elapsed since the preceding step context: 1m 1s.',
)
})
it('formats in one browser zone and falls back when steering supplies mixed zones', async () => {
const { ctx } = await mount({ timeZone: 'UTC' })
const resolved = Session.create(SessionId('browser-zone-resolved'))
openMessageTurn(resolved, 1, 'America/New_York')
await fire(ctx, sessionAgent(resolved), 1, 1)
expect(contextTexts(resolved)[0]).toContain(
'2026-07-13T20:00:00-04:00[America/New_York]\n'
+ 'Browser time zone for this request: America/New_York. '
+ 'Interpret otherwise-unqualified dates and times in this zone.',
)
const mixed = Session.create(SessionId('browser-zone-mixed'))
openMessageTurn(mixed, 1, 'Asia/Shanghai')
mixed.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'steering from another browser' }],
source: {
kind: 'user',
rpcId: 'mixed-steer',
clientTimeZone: 'America/New_York',
} as never,
}), { surfaceOp: 'append' })
await fire(ctx, sessionAgent(mixed), 1, 1)
expect(contextTexts(mixed)[0]).toContain(
'2026-07-14T00:00:00+00:00[UTC]\n'
+ 'Browser time zone for this request: mixed ["America/New_York","Asia/Shanghai"]. '
+ 'Ask the user to clarify otherwise-unqualified dates and times.',
)
})
it('reports an unavailable later-step baseline at the matching turn boundary', async () => {
const { ctx } = await mount()
const session = Session.create(SessionId('later-step-boundary'))
@@ -427,20 +386,6 @@ describe('configuration and lifecycle', () => {
await expect(unresolved.plugin(timeContext, {})).rejects.toThrow(/failed to resolve the system time zone/)
})
it('fails loud when a persisted Session names an invalid zone', async () => {
const { ctx } = await mount()
const id = SessionId('invalid-session-zone')
const session = Session.create(id, [], {
version: 0,
id,
createdAt: BASE,
timeZone: 'Not/A_Real_Zone',
})
openMessageTurn(session, 1)
await expect(fire(ctx, sessionAgent(session), 1, 1)).rejects.toThrow(/invalid Session time zone/)
})
it('rejects invalid refresh intervals at plugin load with one diagnostic', async () => {
const invalid = [-1, 0.5, Number.MAX_SAFE_INTEGER + 1, Number.POSITIVE_INFINITY, Number.NaN]
for (const refreshIntervalMs of invalid) {
@@ -462,26 +407,13 @@ describe('configuration and lifecycle', () => {
expect(contextTexts(session)).toHaveLength(1)
})
it('lets an already-stopped direct registration delegate without contributing', async () => {
const ctx = new Context()
await ctx.plugin(AgentRegistry)
const stop = timeContext.apply(ctx, {})
stop()
const session = Session.create(SessionId('stopped-direct-registration'))
openMessageTurn(session, 1)
await fire(ctx, sessionAgent(session), 1, 1)
expect(contextTexts(session)).toEqual([])
})
})
describe('real agent-loop request history', () => {
it.each([
['throws', 0],
['cancels', 0],
] as const)('does not persist context when a downstream pre-step listener %s', async (mode, expectedContexts) => {
['throws'],
['cancels'],
] as const)('does not commit a preparation reading when a downstream pre-step listener %s', async (mode) => {
const adapter = new ScriptedAdapter([textResponse('unused')])
const ctx = await loopHarness(adapter)
ctx.on('agent/pre-step', ({ agent: subject }, next) => {
@@ -494,170 +426,13 @@ describe('real agent-loop request history', () => {
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'start' }], source: { kind: 'user' } }))
await agent.whenIdle()
expect(contextTexts(agent.session)).toHaveLength(expectedContexts)
expect(contextTexts(agent.session)).toHaveLength(0)
expect(adapter.requests).toHaveLength(0)
expect(agent.session.events.some(event => event.type === 'step/start')).toBe(false)
await ctx.fiber.dispose()
})
it('leaves steering that arrives after claim for the next step and derives fresh context', async () => {
const adapter = new ScriptedAdapter([textResponse('first'), textResponse('second')])
const ctx = await loopHarness(adapter)
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
let blocked = true
ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
if (blocked && context.agent !== undefined) {
entered.resolve(undefined)
await release.promise
}
return next()
})
const agent = ctx.agentLoop.create(SessionId('late-steering'), { provider: 'mock', model: 'mock' })
agent.followup(rpcMessage('start in Shanghai', 'Asia/Shanghai'))
await entered.promise
agent.steer(rpcMessage('switch to New York', 'America/New_York'))
blocked = false
release.resolve(undefined)
await agent.whenIdle()
expect(adapter.requests).toHaveLength(2)
expect(agent.inbox.hasPending).toBe(false)
expect(requestText(adapter.requests[0]!)).toContain('start in Shanghai')
expect(requestText(adapter.requests[0]!)).not.toContain('switch to New York')
expect(requestText(adapter.requests[0]!)).toContain('Client time zone for this request: Asia/Shanghai.')
expect(requestText(adapter.requests[1]!)).toContain('switch to New York')
expect(requestText(adapter.requests[1]!)).toContain(
'Client time zone for this request: mixed ["America/New_York","Asia/Shanghai"].',
)
expect(contextTexts(agent.session)).toHaveLength(2)
await ctx.fiber.dispose()
})
it('does not let time context create an initial step after downstream suppression', async () => {
const adapter = new ScriptedAdapter([textResponse('unused')])
const ctx = await loopHarness(adapter)
ctx.on('agent/pre-step', async (_payload, next) => {
const decision = await next()
return decision.kind === 'reject' ? decision : { kind: 'enter', messages: [] }
})
const agent = ctx.agentLoop.create(SessionId('suppressed-preparation'), {
provider: 'mock',
model: 'mock',
})
agent.followup(rpcMessage('suppress this prompt', 'Asia/Shanghai'))
await agent.whenIdle()
expect(adapter.requests).toEqual([])
expect(agent.session.events.some(event => event.type === 'step/start')).toBe(false)
expect(contextTexts(agent.session)).toEqual([])
expect(agent.inbox.hasPending).toBe(false)
await ctx.fiber.dispose()
})
it('does not revive an empty continuation after a completed step', async () => {
const adapter = new ScriptedAdapter([textResponse('done')])
const ctx = await loopHarness(adapter)
ctx.on('agent/turn-stopping', ({ agent: subject }) => {
subject.inject(createUserMessage({
content: [{ type: 'text', text: 'pending context' }],
source: { kind: 'plugin', plugin: 'test' },
}))
})
ctx.on('agent/pre-step', async ({ step }, next) => {
const decision = await next()
return step === 1 || decision.kind === 'reject'
? decision
: { kind: 'enter', messages: [] }
})
const agent = ctx.agentLoop.create(SessionId('empty-completed-continuation'), {
provider: 'mock',
model: 'mock',
})
agent.followup(rpcMessage('finish once', 'Asia/Shanghai'))
await agent.whenIdle()
expect(adapter.requests).toHaveLength(1)
expect(agent.session.events.filter(event => event.type === 'step/start')).toHaveLength(1)
expect(contextTexts(agent.session)).toHaveLength(1)
expect(agent.inbox.hasPending).toBe(false)
await ctx.fiber.dispose()
})
it('preserves post-claim steering without persisting failed-turn context', async () => {
const adapter = new ScriptedAdapter([textResponse('resumed')])
const ctx = await loopHarness(adapter)
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
let blocked = true
ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
if (blocked && context.agent !== undefined) {
entered.resolve(undefined)
await release.promise
}
return next()
})
const agent = ctx.agentLoop.create(SessionId('cancelled-assembly'), { provider: 'mock', model: 'mock' })
const steering = rpcMessage('preserve this steering', 'America/New_York')
agent.followup(rpcMessage('start', 'Asia/Shanghai'))
await entered.promise
agent.steer(steering)
agent.cancel({ kind: 'user' }, { keepInbox: true })
blocked = false
release.resolve(undefined)
await agent.whenIdle()
expect(agent.session.events.some(event => event.type === 'step/start')).toBe(false)
expect(contextTexts(agent.session)).toHaveLength(0)
expect(agent.inbox.nextStep).toEqual([steering])
expect(agent.inbox.nextStep.some(message =>
message.source.kind === 'plugin' && message.source.plugin === 'time-context')).toBe(false)
agent.followup(rpcMessage('wake', 'America/New_York'))
await agent.whenIdle()
expect(adapter.requests).toHaveLength(1)
expect(requestText(adapter.requests[0]!)).toContain('preserve this steering')
expect(requestText(adapter.requests[0]!)).toContain('Time sampled while preparing turn 2, step 1:')
await ctx.fiber.dispose()
})
it('does not contribute after its disposer wins an in-flight pre-step', async () => {
const adapter = new ScriptedAdapter([textResponse('done')])
const ctx = new Context()
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(AgentLoop, { agents: [] })
const stopTimeContext = timeContext.apply(ctx, {})
ctx.llm.registerAdapter(['mock'], adapter)
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
ctx.on('agent/pre-step', async (_payload, next) => {
entered.resolve(undefined)
await release.promise
return next()
})
const agent = ctx.agentLoop.create(SessionId('dispose-inflight-pre-step'), {
provider: 'mock',
model: 'mock',
})
agent.followup(rpcMessage('continue without disposed context', 'Asia/Shanghai'))
await entered.promise
stopTimeContext()
release.resolve(undefined)
await agent.whenIdle()
expect(adapter.requests).toHaveLength(1)
expect(requestText(adapter.requests[0]!)).not.toContain('Time sampled while preparing')
expect(contextTexts(agent.session)).toEqual([])
expect(agent.inbox.nextStep).toEqual([])
await ctx.fiber.dispose()
})
it('does not add a reading to an empty tool continuation and leaves system headers unchanged', async () => {
it('persists one ordered context per request, accumulates readings, and leaves system headers unchanged', async () => {
const adapter = new ScriptedAdapter([toolCallResponse(), textResponse('done')])
const ctx = await loopHarness(adapter)
ctx.tools.register(defineContentToolFixture({
@@ -678,9 +453,11 @@ describe('real agent-loop request history', () => {
const contexts = agent.session.events.filter(
(event): event is SessionEvent<'user/message'> => event.type === 'user/message' && event.data.source.kind === 'plugin')
const starts = agent.session.events.filter(event => event.type === 'step/start')
expect(contexts).toHaveLength(1)
expect(contexts).toHaveLength(adapter.requests.length)
expect(starts).toHaveLength(adapter.requests.length)
expect(contexts[0]!.seq).toBeGreaterThan(starts[0]!.seq)
for (let index = 0; index < contexts.length; index += 1) {
expect(contexts[index]!.seq).toBeGreaterThan(starts[index]!.seq)
}
expect(contexts.every(event => event.data.source.kind === 'plugin'
&& event.data.source.plugin === 'time-context'
&& event.surfaceOp === 'append')).toBe(true)
@@ -691,7 +468,8 @@ describe('real agent-loop request history', () => {
expect(firstRequestText).toContain('Elapsed since the preceding model-visible message: unavailable.')
expect(firstRequestText).not.toContain('Time sampled while preparing turn 1, step 2:')
expect(secondRequestText).toContain('Time sampled while preparing turn 1, step 1:')
expect(secondRequestText).not.toContain('Time sampled while preparing turn 1, step 2:')
expect(secondRequestText).toContain('Time sampled while preparing turn 1, step 2:')
expect(secondRequestText).toContain('Elapsed since the preceding step context: 1m 1s.')
for (const request of adapter.requests) expect(request.system).not.toContain('Time sampled while preparing')
const headers = agent.session.events.filter(event => event.type === 'request/header')

View File

@@ -1,6 +1,6 @@
import { defineConfig } from 'tsdown'
/** Build both public entries separately so each inlines the shared request-zone helper. */
/** Build both public entries separately so each inlines shared internal helpers. */
export default defineConfig([
{
entry: ['lib/types/index.js'],

View File

@@ -79,11 +79,11 @@ export interface CreateAgentOptions {
/** The live agent/session identity. */
readonly sessionId: SessionId
/**
* Session creation metadata: validated absolute `cwd`, caller-validated
* `timeZone`, `parentSession` fork lineage, the `seedLength` seed boundary,
* the coarse `origin` classification, and the `delegationDepth` recursion
* budget. Mirrors the `cwd`/`timeZone`/`parentSession`/`seedLength`/`origin`/
* `delegationDepth` fields of {@link CreateSessionOptions.meta} in dsh-session (the internal-only
* Session creation metadata: validated absolute `cwd`, `parentSession`
* fork lineage, the `seedLength` seed boundary, the coarse `origin`
* classification, and the `delegationDepth` recursion budget. Mirrors the
* `cwd`/`parentSession`/`seedLength`/`origin`/`delegationDepth` fields of
* {@link CreateSessionOptions.meta} in dsh-session (the internal-only
* `createdAt`, used when reconstructing a persisted session, is deliberately
* excluded — a factory caller never sets it). This is durable session data,
* so the session boundary validates and snapshots it before asynchronous
@@ -91,7 +91,6 @@ export interface CreateAgentOptions {
*/
readonly meta?: {
readonly cwd?: string
readonly timeZone?: string
readonly parentSession?: SessionId
readonly seedLength?: number
readonly origin?: 'subagent'

View File

@@ -12,9 +12,8 @@ Creates and holds event-sourced `Session` instances. Persistence is intentionall
### Public API
- `ctx.sessions.create(id?, { seed?, meta? }?)` validates and detaches durable seed/header data, fills the version and id, defaults `createdAt` to now, publishes the session, and binds it to the calling fiber. Persisted reconstruction supplies its original `createdAt`, optional `timeZone`, `seedLength`, `origin`, and `delegationDepth`.
- `ctx.sessions.flush(session)` dispatches an awaited parallel checkpoint through the session's captured scope. Every listener starts and the call waits for all to settle before reporting failure; observe-only listeners return void, while a persistence listener returns literal `true` only after completing durability work. A fully successful checkpoint with at least one such acknowledgement returns `true` and emits contained `session/flushed(session, throughSeq)` with the exclusive event boundary captured at entry; no durability acknowledgement returns `false`, and unpublished, detached, or stale objects reject. A caller that requires durable storage rejects `false` at its own policy boundary.
- `findLastMessageTurnEnd(events)` pairs message-triggered starts with their ends and returns the latest matched `turn/end`. Outcome consumers use this fold instead of the raw latest log event because between-turn records and non-message turns have no prompt outcome.
- `ctx.sessions.create(id?, { seed?, meta? }?)` validates and detaches durable seed/header data, fills the version and id, defaults `createdAt` to now, publishes the session, and binds it to the calling fiber. Persisted reconstruction supplies its original `createdAt`, `seedLength`, and `delegationDepth`.
- `ctx.sessions.flush(session)` dispatches the awaited parallel durability checkpoint through the session's captured scope. Every listener starts and the call waits for all to settle before reporting failure; unpublished, detached, and stale objects reject.
- `ctx.sessions.fork(source, boundary?, childSessionId?): Session` — Resolve a live session object or id, select a seed through the inclusive `boundary` event seq (default: current last event), require that prefix to end outside an open turn, and create a live child session with lineage metadata.
- `ctx.sessions.get(id: SessionId): Session | undefined`
- `ctx.sessions.list(): Session[]`
@@ -43,7 +42,7 @@ Plain class (not a Cordis Service). Create live sessions through `ctx.sessions.c
- `session.surface` exposes the readonly `SessionSurface` view owned by the session's single incremental surface manager; `replaceGeneration` changes on every committed rewrite.
- `session.events` is a cached frozen snapshot invalidated by append; accepted events remain deeply frozen.
- `session.seq`, `session.id` — current sequence and readonly typed identity.
- `session.header: SessionHeader` — detached, deep-frozen creation metadata (`version`, `id`, `createdAt`, optional `cwd`/`timeZone`/`parentSession`/`seedLength`/`delegationDepth`). Construction validates the durable record and requires its id to match `session.id`.
- `session.header: SessionHeader` — detached, deep-frozen creation metadata (`version`, `id`, `createdAt`, optional `cwd`/`parentSession`/`seedLength`/`delegationDepth`). Construction validates the durable record and requires its id to match `session.id`.
### Lossless JSON utilities
@@ -84,7 +83,7 @@ Every `SessionEvent` carries two optional top-level fields (structural metadata)
### Metadata types (`types.ts`)
- `SessionHeader` — session metadata written once when published as `Session.header`, where detachment and deep-freezing enforce immutability at runtime: `{ version, id, createdAt, cwd?, timeZone?, parentSession?, seedLength?, delegationDepth? }`. The optional `timeZone` is an opaque caller-validated string: session core checks only its stored shape and preserves it verbatim through reconstruction and fork. Persistence loaders may return mutable detached copies of the same data type. Owned here (beside `SessionId`) because `Session.header` is typed by it; persistence backends re-export it rather than own it (which would force a package cycle).
- `SessionHeader` — session metadata written once when published as `Session.header`, where detachment and deep-freezing enforce immutability at runtime: `{ version, id, createdAt, cwd?, parentSession?, seedLength?, delegationDepth? }`. Persistence loaders may return mutable detached copies of the same data type. Owned here (beside `SessionId`) because `Session.header` is typed by it; persistence backends re-export it rather than own it (which would force a package cycle).
### Extension points

View File

@@ -12,9 +12,8 @@
### 公共 API
- `ctx.sessions.create(id?, { seed?, meta? }?)` 校验持久种子/头部数据并生成脱离副本,补齐版本和 id在未提供 `createdAt` 时使用当前时间,发布会话并将其绑定到调用方 fiber。持久化重建会提供原始的 `createdAt`可选的 `timeZone``seedLength``origin``delegationDepth`
- `ctx.sessions.flush(session)` 通过会话捕获的作用域分发受等待的并行检查点。每个监听器都会启动调用会等待全部结算后才报告失败;仅观察的监听器返回 void持久化监听器只有在完成持久化工作后才返回字面量 `true`。全部成功且至少有一个此类确认时,调用返回 `true`,并发布受包含的 `session/flushed(session, throughSeq)`,其中 `throughSeq` 是入口处捕获的事件排他边界;没有持久化确认时返回 `false`未发布、已脱离陈旧对象会被拒绝。要求持久化存储的调用方应在自己的策略边界拒绝 `false`
- `findLastMessageTurnEnd(events)` 将由消息触发的开始与结束配对,并返回最近匹配的 `turn/end`。结果消费方使用该折叠逻辑,而不直接取日志中最近的事件,因为轮次间记录和非消息轮次没有提示词结果。
- `ctx.sessions.create(id?, { seed?, meta? }?)` 校验持久种子/头部数据并生成脱离副本,补齐版本和 id在未提供 `createdAt` 时使用当前时间,发布会话并将其绑定到调用方 fiber。持久化重建会提供原始的 `createdAt``seedLength``delegationDepth`
- `ctx.sessions.flush(session)` 通过会话捕获的作用域分发受等待的并行持久性检查点。每个监听器都会启动调用会等待全部结算后才报告失败未发布、已脱离陈旧对象会被拒绝。
- `ctx.sessions.fork(source, boundary?, childSessionId?): Session`:解析实时会话对象或 id选取截至 `boundary` 事件序号(含该事件)的种子(默认为当前最后一个事件),要求所选前缀结束时没有开放轮次,再创建带谱系元数据的实时子会话。
- `ctx.sessions.get(id: SessionId): Session | undefined`
- `ctx.sessions.list(): Session[]`
@@ -43,7 +42,7 @@
- `session.surface` 暴露只读 `SessionSurface` 视图,由会话唯一的增量 surface 管理器所有;每次提交重写,`replaceGeneration` 都会变化。
- `session.events` 是按追加失效的缓存冻结快照;已接受事件保持深度冻结。
- `session.seq``session.id`:当前序号和只读类型化身份。
- `session.header: SessionHeader`:脱离、深冻结的创建元数据(`version``id``createdAt`,以及可选的 `cwd``timeZone``parentSession``seedLength``delegationDepth`)。构造时会校验持久记录,并要求其中的 id 与 `session.id` 一致。
- `session.header: SessionHeader`:脱离、深冻结的创建元数据(`version``id``createdAt`,以及可选的 `cwd``parentSession``seedLength``delegationDepth`)。构造时会校验持久记录,并要求其中的 id 与 `session.id` 一致。
### 无损 JSON 工具
@@ -84,7 +83,7 @@
### 元数据类型(`types.ts`
- `SessionHeader`:会话元数据,在发布为 `Session.header` 时写入一次;脱离和深冻结保证运行时不可变:`{ version, id, createdAt, cwd?, timeZone?, parentSession?, seedLength?, delegationDepth? }`可选的 `timeZone` 是由调用方校验的不透明字符串:会话核心仅检查其存储形状,并在重建和 fork 过程中原样保留。持久化 loader 可返回相同数据类型的可变脱离副本。该类型由此包与 `SessionId` 一同所有,因为 `Session.header` 以它为类型;持久化后端只是重新导出而不拥有它,否则会形成包循环依赖。
- `SessionHeader`:会话元数据,在发布为 `Session.header` 时写入一次;脱离和深冻结保证运行时不可变:`{ version, id, createdAt, cwd?, parentSession?, seedLength?, delegationDepth? }`。持久化 loader 可返回相同数据类型的可变脱离副本。该类型由此包与 `SessionId` 一同所有,因为 `Session.header` 以它为类型;持久化后端只是重新导出而不拥有它,否则会形成包循环依赖。
### 扩展点

View File

@@ -135,9 +135,6 @@ function validateSessionHeader(id: SessionId, input: unknown): SessionHeader {
throw new Error(`session header cwd must be an absolute path, got "${record.cwd}"`)
}
}
if (record.timeZone !== undefined && typeof record.timeZone !== 'string') {
throw new Error('session header timeZone must be a string')
}
if (record.parentSession !== undefined && typeof record.parentSession !== 'string') {
throw new Error('session header parentSession must be a string')
}
@@ -451,8 +448,8 @@ export class Session {
}
/**
* Detached, deep-frozen creation metadata (format version, cwd, time zone,
* lineage, seed boundary). Supplied by the store via `ctx.sessions.create()`. When a
* Detached, deep-frozen creation metadata (format version, cwd, lineage,
* seed boundary). Supplied by the store via `ctx.sessions.create()`. When a
* `Session` is created without a store-owned header, a minimal header is
* synthesized (stamped with the current {@link SESSION_FORMAT_VERSION}) so
* `session.header` is always present. Kept out of the event log — it is a
@@ -828,8 +825,8 @@ export class SessionStore extends Service {
* Create a session owned by the calling fiber: disposing that fiber stops
* event notification and removes the session from the store. `options.seed`
* populates the session with a copy of those events (replay/fork);
* `options.meta` attaches creation metadata (validated absolute `cwd`, opaque
* time-zone string, seed and parent lineage, and delegation depth) as the immutable
* `options.meta` attaches creation metadata (validated absolute `cwd`, seed
* and parent lineage, and delegation depth) as the immutable
* {@link SessionHeader} (the store fills `version`/`id`/`createdAt`).
*
* For an agent whose session must be torn down IN ORDER with its loop (so the
@@ -897,7 +894,6 @@ export class SessionStore extends Service {
id: sessionId,
createdAt: meta?.createdAt ?? Date.now(),
...meta?.cwd === undefined ? {} : { cwd: meta.cwd },
...meta?.timeZone === undefined ? {} : { timeZone: meta.timeZone },
...meta?.parentSession === undefined ? {} : { parentSession: meta.parentSession },
...meta?.seedLength === undefined ? {} : { seedLength: meta.seedLength },
...meta?.origin === undefined ? {} : { origin: meta.origin },
@@ -1106,7 +1102,6 @@ export class SessionStore extends Service {
seed,
meta: {
...liveSource.header.cwd !== undefined ? { cwd: liveSource.header.cwd } : {},
...liveSource.header.timeZone !== undefined ? { timeZone: liveSource.header.timeZone } : {},
parentSession: liveSource.id,
seedLength: seed.length,
},

View File

@@ -51,11 +51,6 @@ export interface SessionHeader {
readonly createdAt: number
/** Absolute working directory the session was created in (if any). */
readonly cwd?: string
/**
* Optional caller-validated time-zone identifier captured at creation.
* Session core preserves the exact string without interpreting or canonicalizing it.
*/
readonly timeZone?: string
/** The session this one was forked from (seed lineage), if any. */
readonly parentSession?: SessionId
/**
@@ -90,8 +85,6 @@ export interface CreateSessionOptions {
*/
readonly meta?: {
readonly cwd?: string
/** Caller-validated time-zone identifier to preserve verbatim in the header. */
readonly timeZone?: string
readonly parentSession?: SessionId
readonly createdAt?: number
readonly seedLength?: number

View File

@@ -63,9 +63,7 @@ function inherited(session: Session): readonly SessionEvent[] {
describe('SessionStore.fork', () => {
it('forks an empty live session as an empty child with lineage metadata', async () => {
const { ctx, sessions } = await setup()
const source = ctx.sessions.create(SessionId('empty-parent'), {
meta: { cwd: '/workspace', timeZone: 'Asia/Shanghai' },
})
const source = ctx.sessions.create(SessionId('empty-parent'), { meta: { cwd: '/workspace' } })
const child = sessions.fork(source, undefined, SessionId('empty-child'))
@@ -73,21 +71,11 @@ describe('SessionStore.fork', () => {
expect(child.header).toMatchObject({
id: SessionId('empty-child'),
cwd: '/workspace',
timeZone: 'Asia/Shanghai',
parentSession: SessionId('empty-parent'),
seedLength: 0,
})
})
it('keeps a headerless fork headerless', async () => {
const { ctx, sessions } = await setup()
const source = ctx.sessions.create(SessionId('headerless-parent'), { meta: { cwd: '/workspace' } })
const child = sessions.fork(source, undefined, SessionId('headerless-child'))
expect(child.header.timeZone).toBeUndefined()
})
it('forks the latest completed boundary by default into detached frozen seed events', async () => {
const { ctx, sessions } = await setup()
const source = ctx.sessions.create(SessionId('parent'), { meta: { cwd: '/workspace' } })

View File

@@ -997,7 +997,6 @@ describe('Session', () => {
id: SessionId('header-owned'),
createdAt: 123,
cwd: '/accepted',
timeZone: 'Caller/Canonical',
parentSession: SessionId('parent'),
seedLength: 2,
}
@@ -1010,7 +1009,6 @@ describe('Session', () => {
id: 'header-owned',
createdAt: 123,
cwd: '/accepted',
timeZone: 'Caller/Canonical',
parentSession: 'parent',
seedLength: 2,
})
@@ -1065,7 +1063,6 @@ describe('Session', () => {
{ header: { ...base, createdAt: '123' }, error: /createdAt must be a non-negative safe integer/ },
{ header: { ...base, cwd: 1 }, error: /header cwd must be a string/ },
{ header: { ...base, cwd: 'relative' }, error: /header cwd must be an absolute path/ },
{ header: { ...base, timeZone: 1 }, error: /header timeZone must be a string/ },
{ header: { ...base, parentSession: 1 }, error: /header parentSession must be a string/ },
{ header: { ...base, seedLength: '1' }, error: /seedLength must be a non-negative safe integer/ },
{ header: { ...base, seedLength: 0.5 }, error: /seedLength must be a non-negative safe integer/ },
@@ -1276,17 +1273,16 @@ describe('SessionStore', () => {
expect(session.header.parentSession).toBeUndefined()
})
it('attaches cwd, timeZone, and parentSession from meta to the header', async () => {
it('attaches cwd and parentSession from meta to the header', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
const session = ctx.sessions.create(SessionId('child'), {
meta: { cwd: '/work/project', timeZone: 'Asia/Shanghai', parentSession: SessionId('parent') },
meta: { cwd: '/work/project', parentSession: SessionId('parent') },
})
expect(session.header).toMatchObject({
version: SESSION_FORMAT_VERSION,
id: 'child',
cwd: '/work/project',
timeZone: 'Asia/Shanghai',
parentSession: 'parent',
})
})
@@ -1311,7 +1307,6 @@ describe('SessionStore', () => {
const cases: Array<{ meta: unknown; error: RegExp }> = [
{ meta: { parentSession: 1n }, error: /header is not losslessly JSON-serializable/ },
{ meta: { cwd: 1 }, error: /header cwd must be a string/ },
{ meta: { timeZone: 1 }, error: /header timeZone must be a string/ },
{ meta: { parentSession: 1 }, error: /header parentSession must be a string/ },
{ meta: { createdAt: '123' }, error: /header createdAt must be a non-negative safe integer/ },
{ meta: { createdAt: 1.5 }, error: /header createdAt must be a non-negative safe integer/ },

View File

@@ -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 packages/host/apiproxy/README.md
README.md: 9b430fca1c2352334e6428eb37b80726a4e02c02
README.zh.md: c36a88b44348d0054e71ea9d796291b91fadbf20
README.md: 592e831a2e06e144844607cc7d7b71998f7fb11c
README.zh.md: f26cc471b4402c9a1d5fc5029aef4995ee1d1441

View File

@@ -34,6 +34,8 @@ Session titles ride the generic projection pair like every other domain — the
Session model selection is a session-domain contract. `session.models` returns the current `ModelSelection` separately from provider-grouped advisory models, exact-model reasoning metadata, and provider-local lookup failures. The selection may be absent from the groups and is never injected as a synthetic row; clients can prompt for another selection without turning the directory into a routing whitelist. `session.selectModel` validates the optional adapter-owned reasoning effort and assigns the complete selection for the next prompt-assembly boundary. Catalog membership is not validation: an adapter may resolve an unlisted model, while an unavailable provider or unsupported effort returns `model-unavailable`. `session.models` additionally reports `routable`: whether an adapter currently serves the selected provider. This is deliberately not derivable from the groups because an adapter may serve an unadvertised model. `session.prompt` refuses on the same fact with `model-unavailable` before opening a turn; a disabled composer is a client affordance, and the method remains callable.
`session.prompt` also accepts optional request-local `clientTimeZone` provenance. When present, the Host validates and canonicalizes `UTC` or an IANA Area/Location before Agent entry, rejects invalid input with `invalid-time-zone`, and records the canonical value on that exact `user-rpc` message beside its `rpcId`. The value is not Session, connection, create, resume, or fork state; non-browser callers may omit it.
Pending queued input is a live control-plane contract, not conversation history. The gateway derives the complete `next-turn` queue from durable `agent/inbox/spliced` mutations and broadcasts authoritative `session/queue` snapshots after each change and on reconnect; pending `next-step` steering stays outside this Web projection. Within `next-step`, user-origin messages carry the `steering` placement while injected context (approval notices, task completion, attached snapshots) carries `context` and is not surfaced until claimed. The message-local `agent/inbox/inserted`, `claimed`, and `discarded` notifications remain available to lifecycle observers but do not build the queue view. `session.updateQueue` addresses one `MessageId`; edit and remove mutate the attached Agent through `Inbox.splice()`. A claim's pure deletion splice wins races before pre-step admission, so a later operation returns `queue-item-not-found`. `session.cancel` aborts only the active turn and preserves pending inbox work; after cancellation reaches quiescence and the closing turn flushes, AgentLoop claims the next waking message in FIFO order, and the browser never resends or promotes it. Queue operations never resume a cold session, and the client never infers retirement from turn or status events.
Workspace and Session lists are separate reconnect baselines. `workspace.create({ name })` creates a uniquely titled directory under the configured root, while `workspace.create({ path })` adopts an existing canonical directory and permits basename-derived titles to repeat. `workspace.delete` removes only the Workspace registration, `session.create` accepts an optional preallocated Session id, and `host/workspace-changed`, `host/workspace-removed`, plus `host/session-added` carry committed increments in either arrival order. `workspace.archiveSession` adds one session to the registry-global archive set and answers the full updated set; `workspace.list` carries that set as the reconnect baseline and `host/archived-sessions-changed` pushes the full snapshot after every durable change. Archiving hides the session from grouping surfaces without touching its log or its workspace account; a session neither live nor persisted fails with `session-not-found`. Registration deletion preserves the directory and session logs; its Sessions remain in `session.list` and become Ungrouped. `SessionSummary.blank` and the `host/session-added` frame carry the derived zero-events bit: clients hide blank sessions and reuse them per workspace, flip blank on the first `host/session-status(running:true)`, and treat `session.list` as the reconnect authority; cold summaries are never blank because lazy persistence keeps never-appended sessions out of `list()`.

View File

@@ -34,6 +34,8 @@ Settings 分节中的 `reasoningEffort` 在 agent-default-model 插件配置中
会话模型选择属于会话领域约定。`session.models` 将当前 `ModelSelection` 与按提供方分组的建议性模型、精确模型的推理reasoning元数据和逐提供方查询失败记录分开返回。该选择可能不在这些分组中也绝不会作为合成行注入客户端可以提示用户作出另一项选择而无需把目录变成路由白名单。`session.selectModel` 校验由适配器持有的可选推理强度,并指定将在下一提示词组装边界使用的完整选择。目录成员关系不构成校验:适配器可以解析未列出的模型,而不可用的提供方或不受支持的推理强度会返回 `model-unavailable``session.models` 还会报告 `routable`,即当前是否有适配器为所选提供方提供服务。该值刻意不从分组推导,因为适配器可以服务未公布的模型。`session.prompt` 会依据同一事实,在开启轮次之前以 `model-unavailable` 拒绝;客户端禁用 composer 只是提示性设计,这个方法始终可被调用。
`session.prompt` 还接受可选的请求本地 `clientTimeZone` 来源信息。若提供该值Host 会在进入 Agent 前校验 `UTC` 或 IANA Area/Location 并将其规范化;无效输入以 `invalid-time-zone` 拒绝,规范值则与 `rpcId` 一起记录在这条确切的 `user-rpc` 消息上。该值不属于 Session、连接、create、resume 或 fork 状态;非浏览器调用方可以省略它。
待处理的 queued 输入属于实时控制平面约定,而非对话历史。网关根据持久 `agent/inbox/spliced` 变更派生完整的 `next-turn` 队列,并在每次变更后及重连时广播权威 `session/queue` 快照;待处理的 `next-step` steering中途引导不进入此 Web 投影。在 `next-step` 内,用户来源的消息携带 `steering` placement而注入上下文审批通知、任务完成、附加快照携带 `context`,领取前不对外呈现。面向单条消息的 `agent/inbox/inserted``claimed``discarded` 通知仍供生命周期观察方使用,但不用于构建队列视图。`session.updateQueue` 通过 `MessageId` 寻址单个项;编辑和移除经已挂载 Agent 的 `Inbox.splice()` 修改队列。claim 的纯删除 splice 会在 pre-step 准入前赢得竞态,因此之后的操作返回 `queue-item-not-found``session.cancel` 仅中止活动轮次并保留待处理 inbox 工作;取消达到完全停稳且结束中的轮次完成 flush 后AgentLoop 按 FIFO 顺序认领下一条可唤醒消息,浏览器绝不重发或提升它。队列操作绝不恢复冷会话,客户端也绝不根据轮次或状态事件推断某项已退出队列。
Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.create({ name })` 会在配置根目录下创建显示标题唯一的目录,而 `workspace.create({ path })` 会接纳已有的规范目录,并允许由 basename 派生的标题重复。`workspace.delete` 只移除 Workspace 注册记录,`session.create` 接受可选的预分配 Session id`host/workspace-changed``host/workspace-removed``host/session-added` 则以任意到达顺序携带已提交的增量。`workspace.archiveSession` 向注册表级全局归档集合添加一个会话,并应答完整的更新后集合;`workspace.list` 携带该集合作为重连基线,`host/archived-sessions-changed` 在每次持久变更后推送完整快照。归档只把会话从各分组视图中隐藏,不触碰其日志和 workspace 记账;既非实时也未持久化的会话以 `session-not-found` 失败。删除注册记录会保留目录和会话日志;相关 Session 仍留在 `session.list` 中,并进入 Ungrouped。`SessionSummary.blank``host/session-added` 帧携带派生的零事件位:客户端隐藏空白会话并按 workspace 复用它们,在首个 `host/session-status(running:true)` 时翻转 blank并以 `session.list` 作为重连权威;冷会话摘要永远不是空白:惰性持久化让从未追加过事件的会话根本不出现在 `list()` 中。

View File

@@ -99,6 +99,25 @@ const MESSAGE_TYPES = new Set(['user/message', 'assistant/message'])
/** Product settings intentionally exposed beside model-provider namespaces. */
const PRODUCT_SETTINGS_NAMESPACES = new Set(['ui-onboarding'])
/** Strict browser-zone profile: UTC or an IANA Area/Location-style identifier. */
const IANA_TIME_ZONE = /^[A-Za-z][A-Za-z0-9_+.-]*(?:\/[A-Za-z0-9_+.-]+)+$/
/** Validate and canonicalize one browser-supplied IANA zone at the wire boundary. */
function canonicalClientTimeZone(value: string): string | undefined {
if (value.length === 0 || value.trim() !== value
|| (value !== 'UTC' && !IANA_TIME_ZONE.test(value))) return undefined
try {
const canonical = new Intl.DateTimeFormat('en-US', { timeZone: value })
.resolvedOptions().timeZone
/* v8 ignore next -- Intl returns UTC or a canonical IANA Area/Location for accepted input. */
if (canonical !== 'UTC' && !IANA_TIME_ZONE.test(canonical)) return undefined
return canonical
} catch {
// Intl rejects unsupported zone names; the RPC maps that parser rejection below.
return undefined
}
}
/** Read live abort state across awaits without treating it as synchronously immutable. */
function isAborted(signal: AbortSignal): boolean {
return signal.aborted
@@ -1803,12 +1822,26 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro
},
async prompt(request) {
const { sessionId, mode, content } = request.payload
const { sessionId, mode, content, clientTimeZone } = request.payload
const canonicalTimeZone = clientTimeZone === undefined
? undefined
: canonicalClientTimeZone(clientTimeZone)
if (clientTimeZone !== undefined && canonicalTimeZone === undefined) {
return err(request, {
code: 'invalid-time-zone',
message: 'clientTimeZone must be UTC or a valid IANA Area/Location name',
details: { value: clientTimeZone },
})
}
const resolved = await turnAgentFor<{ accepted: true }>(request, sessionId)
if ('refused' in resolved) return resolved.refused
const agent = resolved.agent
// The rpcId rides MessageSource into user/message (merge declaration in api/sessions.ts; provisional correlation).
const source: MessageSource = { kind: 'user', rpcId: request.rpcId }
// Request identity and optional browser zone ride the exact durable user message.
const source: MessageSource = {
kind: 'user',
rpcId: request.rpcId,
...(canonicalTimeZone === undefined ? {} : { clientTimeZone: canonicalTimeZone }),
}
try {
const message: UserMessage = createUserMessage({ content, source })
if (mode === 'steer') agent.steer(message)

View File

@@ -36,25 +36,8 @@ export const rpcErrorSchema: z.ZodType<RpcError> = z.discriminatedUnion('code',
z.object({ code: z.literal('cancelled'), message: z.string(), details: z.object({}) }),
z.object({ code: z.literal('session-not-found'), message: z.string(), details: z.object({ sessionId: z.string() }) }),
z.object({ code: z.literal('model-unavailable'), message: z.string(), details: z.object({ provider: z.string(), model: z.string() }) }),
z.object({
code: z.literal('session-conflict'),
message: z.string(),
details: z.object({
sessionId: z.string(),
requestedCwd: z.string(),
existingCwd: z.string().optional(),
requestedTimeZone: z.string(),
existingTimeZone: z.string().optional(),
}),
}),
z.object({
code: z.literal('invalid-time-zone'),
message: z.string(),
details: z.object({
field: z.union([z.literal('timeZone'), z.literal('clientTimeZone')]),
value: z.union([z.string(), z.null()]),
}),
}),
z.object({ code: z.literal('session-conflict'), message: z.string(), details: z.object({ sessionId: z.string(), requestedCwd: z.string(), existingCwd: z.string().optional() }) }),
z.object({ code: z.literal('invalid-time-zone'), message: z.string(), details: z.object({ value: z.string() }) }),
z.object({ code: z.literal('workspace-attach-failed'), message: z.string(), details: z.object({ sessionId: z.string(), workspaceId: z.string() }) }),
z.object({ code: z.literal('workspace-not-found'), message: z.string(), details: z.object({ workspaceId: z.string() }) }),
z.object({ code: z.literal('workspace-invalid-path'), message: z.string(), details: z.object({ path: z.string() }) }),

View File

@@ -34,14 +34,8 @@ export interface RpcErrorDetailsMap {
'cancelled': {}
'session-not-found': { sessionId: SessionId }
'model-unavailable': { provider: string; model: string }
'session-conflict': {
sessionId: SessionId
requestedCwd: string
existingCwd?: string
requestedTimeZone: string
existingTimeZone?: string
}
'invalid-time-zone': { field: 'timeZone' | 'clientTimeZone'; value: string | null }
'session-conflict': { sessionId: SessionId; requestedCwd: string; existingCwd?: string }
'invalid-time-zone': { value: string }
'workspace-attach-failed': { sessionId: SessionId; workspaceId: string }
'workspace-not-found': { workspaceId: string }
'workspace-invalid-path': { path: string }

View File

@@ -95,12 +95,11 @@ export const sessionSearchValueSchema = z.object({
hasMore: z.boolean(),
}) satisfies z.ZodType<Wire<ResponseValue<'session.search'>>>
/** session.create payload; timeZone stays schema-optional so Host omission returns `invalid-time-zone`. */
/** session.create request payload (at most one of workspaceId / cwd). */
export const sessionCreateRequestSchema = z.object({
workspaceId: workspaceIdSchema.optional(),
cwd: z.string().optional(),
sessionId: sessionIdSchema.optional(),
timeZone: z.string().optional(),
}).refine(
payload => payload.workspaceId === undefined || payload.cwd === undefined,
{ message: 'session.create accepts workspaceId or cwd, not both' },
@@ -247,7 +246,7 @@ export const sessionSelectModelValueSchema = z.object({
/** ContentBlock passthrough: core is merge-extensible — the type discriminant envelope is strict, the rest stays wide. */
export const contentBlockSchema = z.looseObject({ type: z.string() })
/** session.prompt payload; clientTimeZone stays schema-optional so Host omission returns `invalid-time-zone`. */
/** session.prompt request payload, including optional browser-local request provenance. */
export const sessionPromptRequestSchema = z.object({
sessionId: sessionIdSchema,
mode: z.union([z.literal('queue'), z.literal('steer')]),

View File

@@ -20,9 +20,10 @@ declare module '@deepseek-ai/dsh-llm' {
* The prompt's rpcId is passed through MessageSource into the `user/message` event
* (the client uses it to reconcile the optimistically
* echoed provisional message with the event stream). kind stays `'user'` — the model face
* carries no transport vocabulary; rpcId is an extra durable-JSON field passed back to the client with the event.
* carries no transport vocabulary; rpcId and the optional Host-validated browser zone are
* durable JSON fields passed back to the client with the event.
*/
'user-rpc': { kind: 'user'; rpcId: RpcId; clientTimeZone: string }
'user-rpc': { kind: 'user'; rpcId: RpcId; clientTimeZone?: string }
}
}
@@ -204,20 +205,12 @@ export interface SessionsApi {
/**
* Creates a real session and its idle agent. At most one of `workspaceId` /
* `cwd` is accepted; an omitted project uses the Host cwd. A caller may
* preallocate `sessionId`: retries with the same id, cwd, and canonical time
* zone return the same session, while a different owned identity fails with
* `session-conflict`. A headerless persisted session remains compatible with
* the same cwd but never absorbs the request zone. Workspace
* preallocate `sessionId`: retries with the same id and cwd return the same
* session, while a different cwd fails with `session-conflict`. Workspace
* creation attaches the session after publication; an attach failure
* returns `workspace-attach-failed` with the published session id.
*/
create(request: RpcRequest<{
workspaceId?: WorkspaceId
cwd?: string
sessionId?: SessionId
/** Required by the Host; optional here so omission returns the stable `invalid-time-zone` RPC error. */
timeZone?: string
}>):
create(request: RpcRequest<{ workspaceId?: WorkspaceId; cwd?: string; sessionId?: SessionId }>):
Promise<RpcResponse<{ sessionId: SessionId }>>
/**
@@ -296,12 +289,16 @@ export interface SessionsApi {
fork(request: RpcRequest<{ sessionId: SessionId; atSeq?: number }>):
Promise<RpcResponse<{ sessionId: SessionId }>>
/** Sends a message to an ordinary session Agent. Session-backed subagents reject with `agent-busy` and use `subagent.prompt`. */
/**
* Sends a message to an ordinary session Agent. Browser callers attach their current IANA zone;
* the Host validates, canonicalizes, and records it on that exact user message. Omission remains
* valid for non-browser callers. Session-backed subagents reject with `agent-busy` and use
* `subagent.prompt`.
*/
prompt(request: RpcRequest<{
sessionId: SessionId
mode: 'queue' | 'steer'
content: ContentBlock[]
/** Required by the Host; optional here so omission returns the stable `invalid-time-zone` RPC error. */
clientTimeZone?: string
}>):
Promise<RpcResponse<{ accepted: true; command?: { kind: 'success'; text?: string } }>>

View File

@@ -31,10 +31,7 @@ const sid = (id: string): SessionId => id as SessionId
let nextRpc = 1
function request<P>(payload: P): RpcRequest<P> {
return {
rpcId: RpcId(`cold-${String(nextRpc++)}`),
payload: { timeZone: 'UTC', clientTimeZone: 'UTC', ...payload },
}
return { rpcId: RpcId(`cold-${String(nextRpc++)}`), payload }
}
function header(id: string, createdAt: number, extra: Partial<SessionHeader> = {}): SessionHeader {
@@ -471,6 +468,81 @@ describe('subagent ownership fence', () => {
expect(response.result.ok).toBe(true)
expect(followup).toHaveBeenCalledOnce()
})
it('canonicalizes a supplied browser zone on the exact prompt and rejects invalid names', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(AgentRegistry)
await ctx.plugin(UserInteractionService)
const session = ctx.sessions.create(sid('session-browser-zone'), { meta: { cwd: '/proj' } })
const followup = vi.fn()
const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
ctx.agents.register(agent)
const api = createApiProxy(ctx, {
defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
cwd: '/tmp',
workspaceRoot: '/tmp',
})
const alias = 'US/Pacific'
const canonical = new Intl.DateTimeFormat('en-US', { timeZone: alias })
.resolvedOptions().timeZone
const zonedRequest = request({
sessionId: agent.id,
mode: 'queue' as const,
content: [{ type: 'text' as const, text: 'zoned work' }],
clientTimeZone: alias,
})
await expect(api.sessions.prompt(zonedRequest)).resolves.toMatchObject({
result: { ok: true },
})
expect(followup).toHaveBeenNthCalledWith(1, expect.objectContaining({
source: { kind: 'user', rpcId: zonedRequest.rpcId, clientTimeZone: canonical },
}))
const utcRequest = request({
sessionId: agent.id,
mode: 'queue' as const,
content: [{ type: 'text' as const, text: 'UTC work' }],
clientTimeZone: 'UTC',
})
await expect(api.sessions.prompt(utcRequest)).resolves.toMatchObject({
result: { ok: true },
})
expect(followup).toHaveBeenNthCalledWith(2, expect.objectContaining({
source: { kind: 'user', rpcId: utcRequest.rpcId, clientTimeZone: 'UTC' },
}))
const unzonedRequest = request({
sessionId: agent.id,
mode: 'queue' as const,
content: [{ type: 'text' as const, text: 'headless work' }],
})
await expect(api.sessions.prompt(unzonedRequest)).resolves.toMatchObject({
result: { ok: true },
})
expect(followup).toHaveBeenNthCalledWith(3, expect.objectContaining({
source: { kind: 'user', rpcId: unzonedRequest.rpcId },
}))
for (const clientTimeZone of ['', ' UTC', 'CST', 'Not/A_Real_Zone']) {
const invalid = await api.sessions.prompt(request({
sessionId: agent.id,
mode: 'queue' as const,
content: [{ type: 'text' as const, text: 'invalid zone' }],
clientTimeZone,
}))
expect(invalid.result).toEqual({
ok: false,
error: {
code: 'invalid-time-zone',
message: 'clientTimeZone must be UTC or a valid IANA Area/Location name',
details: { value: clientTimeZone },
},
})
}
expect(followup).toHaveBeenCalledTimes(3)
})
})
describe('degenerate composition (no persistence, no factory)', () => {
@@ -513,89 +585,6 @@ describe('degenerate composition (no persistence, no factory)', () => {
})
})
describe('cold Session zone identity', () => {
it('rejects a different requested zone before resuming a persisted identity', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(AgentRegistry)
await ctx.plugin(UserInteractionService)
const sessionId = sid('session-cold-zone-conflict')
const meta = header('session-cold-zone-conflict', 1000, { timeZone: 'UTC' })
ctx.provide('sessionPersistence', {
list: () => Promise.resolve([meta]),
inspect: () => Promise.resolve({ meta, events: [] as SessionEvent[] }),
locate: () => undefined,
} as never)
const resume = vi.spyOn(ctx.agents, 'resume')
const api = createApiProxy(ctx, { defaultTarget: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
const response = await api.sessions.create(request({
sessionId,
cwd: '/proj',
timeZone: 'Asia/Shanghai',
}))
expect(response.result).toMatchObject({
ok: false,
error: {
code: 'session-conflict',
details: {
sessionId,
existingCwd: '/proj',
existingTimeZone: 'UTC',
requestedTimeZone: 'Asia/Shanghai',
},
},
})
expect(resume).not.toHaveBeenCalled()
})
it.each([
['a missing zone', undefined, null],
['an invalid zone', 'CST', 'CST'],
] as const)('rejects %s before resuming a cold Session', async (_case, clientTimeZone, detailValue) => {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(AgentRegistry)
await ctx.plugin(UserInteractionService)
const sessionId = sid('session-cold-prompt-zone')
const meta = header('session-cold-prompt-zone', 1000, { timeZone: 'UTC' })
ctx.provide('sessionPersistence', {
list: () => Promise.resolve([meta]),
inspect: () => Promise.resolve({ meta, events: [] as SessionEvent[] }),
locate: () => undefined,
} as never)
const resume = vi.spyOn(ctx.agents, 'resume')
const api = createApiProxy(ctx, {
defaultTarget: () => ({ provider: 'p', model: 'm' }),
cwd: '/tmp',
workspaceRoot: '/tmp',
})
const promptRequest = request({
sessionId,
mode: 'queue' as const,
content: [{ type: 'text' as const, text: 'rejected before resume' }],
clientTimeZone: clientTimeZone ?? 'UTC',
})
if (clientTimeZone === undefined) {
delete (promptRequest.payload as { clientTimeZone?: string }).clientTimeZone
}
const response = await api.sessions.prompt(promptRequest)
expect(response.result).toMatchObject({
ok: false,
error: {
code: 'invalid-time-zone',
details: { field: 'clientTimeZone', value: detailValue },
},
})
expect(resume).not.toHaveBeenCalled()
expect(ctx.agents.get(sessionId)).toBeUndefined()
await ctx.fiber.dispose()
})
})
describe('sessions.prompt synchronous rejection', () => {
it('maps a synchronous send throw (disposed/invalid input) to agent-busy with the reason attached', async () => {
const ctx = new Context()

View File

@@ -55,7 +55,7 @@ function liveAgent(
id: string,
turns: number,
tail: Tail = 'none',
lineage: { parentSession?: SessionId; origin?: 'subagent'; timeZone?: string } = {},
lineage: { parentSession?: SessionId; origin?: 'subagent' } = {},
): Session {
const session = ctx.sessions.create(sid(id), { meta: { cwd: '/proj', ...lineage } })
for (let turn = 1; turn <= turns; turn++) {
@@ -90,7 +90,7 @@ const api = (ctx: Context) => createApiProxy(ctx, {
describe('sessions.fork', () => {
it('cuts at the anchored completed turn and records lineage and cwd', async () => {
const ctx = await composed()
const source = liveAgent(ctx, 'session-source', 2, 'none', { timeZone: 'Asia/Shanghai' })
const source = liveAgent(ctx, 'session-source', 2)
const response = await api(ctx).sessions.fork(request({ sessionId: source.id, atSeq: 1 }))
expect(response.result.ok).toBe(true)
if (!response.result.ok) return
@@ -100,7 +100,6 @@ describe('sessions.fork', () => {
])
expect(child?.header.parentSession).toBe(source.id)
expect(child?.header.cwd).toBe('/proj')
expect(child?.header.timeZone).toBe('Asia/Shanghai')
await ctx.fiber.dispose()
})
@@ -158,7 +157,6 @@ describe('sessions.fork', () => {
id: sourceId,
createdAt: 1,
cwd: '/proj',
timeZone: 'America/New_York',
parentSession: parentId,
origin: 'subagent',
}
@@ -197,7 +195,6 @@ describe('sessions.fork', () => {
expect(ctx.sessions.get(response.result.value.sessionId)?.header).toMatchObject({
parentSession: sourceId,
cwd: '/proj',
timeZone: 'America/New_York',
})
expect(ctx.sessions.get(response.result.value.sessionId)?.header.origin).toBeUndefined()
await ctx.fiber.dispose()

View File

@@ -315,7 +315,6 @@ describe('Web session model selection', () => {
// callable, so the refusal has to live here.
const refused = await api.sessions.prompt(request({
sessionId, mode: 'queue' as const, content: [{ type: 'text' as const, text: 'hi' }],
clientTimeZone: 'UTC',
}))
expect(refused.result).toMatchObject({
ok: false,

View File

@@ -1,298 +0,0 @@
/**
* Schedule reminder views cross the Host only after persistence proves their
* dispatch prefix. Live append sends raw events; session/flushed replays the
* identical dispatch with a generic sidecar. History independently gates the
* same projection on an identity-matching stored prefix.
*/
import { Context } from 'cordis'
import { describe, expect, it } from 'vitest'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import type { Session, SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRegistry from '@deepseek-ai/dsh-tools'
import type { MuxFrame, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api'
import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
import { createApiProxy } from '@deepseek-ai/dsh-host-apiproxy'
import { ScheduleId } from '@deepseek-ai/dsh-tool-schedule'
interface FlushControl {
handler: () => true | Promise<true>
}
function reminderCreateData(id: string, prompt: string) {
return {
version: 1 as const,
operation: 'create' as const,
schedule: {
id: ScheduleId(id),
kind: 'after' as const,
prompt,
afterSeconds: 1,
scheduledAt: '2026-08-05T12:00:01.000Z',
},
}
}
async function harness(control?: FlushControl): Promise<Context> {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(SystemPrompt, { persona: '' })
await ctx.plugin(ToolRegistry)
await ctx.plugin(UserInteractionService)
await ctx.plugin(AgentRegistry)
if (control !== undefined) ctx.on('session/flush', () => control.handler())
return ctx
}
function appendReminder(
session: Session,
id: string,
prompt: string,
): { create: SessionEvent; dispatch: SessionEvent } {
const scheduleId = ScheduleId(id)
const create = session.append('schedule/change', reminderCreateData(id, prompt))
const dispatch = session.append('schedule/change', {
version: 1,
operation: 'dispatch',
id: scheduleId,
})
return { create, dispatch }
}
async function collectEvents(
iterable: AsyncIterable<RpcRequest<MuxFrame>>,
count: number,
abort: AbortController,
): Promise<Extract<MuxFrame, { type: 'session/event' }>[]> {
const events: Extract<MuxFrame, { type: 'session/event' }>[] = []
for await (const envelope of iterable) {
if (envelope.payload.type !== 'session/event') continue
events.push(envelope.payload)
if (events.length >= count) abort.abort()
}
return events
}
describe('commit-aware Schedule live views', () => {
it('takes the max of reverse flush completion and replays each dispatch once', async () => {
const first = Promise.withResolvers<true>()
let calls = 0
const ctx = await harness({
handler: () => ++calls === 1 ? first.promise : true,
})
const api = createApiProxy(ctx, { defaultTarget: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
const abort = new AbortController()
const collected = collectEvents(
api.events.mux({ rpcId: RpcId('schedule-live'), payload: {} }, abort.signal),
6,
abort,
)
const session = ctx.sessions.create(SessionId('schedule-live'))
const firstPair = appendReminder(session, 'schedule-1', 'first')
const slow = ctx.sessions.flush(session)
const secondPair = appendReminder(session, 'schedule-2', 'second')
await expect(ctx.sessions.flush(session)).resolves.toBe(true)
first.resolve(true)
await expect(slow).resolves.toBe(true)
const frames = await collected
const raw = frames.filter(frame => frame.view === undefined)
const presented = frames.filter(frame => frame.view?.for === 'event')
expect(raw.map(frame => frame.event.seq)).toEqual([0, 1, 2, 3])
expect(presented.map(frame => frame.event.seq)).toEqual([1, 3])
expect(presented[0]?.event).toBe(firstPair.dispatch)
expect(presented[1]?.event).toBe(secondPair.dispatch)
expect(presented.map(frame => frame.view)).toEqual([
{
for: 'event',
view: {
scheduleId: 'schedule-1', prompt: 'first',
occurrenceAt: '2026-08-05T12:00:01.000Z',
},
},
{
for: 'event',
view: {
scheduleId: 'schedule-2', prompt: 'second',
occurrenceAt: '2026-08-05T12:00:01.000Z',
},
},
])
expect(firstPair.create.seq).toBe(0)
await ctx.fiber.dispose()
})
it('withholds a view after rejection and publishes it on the next successful checkpoint', async () => {
let calls = 0
const ctx = await harness({
handler: () => ++calls === 1 ? Promise.reject(new Error('disk unavailable')) : true,
})
const api = createApiProxy(ctx, { defaultTarget: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
const abort = new AbortController()
const collected = collectEvents(
api.events.mux({ rpcId: RpcId('schedule-retry'), payload: {} }, abort.signal),
3,
abort,
)
const session = ctx.sessions.create(SessionId('schedule-retry'))
appendReminder(session, 'schedule-1', 'retry me')
await expect(ctx.sessions.flush(session)).rejects.toThrow('disk unavailable')
await expect(ctx.sessions.flush(session)).resolves.toBe(true)
const frames = await collected
expect(frames.filter(frame => frame.view?.for === 'event')).toHaveLength(1)
expect(frames.at(-1)?.view).toMatchObject({
for: 'event',
})
await ctx.fiber.dispose()
})
})
describe('Schedule history views', () => {
it('presents a resumed ancestor dispatch copied into a fork seed', async () => {
const ctx = await harness()
const scheduleId = ScheduleId('resumed-reminder')
const resumed = ctx.sessions.create(SessionId('schedule-resumed'), {
seed: [{
type: 'schedule/change',
seq: 0,
time: 1,
data: reminderCreateData('resumed-reminder', 'after restart'),
}],
meta: { cwd: '/tmp' },
})
const dispatch = resumed.append('schedule/change', {
version: 1,
operation: 'dispatch',
id: scheduleId,
})
const child = ctx.sessions.fork(resumed, undefined, SessionId('schedule-fork'))
ctx.provide('sessionPersistence', {
readFrom: () => Promise.resolve({ meta: child.header, events: [...child.events] }),
} as never)
const api = createApiProxy(ctx, { defaultTarget: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
const response = await api.sessions.history({
rpcId: RpcId('schedule-resumed-fork'), payload: { sessionId: child.id },
})
if (!response.result.ok) throw new Error(response.result.error.message)
expect(response.result.value.events.find(entry => entry.event.seq === dispatch.seq)?.view).toEqual({
for: 'event',
view: {
scheduleId,
prompt: 'after restart',
occurrenceAt: '2026-08-05T12:00:01.000Z',
},
})
await ctx.fiber.dispose()
})
it('uses only the attached identity-matching stored prefix and fails soft to raw history', async () => {
const ctx = await harness()
const parent = ctx.sessions.create(SessionId('schedule-parent'), { meta: { cwd: '/tmp' } })
appendReminder(parent, 'parent-reminder', 'from parent')
const session = ctx.sessions.create(SessionId('schedule-attached'), {
seed: [...parent.events],
meta: { cwd: '/tmp', parentSession: parent.id, seedLength: 2 },
})
let readFrom = (): Promise<{ meta: SessionHeader; events: SessionEvent[] }> => Promise.resolve({
meta: session.header,
events: [...session.events.slice(0, 1)],
})
ctx.provide('sessionPersistence', {
readFrom: () => readFrom(),
} as never)
const api = createApiProxy(ctx, { defaultTarget: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
const history = async () => {
const response = await api.sessions.history({
rpcId: RpcId('schedule-history'), payload: { sessionId: session.id },
})
if (!response.result.ok) throw new Error(response.result.error.message)
return response.result.value.events
}
expect((await history()).find(entry => entry.event.seq === 1)?.view).toBeUndefined()
readFrom = () => Promise.resolve({
meta: { ...session.header, delegationDepth: 0 },
events: [...session.events.slice(0, 2)],
})
expect((await history()).find(entry => entry.event.seq === 1)?.view).toMatchObject({
for: 'event',
})
readFrom = () => Promise.resolve({
meta: { ...session.header, cwd: '/different', delegationDepth: 0 },
events: [...session.events.slice(0, 2)],
})
expect((await history()).find(entry => entry.event.seq === 1)?.view).toBeUndefined()
readFrom = () => Promise.resolve({
meta: { ...session.header, timeZone: 'UTC', delegationDepth: 0 },
events: [...session.events.slice(0, 2)],
})
expect((await history()).find(entry => entry.event.seq === 1)?.view).toBeUndefined()
readFrom = () => Promise.reject(new Error('physical read unavailable'))
expect((await history()).find(entry => entry.event.seq === 1)?.view).toBeUndefined()
await ctx.fiber.dispose()
})
it('presents every dispatch in detached persisted history', async () => {
const ctx = await harness()
let source: Session | undefined
const owner = await ctx.plugin(Object.assign((inner: Context) => {
source = inner.sessions.create(SessionId('schedule-source'), { meta: { cwd: '/tmp' } })
}, { inject: ['sessions'] }))
if (source === undefined) throw new Error('session owner did not publish its session')
appendReminder(source, 'schedule-1', 'cold reminder')
const meta = source.header
const events = [...source.events]
await owner.dispose()
ctx.provide('sessionPersistence', {
list: () => Promise.resolve([meta]),
inspect: () => Promise.resolve({ meta, events }),
readFrom: () => Promise.resolve({ meta, events }),
} as never)
const api = createApiProxy(ctx, { defaultTarget: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
const response = await api.sessions.history({
rpcId: RpcId('schedule-cold'), payload: { sessionId: meta.id },
})
if (!response.result.ok) throw new Error(response.result.error.message)
expect(response.result.value.events.find(entry => entry.event.seq === 1)?.view).toMatchObject({
for: 'event',
})
await ctx.fiber.dispose()
})
it('withholds a detached view that exists only in a logical inspection', async () => {
const ctx = await harness()
let source: Session | undefined
const owner = await ctx.plugin(Object.assign((inner: Context) => {
source = inner.sessions.create(SessionId('schedule-logical-only'), { meta: { cwd: '/tmp' } })
}, { inject: ['sessions'] }))
if (source === undefined) throw new Error('session owner did not publish its session')
appendReminder(source, 'schedule-logical', 'not physically committed')
const meta = source.header
const events = [...source.events]
await owner.dispose()
let physicalEvents = events.slice(0, 1)
ctx.provide('sessionPersistence', {
list: () => Promise.resolve([meta]),
inspect: () => Promise.resolve({ meta, events }),
readFrom: () => Promise.resolve({ meta, events: physicalEvents }),
} as never)
const api = createApiProxy(ctx, { defaultTarget: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
const history = async () => {
const response = await api.sessions.history({
rpcId: RpcId('schedule-logical-only-history'), payload: { sessionId: meta.id },
})
if (!response.result.ok) throw new Error(response.result.error.message)
return response.result.value.events
}
expect((await history()).find(entry => entry.event.seq === 1)?.view).toBeUndefined()
physicalEvents = events
expect((await history()).find(entry => entry.event.seq === 1)?.view).toMatchObject({ for: 'event' })
await ctx.fiber.dispose()
})
})

View File

@@ -22,10 +22,7 @@ import { MemoryStorageBackend } from '../../../storage/storage-domain/tests/help
let nextRpc = 1
function request<P>(payload: P): RpcRequest<P> {
return {
rpcId: RpcId(`workspace-${String(nextRpc++)}`),
payload: { timeZone: 'UTC', clientTimeZone: 'UTC', ...payload },
}
return { rpcId: RpcId(`workspace-${String(nextRpc++)}`), payload }
}
function expectOk<T>(response: RpcResponse<T>): T {
@@ -362,157 +359,6 @@ describe('session creation and Workspace membership', () => {
expectOk(await api.sessions.create(request({ workspaceId: created.workspaceId, sessionId })))
expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId])
})
it('canonicalizes the immutable Session zone and rejects identity conflicts', async () => {
const { api, ctx, workspaceRoot } = await harness()
const sessionId = SessionId('session-zone-identity')
const alias = 'US/Eastern'
const canonical = new Intl.DateTimeFormat('en-US', { timeZone: alias })
.resolvedOptions().timeZone
expectOk(await api.sessions.create(request({ sessionId, cwd: workspaceRoot, timeZone: alias })))
expect(ctx.agents.get(sessionId)?.session.header.timeZone).toBe(canonical)
expectOk(await api.sessions.create(request({ sessionId, cwd: workspaceRoot, timeZone: canonical })))
const conflict = await api.sessions.create(request({
sessionId,
cwd: workspaceRoot,
timeZone: 'Asia/Shanghai',
}))
expect(conflict.result).toMatchObject({
ok: false,
error: {
code: 'session-conflict',
details: {
sessionId,
requestedCwd: workspaceRoot,
requestedTimeZone: 'Asia/Shanghai',
existingTimeZone: canonical,
},
},
})
})
it('keeps a live headerless Session compatible without absorbing a request zone', async () => {
const { api, ctx, workspaceRoot } = await harness()
const session = ctx.sessions.create(SessionId('session-zone-headerless'), {
meta: { cwd: workspaceRoot },
})
ctx.agents.register(stubAgent(session))
expectOk(await api.sessions.create(request({
sessionId: session.id,
cwd: workspaceRoot,
timeZone: 'Asia/Shanghai',
})))
expect(session.header.timeZone).toBeUndefined()
})
it('serializes different-zone creates so the first immutable identity wins', async () => {
const { api, ctx, workspaceRoot } = await harness()
const sessionId = SessionId('session-zone-race')
const first = api.sessions.create(request({
sessionId,
cwd: workspaceRoot,
timeZone: 'UTC',
}))
const second = api.sessions.create(request({
sessionId,
cwd: workspaceRoot,
timeZone: 'Asia/Shanghai',
}))
const [firstResult, secondResult] = await Promise.all([first, second])
expect(firstResult.result).toMatchObject({ ok: true, value: { sessionId } })
expect(secondResult.result).toMatchObject({
ok: false,
error: { code: 'session-conflict', details: { existingTimeZone: 'UTC' } },
})
expect(ctx.agents.get(sessionId)?.session.header.timeZone).toBe('UTC')
})
it.each([
[undefined, null],
['', ''],
[' UTC', ' UTC'],
['CST', 'CST'],
['GMT', 'GMT'],
['+08:00', '+08:00'],
['Not/A_Real_Zone', 'Not/A_Real_Zone'],
] as const)('rejects invalid Session zone input %j before Agent creation', async (timeZone, value) => {
const { api, ctx } = await harness()
const invalidRequest = request({})
Object.assign(invalidRequest.payload, { timeZone })
const response = await api.sessions.create(invalidRequest)
expect(response.result).toMatchObject({
ok: false,
error: { code: 'invalid-time-zone', details: { field: 'timeZone', value } },
})
expect(ctx.agents.list()).toHaveLength(0)
})
it('binds each canonical client zone to its own queued or steering message source', async () => {
const { api, ctx } = await harness()
const sessionId = expectOk(await api.sessions.create(request({ timeZone: 'UTC' }))).sessionId
const agent = ctx.agents.get(sessionId)
if (agent === undefined) throw new Error('created Agent missing')
const followup = vi.spyOn(agent, 'followup')
const steer = vi.spyOn(agent, 'steer')
const alias = 'US/Eastern'
const canonical = new Intl.DateTimeFormat('en-US', { timeZone: alias })
.resolvedOptions().timeZone
expectOk(await api.sessions.prompt(request({
sessionId,
mode: 'queue',
content: [{ type: 'text', text: 'queue' }],
clientTimeZone: alias,
})))
expectOk(await api.sessions.prompt(request({
sessionId,
mode: 'steer',
content: [{ type: 'text', text: 'steer' }],
clientTimeZone: 'Asia/Shanghai',
})))
expect(followup.mock.calls[0]?.[0].source).toMatchObject({
kind: 'user',
clientTimeZone: canonical,
})
expect(steer.mock.calls[0]?.[0].source).toMatchObject({
kind: 'user',
clientTimeZone: 'Asia/Shanghai',
})
})
it.each([undefined, '', 'CST', 'Not/A_Real_Zone'] as const)(
'rejects invalid prompt zone input %j before delivery',
async (clientTimeZone) => {
const { api, ctx } = await harness()
const sessionId = expectOk(await api.sessions.create(request({ timeZone: 'UTC' }))).sessionId
const agent = ctx.agents.get(sessionId)
if (agent === undefined) throw new Error('created Agent missing')
const followup = vi.spyOn(agent, 'followup')
const invalidRequest = request({
sessionId,
mode: 'queue' as const,
content: [{ type: 'text' as const, text: 'rejected' }],
})
Object.assign(invalidRequest.payload, { clientTimeZone })
const response = await api.sessions.prompt(invalidRequest)
expect(response.result).toMatchObject({
ok: false,
error: {
code: 'invalid-time-zone',
details: { field: 'clientTimeZone', value: clientTimeZone ?? null },
},
})
expect(followup).not.toHaveBeenCalled()
},
)
})
describe('Host Workspace increments', () => {

View File

@@ -310,7 +310,7 @@ describe('unary round trip (handler ⇄ client, no network)', () => {
ok: true,
value: { items: [{ sessionId: 's1', snippet: 'fixture match' }], hasMore: false },
})
expect((await c.sessions.create({ timeZone: 'UTC' })).result.ok).toBe(true)
expect((await c.sessions.create({})).result.ok).toBe(true)
expect((await c.sessions.models({ sessionId: 's' as never })).result.ok).toBe(true)
const selected = await c.sessions.selectModel({
sessionId: 's' as never,
@@ -330,12 +330,7 @@ describe('unary round trip (handler ⇄ client, no network)', () => {
})
const renamed = await c.sessions.rename({ sessionId: 's' as never, title: 'named' })
expect(renamed.result).toMatchObject({ ok: true, value: { title: 'named', seq: 0 } })
expect((await c.sessions.prompt({
sessionId: 's' as never,
mode: 'queue',
content: [{ type: 'text', text: 'x' }],
clientTimeZone: 'UTC',
})).result.ok).toBe(true)
expect((await c.sessions.prompt({ sessionId: 's' as never, mode: 'queue', content: [{ type: 'text', text: 'x' }] })).result.ok).toBe(true)
expect((await c.sessions.updateQueue({
sessionId: 's' as never,
itemId: 'item-1' as never,

View File

@@ -59,7 +59,8 @@ describe('rpcErrorSchema', () => {
expect(rpcErrorSchema.parse({ code: 'bad-request', message: 'm', details: { issues: [] } }).code).toBe('bad-request')
expect(rpcErrorSchema.parse({ code: 'cancelled', message: 'm', details: {} }).code).toBe('cancelled')
expect(rpcErrorSchema.parse({ code: 'session-not-found', message: 'm', details: { sessionId: 's' } }).code).toBe('session-not-found')
expect(rpcErrorSchema.parse({ code: 'session-conflict', message: 'm', details: { sessionId: 's', requestedCwd: '/a', existingCwd: '/b', requestedTimeZone: 'UTC' } }).code).toBe('session-conflict')
expect(rpcErrorSchema.parse({ code: 'session-conflict', message: 'm', details: { sessionId: 's', requestedCwd: '/a', existingCwd: '/b' } }).code).toBe('session-conflict')
expect(rpcErrorSchema.parse({ code: 'invalid-time-zone', message: 'm', details: { value: 'CST' } }).code).toBe('invalid-time-zone')
expect(rpcErrorSchema.parse({ code: 'workspace-attach-failed', message: 'm', details: { sessionId: 's', workspaceId: 'w' } }).code).toBe('workspace-attach-failed')
expect(rpcErrorSchema.parse({ code: 'workspace-not-found', message: 'm', details: { workspaceId: 'w' } }).code).toBe('workspace-not-found')
expect(rpcErrorSchema.parse({ code: 'workspace-invalid-path', message: 'm', details: { path: '/x' } }).code).toBe('workspace-invalid-path')
@@ -245,8 +246,17 @@ describe('sessions domain schemas', () => {
}],
failures: [],
})).toThrow()
const prompt = sessionPromptRequestSchema.parse({ sessionId: 's1', mode: 'queue', content: [{ type: 'text', text: 'hi' }] })
const prompt = sessionPromptRequestSchema.parse({
sessionId: 's1',
mode: 'queue',
content: [{ type: 'text', text: 'hi' }],
clientTimeZone: 'Asia/Shanghai',
})
expect(prompt.mode).toBe('queue')
expect(prompt.clientTimeZone).toBe('Asia/Shanghai')
expect(sessionPromptRequestSchema.parse({
sessionId: 's1', mode: 'queue', content: [],
}).clientTimeZone).toBeUndefined()
expect(() => sessionPromptRequestSchema.parse({ sessionId: 's1', mode: 'inject', content: [] })).toThrow()
expect(sessionPromptValueSchema.parse({ accepted: true }).accepted).toBe(true)
// The command slot appears only when the prompt dispatched a slash command.

View File

@@ -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 packages/schedule/tool-schedule/README.md
README.md: 3e0a0cea98dbe593974c5604736d155508f28044
README.zh.md: b08bad14d50b07af2c36796335452b835fb9680a
README.md: 144a72d0af36970b7888c15b16713b2ea92c1dea
README.zh.md: 8fe59f30d6f317d188e5a6c489b889af066ad46f

View File

@@ -2,49 +2,47 @@
English | [中文](README.zh.md)
`dsh-tool-schedule` gives future live root agents three session-scoped tools for durable one-shot reminders. Version 1 accepts positive safe-integer `after_seconds` delays and absolute `at` targets. The session event log owns reminder state; timers, tool values, and model followups are disposable projections of that log.
`dsh-tool-schedule` gives future live root Agents three Session-scoped tools for durable one-shot reminders. Version 1 accepts positive safe-integer `after_seconds` delays and explicit absolute `at` targets. The Session event log owns reminder state; timers, tool values, and model follow-ups are disposable projections of that log.
## Composition
Load this function plugin after `ctx.sessions`, `ctx.agents`, `ctx.tools`, `ctx.sessionPersistence`, and the persistence listener that implements Session flushes. Static injection makes a missing persistence service a composition error. The plugin listens only to later `agent/created` events, installs on runtime roots, and registers all tools through the exact `agent.ctx`. Agents that already existed when the plugin loaded and runtime children do not receive Schedule.
Load `@deepseek-ai/dsh-time-context` before publishing a root that should resolve local `at` values without an explicit zone. The official Schedule Web overlay does so. Explicit-offset and explicit-zone values remain usable without implicit request-zone context.
Time-context is not a Schedule dependency. A composition may mount `@deepseek-ai/dsh-time-context` so the model can interpret natural language in the browser's request-local zone, as the official Schedule Web overlay does. The model must still pass an explicit offset or `time_zone` to `schedule_create`; Schedule never imports or infers from model context.
Every operation that reads or decides from the Schedule fold first awaits `ctx.sessions.flush(session)`. A missing, rejected, or detached persistence path returns `persistence_uncertain`; it never turns an unconfirmed live suffix into a list or not-found answer. A successful create or actual delete also awaits a post-append barrier before confirming the mutation.
## Durable state
The package owns the strict version-1 `schedule/change` create, delete, and dispatch union. Every create record contains a stable session-local `ScheduleId`, the trimmed prompt, and a four-digit-year RFC 3339 UTC `scheduledAt`. An `after` record also stores `afterSeconds`; an `at` record stores no copy of the submitted offset, local calendar fields, or interpreting zone. Delete and one-shot dispatch carry only the id.
The package owns the strict version-1 `schedule/change` create, delete, and dispatch union. Every create record contains a stable Session-local `ScheduleId`, the trimmed prompt, and a four-digit-year RFC 3339 UTC `scheduledAt`. An `after` record also stores `afterSeconds`; an `at` record stores no copy of its submitted offset, local calendar fields, or interpreting zone. Delete and one-shot dispatch carry only the id.
Replay rejects unknown versions, extra fields, reused ids, and delete or dispatch transitions against inactive records. Normal sessions fold the complete log. A fork folds only `session.events.slice(session.header.seedLength ?? 0)`, so it does not inherit its parent's reminders. The package's `./invariant` companion applies the same policy to existing logs and candidate events.
Replay rejects unknown versions, extra fields, reused ids, and delete or dispatch transitions against inactive records. Normal Sessions fold the complete log. A fork folds only `session.events.slice(session.header.seedLength ?? 0)`, so it does not inherit its parent's reminders. The package's `./invariant` companion applies the same policy to existing logs and candidate events.
`scheduleReminderPresentation(events, dispatchSeq, seedLength)` is the pure Host-facing receipt projection. It returns `scheduleId`, prompt, and occurrence from the dispatch's nearest preceding same-id create; the client renderer adds the fixed `session-local` label. The current fork's `seedLength` is a hard boundary for child-owned dispatches, while inherited dispatches search their persisted prefix; resumed ancestors therefore remain renderable, nested generations may reuse session-local ids, and presentation never changes live ownership.
## Absolute-time input
## Absolute-time context
The `at` selector is either a strict `YYYY-MM-DDTHH:mm:ss[.S|.SS|.SSS](Z|±HH:MM)` string or `{ date: "YYYY-MM-DD", time: "HH:mm:ss[.S|.SS|.SSS]", time_zone: string }`. The string identifies an instant through `Z` or its numeric offset. The local form always requires explicit `UTC` or a valid IANA Area/Location zone. Missing `time_zone`, offset-free strings, extra keys, normalized calendar dates, invalid offsets, and non-future targets are rejected.
The `at` selector is either a strict `YYYY-MM-DDTHH:mm:ss[.S|.SS|.SSS](Z|±HH:MM)` string or `{ date: "YYYY-MM-DD", time: "HH:mm:ss[.S|.SS|.SSS]", time_zone?: string }`. The offset form already identifies one instant. The local form validates an explicit `UTC` or IANA Area/Location zone, or may omit `time_zone` only when the current open turn has a time-context reading and its original user-rpc sources derive one client zone equal to the immutable Session zone.
The Web Host validates and canonicalizes the browser zone at Session creation and on every prompt. Session creation fixes `SessionHeader.timeZone`; each prompt instead carries its own `clientTimeZone` in the user-message source, so concurrent tabs do not overwrite shared state. Schedule derives directly from those original owners rather than copying them into the time-context source. A headerless Session, a missing or mixed client-zone result, or a client/Session mismatch returns `timezone_confirmation_required` with the known zones and requires an explicit `time_zone`.
Local times inside a daylight-saving gap are rejected. An overlap chooses its first, earlier instant. A successful create retains only the canonical UTC target, and no Schedule path reads the process time zone.
Schedule owns deterministic calendar normalization. Local times inside a daylight-saving gap are rejected. An overlap chooses its first, earlier instant. A successful create retains only canonical UTC `scheduledAt`; no Schedule path reads the browser, Session header, model time-context, connection, or process time zone.
## Management tools
The generated [tool catalog](../../../docs/tool-catalog.md) owns the argument and output schemas for `schedule_create`, `schedule_list`, and `schedule_delete`. Their canonical values use camelCase record fields even though model input uses `after_seconds`.
The generated [tool catalog](../../../docs/tool-catalog.md) owns the argument and output schemas for `schedule_create`, `schedule_list`, and `schedule_delete`. Their canonical values use camelCase record fields even though model input uses `after_seconds` and `time_zone`.
One Agent-scoped queue serializes each accepted management transaction and the live owner's due transaction from preflight through any post-append barrier. Direct callers therefore cannot interleave a fold with another Schedule mutation or observe a dispatch before its own barrier. `schedule_create` requires exactly one of `after_seconds` or `at`, validates shape-only failures before entering that queue, then checkpoints, allocates a never-reused id, appends the create, and checkpoints again; an absolute target must be strictly future. `schedule_list` returns every active record in create order with `state: "scheduled" | "overdue"` and `deliveryMode: "session-local"`. `schedule_delete` rejects an empty or whitespace-padded id before entering the queue and appends only for an active id; an unknown or terminal id returns `{ id, deleted: false, code: "schedule_not_found" }` after its preflight.
One Agent-scoped queue serializes each accepted management transaction and the live owner's due transaction from preflight through any post-append barrier. `schedule_create` requires exactly one of `after_seconds` or `at`, validates shape-only failures before entering the queue, then checkpoints, allocates a never-reused id, appends create, and checkpoints again. `schedule_list` returns active records in creation order with `state: "scheduled" | "overdue"` and `deliveryMode: "session-local"`. `schedule_delete` rejects an empty or whitespace-padded id before the queue and appends only for an active id; an unknown or terminal id returns `{ id, deleted: false, code: "schedule_not_found" }` after preflight.
Every successful management preflight also asks the live owner to recompute. This matters after a create or delete barrier returned `persistence_uncertain`: a later list or mutation can confirm the retained batch and immediately arm or retire the now-durable record without a private persistence-retry timer.
Every successful management preflight also asks the live owner to recompute. This recovers a retained create or delete batch after a previous post-append barrier returned `persistence_uncertain`, without a Schedule-specific persistence-retry timer.
The closed v1 domain error codes are `invalid_prompt`, `invalid_selector`, `invalid_rule`, `invalid_time_zone`, `timezone_confirmation_required`, `not_future`, `time_out_of_range`, `corrupt_schedule_log`, `persistence_uncertain`, and `internal_error`. Diagnostics are stable and do not expose backend exceptions. Rendered content is deterministic JSON of the canonical value; generic tool-result policy remains responsible for any model-facing spill behavior.
The closed version-1 domain error codes are `invalid_prompt`, `invalid_selector`, `invalid_rule`, `invalid_time_zone`, `not_future`, `time_out_of_range`, `corrupt_schedule_log`, `persistence_uncertain`, and `internal_error`. Diagnostics are stable and do not expose backend exceptions. Rendered content is deterministic JSON of the canonical value; generic tool-result policy remains responsible for any model-facing spill behavior.
## Delivery lifecycle
The live owner derives the earliest target from the durable fold. It splits waits longer than the Node timer range and rereads the wall clock after every wake, so a rollback cannot fire early and a forward jump makes the record overdue.
An overdue reminder first checkpoints persistence. If a turn or another maintenance task already owns the Agent, `runMaintenance()` rejects the idle-phase claim; the record stays active and the owner retries after `whenIdle()`. A successful maintenance task samples one decision time, builds the complete framing, synchronously queues `followup()`, and appends an id-only dispatch before releasing the phase. Waking input remains parked until that release, after which the owner checkpoints dispatch. Framing or synchronous followup failure writes no dispatch. An append failure faults that owner because the message may already be queued; a barrier rejection leaves the dispatch pending for a later ordinary preflight and does not start a private retry timer.
An overdue reminder first checkpoints persistence. If a turn or another maintenance task owns the Agent, `runMaintenance()` rejects the idle-phase claim; the record stays active and the owner retries after `whenIdle()`. A successful maintenance task refolds, builds the fixed reminder framing, synchronously queues `followup()`, and appends an id-only dispatch before releasing the phase. Waking input remains parked until that release, after which the owner checkpoints dispatch.
Agent or plugin disposal cancels timers, stops new work, and awaits in-flight preflights and idle waits. It never appends delete records during teardown.
The follow-up opens a normal later turn after the Agent becomes fully idle; it never steers or interrupts the current conversation. Its assistant output appears through the ordinary transcript, with no independent receipt or Schedule-specific browser UI. Dispatch means the follow-up was queued and recorded, not that the model succeeded or the user read the answer.
Framing or synchronous follow-up failure writes no dispatch. An append failure faults that owner because the message may already be queued; a barrier rejection leaves dispatch pending for a later ordinary preflight. Agent or plugin disposal cancels timers, stops new work, and awaits in-flight preflights and idle waits without deleting durable records.
## Model Experience
@@ -52,7 +50,7 @@ Agent or plugin disposal cancels timers, stops new work, and awaits in-flight pr
#### What the model sees
The model sees the three generated tool schemas only in a live root agent created after this plugin loads. Tool results contain the canonical JSON values described above.
The model sees the three generated tool schemas only in a live root Agent created after this plugin loads. Tool results contain the canonical JSON values described above.
#### Token effect
@@ -62,7 +60,7 @@ The scoped schemas add a fixed request prefix while Schedule is installed. Each
The three schemas remain prefix-stable while their definitions and scope stay unchanged. Tool calls and results append to later history and preserve an already reusable prefix.
### Due reminder followup
### Due reminder follow-up
#### What the model sees
@@ -80,17 +78,17 @@ reminder_prompt_json: <JSON.stringify(prompt)>
#### Token effect
Each dispatched `after` or `at` reminder adds one data-dependent user-role message. The message remains in session history and therefore contributes tokens to later requests until ordinary compaction removes or replaces that history.
Each dispatched one-shot reminder adds one data-dependent user-role message. It remains in Session history and contributes tokens until ordinary compaction removes or replaces that history.
#### KV Cache effect
The reminder appends after existing history and preserves its reusable prefix. Its id, occurrence, or prompt changes only the appended suffix.
The reminder appends after existing history and preserves its reusable prefix. Its id, occurrence, and prompt affect only the appended suffix.
## Known Limitations and Deferred Work
- **Session-local delivery only** — a reminder runs on time only while its original session is live; a cold session receives no external notification and processes an overdue record only after resume.
- **Activity-driven retry** — a rejected due preflight or contained framing/enqueue failure leaves the overdue record active but starts no private retry timer; the owner retries after later Agent activity reaches idle or a successful Schedule management preflight asks it to recompute.
- **One-shot protocol only** — version 1 supports `after` and `at` but rejects `every_seconds` and `cron`; recurring rules require their own transition and budget semantics rather than hidden compatibility fields.
- **Immutable Session zone** — a new Schedule Web Session captures one default browser zone and has no zone editor. Older headerless Sessions remain `unavailable`, and a mismatched or ambiguous request must name `time_zone` explicitly.
- **Narrow crash duplicate window** — a crash after synchronous followup admission but before the dispatch checkpoint can repeat the reminder after recovery; the package does not claim model completion, user acknowledgement, or exactly-once external effects.
- **Load-order boundary** — the plugin does not scan or adopt agents that were already live when it loaded.
- **Session-local delivery only** — a reminder runs on time only while its original Session is live; a cold Session receives no external notification and processes an overdue record only after resume.
- **Activity-driven retry** — a rejected due preflight or contained framing/enqueue failure leaves the record active but starts no private retry timer; later Agent activity or a successful Schedule preflight triggers recomputation.
- **Explicit local zone** — `at` never imports browser context; callers must translate natural language into either an offset-bearing RFC 3339 string or a local object with `time_zone`.
- **One-shot protocol only** — version 1 supports `after` and `at` and rejects `every_seconds` and `cron`; recurrence needs explicit transition, catch-up, and model-budget semantics.
- **Narrow crash duplicate window** — a crash after synchronous follow-up admission but before the dispatch checkpoint can repeat the reminder; the package does not claim model completion, user acknowledgement, or exactly-once effects.
- **Load-order boundary** — the plugin does not scan or adopt Agents that were already live when it loaded.

View File

@@ -2,49 +2,47 @@
[English](README.md) | 中文
`dsh-tool-schedule` 为未来创建的 live 根 agent智能体提供 3 个会话范围内的工具,用于管理持久的一次性提醒。版本 1 接受正的安全整数 `after_seconds` 延时与绝对 `at` 目标。会话事件日志拥有提醒状态timer、工具值模型 `followup` 都是该日志的可丢弃投影。
`dsh-tool-schedule` 为未来创建的 live 根 agent智能体提供 3 个会话范围内的工具,用于管理持久的一次性提醒。版本 1 接受正的安全整数 `after_seconds` 延时和显式绝对时间 `at` 目标。会话事件日志拥有提醒状态timer、工具值模型 follow-up 都是该日志的可丢弃投影。
## 组合
请在 `ctx.sessions``ctx.agents``ctx.tools``ctx.sessionPersistence`,以及实现 Session flush 的持久化监听器之后加载此函数插件。静态注入会使缺少持久化服务的组合直接失败。此插件只监听后续的 `agent/created` 事件,在运行时根 agent 上安装,并通过完全相同的 `agent.ctx` 注册所有工具。插件加载时已经存在的 agent 与运行时子 agent 不会获得 Schedule。
若根 agent 需要在未显式指定时区时解析本地 `at` 值,请在发布该 agent 前加载 `@deepseek-ai/dsh-time-context`。官方 Schedule Web overlay 会按此顺序加载。带显式偏移量的值和带显式时区的值即使没有隐式请求时区上下文仍可使用
Time-context 不是 Schedule 的依赖。组合可以挂载 `@deepseek-ai/dsh-time-context`,使模型能够按浏览器的请求本地时区解释自然语言;官方 Schedule Web overlay 正是如此。模型仍必须向 `schedule_create` 传入显式偏移量或 `time_zone`Schedule 绝不会从模型上下文中导入或推断该值
每项从 Schedule 折叠结果读取或作出判断的操作,都会先等待 `ctx.sessions.flush(session)`。持久化路径缺失、拒绝或已分离时,操作返回 `persistence_uncertain`;它绝不会把未经确认的 live 后缀当成列表或未找到结果。成功创建或实际删除后,还会等待追加后的持久化 barrier屏障再确认变更。
## 持久状态
此包package拥有严格的版本 1 `schedule/change` create、delete 与 dispatch 联合。每条 create 记录都包含稳定的会话本地 `ScheduleId`、已 trim 的 prompt,以及使用四位年份的 RFC 3339 UTC `scheduledAt``after` 记录还会存储 `afterSeconds``at` 记录不会保留所提交的偏移量、本地日历字段或解释该值时所用的时区。delete 与一次性 dispatch 只携带 id。
此包拥有严格的版本 1 `schedule/change` create、delete 与 dispatch 联合。每条 create 记录都包含稳定的会话本地 `ScheduleId`、已 trim 的提示词,以及使用四位年份的 RFC 3339 UTC `scheduledAt``after` 记录还会存储 `afterSeconds``at` 记录不会保留所提交的偏移量、本地日历字段或解释该值时所用的时区。delete 与一次性 dispatch 只携带 id。
回放会拒绝未知版本、额外字段、重复使用的 id以及针对非活动记录的 delete 或 dispatch 转换。普通会话折叠完整日志。fork 只折叠 `session.events.slice(session.header.seedLength ?? 0)`,因此不会继承父会话的提醒。此包的 `./invariant` 配套会对现有日志和候选事件应用相同策略。
回放会拒绝未知版本、额外字段、重复使用的 id以及针对非活动记录的 delete 或 dispatch 转换。普通会话折叠完整日志。fork 只折叠 `session.events.slice(session.header.seedLength ?? 0)`,因此不会继承父会话的提醒。此包的 `./invariant` 配套模块会对现有日志和候选事件应用相同策略。
`scheduleReminderPresentation(events, dispatchSeq, seedLength)` 是供 Host 使用的纯回执投影。它从 dispatch 之前最近的同 id create 返回 `scheduleId`、prompt 和 occurrenceclient renderer 添加固定的 `session-local` 标签。当前 fork 的 `seedLength` 是 child 自有 dispatch 的硬边界,而继承的 dispatch 则会搜索其已持久前缀;因此恢复后的祖先仍可渲染,嵌套 generation 可以复用会话本地 idpresentation 绝不会改变 live ownership。
## 绝对时间输入
## 绝对时间上下文
`at` selector 可以是严格的 `YYYY-MM-DDTHH:mm:ss[.S|.SS|.SSS](Z|±HH:MM)` 字符串,也可以是 `{ date: "YYYY-MM-DD", time: "HH:mm:ss[.S|.SS|.SSS]", time_zone: string }`。字符串通过 `Z` 或数值偏移量标识一个时刻。本地形式始终要求显式 `UTC` 或有效的 IANA Area/Location 时区。缺少 `time_zone`、不带偏移量的字符串、额外键、需要规范化的日历日期、无效偏移量和非未来目标都会被拒绝。
`at` selector 可以是严格的 `YYYY-MM-DDTHH:mm:ss[.S|.SS|.SSS](Z|±HH:MM)` 字符串,也可以是 `{ date: "YYYY-MM-DD", time: "HH:mm:ss[.S|.SS|.SSS]", time_zone?: string }`。偏移量形式本身即可确定一个时刻。本地形式会校验显式指定的 `UTC` 或 IANA Area/Location 时区;仅当当前 open turn 含有 time-context 读数,并且其原始 user-rpc 来源派生出唯一一个与不可变 Session 时区相等的客户端时区时,才可以省略 `time_zone`
Web Host 会在创建 Session 时以及每次提交提示词时校验并规范化浏览器时区。Session 创建会固定 `SessionHeader.timeZone`;每条提示词则会在用户消息来源中携带自己的 `clientTimeZone`因此并发标签页不会覆盖共享状态。Schedule 会直接从这些原始拥有方派生,而不会把它们复制进 time-context source。如果 Session 没有 header、客户端时区结果缺失或混杂或客户端与 Session 不匹配,系统会返回 `timezone_confirmation_required` 并附上已知时区,同时要求显式指定 `time_zone`
落在夏令时空档内的本地时间会被拒绝。遇到重叠时会选择第一次出现的较早时刻。创建成功后只保留规范化后的 UTC 目标Schedule 的任何路径都不会读取进程时区。
Schedule 负责确定性的日历规范化。落在夏令时缺口内的本地时间会被拒绝;遇到重叠时会选择第一次出现的较早时刻。创建成功后只保留规范化后的 UTC `scheduledAt`Schedule 的任何路径都不会读取浏览器、Session 标头、模型 time-context、连接或进程时区
## 管理工具
生成的[工具目录](../../../docs/tool-catalog.md)负责 `schedule_create``schedule_list``schedule_delete` 的参数与输出 schema。虽然模型输入使用 `after_seconds`,但其规范值中的记录字段使用 camelCase。
生成的[工具目录](../../../docs/tool-catalog.md)负责 `schedule_create``schedule_list``schedule_delete` 的参数与输出 schema。虽然模型输入使用 `after_seconds``time_zone`,但其规范值中的记录字段使用 camelCase。
一条 Agent-scoped 队列会将每项已接纳的管理事务与 live owner 的到期事务从 preflight 到任何 post-append barrier 全程串行化。因此,直接调用方无法让一次 fold 与另一项 Schedule 变更交错,也无法在自身的 barrier 前观察到 dispatch。`schedule_create` 要求 `after_seconds``at` 有且只有一项;它会在进入队列前验证只依赖输入形状的失败,随后执行检查点、分配永不复用的 id、追加 create再次执行检查点;绝对目标必须严格位于未来`schedule_list` 按创建顺序返回所有活动记录,其中包含 `state: "scheduled" | "overdue"``deliveryMode: "session-local"``schedule_delete` 会在进入队列前拒绝空 id 或前后带空白的 id并只为活动 id 追加事件;未知或已终结的 id 会在 preflight(预检)后返回 `{ id, deleted: false, code: "schedule_not_found" }`
一条 Agent-scoped 队列会将每项已接纳的管理事务与 live owner 的到期事务从 preflight 到任何 post-append barrier 全程串行化。`schedule_create` 要求 `after_seconds``at` 有且只有一项;它会在进入队列前验证只依赖输入形状的失败,随后执行检查点、分配永不复用的 id、追加 create再次执行检查点。`schedule_list` 按创建顺序返回活动记录,其中包含 `state: "scheduled" | "overdue"``deliveryMode: "session-local"``schedule_delete` 会在进入队列前拒绝空 id 或前后带空白的 id并只为活动 id 追加事件;未知或已终结的 id 会在 preflight 后返回 `{ id, deleted: false, code: "schedule_not_found" }`
每次成功的管理 preflight 还会要求 live owner 重新计算。这对 create 或 delete barrier 返回 `persistence_uncertain` 的情况很重要:后续 list 或 mutation 可以确认保留的 batch并立即 arm 或退役此时已持久化的 record而无需私有 persistence retry timer。
每次成功的管理 preflight 还会要求 live owner 重新计算。如果先前的 post-append barrier 返回 `persistence_uncertain`,这会恢复所保留的 create 或 delete batch而无需 Schedule 专属的持久化重试 timer。
版本 1 的封闭领域错误代码包括 `invalid_prompt``invalid_selector``invalid_rule``invalid_time_zone``timezone_confirmation_required``not_future``time_out_of_range``corrupt_schedule_log``persistence_uncertain``internal_error`。诊断文本保持稳定,不会暴露后端异常。渲染内容是规范值的确定性 JSON通用工具结果策略仍负责模型可见内容的 spill 行为。
版本 1 的封闭领域错误代码包括 `invalid_prompt``invalid_selector``invalid_rule``invalid_time_zone``not_future``time_out_of_range``corrupt_schedule_log``persistence_uncertain``internal_error`。诊断文本保持稳定,不会暴露后端异常。渲染内容是规范值的确定性 JSON通用工具结果策略仍负责模型可见内容的 spill 行为。
## 交付生命周期
live owner 从持久折叠结果派生最早的目标。它会拆分超过 Node timer 范围的等待,并在每次唤醒后重新读取墙钟,因此时钟回拨不会提前触发,时钟前跳则会使记录进入 overdue 状态。
overdue 提醒首先为持久化建立检查点。如果 agent 已被某个轮次或另一项 maintenance task 占用,`runMaintenance()` 会拒绝对 idle phase 的认领记录会保持活动owner 会在 `whenIdle()` 后重试。获准执行的 maintenance task 会采样一次决策时间,构造完整 framing同步将 `followup()` 入队,并在释放 phase 前追加只含 id 的 dispatch。触发唤醒的 input 会保持 parked直到该 phase 释放;随后 owner 为 dispatch 建立检查点。framing 构造或同步 `followup` 失败不会写入 dispatch。追加失败会使该 owner 进入故障状态因为消息可能已经入队barrier 拒绝会把 dispatch 留给后续普通 preflight 处理,而不会启动私有重试 timer。
overdue 提醒首先为持久化建立检查点。如果 agent 已被某个轮次或另一项 maintenance task 占用,`runMaintenance()` 会拒绝对 idle phase 的认领记录会保持活动owner 会在 `whenIdle()` 后重试。获准执行的 maintenance task 会重新折叠、构造固定的提醒 framing同步将 `followup()` 入队,并在释放 phase 前追加只含 id 的 dispatch。触发唤醒的 input 会保持 parked直到该 phase 释放;随后 owner 为 dispatch 建立检查点。
agent 或插件执行 dispose资源释放会取消 timer、停止新工作并等待进行中的 preflight 和 idle wait。清理期间绝不会追加 delete 记录
Agent 完全 idle 后follow-up 会开启一个普通的后续轮次它绝不会中途引导或中断当前对话。assistant 输出通过普通 transcript文本记录显示不存在独立回执或 Schedule 专属浏览器 UI。dispatch 表示 follow-up 已入队并被记录,不表示模型成功或用户已读取回答
framing 构造或同步 follow-up 失败不会写入 dispatch。追加失败会使该 owner 进入故障状态因为消息可能已经入队barrier 拒绝会把 dispatch 留给后续普通 preflight。agent 或插件执行资源释放时,会取消 timer、停止新工作并等待进行中的 preflight 与 idle wait且不会删除持久记录。
## 模型体验
@@ -62,7 +60,7 @@ agent 或插件执行 dispose资源释放会取消 timer、停止新
3 个 schema 的定义与范围不变时,前缀保持稳定。工具调用和结果会追加到后续历史中,并保留已经可以复用的前缀。
### 到期提醒 followup
### 到期提醒 follow-up
#### 模型看到的内容
@@ -80,17 +78,17 @@ reminder_prompt_json: <JSON.stringify(prompt)>
#### Token 影响
每条已 dispatch 的 `after``at` 提醒会增加一条与数据相关的用户角色消息。该消息保留在会话历史中,因此会持续为后续请求贡献 token直到普通压缩compaction移除或替换这段历史。
每条已 dispatch 的一次性提醒会增加一条与数据相关的用户角色消息。该消息保留在会话历史中,并持续贡献 token直到普通压缩compaction移除或替换这段历史。
#### KV Cache 影响
提醒会追加到现有历史之后,并保留可复用的前缀。提醒的 id、occurrence 或 prompt 只会改变追加的后缀。
提醒会追加到现有历史之后,并保留可复用的前缀。提醒的 id、occurrence 和提示词只会影响追加的后缀。
## 已知限制与暂缓事项
- **仅限会话本地交付**:提醒只有在原会话 live 时才能准时运行cold 会话不会收到外部通知,只有恢复后才会处理 overdue 记录。
- **活动驱动的重试**:到期 preflight 被拒绝或 framing入队失败被收容后overdue 记录仍保持活动,但不会启动私有重试 timer后续 agent 活动进入 idle或成功的 Schedule 管理 preflight 要求 owner 重新计算后owner 会重试
- **仅支持一次性协议**:版本 1 支持 `after``at`,但拒绝 `every_seconds``cron`;周期性规则需要各自的转换与预算语义,而不是隐藏的兼容字段
- **Session 时区不可变**:新的 Schedule Web Session 会记录一个默认浏览器时区,且没有时区编辑器。旧有的无 header Session 仍为 `unavailable`,不匹配或有歧义的请求必须显式指定 `time_zone`
- **存在狭窄的崩溃重复窗口**:同步 `followup` 获得准入后、dispatch 检查点完成前发生崩溃,可能使提醒在恢复后重复;此包不承诺模型完成、用户确认或外部副作用恰好一次。
- **加载顺序边界**:插件不会扫描或接管加载时已经 live 的 agent。
- **活动驱动的重试**:到期 preflight 被拒绝或 framing入队失败被收容后记录仍保持活动但不会启动私有重试 timer后续 Agent 活动或成功的 Schedule preflight 会触发重新计算
- **显式本地时区**`at` 绝不会导入浏览器上下文;调用方必须把自然语言转换为带偏移量的 RFC 3339 字符串,或带 `time_zone` 的本地对象
- **仅支持一次性协议**:版本 1 支持 `after``at`,并拒绝 `every_seconds``cron`;周期性规则需要显式的状态转换、追赶和模型预算语义
- **存在狭窄的崩溃重复窗口**:同步 follow-up 获得准入后、dispatch 检查点完成前发生崩溃,可能使提醒重复;此包不承诺模型完成、用户确认或副作用恰好执行一次。
- **加载顺序边界**:插件不会扫描或接管加载时已经 live 的 Agent。

View File

@@ -31,7 +31,6 @@
"@deepseek-ai/dsh-llm": "^0.0.1",
"@deepseek-ai/dsh-session": "^0.0.1",
"@deepseek-ai/dsh-session-persistence": "^0.0.1",
"@deepseek-ai/dsh-time-context": "^0.0.1",
"@deepseek-ai/dsh-tools": "^0.0.1",
"cordis": "^4.0.0-rc.7"
},
@@ -47,7 +46,6 @@
"@deepseek-ai/dsh-session-persistence": "workspace:^",
"@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^",
"@deepseek-ai/dsh-system-prompt": "workspace:^",
"@deepseek-ai/dsh-time-context": "workspace:^",
"@deepseek-ai/dsh-tools": "workspace:^",
"cordis": "^4.0.0-rc.7"
}

View File

@@ -12,7 +12,6 @@ import type {
ScheduleChange,
ScheduleId as ScheduleIdType,
ScheduleRecord,
ScheduleReminderPresentation,
ScheduleView,
} from './types.ts'
@@ -48,14 +47,13 @@ export class ScheduleLogError extends Error {
}
}
/** Error from a model-supplied after rule that cannot become a record. */
/** Error from a model-supplied Schedule rule that cannot become a record. */
export class ScheduleInputError extends Error {
/** Stable public Schedule input code. */
readonly code:
| 'invalid_prompt'
| 'invalid_rule'
| 'invalid_time_zone'
| 'timezone_confirmation_required'
| 'not_future'
| 'time_out_of_range'
@@ -70,7 +68,6 @@ export class ScheduleInputError extends Error {
| 'invalid_prompt'
| 'invalid_rule'
| 'invalid_time_zone'
| 'timezone_confirmation_required'
| 'not_future'
| 'time_out_of_range',
message: string,
@@ -568,7 +565,6 @@ export function createAfterScheduleRecord(
* @param prompt - User-authored reminder content.
* @param at - Explicit-offset instant or structured local calendar value.
* @param now - Single creation-time wall-clock sample in epoch milliseconds.
* @param implicitTimeZone - Confirmed Session zone for a local value that omits `time_zone`.
* @returns Frozen durable absolute one-shot record.
*/
export function createAtScheduleRecord(
@@ -576,7 +572,6 @@ export function createAtScheduleRecord(
prompt: string,
at: AtInput,
now: number,
implicitTimeZone?: string,
): AtScheduleRecord {
const normalizedPrompt = prompt.trim()
if (normalizedPrompt.length === 0) {
@@ -587,29 +582,22 @@ export function createAtScheduleRecord(
if (typeof at === 'string') {
target = parseOffsetInstant(at)
} else if (isRecord(at)) {
if (!hasExactKeys(at, ['date', 'time']) && !hasExactKeys(at, ['date', 'time', 'time_zone'])) {
throw new ScheduleInputError('invalid_rule', 'Local at must contain exactly date, time, and optional time_zone.')
if (!hasExactKeys(at, ['date', 'time', 'time_zone'])) {
throw new ScheduleInputError('invalid_rule', 'Local at must contain exactly date, time, and time_zone.')
}
if (typeof at['date'] !== 'string' || typeof at['time'] !== 'string') {
throw new ScheduleInputError('invalid_rule', 'Local at date and time must be strings.')
}
const rawTimeZone = at['time_zone']
if (rawTimeZone !== undefined && typeof rawTimeZone !== 'string') {
if (typeof rawTimeZone !== 'string') {
throw new ScheduleInputError('invalid_time_zone', 'time_zone must be a string.')
}
const selectedTimeZone = rawTimeZone ?? implicitTimeZone
if (selectedTimeZone === undefined) {
throw new ScheduleInputError(
'timezone_confirmation_required',
'Local at requires an explicit time_zone for this request.',
)
}
const local: LocalAtInput = {
date: at['date'],
time: at['time'],
...(rawTimeZone === undefined ? {} : { time_zone: rawTimeZone }),
time_zone: rawTimeZone,
}
target = resolveLocalInstant(parseLocalAt(local), canonicalizeTimeZone(selectedTimeZone))
target = resolveLocalInstant(parseLocalAt(local), canonicalizeTimeZone(rawTimeZone))
} else {
throw new ScheduleInputError('invalid_rule', 'at must be an explicit-offset string or local calendar object.')
}
@@ -636,64 +624,6 @@ export function scheduleView(record: ScheduleRecord, now: number): ScheduleView
})
}
/**
* Derive the Web receipt for one dispatch from its owning stream segment.
* A child-owned dispatch cannot cross the current fork's `seedLength`.
* An inherited dispatch pairs with its nearest preceding same-id create, so
* resumed ancestors remain renderable and nested forks may reuse local ids.
* @param events - Complete contiguous Session log.
* @param dispatchSeq - Exact event seq to present.
* @param seedLength - Inherited fork prefix length.
* @returns The immutable receipt, or `undefined` when the selected event is not a dispatch.
*/
export function scheduleReminderPresentation(
events: readonly SessionEvent[],
dispatchSeq: number,
seedLength = 0,
): ScheduleReminderPresentation | undefined {
if (!Number.isSafeInteger(dispatchSeq) || dispatchSeq < 0) {
throw new ScheduleLogError('schedule presentation seq must be a non-negative safe integer')
}
if (!Number.isSafeInteger(seedLength) || seedLength < 0 || seedLength > events.length) {
throw new ScheduleLogError('schedule seedLength must be within the supplied event log')
}
const event = events[dispatchSeq]
if (event === undefined || event.seq !== dispatchSeq) {
throw new ScheduleLogError('schedule presentation seq must identify the matching contiguous event')
}
if (event.type !== 'schedule/change') return undefined
const dispatch = decodeScheduleChange(event.data)
if (dispatch.operation !== 'dispatch') return undefined
const segmentStart = dispatchSeq < seedLength ? 0 : seedLength
for (let index = dispatchSeq - 1; index >= segmentStart; index -= 1) {
const candidate = events[index]
if (candidate?.type !== 'schedule/change') continue
const change = decodeScheduleChange(candidate.data)
switch (change.operation) {
case 'create':
if (change.schedule.id !== dispatch.id) break
return Object.freeze({
scheduleId: change.schedule.id,
prompt: change.schedule.prompt,
occurrenceAt: change.schedule.scheduledAt,
})
case 'delete':
case 'dispatch':
if (change.id === dispatch.id) {
throw new ScheduleLogError(`schedule dispatch targets inactive id ${JSON.stringify(dispatch.id)}`)
}
break
/* v8 ignore next 3 -- decodeScheduleChange returns a closed operation union. */
default: {
const unreachable: never = change
throw new ScheduleLogError(`unknown decoded schedule change ${String(unreachable)}`)
}
}
}
throw new ScheduleLogError(`schedule dispatch targets inactive id ${JSON.stringify(dispatch.id)}`)
}
/**
* Render the fixed injection-resistant model framing for a due reminder.
* @param record - Due active record.

View File

@@ -17,6 +17,7 @@ export {
ScheduleLogError,
allocateScheduleId,
createAfterScheduleRecord,
createAtScheduleRecord,
decodeScheduleChange,
foldScheduleEvents,
renderReminderFraming,

View File

@@ -6,8 +6,6 @@
import type { Context } from 'cordis'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import type { SessionEvent } from '@deepseek-ai/dsh-session'
import { deriveClientTimeZoneContext } from '@deepseek-ai/dsh-time-context'
import { defineTool } from '@deepseek-ai/dsh-tools'
import type { GenericCallView } from '@deepseek-ai/dsh-tools'
import {
@@ -87,17 +85,6 @@ const BASIC_ERROR_SCHEMAS = [
basicErrorSchema('internal_error'),
] as const
const TIME_ZONE_CONFIRMATION_SCHEMA = {
type: 'object',
additionalProperties: false,
properties: {
code: { type: 'string', required: true, const: 'timezone_confirmation_required' },
message: { type: 'string', required: true },
sessionTimeZone: { type: 'string', required: true },
clientTimeZones: { type: 'array', required: true, items: { type: 'string' } },
},
} as const
const PERSISTENCE_ERROR_SCHEMA = {
type: 'object',
additionalProperties: false,
@@ -111,7 +98,6 @@ const PERSISTENCE_ERROR_SCHEMA = {
const ERROR_SCHEMAS = [
...BASIC_ERROR_SCHEMAS,
TIME_ZONE_CONFIRMATION_SCHEMA,
PERSISTENCE_ERROR_SCHEMA,
] as const
@@ -211,103 +197,8 @@ function persistenceError(
}
}
/** Request-local zone evidence returned with an implicit-local confirmation failure. */
interface AtTimeZoneContext {
readonly implicitTimeZone?: string
readonly sessionTimeZone: string
readonly clientTimeZones: string[]
}
/** Whether one durable message is the exact time-context snapshot marker. */
function isTimeContextReading(event: SessionEvent): boolean {
if (event.type !== 'user/message') return false
const source = event.data.source
if (source.kind !== 'plugin'
|| source.plugin !== 'time-context'
|| Object.keys(source).length !== 4
|| source.form !== 'snapshot') return false
const blockValue: unknown = event.data.content[0]
const block = typeof blockValue === 'object' && blockValue !== null
? blockValue as Record<string, unknown>
: undefined
const sections: unknown = source.sections
const sectionValue: unknown = Array.isArray(sections) ? sections[0] : undefined
const section = typeof sectionValue === 'object' && sectionValue !== null
? sectionValue as Record<string, unknown>
: undefined
return event.data.content.length === 1
&& block !== undefined
&& Object.keys(block).length === 2
&& block.type === 'text'
&& typeof block.text === 'string'
&& Array.isArray(sections)
&& sections.length === 1
&& section !== undefined
&& Object.keys(section).length === 2
&& section.name === 'time-context'
&& section.text === block.text
}
/** Derive request zones only while the current open turn contains a time-context reading. */
function currentClientTimeZoneContext(agent: Agent): ReturnType<typeof deriveClientTimeZoneContext> | undefined {
const events = agent.session.events
let stepStart = -1
let turn = 0
for (let index = events.length - 1; index >= 0; index--) {
const event = events[index]
/* v8 ignore next -- the loop bounds index to the dense Session event array. */
if (event === undefined) continue
if (event.type === 'step/end' || event.type === 'turn/end') return undefined
if (event.type === 'step/start') {
stepStart = index
turn = event.data.turn
break
}
}
if (stepStart < 0) return undefined
const turnStart = events.findLastIndex(event => event.type === 'turn/start' && event.data.turn === turn)
if (turnStart < 0) return undefined
const hasReading = events.slice(turnStart + 1).some(isTimeContextReading)
if (!hasReading) return undefined
const messages = events.slice(turnStart + 1)
.flatMap(event => event.type === 'user/message' ? [event.data] : [])
return deriveClientTimeZoneContext(messages)
}
/** Resolve the only request state that may supply an omitted local time zone. */
function atTimeZoneContext(agent: Agent): AtTimeZoneContext {
const sessionTimeZone = agent.session.header.timeZone ?? 'unavailable'
const client = currentClientTimeZoneContext(agent)
const clientTimeZones = client === undefined || client.kind === 'missing'
? []
: client.kind === 'resolved'
? [client.timeZone]
: [...client.timeZones]
const implicitTimeZone = sessionTimeZone !== 'unavailable'
&& client?.kind === 'resolved'
&& client.timeZone === sessionTimeZone
? sessionTimeZone
: undefined
return {
...(implicitTimeZone === undefined ? {} : { implicitTimeZone }),
sessionTimeZone,
clientTimeZones,
}
}
/** Translate one contained input failure to the closed tool union. */
function inputError(error: ScheduleInputError, timeZone?: AtTimeZoneContext): ScheduleToolError {
if (error.code === 'timezone_confirmation_required') {
// The domain emits this code only for the omitted-zone local-at arm,
// whose request context is computed immediately before decoding.
const requestTimeZone = timeZone as AtTimeZoneContext
return {
code: error.code,
message: error.message,
sessionTimeZone: requestTimeZone.sessionTimeZone,
clientTimeZones: requestTimeZone.clientTimeZones,
}
}
function inputError(error: ScheduleInputError): ScheduleToolError {
return { code: error.code, message: error.message }
}
@@ -406,7 +297,7 @@ export function registerScheduleTools(
description: 'Positive safe-integer delay in seconds.',
},
at: {
description: 'Absolute target as strict offset RFC 3339 or local date/time with optional IANA zone.',
description: 'Absolute target as strict offset RFC 3339 or local date/time with an explicit IANA zone.',
oneOf: [
{ type: 'string' },
{
@@ -415,7 +306,7 @@ export function registerScheduleTools(
properties: {
date: { type: 'string', required: true },
time: { type: 'string', required: true },
time_zone: { type: 'string' },
time_zone: { type: 'string', required: true },
},
},
],
@@ -434,25 +325,15 @@ export function registerScheduleTools(
if (isToolError(folded)) return folded
const id = allocateScheduleId(folded)
let record: ScheduleRecord
let timeZone: AtTimeZoneContext | undefined
try {
if (args.after_seconds === undefined) {
const at = args.at as AtInput
timeZone = typeof at === 'string' || at.time_zone !== undefined
? undefined
: atTimeZoneContext(agent)
record = createAtScheduleRecord(
id,
args.prompt,
at,
Date.now(),
timeZone?.implicitTimeZone,
)
record = createAtScheduleRecord(id, args.prompt, at, Date.now())
} else {
record = createAfterScheduleRecord(id, args.prompt, args.after_seconds, Date.now())
}
} catch (error: unknown) {
return error instanceof ScheduleInputError ? inputError(error, timeZone) : internalError()
return error instanceof ScheduleInputError ? inputError(error) : internalError()
}
const cancelledBeforeAppend = cancellationPlaceholder(exec.signal)
if (cancelledBeforeAppend !== undefined) return cancelledBeforeAppend

View File

@@ -41,8 +41,8 @@ export interface LocalAtInput {
readonly date: string
/** Local wall-clock time with optional one-to-three digit milliseconds. */
readonly time: string
/** Explicit IANA zone; omit only when current request authority permits the Session zone. */
readonly time_zone?: string
/** Explicit UTC or IANA Area/Location zone. */
readonly time_zone: string
}
/** Absolute selector accepted by `schedule_create`. */
@@ -116,14 +116,6 @@ export interface InvalidTimeZoneError {
readonly message: string
}
/** Stable error returned when a local absolute time needs an explicit zone choice. */
export interface TimeZoneConfirmationRequiredError {
readonly code: 'timezone_confirmation_required'
readonly message: string
readonly sessionTimeZone: string
readonly clientTimeZones: string[]
}
/** Stable error returned when an absolute target is not strictly future. */
export interface NotFutureError {
readonly code: 'not_future'
@@ -162,7 +154,6 @@ export type ScheduleToolError =
| InvalidSelectorError
| InvalidRuleError
| InvalidTimeZoneError
| TimeZoneConfirmationRequiredError
| NotFutureError
| TimeOutOfRangeError
| CorruptScheduleLogError

View File

@@ -207,19 +207,8 @@ describe('absolute record and time-zone resolution', () => {
expect((error as ScheduleInputError).code).toBe('not_future')
}
}
try {
createAtScheduleRecord(
ScheduleId('schedule-at'),
'x',
'9999-12-31T23:59:59.999-23:59',
now,
)
throw new Error('expected range failure')
} catch (error: unknown) {
expect(error).toBeInstanceOf(ScheduleInputError)
expect((error as ScheduleInputError).code).toBe('time_out_of_range')
}
for (const [at, sampleNow] of [
['9999-12-31T23:59:59.999-23:59', now],
['0001-01-01T00:00:00+23:59', Date.parse('0001-01-01T00:00:00.000Z') - 1],
['2026-08-06T01:00:00Z', Number.NaN],
] as const) {
@@ -248,13 +237,10 @@ describe('absolute record and time-zone resolution', () => {
}
})
it('resolves local calendar time, rejects a gap, and chooses the first overlap instant', () => {
it('resolves explicit local time, rejects a DST gap, and chooses the first overlap instant', () => {
expect(createAtScheduleRecord(ScheduleId('shanghai'), 'x', {
date: '2026-08-06', time: '09:00:00', time_zone: 'Asia/Shanghai',
}, now).scheduledAt).toBe('2026-08-06T01:00:00.000Z')
expect(createAtScheduleRecord(ScheduleId('implicit'), 'x', {
date: '2026-08-06', time: '09:00:00.25',
}, now, 'Asia/Shanghai').scheduledAt).toBe('2026-08-06T01:00:00.250Z')
date: '2026-08-06', time: '09:00:00.25', time_zone: 'Asia/Shanghai',
}, now).scheduledAt).toBe('2026-08-06T01:00:00.250Z')
expect(createAtScheduleRecord(ScheduleId('utc'), 'x', {
date: '2026-08-06', time: '09:00:00', time_zone: 'UTC',
}, now).scheduledAt).toBe('2026-08-06T09:00:00.000Z')
@@ -273,6 +259,7 @@ describe('absolute record and time-zone resolution', () => {
})
it.each([
[{ date: '2026-08-06', time: '09:00:00' }],
[{ date: '2026-08-06', time: '09:00:00', time_zone: 'UTC', extra: true }],
[{ date: 20260806, time: '09:00:00', time_zone: 'UTC' }],
[{ date: '2026-08-06', time: '09:00:00', time_zone: 8 }],
@@ -289,7 +276,7 @@ describe('absolute record and time-zone resolution', () => {
)).toThrow(ScheduleInputError)
})
it('rejects empty at prompts and local instants outside the four-digit range', () => {
it('rejects empty prompts and local instants outside the four-digit range', () => {
expect(() => createAtScheduleRecord(
ScheduleId('schedule-at'), ' ', '2026-08-06T01:00:00Z', now,
)).toThrow(ScheduleInputError)
@@ -304,19 +291,7 @@ describe('absolute record and time-zone resolution', () => {
}
})
it('fails closed when local calendar input has no confirmed zone', () => {
try {
createAtScheduleRecord(ScheduleId('schedule-at'), 'x', {
date: '2026-08-06', time: '09:00:00',
}, now)
throw new Error('expected confirmation failure')
} catch (error: unknown) {
expect(error).toBeInstanceOf(ScheduleInputError)
expect((error as ScheduleInputError).code).toBe('timezone_confirmation_required')
}
})
it('derives an at view and reminder framing without persisting input interpretation', () => {
it('derives an at view and model framing without persisting input interpretation', () => {
const record = createAtScheduleRecord(
ScheduleId('schedule-at'),
'join meeting',
@@ -329,9 +304,5 @@ describe('absolute record and time-zone resolution', () => {
deliveryMode: 'session-local',
})
expect(renderReminderFraming(record)).toContain('occurrence_at: 2026-08-06T01:00:00.000Z')
expect(scheduleReminderPresentation([
scheduleEvent(atCreateData(), 0),
scheduleEvent({ version: 1, operation: 'dispatch', id: 'schedule-at' }, 1),
], 1)).toMatchObject({ scheduleId: 'schedule-at', occurrenceAt: '2026-08-06T01:00:00.000Z' })
})
})

View File

@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Context } from 'cordis'
import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent'
import type { Agent, AgentCancelCause, InboxTarget } from '@deepseek-ai/dsh-agent'
import { CallId, createUserMessage } from '@deepseek-ai/dsh-llm'
import { CallId } from '@deepseek-ai/dsh-llm'
import type { UserMessage } from '@deepseek-ai/dsh-llm'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
@@ -22,10 +22,8 @@ interface ToolHarness {
readonly disposeTools: () => void
}
function stubAgent(ctx: Context, id: string, timeZone?: string): Agent {
const session = ctx.sessions.create(SessionId(id), {
...(timeZone === undefined ? {} : { meta: { timeZone } }),
})
function stubAgent(ctx: Context, id: string): Agent {
const session = ctx.sessions.create(SessionId(id))
const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} })
return {
id: session.id,
@@ -35,23 +33,23 @@ function stubAgent(ctx: Context, id: string, timeZone?: string): Agent {
status: 'idle',
ctx: new Context(),
send(_message: UserMessage, _target: InboxTarget, _wakeup: boolean) {},
runMaintenance: task => task(signal),
cancel(_cause: AgentCancelCause) {},
whenIdle: () => Promise.resolve(),
runMaintenance: task => task(signal),
followup(_message: UserMessage) {},
steer(_message: UserMessage) {},
inject(_message: UserMessage) {},
}
}
async function harness(withPersistence = true, timeZone?: string): Promise<ToolHarness> {
async function harness(withPersistence = true): Promise<ToolHarness> {
const ctx = new Context()
contexts.push(ctx)
await ctx.plugin(SessionStore)
await ctx.plugin(AgentRegistry)
await ctx.plugin(SystemPrompt, {})
await ctx.plugin(ToolRegistry)
const agent = stubAgent(ctx, `schedule-tools-${Math.random()}`, timeZone)
const agent = stubAgent(ctx, `schedule-tools-${Math.random()}`)
ctx.agents.register(agent)
const flushes = { count: 0, outcomes: [] as Array<'resolve' | 'reject' | Promise<'resolve' | 'reject'>> }
if (withPersistence) {
@@ -91,25 +89,6 @@ function value(result: ToolExecutionResult): unknown {
return result.value
}
function appendRequestContext(agent: Agent, clientTimeZones: readonly string[]): void {
for (const [index, clientTimeZone] of clientTimeZones.entries()) {
agent.session.append('user/message', createUserMessage({
content: [{ type: 'text', text: `request ${index + 1}` }],
source: { kind: 'user', rpcId: `request-zone-${String(index + 1)}`, clientTimeZone } as never,
}), { surfaceOp: 'append' })
}
const text = 'time context'
agent.session.append('user/message', createUserMessage({
content: [{ type: 'text', text }],
source: {
kind: 'plugin',
plugin: 'time-context',
form: 'snapshot',
sections: [{ name: 'time-context', text }],
},
}), { surfaceOp: 'append' })
}
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-08-05T12:00:00.000Z'))
@@ -225,7 +204,7 @@ describe('Schedule tool protocol', () => {
expect(test.flushes.count).toBe(0)
})
it('creates explicit-offset and explicit-zone at records without persisting their interpretation', async () => {
it('creates offset and explicit-zone at records without persisting their input interpretation', async () => {
const test = await harness()
expect(value(await execute(test, 'schedule_create', {
prompt: 'join meeting', at: '2026-08-06T09:00:00+08:00',
@@ -255,203 +234,6 @@ describe('Schedule tool protocol', () => {
expect(changes[0]?.data).not.toHaveProperty('time_zone')
})
it('fails closed when local at lacks confirmed request-zone context', async () => {
const test = await harness()
expect(value(await execute(test, 'schedule_create', {
prompt: 'ambiguous', at: { date: '2026-08-06', time: '09:00:00' },
}))).toEqual({
code: 'timezone_confirmation_required',
message: 'Local at requires an explicit time_zone for this request.',
sessionTimeZone: 'unavailable',
clientTimeZones: [],
})
expect(test.flushes.count).toBe(1)
expect(test.agent.session.events.filter(event => event.type === 'schedule/change')).toEqual([])
const unmarked = await harness(true, 'Asia/Shanghai')
unmarked.agent.session.append('turn/start', { turn: 1 })
unmarked.agent.session.append('step/start', { turn: 1, step: 1 })
unmarked.agent.session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'request without time reading' }],
source: { kind: 'user', rpcId: 'unmarked-request', clientTimeZone: 'Asia/Shanghai' } as never,
}), { surfaceOp: 'append' })
expect(value(await execute(unmarked, 'schedule_create', {
prompt: 'unmarked', at: { date: '2026-08-06', time: '09:00:00' },
}))).toMatchObject({
code: 'timezone_confirmation_required',
sessionTimeZone: 'Asia/Shanghai',
clientTimeZones: [],
})
})
it('uses the current turn request zones behind a current-step time-context marker', async () => {
const test = await harness(true, 'Asia/Shanghai')
test.agent.session.append('turn/start', { turn: 1 })
test.agent.session.append('step/start', { turn: 1, step: 1 })
appendRequestContext(test.agent, ['Asia/Shanghai'])
expect(value(await execute(test, 'schedule_create', {
prompt: 'implicit local', at: { date: '2026-08-06', time: '09:00:00' },
}))).toMatchObject({
kind: 'at',
scheduledAt: '2026-08-06T01:00:00.000Z',
})
})
it('reports the actual Session and request zones when implicit local at needs confirmation', async () => {
const mismatch = await harness(true, 'Asia/Shanghai')
mismatch.agent.session.append('turn/start', { turn: 1 })
mismatch.agent.session.append('step/start', { turn: 1, step: 1 })
appendRequestContext(mismatch.agent, ['America/New_York'])
expect(value(await execute(mismatch, 'schedule_create', {
prompt: 'mismatch', at: { date: '2026-08-06', time: '09:00:00' },
}))).toEqual({
code: 'timezone_confirmation_required',
message: 'Local at requires an explicit time_zone for this request.',
sessionTimeZone: 'Asia/Shanghai',
clientTimeZones: ['America/New_York'],
})
const mixed = await harness(true, 'Asia/Shanghai')
mixed.agent.session.append('turn/start', { turn: 1 })
mixed.agent.session.append('step/start', { turn: 1, step: 1 })
appendRequestContext(mixed.agent, ['Asia/Shanghai', 'America/New_York'])
expect(value(await execute(mixed, 'schedule_create', {
prompt: 'mixed', at: { date: '2026-08-06', time: '09:00:00' },
}))).toMatchObject({
sessionTimeZone: 'Asia/Shanghai',
clientTimeZones: ['America/New_York', 'Asia/Shanghai'],
})
const unavailable = await harness()
unavailable.agent.session.append('turn/start', { turn: 1 })
unavailable.agent.session.append('step/start', { turn: 1, step: 1 })
appendRequestContext(unavailable.agent, ['America/New_York'])
expect(value(await execute(unavailable, 'schedule_create', {
prompt: 'legacy', at: { date: '2026-08-06', time: '09:00:00' },
}))).toMatchObject({
sessionTimeZone: 'unavailable',
clientTimeZones: ['America/New_York'],
})
})
it('reuses a same-turn snapshot marker across an empty continuation and ignores a malformed source', async () => {
const test = await harness(true, 'Asia/Shanghai')
test.agent.session.append('turn/start', { turn: 1 })
test.agent.session.append('step/start', { turn: 1, step: 1 })
appendRequestContext(test.agent, ['Asia/Shanghai'])
test.agent.session.append('step/end', { turn: 1, step: 1 })
test.agent.session.append('step/start', { turn: 1, step: 2 })
test.agent.session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'malformed authority' }],
source: {
kind: 'plugin',
plugin: 'time-context',
authority: { turn: 1, step: 2, session: { kind: 'unavailable' }, client: { kind: 'future' } },
} as never,
}), { surfaceOp: 'append' })
expect(value(await execute(test, 'schedule_create', {
prompt: 'same-turn local', at: { date: '2026-08-06', time: '09:00:00' },
}))).toMatchObject({
kind: 'at',
scheduledAt: '2026-08-06T01:00:00.000Z',
})
})
it('does not let an array-like snapshot marker authorize an implicit local at', async () => {
const test = await harness(true, 'Asia/Shanghai')
test.agent.session.append('turn/start', { turn: 1 })
test.agent.session.append('step/start', { turn: 1, step: 1 })
test.agent.session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'request' }],
source: { kind: 'user', rpcId: 'array-like-request', clientTimeZone: 'Asia/Shanghai' } as never,
}), { surfaceOp: 'append' })
const text = 'time context'
test.agent.session.append('user/message', createUserMessage({
content: [{ type: 'text', text }],
source: {
kind: 'plugin',
plugin: 'time-context',
form: 'snapshot',
sections: { 0: { name: 'time-context', text }, length: 1 },
} as never,
}), { surfaceOp: 'append' })
expect(value(await execute(test, 'schedule_create', {
prompt: 'malformed marker', at: { date: '2026-08-06', time: '09:00:00' },
}))).toMatchObject({
code: 'timezone_confirmation_required',
sessionTimeZone: 'Asia/Shanghai',
clientTimeZones: [],
})
})
it.each([
['a non-object text block', 7, [{ name: 'time-context', text: 'time context' }]],
['matched non-string text', { type: 'text', text: 7 }, [{ name: 'time-context', text: 7 }]],
['extra text-block field', { type: 'text', text: 'time context', extra: true }, [{ name: 'time-context', text: 'time context' }]],
['extra section field', { type: 'text', text: 'time context' }, [{ name: 'time-context', text: 'time context', extra: true }]],
] as const)(
'does not let snapshot provenance with %s authorize an implicit local at',
async (_name, block, sections) => {
const test = await harness(true, 'Asia/Shanghai')
test.agent.session.append('turn/start', { turn: 1 })
test.agent.session.append('step/start', { turn: 1, step: 1 })
test.agent.session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'request' }],
source: { kind: 'user', rpcId: 'malformed-marker-request', clientTimeZone: 'Asia/Shanghai' } as never,
}), { surfaceOp: 'append' })
test.agent.session.append('user/message', createUserMessage({
content: [block as never],
source: { kind: 'plugin', plugin: 'time-context', form: 'snapshot', sections } as never,
}), { surfaceOp: 'append' })
expect(value(await execute(test, 'schedule_create', {
prompt: 'malformed marker', at: { date: '2026-08-06', time: '09:00:00' },
}))).toMatchObject({
code: 'timezone_confirmation_required',
sessionTimeZone: 'Asia/Shanghai',
clientTimeZones: [],
})
},
)
it.each(['step/end', 'turn/end'] as const)(
'fails closed after the current %s boundary',
async (boundary) => {
const test = await harness(true, 'Asia/Shanghai')
test.agent.session.append('turn/start', { turn: 1 })
test.agent.session.append('step/start', { turn: 1, step: 1 })
appendRequestContext(test.agent, ['Asia/Shanghai'])
test.agent.session.append('step/end', { turn: 1, step: 1 })
if (boundary === 'turn/end') {
test.agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
}
expect(value(await execute(test, 'schedule_create', {
prompt: `closed ${boundary}`,
at: { date: '2026-08-06', time: '09:00:00' },
}))).toMatchObject({
sessionTimeZone: 'Asia/Shanghai',
clientTimeZones: [],
})
},
)
it('fails closed when an open step has no owning turn boundary', async () => {
const test = await harness(true, 'Asia/Shanghai')
test.agent.session.append('step/start', { turn: 1, step: 1 })
appendRequestContext(test.agent, ['Asia/Shanghai'])
expect(value(await execute(test, 'schedule_create', {
prompt: 'missing turn', at: { date: '2026-08-06', time: '09:00:00' },
}))).toMatchObject({
sessionTimeZone: 'Asia/Shanghai',
clientTimeZones: [],
})
})
it('returns stable at validation errors after persistence preflight', async () => {
const test = await harness()
expect(value(await execute(test, 'schedule_create', {

View File

@@ -26,9 +26,6 @@
{
"path": "../../core/agent"
},
{
"path": "../../context/time-context"
},
{
"path": "../../core/tools"
},

View File

@@ -796,7 +796,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
methods: [
{
signature: 'create(id?: SessionId, options?: CreateSessionOptions): Session',
jsDoc: '/**\n * Create a session owned by the calling fiber: disposing that fiber stops\n * event notification and removes the session from the store. `options.seed`\n * populates the session with a copy of those events (replay/fork);\n * `options.meta` attaches creation metadata (validated absolute `cwd`, opaque\n * time-zone string, seed and parent lineage, and delegation depth) as the immutable\n * {@link SessionHeader} (the store fills `version`/`id`/`createdAt`).\n *\n * For an agent whose session must be torn down IN ORDER with its loop (so the\n * loop\'s final events are published before the store attachment ends), do NOT use this\n * — fold the session lifecycle into the agent\'s own effect via\n * {@link prepare} + {@link enter} + {@link announce} (see\n * `dsh-agent-loop`\'s creation transaction).\n *\n * @param id - the session id; omitted, the store mints `session-<n>`.\n * @param options - seed events and/or creation metadata for the header.\n * @returns the live session, already entered and announced.\n * @throws if a session with `id` already exists, metadata is not a plain\n * lossless-JSON record with valid scalar fields, or `meta.cwd` is a\n * non-absolute path (storage backends key directories off it).\n */',
jsDoc: '/**\n * Create a session owned by the calling fiber: disposing that fiber stops\n * event notification and removes the session from the store. `options.seed`\n * populates the session with a copy of those events (replay/fork);\n * `options.meta` attaches creation metadata (validated absolute `cwd`, seed\n * and parent lineage, and delegation depth) as the immutable\n * {@link SessionHeader} (the store fills `version`/`id`/`createdAt`).\n *\n * For an agent whose session must be torn down IN ORDER with its loop (so the\n * loop\'s final events are published before the store attachment ends), do NOT use this\n * — fold the session lifecycle into the agent\'s own effect via\n * {@link prepare} + {@link enter} + {@link announce} (see\n * `dsh-agent-loop`\'s creation transaction).\n *\n * @param id - the session id; omitted, the store mints `session-<n>`.\n * @param options - seed events and/or creation metadata for the header.\n * @returns the live session, already entered and announced.\n * @throws if a session with `id` already exists, metadata is not a plain\n * lossless-JSON record with valid scalar fields, or `meta.cwd` is a\n * non-absolute path (storage backends key directories off it).\n */',
},
{
signature: 'prepare(id?: SessionId, options?: PrepareSessionOptions): Session',
@@ -1909,7 +1909,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'CreateAgentOptions',
declaration: 'export interface CreateAgentOptions {\n readonly sessionId: SessionId;\n readonly meta?: {\n readonly cwd?: string;\n readonly timeZone?: string;\n readonly parentSession?: SessionId;\n readonly seedLength?: number;\n readonly origin?: \'subagent\';\n readonly delegationDepth?: number;\n };\n readonly seed?: readonly SessionEvent[];\n readonly agentOptions?: AgentOptions;\n readonly signal?: AbortSignal;\n readonly setup?: AgentSetup;\n}',
declaration: 'export interface CreateAgentOptions {\n readonly sessionId: SessionId;\n readonly meta?: {\n readonly cwd?: string;\n readonly parentSession?: SessionId;\n readonly seedLength?: number;\n readonly origin?: \'subagent\';\n readonly delegationDepth?: number;\n };\n readonly seed?: readonly SessionEvent[];\n readonly agentOptions?: AgentOptions;\n readonly signal?: AbortSignal;\n readonly setup?: AgentSetup;\n}',
},
{
name: 'CreateGoalRequest',
@@ -1921,7 +1921,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'CreateSessionOptions',
declaration: 'export interface CreateSessionOptions {\n readonly seed?: readonly SessionEvent[];\n readonly meta?: {\n readonly cwd?: string;\n readonly timeZone?: string;\n readonly parentSession?: SessionId;\n readonly createdAt?: number;\n readonly seedLength?: number;\n readonly origin?: \'subagent\';\n readonly delegationDepth?: number;\n };\n}',
declaration: 'export interface CreateSessionOptions {\n readonly seed?: readonly SessionEvent[];\n readonly meta?: {\n readonly cwd?: string;\n readonly parentSession?: SessionId;\n readonly createdAt?: number;\n readonly seedLength?: number;\n readonly origin?: \'subagent\';\n readonly delegationDepth?: number;\n };\n}',
},
{
name: 'CredentialInfo',
@@ -2589,7 +2589,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'SessionHeader',
declaration: 'export interface SessionHeader {\n readonly version: number;\n readonly id: SessionId;\n readonly createdAt: number;\n readonly cwd?: string;\n readonly timeZone?: string;\n readonly parentSession?: SessionId;\n readonly seedLength?: number;\n readonly origin?: \'subagent\';\n readonly delegationDepth?: number;\n}',
declaration: 'export interface SessionHeader {\n readonly version: number;\n readonly id: SessionId;\n readonly createdAt: number;\n readonly cwd?: string;\n readonly parentSession?: SessionId;\n readonly seedLength?: number;\n readonly origin?: \'subagent\';\n readonly delegationDepth?: number;\n}',
},
{
name: 'SessionId',

View File

@@ -14,7 +14,7 @@ The JSONL durable session-persistence backend — a concrete `SessionPersistence
session.jsonl # only with compression: 'none'
```
- The first logical line is the immutable `SessionHeader` tagged `{ type: 'session', version, id, cwd?, timeZone?, createdAt, parentSession?, seedLength?, origin?, delegationDepth }`. An optional string `timeZone` is preserved verbatim; its absence stays absent, and a non-string stored value rejects the log. `delegationDepth` is required on disk and is `0` for a top-level session; a missing or invalid value rejects the log. Every subsequent logical line is one storage record; `assistant/chunk` events are never dropped, and `seq` stays contiguous across the decoded log (`events[i].seq === i`).
- The first logical line is the immutable `SessionHeader` tagged `{ type: 'session', version, id, cwd?, createdAt, parentSession?, seedLength?, origin?, delegationDepth }`. `delegationDepth` is required on disk and is `0` for a top-level session; a missing or invalid value rejects the log. Every subsequent logical line is one storage record; `assistant/chunk` events are never dropped, and `seq` stays contiguous across the decoded log (`events[i].seq === i`).
- A storage record is a `SessionEvent` JSON verbatim, or — for an eligible run when `packChunks` is enabled — a **packed chunk row** (`text-chunks` / `reasoning-chunks` / `tool-call-chunks`; bare slash-less tags like the header's `session`, so row tags cannot be confused with event types): one line holding a run of ≥3 consecutive same-block `assistant/chunk` delta events, `seq0`/`time0` plus per-member `dt` gaps reconstructing every member's `seq`/`time` exactly. The lossless codec lives in `@deepseek-ai/dsh-session` (`packChunkRuns`/`decodeStorageRecord`) and whitelists exact shapes — anything unrecognized stores verbatim. Reading is layout-blind: `load` always decodes rows, so packed, unpacked, and mixed files load identically.
- The project directory keeps the normalized cwd readable for navigation and is bounded for filesystem component limits. Separator replacement and truncation are intentionally lossy, so cwd strings that normalize alike share a project directory; session ids still select distinct session directories. On a case-insensitive filesystem, identity validation accepts an alternate path spelling only when filesystem canonicalization resolves both spellings to the same transcript. The configured root remains deployment-controlled: it may be project-local, shared, temporary, or centralized. The [project-session directory decision](../../../.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md) records this tradeoff.
- Session ids are unvalidated branded strings, so they are injectively escaped to a single safe path segment before use (no traversal, no collision). The resulting directory is reserved for additional session-owned artifacts; discovery reads only the fixed transcript filename.

View File

@@ -14,7 +14,7 @@ JSONL 持久会话存储后端:`SessionPersistence` 的一个具体实现(`d
session.jsonl # only with compression: 'none'
```
- 第一个逻辑行是不可变的 `SessionHeader`,标记为 `{ type: 'session', version, id, cwd?, timeZone?, createdAt, parentSession?, seedLength?, origin?, delegationDepth }`可选字符串 `timeZone` 会原样保留;缺失时保持缺失,已存储值不是字符串时会拒绝日志。`delegationDepth` 在磁盘上必需,顶层会话为 `0`;缺失或无效值会拒绝日志。后续每个逻辑行是一条存储记录;`assistant/chunk` 事件绝不丢弃,且 `seq` 在解码日志中保持连续(`events[i].seq === i`)。
- 第一个逻辑行是不可变的 `SessionHeader`,标记为 `{ type: 'session', version, id, cwd?, createdAt, parentSession?, seedLength?, origin?, delegationDepth }``delegationDepth` 在磁盘上必需,顶层会话为 `0`;缺失或无效值会拒绝日志。后续每个逻辑行是一条存储记录;`assistant/chunk` 事件绝不丢弃,且 `seq` 在解码日志中保持连续(`events[i].seq === i`)。
- 存储记录是原样 `SessionEvent` JSON或在 `packChunks` 已启用且连续段符合条件时写入的**打包分片行**`text-chunks` / `reasoning-chunks` / `tool-call-chunks`;像 header 的 `session` 一样不带斜杠,因此行 tag 不会与事件类型混淆):一行保存至少 3 个连续同 block `assistant/chunk` delta 事件,`seq0`/`time0` 和每成员 `dt` 间隔精确重建每个成员的 `seq`/`time`。无损 codec 位于 `@deepseek-ai/dsh-session``packChunkRuns`/`decodeStorageRecord`),并使用精确形态 allowlist任何未识别内容原样存储。读取与布局无关`load` 始终解码行,因此打包、非打包和混合文件加载结果一致。
- 项目目录保留规范化 cwd 可读,并限制在文件系统组件上限内。分隔符替换和截断刻意有损,因此规范化相同的 cwd 字符串共享项目目录;会话 id 仍选择不同会话目录。在不区分大小写的文件系统上,只有文件系统规范化将两种写法解析到同一 transcript文本记录身份验证才接受备选路径写法。配置根仍由部署控制可以是项目本地、共享、临时或集中式。[项目会话目录决策](../../../.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md) 记录这项取舍。
- 会话 id 是未验证的带品牌类型的字符串,因此在使用前单射转义为一个安全路径段(无遍历、无冲突)。结果目录保留给其他会话自有产物;发现只读取固定 transcript 文件名。

View File

@@ -35,7 +35,6 @@ export interface HeaderLine {
id: SessionId
createdAt: number
cwd?: string
timeZone?: string
parentSession?: SessionId
seedLength?: number
origin?: 'subagent'
@@ -54,7 +53,6 @@ export function toHeaderLine(header: SessionHeader): HeaderLine {
id: header.id,
createdAt: header.createdAt,
...header.cwd !== undefined ? { cwd: header.cwd } : {},
...header.timeZone !== undefined ? { timeZone: header.timeZone } : {},
...header.parentSession !== undefined ? { parentSession: header.parentSession } : {},
...header.seedLength !== undefined ? { seedLength: header.seedLength } : {},
...header.origin !== undefined ? { origin: header.origin } : {},
@@ -76,7 +74,6 @@ export function fromHeaderLine(line: HeaderLine): SessionHeader {
id: line.id,
createdAt: line.createdAt,
...line.cwd !== undefined ? { cwd: line.cwd } : {},
...line.timeZone !== undefined ? { timeZone: line.timeZone } : {},
...line.parentSession !== undefined ? { parentSession: line.parentSession } : {},
...line.seedLength !== undefined ? { seedLength: line.seedLength } : {},
...line.origin !== undefined ? { origin: line.origin } : {},
@@ -95,8 +92,6 @@ function isHeaderLine(value: unknown): value is HeaderLine {
&& Number.isSafeInteger((value as { createdAt: number }).createdAt)
&& (value as { createdAt: number }).createdAt >= 0
&& !Object.is((value as { createdAt: number }).createdAt, -0)
&& ((value as { timeZone?: unknown }).timeZone === undefined
|| typeof (value as { timeZone?: unknown }).timeZone === 'string')
&& typeof (value as { delegationDepth?: unknown }).delegationDepth === 'number'
&& Number.isSafeInteger((value as { delegationDepth: number }).delegationDepth)
&& (value as { delegationDepth: number }).delegationDepth >= 0

View File

@@ -786,15 +786,6 @@ describe('SessionPersistenceJsonl: scanLog unit', () => {
expect(() => scanLog(Buffer.from(log))).toThrow(/session header/)
})
it('round-trips an optional timeZone and rejects a non-string stored value', () => {
const zoned = meta('zoned-header', '/work', 'Asia/Shanghai')
const scanned = scanLog(Buffer.from(`${JSON.stringify(toHeaderLine(zoned))}\n`))
expect(scanned.meta).toEqual({ ...zoned, delegationDepth: 0 })
const invalid = { ...toHeaderLine(zoned), timeZone: 8 }
expect(() => scanLog(Buffer.from(`${JSON.stringify(invalid)}\n`))).toThrow(/session header/)
})
it.each([
['missing', undefined],
['a string', '1'],

View File

@@ -10,9 +10,9 @@ A SQLite durable session-persistence backend — a second `SessionPersistence` p
## Storage model
Each `SessionEvent` maps 1:1 onto a row in an `events` table `(session_id, seq, type, time, data, source_event_seqs, surface_op)``data` is the event payload as JSON text, so the row shape is the event verbatim (including `assistant/chunk`, keeping `seq` contiguous). The two `TEXT` columns `source_event_seqs` and `surface_op` are nullable; they store the event's optional surface-metadata fields (see [session surface](../../../.agents/notes/implemented/architecture/2026-06-18-session-surface.md)). Out-of-log metadata (`SessionHeader`), a per-materialization incarnation id, and a monotonic per-log revision live in a `sessions` row; `createdAt` is a non-negative safe integer stored in a strict `INTEGER` column, and nullable `time_zone` preserves an optional `timeZone` string. A singleton state row carries the immutable store id. A `sessions` row is written only by the first `append` — its existence is the lazy-materialization signal (`list` reports exactly the sessions that have a row).
Each `SessionEvent` maps 1:1 onto a row in an `events` table `(session_id, seq, type, time, data, source_event_seqs, surface_op)``data` is the event payload as JSON text, so the row shape is the event verbatim (including `assistant/chunk`, keeping `seq` contiguous). The two `TEXT` columns `source_event_seqs` and `surface_op` are nullable; they store the event's optional surface-metadata fields (see [session surface](../../../.agents/notes/implemented/architecture/2026-06-18-session-surface.md)). Out-of-log metadata (`SessionHeader`), a per-materialization incarnation id, and a monotonic per-log revision live in a `sessions` row; `createdAt` is a non-negative safe integer stored in a strict `INTEGER` column. A singleton state row carries the immutable store id. A `sessions` row is written only by the first `append` — its existence is the lazy-materialization signal (`list` reports exactly the sessions that have a row).
The repository's Node range supports unflagged `node:sqlite`. The database enables foreign keys and uses the configured journal mode (`wal` by default; use a rollback mode where WAL shared-memory files are unsuitable). `PRAGMA application_id` identifies the canonical persistence database, and `PRAGMA user_version` stores its layout version. A fresh database must have no application identity or user-defined schema objects; initialization creates every table and stamps both pragmas in one transaction. The one supported upgrade accepts an owned v13 database, adds nullable `time_zone`, and advances `user_version` to 14 inside the existing `BEGIN IMMEDIATE`; old rows remain `NULL`. A failure rolls back both changes. Non-pristine unversioned databases, foreign application identities, and every other version reject before journal-mode mutation.
The repository's Node range supports unflagged `node:sqlite`. The database enables foreign keys and uses the configured journal mode (`wal` by default; use a rollback mode where WAL shared-memory files are unsuitable). `PRAGMA application_id` identifies the canonical persistence database, and `PRAGMA user_version` stores its layout version. A fresh database must have no application identity or user-defined schema objects; initialization creates every table and stamps both pragmas in one transaction. Non-pristine unversioned databases, foreign application identities, and every non-current version reject before journal-mode mutation because this unreleased format has no migrations.
On filesystems with POSIX modes, the backend requests mode `0700` for missing directories and exclusively creates a missing database with mode `0600` before SQLite opens it; the process umask may further restrict both. New WAL, shared-memory, and persistent rollback-journal sidecars receive the database's resulting owner-only mode. Existing directories, database files, and sidecars keep their modes; filesystem setup errors other than an existing database fail initialization. These defaults prevent incidental exposure through a permissive process umask, but do not protect database confidentiality or integrity when another principal can replace the database entry in its parent directory.
@@ -59,5 +59,5 @@ SQLite storage does not mutate live request prefixes. A resumed loop can reuse p
- **`DatabaseSync` is synchronous** — every append transaction blocks the event loop for its duration; acceptable for local stores, a throughput ceiling for busy multi-session servers.
- **Write contention has no wait or retry policy** — the backend sets no busy timeout and retries no locked-database error, so another connection holding a write transaction makes the operation reject immediately.
- **Only a pristine new database, an owned v13 database eligible for the v14 upgrade, or the current owned `SCHEMA_VERSION` opens** — unversioned schema objects, foreign application identities, and every other schema version are rejected.
- **Only a pristine new database or the current owned `SCHEMA_VERSION` opens** — unversioned schema objects, foreign application identities, and every other schema version are rejected rather than migrated (unreleased software; no persisted user data to preserve).
- **Nothing deletes stored sessions** — rows accumulate until removed externally (the seam has no deletion surface; `ON DELETE CASCADE` is wired for such out-of-band cleanup).

View File

@@ -10,9 +10,9 @@ SQLite 持久会话存储后端:第二个 `SessionPersistence` 提供方(见
## 存储模型
每个 `SessionEvent` 1:1 映射到 `events` 表中的一行 `(session_id, seq, type, time, data, source_event_seqs, surface_op)``data` 是作为 JSON 文本的事件 payload因此行结构就是原始事件本身包括 `assistant/chunk`,保持 `seq` 连续)。两个 `TEXT``source_event_seqs``surface_op` 可为空,存储事件可选接口元数据字段(见[会话接口](../../../.agents/notes/implemented/architecture/2026-06-18-session-surface.md))。日志外元数据(`SessionHeader`)、每实体化 incarnation id 和每日志单调修订位于 `sessions` 行;`createdAt` 是存储在 strict `INTEGER` 列中的非负安全整数,可为空的 `time_zone` 则保留可选的 `timeZone` 字符串。单例状态行携带不可变存储 id。`sessions` 行只由第一次 `append` 写入,其存在性是延迟实体化信号(`list` 精确报告有行的会话)。
每个 `SessionEvent` 1:1 映射到 `events` 表中的一行 `(session_id, seq, type, time, data, source_event_seqs, surface_op)``data` 是作为 JSON 文本的事件 payload因此行结构就是原始事件本身包括 `assistant/chunk`,保持 `seq` 连续)。两个 `TEXT``source_event_seqs``surface_op` 可为空,存储事件可选接口元数据字段(见[会话接口](../../../.agents/notes/implemented/architecture/2026-06-18-session-surface.md))。日志外元数据(`SessionHeader`)、每实体化 incarnation id 和每日志单调修订位于 `sessions` 行;`createdAt` 是存储在 strict `INTEGER` 列中的非负安全整数。单例状态行携带不可变存储 id。`sessions` 行只由第一次 `append` 写入,其存在性是延迟实体化信号(`list` 精确报告有行的会话)。
仓库支持的 Node 范围可不加 flag 使用 `node:sqlite`。数据库启用外键,并使用已配置 journal mode默认 `wal`WAL 共享内存文件不适用时使用 rollback mode`PRAGMA application_id` 标识规范持久化数据库,`PRAGMA user_version` 存储布局版本。新数据库必须没有 application identity 或用户定义 schema 对象;初始化在一个事务中创建全部表并盖上两个 pragma。唯一受支持的升级接受自有 v13 数据库,在既有 `BEGIN IMMEDIATE` 中添加可为空的 `time_zone`,并将 `user_version` 推进到 14旧行保持 `NULL`。失败会回滚这两项变更。非 pristine 无版本数据库、外部 application identity 和所有其他版本在 journal-mode 变更前均会被拒绝。
仓库支持的 Node 范围可不加 flag 使用 `node:sqlite`。数据库启用外键,并使用已配置 journal mode默认 `wal`WAL 共享内存文件不适用时使用 rollback mode`PRAGMA application_id` 标识规范持久化数据库,`PRAGMA user_version` 存储布局版本。新数据库必须没有 application identity 或用户定义 schema 对象;初始化在一个事务中创建全部表并盖上两个 pragma。非 pristine 无版本数据库、外部 application identity 和所有非当前版本在 journal-mode 变更前均会被拒绝,因为该未发布格式无迁移
在具有 POSIX mode 的文件系统上,后端为缺失目录请求 mode `0700`,并在 SQLite 打开前以 mode `0600` 排他创建缺失数据库;进程 umask 可进一步限制两者。新 WAL、共享内存和持久 rollback-journal sidecar 获得数据库最终的仅所有者 mode。现有目录、数据库文件和 sidecar 保留原 mode除已存在数据库外的文件系统设置错误会使初始化失败。这些默认值防止宽松进程 umask 造成的意外暴露,但当其他 principal 能替换父目录中的数据库条目时,不保护数据库机密性或完整性。
@@ -59,5 +59,5 @@ SQLite 存储不修改当前请求前缀。只有重建历史、当前 envelope
- **`DatabaseSync` 是同步的**:每个 append 事务在整个期间阻塞事件循环;对本地存储可接受,对繁忙多会话服务器是吞吐上限。
- **写入争用无等待或重试策略**:后端不设置 busy timeout也不重试 locked-database 错误,因此其他连接持有写事务时操作立即拒绝。
- **只有 pristine 新数据库、符合 v14 升级条件的自有 v13 数据库或当前自有 `SCHEMA_VERSION` 才能打开**:无版本 schema 对象、外部 application identity 和所有其他 schema 版本都会被拒绝。
- **只有 pristine 新数据库或当前自有 `SCHEMA_VERSION` 才能打开**:无版本 schema 对象、外部 application identity 和所有其他 schema 版本被拒绝,而不是迁移(未发布软件,无持久用户数据需要保留)
- **不删除已存储会话**行会累积直到外部移除seam 无删除接口;`ON DELETE CASCADE` 已为这种带外清理配置)。

View File

@@ -380,13 +380,12 @@ export class SessionPersistenceSqlite extends SessionPersistence implements Pers
private writeRow(meta: SessionHeader): void {
this.db.prepare(`
INSERT INTO sessions
(id, version, created_at, cwd, time_zone, parent_session, seed_length, origin, delegation_depth, incarnation, revision)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
(id, version, created_at, cwd, parent_session, seed_length, origin, delegation_depth, incarnation, revision)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
ON CONFLICT(id) DO UPDATE SET
version = excluded.version,
created_at = excluded.created_at,
cwd = excluded.cwd,
time_zone = excluded.time_zone,
parent_session = excluded.parent_session,
seed_length = excluded.seed_length,
origin = excluded.origin,
@@ -396,7 +395,6 @@ export class SessionPersistenceSqlite extends SessionPersistence implements Pers
meta.version,
meta.createdAt,
meta.cwd ?? null,
meta.timeZone ?? null,
meta.parentSession ?? null,
meta.seedLength ?? null,
meta.origin ?? null,

View File

@@ -17,55 +17,7 @@ import type { SessionEvent, SessionId, SessionHeader, SurfaceOp } from '@deepsee
* layout; orthogonal to a session's own `version` (which versions the EVENT
* vocabulary, stored per session in the `sessions` row).
*/
export const SCHEMA_VERSION = 14
/** The one owned schema layout this build upgrades in place. */
const MIGRATABLE_SCHEMA_VERSION = 13
/** Exact user objects emitted by the v13 schema owner, before `time_zone`. */
const MIGRATABLE_V13_SCHEMA = [
{
type: 'table',
name: 'events',
tableName: 'events',
sql: `CREATE TABLE events (
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
seq INTEGER NOT NULL,
type TEXT NOT NULL,
time INTEGER NOT NULL,
data TEXT NOT NULL,
source_event_seqs TEXT,
surface_op TEXT,
PRIMARY KEY (session_id, seq)
) STRICT`,
},
{
type: 'table',
name: 'persistence_state',
tableName: 'persistence_state',
sql: `CREATE TABLE persistence_state (
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
store_id TEXT NOT NULL
) STRICT`,
},
{
type: 'table',
name: 'sessions',
tableName: 'sessions',
sql: `CREATE TABLE sessions (
id TEXT PRIMARY KEY,
version INTEGER NOT NULL,
created_at INTEGER NOT NULL,
cwd TEXT,
parent_session TEXT,
seed_length INTEGER,
origin TEXT,
delegation_depth INTEGER,
incarnation TEXT NOT NULL,
revision INTEGER NOT NULL
) STRICT`,
},
] as const
export const SCHEMA_VERSION = 13
/** SQLite application id protecting unrelated databases from persistence writes. */
export const SESSION_PERSISTENCE_SQLITE_APPLICATION_ID = 0x44534850
@@ -82,7 +34,6 @@ export interface SessionRow {
version: number
created_at: number
cwd: string | null
time_zone: string | null
parent_session: string | null
seed_length: number | null
origin: 'subagent' | null
@@ -117,9 +68,9 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist'
/**
* Open the database and apply its schema and pragmas. An empty database with a
* zero `user_version` is initialized at {@link SCHEMA_VERSION}; an owned v13
* database is upgraded atomically, while a nonempty unversioned database and
* every other non-current version reject.
* zero `user_version` is initialized at {@link SCHEMA_VERSION}; a nonempty
* unversioned database and every other non-current version reject rather than
* being migrated in place.
* @param path - the SQLite database file to open (created when absent).
* @param journalMode - validated journal pragma.
* @returns the open handle with pragmas applied and all three tables ensured.
@@ -151,19 +102,14 @@ function configureDatabase(db: DatabaseSync, path: string, journalMode: JournalM
if (onDisk === 0 && (applicationId !== 0 || userObjectCount > 0)) {
throw new Error(`session database at "${path}" has an unversioned schema or application identity`)
}
if (onDisk !== 0 && onDisk !== MIGRATABLE_SCHEMA_VERSION && onDisk !== SCHEMA_VERSION) {
if (onDisk !== 0 && onDisk !== SCHEMA_VERSION) {
throw new Error(`session database at "${path}" has schema version ${onDisk}, incompatible with this build (${SCHEMA_VERSION})`)
}
if ((onDisk === MIGRATABLE_SCHEMA_VERSION || onDisk === SCHEMA_VERSION)
&& applicationId !== SESSION_PERSISTENCE_SQLITE_APPLICATION_ID) {
if (onDisk === SCHEMA_VERSION && applicationId !== SESSION_PERSISTENCE_SQLITE_APPLICATION_ID) {
throw new Error(
`session database at "${path}" has application id ${applicationId}, expected ${SESSION_PERSISTENCE_SQLITE_APPLICATION_ID}`,
)
}
if (onDisk === MIGRATABLE_SCHEMA_VERSION) {
assertMigratableV13Schema(db, path)
db.exec('ALTER TABLE sessions ADD COLUMN time_zone TEXT')
}
db.exec(`
CREATE TABLE IF NOT EXISTS persistence_state (
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
@@ -175,7 +121,6 @@ function configureDatabase(db: DatabaseSync, path: string, journalMode: JournalM
version INTEGER NOT NULL,
created_at INTEGER NOT NULL,
cwd TEXT,
time_zone TEXT,
parent_session TEXT,
seed_length INTEGER,
origin TEXT,
@@ -200,8 +145,6 @@ function configureDatabase(db: DatabaseSync, path: string, journalMode: JournalM
).run(randomUUID())
if (onDisk === 0) {
db.exec(`PRAGMA application_id = ${SESSION_PERSISTENCE_SQLITE_APPLICATION_ID}`)
}
if (onDisk === 0 || onDisk === MIGRATABLE_SCHEMA_VERSION) {
db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`)
}
db.exec('COMMIT')
@@ -223,34 +166,6 @@ function configureDatabase(db: DatabaseSync, path: string, journalMode: JournalM
db.exec(`PRAGMA journal_mode = ${journalMode.toUpperCase()}`)
}
/** Reject spoofed or modified v13 layouts before the migration changes them. */
function assertMigratableV13Schema(db: DatabaseSync, path: string): void {
const objects = db.prepare(`
SELECT type, name, tbl_name AS tableName, sql
FROM sqlite_schema
WHERE name NOT GLOB 'sqlite_*'
ORDER BY type, name
`).all() as Array<{ type: string; name: string; tableName: string; sql: string | null }>
const matches = objects.length === MIGRATABLE_V13_SCHEMA.length
&& objects.every((object, index) => {
const expected = MIGRATABLE_V13_SCHEMA[index]
return expected !== undefined
&& object.type === expected.type
&& object.name === expected.name
&& object.tableName === expected.tableName
&& object.sql !== null
&& normalizeSchemaSql(object.sql) === normalizeSchemaSql(expected.sql)
})
if (!matches) {
throw new Error(`session database at "${path}" does not match the owned v13 schema`)
}
}
/** Ignore formatting while preserving every schema token and its order. */
function normalizeSchemaSql(sql: string): string {
return sql.replace(/\s+/g, ' ').trim()
}
/**
* Reconstruct the {@link SessionHeader} from a `sessions` row.
* @param row - the `sessions` table row.
@@ -265,7 +180,6 @@ export function rowToMeta(row: SessionRow): SessionHeader {
id: row.id as SessionId,
createdAt: row.created_at,
...row.cwd !== null ? { cwd: row.cwd } : {},
...row.time_zone !== null ? { timeZone: row.time_zone } : {},
...row.parent_session !== null ? { parentSession: row.parent_session as SessionId } : {},
...row.seed_length !== null ? { seedLength: row.seed_length } : {},
...row.origin !== null ? { origin: row.origin } : {},

View File

@@ -40,48 +40,6 @@ async function freshDbPath(): Promise<string> {
return join(dir, 'sessions.db')
}
/** Create the exact owned v13 layout without passing through the v14 opener. */
function createV13Database(path: string): DatabaseSync {
const db = new DatabaseSync(path)
db.exec(`
PRAGMA foreign_keys = ON;
CREATE TABLE persistence_state (
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
store_id TEXT NOT NULL
) STRICT;
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
version INTEGER NOT NULL,
created_at INTEGER NOT NULL,
cwd TEXT,
parent_session TEXT,
seed_length INTEGER,
origin TEXT,
delegation_depth INTEGER,
incarnation TEXT NOT NULL,
revision INTEGER NOT NULL
) STRICT;
CREATE TABLE events (
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
seq INTEGER NOT NULL,
type TEXT NOT NULL,
time INTEGER NOT NULL,
data TEXT NOT NULL,
source_event_seqs TEXT,
surface_op TEXT,
PRIMARY KEY (session_id, seq)
) STRICT;
PRAGMA application_id = ${SESSION_PERSISTENCE_SQLITE_APPLICATION_ID};
PRAGMA user_version = 13;
`)
db.prepare('INSERT INTO persistence_state (singleton, store_id) VALUES (1, ?)').run('v13-fixture-store')
return db
}
/** A context with the session store + SQLite backend, plus a teardown. */
async function backend(path = ':memory:'): Promise<{ ctx: Context; dispose: () => Promise<void> }> {
const ctx = new Context()
@@ -208,14 +166,13 @@ describe('rowToMeta', () => {
version: 0,
created_at: 1,
cwd: null,
time_zone: 'Asia/Shanghai',
parent_session: null,
seed_length: null,
origin: 'subagent',
incarnation: 'with-origin',
revision: 1,
delegation_depth: null,
})).toMatchObject({ id: 'with-origin', origin: 'subagent', timeZone: 'Asia/Shanghai' })
})).toMatchObject({ id: 'with-origin', origin: 'subagent' })
})
it('rejects fractional stored creation metadata', () => {
@@ -224,7 +181,6 @@ describe('rowToMeta', () => {
version: 0,
created_at: 1.5,
cwd: null,
time_zone: null,
parent_session: null,
seed_length: null,
origin: null,
@@ -372,7 +328,7 @@ describe('SessionPersistenceSqlite: durability and crash semantics', () => {
await b2.dispose()
})
it('rejects opening a database whose schema version is neither v13 nor the current build', async () => {
it('rejects opening a database whose schema version is not the current build (newer OR older)', async () => {
const path = await freshDbPath()
openDatabase(path, 'wal').close() // stamp user_version = SCHEMA_VERSION
// Bump user_version past what this build supports.
@@ -381,84 +337,16 @@ describe('SessionPersistenceSqlite: durability and crash semantics', () => {
dbNewer.close()
expect(() => openDatabase(path, 'wal')).toThrow(/incompatible with this build/)
// Versions older than the one explicit migration remain unsupported.
// The immediately preceding layout lacks the required store identity and is
// rejected rather than migrated (unreleased software, no backward-compat).
const olderPath = await freshDbPath()
openDatabase(olderPath, 'wal').close()
const dbOlder = openDatabase(olderPath, 'wal')
dbOlder.exec(`PRAGMA user_version = ${SCHEMA_VERSION - 2}`)
dbOlder.exec(`PRAGMA user_version = ${SCHEMA_VERSION - 1}`)
dbOlder.close()
expect(() => openDatabase(olderPath, 'wal')).toThrow(/incompatible with this build/)
})
it('atomically migrates an owned v13 fixture and leaves old rows headerless', async () => {
const path = await freshDbPath()
const old = meta('v13-headerless', '/work')
const legacy = createV13Database(path)
legacy.prepare(`
INSERT INTO sessions
(id, version, created_at, cwd, parent_session, seed_length, origin, delegation_depth, incarnation, revision)
VALUES (?, ?, ?, ?, NULL, NULL, NULL, NULL, ?, 1)
`).run(old.id, old.version, old.createdAt, old.cwd ?? null, 'v13-headerless-incarnation')
const insertEvent = legacy.prepare(
'INSERT INTO events (session_id, seq, type, time, data, source_event_seqs, surface_op) VALUES (?, ?, ?, ?, ?, ?, ?)',
)
for (const event of oneTurnLog()) {
const surface = event as SessionEvent<SurfaceEventType>
insertEvent.run(
old.id,
event.seq,
event.type,
event.time,
JSON.stringify(event.data),
surface.sourceEventSeqs !== undefined ? JSON.stringify(surface.sourceEventSeqs) : null,
surface.surfaceOp !== undefined ? JSON.stringify(surface.surfaceOp) : null,
)
}
legacy.close()
const migrated = openDatabase(path, 'wal')
expect(migrated.prepare('PRAGMA user_version').get()).toEqual({ user_version: 14 })
expect(migrated.prepare('SELECT time_zone FROM sessions WHERE id = ?').get(old.id))
.toEqual({ time_zone: null })
migrated.close()
const mounted = await backend(path)
try {
const loaded = await mounted.ctx.sessionPersistence.load(old.id)
expect(loaded.meta.timeZone).toBeUndefined()
expect(loaded.events).toEqual(oneTurnLog())
const zoned = meta('v14-zoned', '/work', 'Asia/Shanghai')
await mounted.ctx.sessionPersistence.create(zoned)
await mounted.ctx.sessionPersistence.append(zoned.id, oneTurnLog())
expect((await mounted.ctx.sessionPersistence.load(zoned.id)).meta.timeZone).toBe('Asia/Shanghai')
} finally {
await mounted.dispose()
}
})
it('rejects a spoofed v13 layout without changing its schema or version', async () => {
const path = await freshDbPath()
const malformed = new DatabaseSync(path)
malformed.exec(`
CREATE TABLE sessions (id TEXT);
PRAGMA application_id = ${SESSION_PERSISTENCE_SQLITE_APPLICATION_ID};
PRAGMA user_version = 13;
`)
malformed.close()
expect(() => openDatabase(path, 'wal')).toThrow(/does not match the owned v13 schema/)
const unchanged = new DatabaseSync(path)
const columns = unchanged.prepare('PRAGMA table_info(sessions)').all() as Array<{ name: string }>
expect(columns.map(column => column.name)).toEqual(['id'])
expect(unchanged.prepare('PRAGMA user_version').get()).toEqual({ user_version: 13 })
expect(unchanged.prepare(
"SELECT name FROM sqlite_schema WHERE name IN ('persistence_state', 'events')",
).all()).toEqual([])
unchanged.close()
})
it('rejects a table-backed unversioned database before stamping or changing journal mode', async () => {
const path = await freshDbPath()
const legacy = new DatabaseSync(path)
@@ -520,23 +408,23 @@ describe('SessionPersistenceSqlite: durability and crash semantics', () => {
unchangedApplication.close()
})
it.each([13, SCHEMA_VERSION])('rejects a schema-v%i database with a foreign application identity', async (version) => {
it('rejects a current-version database with a foreign application identity', async () => {
const path = await freshDbPath()
const foreign = new DatabaseSync(path)
foreign.exec('PRAGMA application_id = 12345')
foreign.exec(`PRAGMA user_version = ${version}`)
foreign.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`)
foreign.close()
expect(() => openDatabase(path, 'wal')).toThrow(/has application id 12345/)
const unchanged = new DatabaseSync(path)
expect(unchanged.prepare('PRAGMA application_id').get()).toEqual({ application_id: 12345 })
expect(unchanged.prepare('PRAGMA user_version').get()).toEqual({ user_version: version })
expect(unchanged.prepare('PRAGMA user_version').get()).toEqual({ user_version: SCHEMA_VERSION })
expect(unchanged.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'delete' })
unchanged.close()
})
it('rolls back tables created before persistence-state initialization fails', async () => {
it('rolls back schema objects and identity stamps when initialization fails', async () => {
const path = await freshDbPath()
const conflicting = new DatabaseSync(path)
conflicting.exec(`PRAGMA application_id = ${SESSION_PERSISTENCE_SQLITE_APPLICATION_ID}`)
@@ -571,11 +459,6 @@ describe('SessionPersistenceSqlite: durability and crash semantics', () => {
expect(db.prepare('PRAGMA application_id').get())
.toEqual({ application_id: SESSION_PERSISTENCE_SQLITE_APPLICATION_ID })
expect(db.prepare('PRAGMA user_version').get()).toEqual({ user_version: SCHEMA_VERSION })
expect(db.prepare('PRAGMA table_info(sessions)').all()).toContainEqual(expect.objectContaining({
name: 'time_zone',
type: 'TEXT',
notnull: 0,
}))
db.close()
})
@@ -755,7 +638,7 @@ describe('SessionPersistenceSqlite: durability and crash semantics', () => {
})
it('exposes the schema version constant', () => {
expect(SCHEMA_VERSION).toBe(14)
expect(SCHEMA_VERSION).toBe(13)
})
it('keeps the revision stable for an empty repair hook', async () => {

View File

@@ -4,7 +4,7 @@ English | [中文](README.zh.md)
The durable session-persistence Service Definition (`ctx.sessionPersistence`). Defines WHAT a persistence backend does — durably store, reload, and list sessions — without saying HOW. Mirrors the `dsh-bash` capability-seam template ([capability seams](../../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)): an abstract service here, a Service provider in a sibling package, and Consumers that inject the service.
The persisted unit IS the existing `SessionEvent` (event-sourced model — the log is the single source of truth), so there is no parallel "persisted message" type. Metadata that is NOT replayable conversation state (format version, cwd, optional time zone, lineage, seed boundary, origin, delegation depth) travels separately as `SessionHeader`, owned by `dsh-session` and re-exported here.
The persisted unit IS the existing `SessionEvent` (event-sourced model — the log is the single source of truth), so there is no parallel "persisted message" type. Metadata that is NOT replayable conversation state (format version, cwd, lineage, seed boundary, origin, delegation depth) travels separately as `SessionHeader`, owned by `dsh-session` and re-exported here.
## Service API (`ctx.sessionPersistence`)
@@ -33,9 +33,7 @@ The persisted unit IS the existing `SessionEvent` (event-sourced model — the l
Each `session/event` copies its event into the session controller. The first pending event starts a fixed batching window; later events join without resetting its deadline. The configured `writeBatchMaxDelayMs` bounds this intentional wait, not event-loop, initialization, serialized-operation, or backend latency. Events admitted during a write form a new bounded batch. `session/flush` cancels the wait and is a shared quiescence barrier that drains events admitted while it runs. A background failure is logged once, retains the ordered batch, and pauses automatic retry; a new event starts a fresh window, while explicit flush or backend teardown retries immediately and surfaces a repeated failure.
A live controller retains no seed copy. If first initialization rejects, the next flush borrows the current append-only Session log, rechecks the backend's actual cursor, and appends only the missing suffix before draining retained events. Concurrent retries share one initialization attempt; a committed-but-rejected write therefore neither duplicates the prefix nor permanently poisons the Session.
Crash repair is cold-only. For a live id, `load(id)` snapshots the authoritative in-memory log, waits for that snapshot to become durable, and returns it with the coordinator's stored header only when balanced; an open live turn rejects instead of receiving synthetic interruption closers. For a cold id, inspection reads, validates, freezes, and constructs one unpublished Session; repeated inspection reuses that object graph only while its source revision remains current. `prepare(id)` performs the same check before repair, reserves the exact Session across backend reads and repair writes, commits any pending torn-tail/interrupted-turn repair, and returns it for publication. HMR adoption reads through `loadStored`, requires exact stored/live cwd and optional-`timeZone` identity, and never closes the active turn. Normal resume reconstructs a headerless live Session from its stored header, so it remains zone-unavailable and is never backfilled; a zoned live object cannot adopt that prefix.
Crash repair is cold-only. For a live id, `load(id)` snapshots the authoritative in-memory log, waits for that snapshot to become durable, and returns it only when balanced; an open live turn rejects instead of receiving synthetic interruption closers. For a cold id, inspection reads, validates, freezes, and constructs one unpublished Session; repeated inspection reuses that object graph only while its source revision remains current. `prepare(id)` performs the same check before repair, reserves the exact Session, commits any pending torn-tail/interrupted-turn repair, and returns it for publication. HMR adoption reads through `loadStored`, applies the coordinator's cwd check, and never closes the active turn.
Backend reads normalize the exact supported same-version shapes before current-shape validation. Pre-identity messages receive the deterministic id `legacy-message:<session-id>:<event-seq>`; a tool-result content replacement inherits its target's imported id. A pre-react-loop `turn/start` loses its obsolete trigger, a removed `steering/message` becomes the same identified `user/message`, and an older `turn/end` maps its terminal reason without inventing a caller that the old record did not name. The coordinator uses the same normalized view for `load`, `inspect`, `readFrom`, ownerless-state claims, and HMR prefix adoption. Storage remains append-only: reads do not rewrite old records, and later appends use the current shape. These are narrow import exceptions from the [pre-identity message](../../../.agents/notes/implemented/bug-fix/2026-07-28-load-pre-identity-session-messages.md) and [pre-react-loop session](../../../.agents/notes/implemented/bug-fix/2026-08-04-load-pre-react-loop-sessions.md) decisions, not a general v0 migration promise.
@@ -56,11 +54,11 @@ The `PersistenceBackend<TornMarker>` hooks (the only contract between the coordi
| `list(signal?)` | List all stored metadata, observing optional cancellation. |
| `close?()` | Optional lifecycle teardown (e.g. close a db handle), awaited after the dispose drain. |
The coordinator asserts the stored id and validates the optional stored `timeZone` as a string before repair or publication. Live adoption requires exact stored/live cwd and optional-zone equality, including headerless-to-headerless identity. Its `inspect()` path takes ownership of fresh backend values, validates and freezes them once, and retains at most the configured number of unpublished Sessions without calling `commitRepair`. A retained source is reused or repaired only when its revision still equals `readStoredRevision`; otherwise the coordinator reloads it. This freshness check does not add cross-process writer exclusion. Revision retries converge when the durable log remains unchanged for one read/check round trip; continuous external writers can delay `load`, `inspect`, or `prepare`. The `tornMarker` is fully OPAQUE: the coordinator only tests `!== undefined` and round-trips it to `commitRepair`, never inspecting its value (the JSONL backend uses the byte offset to truncate to, the SQLite backend the seq to delete from). A third-party backend MAY implement the abstract service directly without the coordinator, but it must provide the same non-mutating inspection and trustworthy lightweight snapshot revisions. See [the write-coordinator Agent Note](../../../.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md).
The coordinator asserts the stored id and compares stored/live cwd before repair or live adoption. Its `inspect()` path takes ownership of fresh backend values, validates and freezes them once, and retains at most the configured number of unpublished Sessions without calling `commitRepair`. A retained source is reused or repaired only when its revision still equals `readStoredRevision`; otherwise the coordinator reloads it. This freshness check does not add cross-process writer exclusion. Revision retries converge when the durable log remains unchanged for one read/check round trip; continuous external writers can delay `load`, `inspect`, or `prepare`. The `tornMarker` is fully OPAQUE: the coordinator only tests `!== undefined` and round-trips it to `commitRepair`, never inspecting its value (the JSONL backend uses the byte offset to truncate to, the SQLite backend the seq to delete from). A third-party backend MAY implement the abstract service directly without the coordinator, but it must provide the same non-mutating inspection and trustworthy lightweight snapshot revisions. See [the write-coordinator Agent Note](../../../.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md).
## Metadata and location types
Re-exported from `dsh-session`: `SessionHeader` (immutable session metadata: `version`, `id`, `createdAt`, `cwd?`, `timeZone?`, `parentSession?`, `seedLength?`, `origin?`, `delegationDepth?`). `SessionLocation` is `{ readonly kind: string; readonly path: string }`; its path is an absolute backend target, not proof that the artifact exists or contains an unflushed turn.
Re-exported from `dsh-session`: `SessionHeader` (immutable session metadata: `version`, `id`, `createdAt`, `cwd?`, `parentSession?`, `seedLength?`, `origin?`, `delegationDepth?`). `SessionLocation` is `{ readonly kind: string; readonly path: string }`; its path is an absolute backend target, not proof that the artifact exists or contains an unflushed turn.
## Model Experience

View File

@@ -589,9 +589,6 @@ export class PersistenceCoordinator<TornMarker = unknown> {
if (!Number.isSafeInteger(snapshot.createdAt) || snapshot.createdAt < 0) {
return Promise.reject(new TypeError('session metadata createdAt must be a non-negative safe integer'))
}
if (snapshot.timeZone !== undefined && typeof snapshot.timeZone !== 'string') {
return Promise.reject(new TypeError('session metadata timeZone must be a string'))
}
return this.serialize(snapshot.id, () => this.createCore(snapshot))
}
@@ -804,7 +801,7 @@ export class PersistenceCoordinator<TornMarker = unknown> {
signal?.throwIfAborted()
if (suffix === undefined) throw new Error(`session "${id}" not found`)
this.assertStoredId(id, suffix.meta)
this.assertStoredHeader(suffix.meta)
this.assertVersion(suffix.meta)
if (suffix.events.some(needsLegacyPrefix)) {
const whole = await this.readStoredPrefix(id, signal)
return { meta: whole.meta, events: whole.events.filter(event => event.seq >= fromSeq) }
@@ -826,7 +823,7 @@ export class PersistenceCoordinator<TornMarker = unknown> {
signal?.throwIfAborted()
if (stored === undefined) throw new Error(`session "${id}" not found`)
this.assertStoredId(id, stored.meta)
this.assertStoredHeader(stored.meta)
this.assertVersion(stored.meta)
return {
meta: structuredClone(stored.meta),
events: snapshotStoredEvents(stored.events, id),
@@ -840,7 +837,7 @@ export class PersistenceCoordinator<TornMarker = unknown> {
try {
const { meta, events, revision, tornMarker } = stored
this.assertStoredId(id, meta)
this.assertStoredHeader(meta)
this.assertVersion(meta)
const storedEvents = adoptStoredEvents(events, id)
// Preserve complete interrupted events and synthesize only missing closers.
@@ -984,14 +981,10 @@ export class PersistenceCoordinator<TornMarker = unknown> {
}
}
/** Validate fixed fields decoded from backend-owned storage. */
private assertStoredHeader(meta: SessionHeader): void {
private assertVersion(meta: SessionHeader): void {
if (meta.version !== SESSION_FORMAT_VERSION) {
throw new Error(`unsupported session format version ${meta.version} for "${meta.id}" (only v${SESSION_FORMAT_VERSION} is supported)`)
}
if (meta.timeZone !== undefined && typeof meta.timeZone !== 'string') {
throw new Error(`stored session "${meta.id}" timeZone must be a string`)
}
}
/** Reject backend metadata that is not bound to the requested session id. */
@@ -1001,17 +994,6 @@ export class PersistenceCoordinator<TornMarker = unknown> {
}
}
/** Compare the immutable metadata fields that participate in live adoption identity. */
private assertAdoptableIdentity(meta: SessionHeader, session: Session): void {
this.assertStoredHeader(meta)
if (meta.cwd !== session.header.cwd) {
throw new Error(`session "${session.header.id}" is already persisted at a different cwd (persisted: ${String(meta.cwd)}, live: ${String(session.header.cwd)}) (id collision)`)
}
if (meta.timeZone !== session.header.timeZone) {
throw new Error(`session "${session.header.id}" is already persisted with a different timeZone (persisted: ${String(meta.timeZone)}, live: ${String(session.header.timeZone)}) (id collision)`)
}
}
// --- write path (session/event → flush drain) ---
private installWritePath(): void {
@@ -1179,7 +1161,9 @@ export class PersistenceCoordinator<TornMarker = unknown> {
// the stored header's cwd. The seed guard then ensures the live events
// reproduce the persisted prefix; otherwise a fresh session reusing the
// id could have its leading events filtered as already written.
this.assertAdoptableIdentity(tracked.meta, session)
if (tracked.meta.cwd !== session.header.cwd) {
throw new Error(`session "${id}" is already persisted at a different cwd (persisted: ${String(tracked.meta.cwd)}, live: ${String(session.header.cwd)}) (id collision)`)
}
if (!await this.seedMatchesPersisted(id, seed, tracked.cursor)) {
throw new Error(`session "${id}" is already persisted with ${tracked.cursor} event(s) that do not match this live session (id collision)`)
}
@@ -1230,7 +1214,10 @@ export class PersistenceCoordinator<TornMarker = unknown> {
private async adoptLivePrefix(session: Session, seed: readonly SessionEvent[], stored: StoredPrefix<TornMarker>): Promise<void> {
const { meta, events, tornMarker } = stored
this.assertStoredId(session.header.id, meta)
this.assertAdoptableIdentity(meta, session)
if (meta.cwd !== session.header.cwd) {
throw new Error(`session "${session.header.id}" is already persisted at a different cwd (persisted: ${String(meta.cwd)}, live: ${String(session.header.cwd)}) (id collision)`)
}
this.assertVersion(meta)
const storedEvents = snapshotStoredEvents(events, session.header.id)
if (!seedCoversPrefix(seed, storedEvents)) {
throw new Error(`session "${session.header.id}" already has a persisted log on disk that does not match this live session (id collision)`)

View File

@@ -21,13 +21,12 @@ export interface ContractBackend {
}
/** Build a minimal {@link SessionHeader} for a session id. */
export function meta(id: string, cwd?: string, timeZone?: string): SessionHeader {
export function meta(id: string, cwd?: string): SessionHeader {
return {
version: SESSION_FORMAT_VERSION,
id: SessionId(id),
createdAt: 1000,
...cwd !== undefined ? { cwd } : {},
...timeZone !== undefined ? { timeZone } : {},
}
}
@@ -87,49 +86,19 @@ export function runPersistenceContract(name: string, make: () => Promise<Contrac
it('round-trips a session: create + append → load returns identical meta and byte-identical events', async () => {
const { persistence, dispose } = await make()
try {
const m = meta('s1', '/work', 'Asia/Shanghai')
const m = meta('s1', '/work')
const log = oneTurnLog()
await persistence.create(m)
await persistence.append(m.id, log)
const loaded = await persistence.load(m.id)
expect(loaded.meta).toMatchObject(m)
expect(loaded.meta).toMatchObject({ version: SESSION_FORMAT_VERSION, id: m.id, cwd: '/work' })
expect(loaded.events).toEqual(log)
} finally {
await dispose()
}
})
it('keeps a headerless session headerless across storage reads', async () => {
const { persistence, dispose } = await make()
try {
const m = meta('headerless', '/work')
await persistence.create(m)
await persistence.append(m.id, oneTurnLog())
expect((await persistence.inspect(m.id)).meta.timeZone).toBeUndefined()
expect((await persistence.load(m.id)).meta.timeZone).toBeUndefined()
expect((await persistence.list()).find(header => header.id === m.id)?.timeZone).toBeUndefined()
} finally {
await dispose()
}
})
it('rejects non-string timeZone metadata without reserving its session id', async () => {
const { persistence, dispose } = await make()
try {
const invalid = { ...meta('invalid-time-zone'), timeZone: 1 as unknown as string }
await expect(persistence.create(invalid)).rejects.toThrow('session metadata timeZone must be a string')
const valid = meta('invalid-time-zone', undefined, 'UTC')
await persistence.create(valid)
await persistence.append(valid.id, oneTurnLog())
expect((await persistence.load(valid.id)).meta.timeZone).toBe('UTC')
} finally {
await dispose()
}
})
it('rejects a fractional creation timestamp without reserving its session id', async () => {
const { persistence, dispose } = await make()
try {

View File

@@ -908,68 +908,6 @@ export function runCoordinatorContract(name: string, makeFixture: () => Promise<
}
})
it('stored-prefix adoption rejects a different present timeZone', async () => {
const fix = await makeFixture()
const first = await freshCtx(fix)
try {
const stored = first.ctx.sessions.create(SessionId('zone-adoption'), {
meta: { cwd: WORK, timeZone: 'Asia/Shanghai' },
})
send(stored, oneTurnLog())
await first.ctx.sessions.flush(stored)
} finally {
await first.fiber.dispose()
}
const ctx = new Context()
await ctx.plugin(SessionStore)
const live = ctx.sessions.create(SessionId('zone-adoption'), {
seed: oneTurnLog(),
meta: { cwd: WORK, timeZone: 'America/New_York' },
})
const second = await fix.mount(ctx)
try {
await expect(ctx.sessions.flush(live)).rejects.toThrow(/different timeZone|id collision/)
} finally {
await second.dispose()
await ctx.fiber.dispose()
await fix.cleanup()
}
})
it('stored-prefix adoption rejects a zoned live session for a headerless record', async () => {
const fix = await makeFixture()
const log = [
...oneTurnLog(),
{ type: 'session/end-seed', seq: 6, time: 7, data: {} },
] as SessionEvent[]
const first = await freshCtx(fix)
try {
const stored = first.ctx.sessions.create(SessionId('headerless-zone-adoption'), {
seed: log,
meta: { cwd: WORK },
})
await first.ctx.sessions.flush(stored)
} finally {
await first.fiber.dispose()
}
const ctx = new Context()
await ctx.plugin(SessionStore)
const live = ctx.sessions.create(SessionId('headerless-zone-adoption'), {
seed: log,
meta: { cwd: WORK, timeZone: 'Asia/Shanghai' },
})
const second = await fix.mount(ctx)
try {
await expect(ctx.sessions.flush(live)).rejects.toThrow(/different timeZone|id collision/)
} finally {
await second.dispose()
await ctx.fiber.dispose()
await fix.cleanup()
}
})
it('HMR: adoption persists the live SUFFIX that was ahead of the stored prefix', async () => {
const fix = await makeFixture()
const ctx = new Context()
@@ -1166,54 +1104,6 @@ export function runCoordinatorContract(name: string, makeFixture: () => Promise<
}
})
it('a zoned live session cannot claim headerless ownerless state', async () => {
const fix = await makeFixture()
const { ctx, fiber } = await freshCtx(fix)
try {
await ctx.sessionPersistence.create(meta('headerless-zone-claim', WORK))
const live = ctx.sessions.create(SessionId('headerless-zone-claim'), {
seed: oneTurnLog(),
meta: { cwd: WORK, timeZone: 'Asia/Shanghai' },
})
await expect(ctx.sessions.flush(live)).rejects.toThrow(/different timeZone|id collision/)
} finally {
await fiber.dispose()
await fix.cleanup()
}
})
it('ownerless state with a timeZone only accepts the same live identity', async () => {
const fix = await makeFixture()
const { ctx, fiber } = await freshCtx(fix)
try {
await ctx.sessionPersistence.create(meta('same-zone-claim', WORK, 'Asia/Shanghai'))
const matching = ctx.sessions.create(SessionId('same-zone-claim'), {
seed: oneTurnLog(),
meta: { cwd: WORK, timeZone: 'Asia/Shanghai' },
})
await expect(ctx.sessions.flush(matching)).resolves.toBe(true)
expect((await ctx.sessionPersistence.load(matching.id)).meta.timeZone).toBe('Asia/Shanghai')
await ctx.sessionPersistence.create(meta('different-zone-claim', WORK, 'Asia/Shanghai'))
const conflicting = ctx.sessions.create(SessionId('different-zone-claim'), {
seed: oneTurnLog(),
meta: { cwd: WORK, timeZone: 'America/New_York' },
})
await expect(ctx.sessions.flush(conflicting)).rejects.toThrow(/different timeZone|id collision/)
await ctx.sessionPersistence.create(meta('missing-zone-claim', WORK, 'Asia/Shanghai'))
const missing = ctx.sessions.create(SessionId('missing-zone-claim'), {
seed: oneTurnLog(),
meta: { cwd: WORK },
})
await expect(ctx.sessions.flush(missing)).rejects.toThrow(/different timeZone|id collision/)
} finally {
await fiber.dispose()
await fix.cleanup()
}
})
it('a fresh session reusing a previously-loaded id is rejected (ownerless guard)', async () => {
const fix = await makeFixture()
const { ctx, fiber } = await freshCtx(fix)

View File

@@ -374,28 +374,6 @@ describe('PersistenceCoordinator bounded writes', () => {
})
describe('PersistenceCoordinator stored identity', () => {
it('rejects a non-string timeZone decoded by a backend', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
const backend = new ControlledBackend()
const id = SessionId('invalid-stored-zone')
backend.store.set(id, {
meta: { ...meta(id), timeZone: 1 as unknown as string },
events: [],
})
let coordinator!: PersistenceCoordinator<never>
const fiber = await ctx.plugin(Object.assign((inner: Context) => {
coordinator = new PersistenceCoordinator(inner, backend)
}, { inject: ['sessions'] }))
try {
await expect(coordinator.inspect(id)).rejects.toThrow(/stored session .* timeZone must be a string/)
expect((coordinator as unknown as CoordinatorInternals).states.size).toBe(0)
} finally {
await fiber.dispose()
await ctx.fiber.dispose()
}
})
it('rejects a mismatched backend header before repair or state publication', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)