refactor(schedule): make absolute times explicit
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -17,6 +17,7 @@ export {
|
||||
ScheduleLogError,
|
||||
allocateScheduleId,
|
||||
createAfterScheduleRecord,
|
||||
createAtScheduleRecord,
|
||||
decodeScheduleChange,
|
||||
foldScheduleEvents,
|
||||
renderReminderFraming,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user