@niscorp/tide 0.1.11 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schemas/trigger.schema.ts","../src/schemas/policy.schema.ts","../src/schemas/reflex.schema.ts","../src/agent/dates.ts","../src/agent/reflex-agent.ts"],"names":["z","WEEKDAYS","days","defineAgent"],"mappings":";;;;;;AAEO,IAAM,QAAA,GAAW,CAAC,KAAA,EAAO,KAAA,EAAO,OAAO,KAAA,EAAO,KAAA,EAAO,OAAO,KAAK,CAAA;AAExE,IAAM,IAAA,GAAO,2BAAA;AACb,IAAM,IAAA,GAAO,yCAAA;AACb,IAAM,cAAA,GAAiB,wDAAA;AAEvB,IAAM,SAAA,GAAY,CAAC,EAAA,KAAwB;AACzC,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,IAAA,CAAK,cAAA,CAAe,OAAA,EAAS,EAAE,QAAA,EAAU,EAAA,EAAI,CAAA,CAAE,eAAA,EAAgB,CAAE,QAAA,KAAa,EAAA;AAAA,EAC3F,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF,CAAA;AAEO,IAAM,cAAA,GAAiBA,KAAA,CAAE,MAAA,EAAO,CAAE,MAAA,CAAO,SAAA,EAAW,EAAE,OAAA,EAAS,4BAAA,EAA8B,CAAA,CAAE,QAAA,CAAS,qBAAqB,CAAA;AAE7H,IAAM,eAAA,GAAkBA,MAAE,IAAA,CAAK,CAAC,OAAO,MAAA,EAAQ,OAAA,EAAS,MAAM,CAAC,CAAA;AAE/D,IAAM,oBAAA,GAAuBA,MACjC,MAAA,CAAO;AAAA,EACN,KAAA,EAAO,eAAA,CAAgB,QAAA,CAAS,6JAAwJ,CAAA;AAAA,EACxL,IAAIA,KAAA,CACD,KAAA,CAAM,CAACA,KAAA,CAAE,QAAO,CAAE,GAAA,EAAI,CAAE,GAAA,CAAI,CAAC,CAAA,CA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AK,GAAI,EAAE,KAAA,EAAO,QAAA,CAAS,IAAA,CAAK,IAAI,CAAA,EAAE;AAAA,IAC7E;AAAA;AAEJ,CAAC","file":"agent.cjs","sourcesContent":["import { z } from 'zod';\n\nexport const WEEKDAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const;\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/;\nconst MMDD = /^(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$/;\nconst LOCAL_DATETIME = /^\\d{4}-\\d{2}-\\d{2}T([01]\\d|2[0-3]):[0-5]\\d(:[0-5]\\d)?$/;\n\nconst knownZone = (tz: string): boolean => {\n try {\n return new Intl.DateTimeFormat('en-US', { timeZone: tz }).resolvedOptions().timeZone !== '';\n } catch {\n return false;\n }\n};\n\nexport const TimeZoneSchema = z.string().refine(knownZone, { message: 'not a time zone Intl knows' }).describe('IANA timezone name.');\n\nexport const ClockUnitSchema = z.enum(['day', 'week', 'month', 'year']);\n\nexport const ClockRecurringSchema = z\n .object({\n every: ClockUnitSchema.describe('The calendar period it repeats on. A repeating clock fires on every such period until the reflex is removed — only for a request that says it repeats.'),\n on: z\n .union([z.number().int().min(1).max(31), z.enum(WEEKDAYS), z.array(z.enum(WEEKDAYS)).min(1), z.string().regex(MMDD)])\n .optional()\n .describe(\n 'week → a weekday, or a list of them: [\"mon\",\"tue\",\"wed\",\"thu\",\"fri\"] is every weekday; month → 1..31, where 31 is the last day of every month (a shorter month clamps to its end); year → \"MM-DD\". Omitted for day.',\n ),\n at: z.string().regex(HHMM).describe('Local wall-clock time, \"HH:MM\".'),\n tz: TimeZoneSchema,\n })\n .strict()\n .superRefine((clock, ctx) => {\n const fail = (message: string) => ctx.addIssue({ code: 'custom', message, path: ['on'] });\n if (clock.every === 'day' && clock.on !== undefined) fail('a daily clock takes no `on`');\n const weekday = (value: unknown): boolean => typeof value === 'string' && WEEKDAYS.some((d) => d === value);\n const weekdays = Array.isArray(clock.on) && clock.on.length > 0 && new Set(clock.on).size === clock.on.length;\n if (clock.every === 'week' && !weekday(clock.on) && !weekdays) fail('a weekly clock needs `on` as a weekday (mon..sun), or a list of different weekdays');\n if (clock.every !== 'week' && Array.isArray(clock.on)) fail('only a weekly clock takes a list of weekdays');\n if (clock.every === 'month' && typeof clock.on !== 'number') fail('a monthly clock needs `on` as a day number');\n if (clock.every === 'year' && !(typeof clock.on === 'string' && MMDD.test(clock.on)))\n fail('a yearly clock needs `on` as \"MM-DD\"');\n })\n .describe('Repeats: fires on every day, week, month or year, at a time of day, until the reflex is removed.');\n\nexport const ClockOnceSchema = z\n .object({\n at: z.string().regex(LOCAL_DATETIME).describe('A fixed local date and time, once: \"YYYY-MM-DDTHH:MM\" or, to the second, \"YYYY-MM-DDTHH:MM:SS\".'),\n tz: TimeZoneSchema,\n })\n .strict()\n .describe('Once: fires at one date and time, then never again.');\n\nexport const ClockTriggerSchema = z\n .object({ clock: z.union([ClockRecurringSchema, ClockOnceSchema]) })\n .strict()\n .describe('Fires on the calendar: once, at a date and time, or repeating at a time of day.');\n\nexport const OpSchema = z.enum(['insert', 'update', 'delete']);\n\nexport const WriteTriggerSchema = z\n .object({\n fact: z\n .object({\n entity: z.string().describe('The table or entity whose writes wake this reflex.'),\n op: OpSchema.optional().describe('Narrow to one op — \"only on create\" is op: \"insert\".'),\n })\n .strict(),\n })\n .strict()\n .describe('Fires when a row of an entity is written — created, changed or deleted.');\n\nexport const SignalTriggerSchema = z\n .object({ fact: z.object({ signal: z.string().describe('A named external intake.') }).strict() })\n .strict()\n .describe('Fires when an event arrives from outside, on a named intake.');\n\nexport const RunTriggerSchema = z\n .object({\n fact: z\n .object({ run: z.string().describe('A reflex id — fires when THAT reflex\\'s run settles. Fan-in and dependency.') })\n .strict(),\n })\n .strict()\n .describe('Fires when another reflex has run: one automation after another.');\n\nexport const ManualTriggerSchema = z\n .object({ manual: z.object({}).strict() })\n .strict()\n .describe('Fires only when somebody fires it by hand.');\n\nexport const TriggerSchema = z.union([\n ClockTriggerSchema,\n WriteTriggerSchema,\n SignalTriggerSchema,\n RunTriggerSchema,\n ManualTriggerSchema,\n]);\n\nexport type ClockRecurring = z.infer<typeof ClockRecurringSchema>;\nexport type ClockOnce = z.infer<typeof ClockOnceSchema>;\nexport type Clock = ClockRecurring | ClockOnce;\nexport type Trigger = z.infer<typeof TriggerSchema>;\nexport type Op = z.infer<typeof OpSchema>;\nexport type Weekday = (typeof WEEKDAYS)[number];\n\nexport const clockOf = (trigger: Trigger): Clock | undefined => ('clock' in trigger ? trigger.clock : undefined);\n\nexport const isRecurring = (clock: Clock): clock is ClockRecurring => 'every' in clock;\n\nexport const factOf = (\n trigger: Trigger,\n): { entity?: string; op?: Op; signal?: string; run?: string } | undefined =>\n 'fact' in trigger ? trigger.fact : undefined;\n\nexport const isManual = (trigger: Trigger): boolean => 'manual' in trigger;\n","import { z } from 'zod';\n\nexport const RetrySchema = z\n .object({\n max: z.number().int().min(0).default(3).describe('Attempts after the first before the task parks `failed`.'),\n backoff: z.enum(['fixed', 'exponential']).default('exponential'),\n baseMs: z.number().int().positive().default(60_000),\n })\n .strict();\n\nexport const PolicySchema = z\n .object({\n retry: RetrySchema.optional(),\n timeoutMs: z.number().int().positive().default(30_000),\n overlap: z.enum(['skip', 'allow']).default('skip'),\n catchUp: z.enum(['run', 'skip', 'latest']).default('run'),\n // Read by `catchUp: 'skip'` only. What `catchUp` opens still passes\n // `overlap`: occurrences missed together are repeats of one another, so\n // under `overlap: 'skip'` the oldest runs and the rest are skipped.\n lateMs: z.number().int().positive().default(3_600_000),\n order: z.enum(['any', 'serial']).default('any'),\n })\n .strict();\n\nexport type Retry = z.infer<typeof RetrySchema>;\nexport type Policy = z.infer<typeof PolicySchema>;\n\nexport const DEFAULT_POLICY: Policy = PolicySchema.parse({});\n","import { z } from 'zod';\nimport { ClockTriggerSchema, ManualTriggerSchema, RunTriggerSchema, SignalTriggerSchema, TriggerSchema, WriteTriggerSchema } from './trigger.schema';\nimport { DEFAULT_POLICY, PolicySchema } from './policy.schema';\n\nexport const SelectionSchema = z\n .object({\n query: z.unknown().describe('Handed to the `select` seam verbatim. Under moss: a vex { fingerprint, context } replay.'),\n mode: z\n .enum(['each', 'batch'])\n .default('each')\n .describe('each → one task per row; batch → one task carrying all rows (bounded sets only).'),\n unitKey: z.string().optional().describe('The row field keying a unit task. `each` mode only; duplicates fail the firing.'),\n })\n .strict();\n\nexport const EffectRefSchema = z\n .object({\n name: z.string().describe('A registered effect. The reflex names it; the registry supplies the handler.'),\n input: z.unknown().optional().describe('A template, evaluated per unit by the `transform` seam.'),\n })\n .strict();\n\nconst reflexFields = {\n id: z.string().min(1).describe(\"Unique. A tenant's reflex is the tenant's own row, with its own id.\"),\n intent: z.string().min(1).describe(\"One factual sentence — what this does, in the person's language.\"),\n on: TriggerSchema,\n as: z.string().optional().describe('The identity this runs under. Opaque to tide; the host resolves it.'),\n params: z.record(z.string(), z.unknown()).optional().describe('Authored knobs, visible to templates as $.params.'),\n select: SelectionSchema.optional().describe('Omitted = the trigger itself is the unit.'),\n when: z.unknown().optional().describe('A predicate template. FACT triggers only — a query belongs in `select`.'),\n effect: EffectRefSchema,\n policy: PolicySchema.default(DEFAULT_POLICY),\n enabled: z.boolean().default(true).describe('A switch on the row, not part of the definition — flipping it is not an edit.'),\n};\n\nconst reflexRules = (reflex: { on: object; when?: unknown; select?: { mode: string; unitKey?: string | undefined } | undefined }, ctx: z.RefinementCtx): void => {\n if (reflex.when !== undefined && !('fact' in reflex.on))\n ctx.addIssue({ code: 'custom', message: '`when` is for fact triggers; a clock condition belongs in `select`', path: ['when'] });\n if (reflex.select?.mode === 'each' && reflex.select.unitKey === undefined)\n ctx.addIssue({ code: 'custom', message: \"`each` mode needs a unitKey — it is the task's idempotency grain\", path: ['select', 'unitKey'] });\n};\n\nexport const ReflexSchema = z.object(reflexFields).strict().superRefine(reflexRules);\n\nexport const REFLEX_TRIGGERS = {\n clock: ClockTriggerSchema,\n write: WriteTriggerSchema,\n signal: SignalTriggerSchema,\n run: RunTriggerSchema,\n manual: ManualTriggerSchema,\n} as const;\nexport type ReflexTrigger = keyof typeof REFLEX_TRIGGERS;\n\nexport const reflexSchemaOf = (choice: { triggers?: readonly ReflexTrigger[] } = {}): z.ZodType<Reflex, ReflexInput> => {\n if (choice.triggers === undefined) return ReflexSchema;\n const [first, ...rest] = choice.triggers.map((kind): z.ZodType<Reflex['on'], ReflexInput['on']> => REFLEX_TRIGGERS[kind]);\n if (first === undefined) throw new Error('tide: a reflex needs at least one trigger kind');\n const on: z.ZodType<Reflex['on'], ReflexInput['on']> = rest.length === 0 ? first : z.union([first, ...rest]);\n return z.object({ ...reflexFields, on }).strict().superRefine(reflexRules);\n};\n\nexport const TimerSchema = z\n .object({\n hours: z.number().int().min(0).optional(),\n minutes: z.number().int().min(0).optional(),\n seconds: z.number().int().min(0).optional(),\n })\n .strict()\n .refine((timer) => (timer.hours ?? 0) + (timer.minutes ?? 0) + (timer.seconds ?? 0) > 0, { message: 'a timer needs a length' });\n\nexport const TimerTriggerSchema = z\n .object({ timer: TimerSchema.describe('A length of time from now, as hours, minutes and seconds (each optional, together more than zero). Fires once, that long after the reflex is saved — not after it is written. A clock is for a time of day or a date.') })\n .strict();\n\nexport const DRAFT_TRIGGERS = {\n clock: ClockTriggerSchema,\n timer: TimerTriggerSchema,\n write: WriteTriggerSchema,\n signal: SignalTriggerSchema,\n run: RunTriggerSchema,\n manual: ManualTriggerSchema,\n} as const;\nexport type DraftTrigger = keyof typeof DRAFT_TRIGGERS;\nconst ALL_DRAFT_TRIGGERS: readonly DraftTrigger[] = ['clock', 'timer', 'write', 'signal', 'run', 'manual'];\n\nexport type DraftField = 'params' | 'select' | 'when';\n\nexport type DraftChoice = { triggers?: readonly DraftTrigger[]; fields?: readonly DraftField[] };\n\nconst draftCore = {\n id: z.string().min(1).describe('A short name you make up from the request, like \"call-mum\". Never ask the person for it.'),\n intent: reflexFields.intent,\n effect: EffectRefSchema,\n};\n\nconst WidestDraftSchema = z\n .object({ ...draftCore, on: z.union([TriggerSchema, TimerTriggerSchema]), params: reflexFields.params, select: reflexFields.select, when: reflexFields.when })\n .strict();\nexport type ReflexDraft = z.infer<typeof WidestDraftSchema>;\n\nexport const draftSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexDraft> => {\n const [first, ...rest] = (choice.triggers ?? ALL_DRAFT_TRIGGERS).map((kind): z.ZodType<ReflexDraft['on']> => DRAFT_TRIGGERS[kind]);\n if (first === undefined) throw new Error('tide: a draft needs at least one trigger kind');\n const on: z.ZodType<ReflexDraft['on']> = rest.length === 0 ? first : z.union([first, ...rest]);\n const has = (field: DraftField): boolean => choice.fields?.includes(field) ?? false;\n const keep: { [key in keyof ReflexDraft]?: true } = {\n id: true,\n intent: true,\n effect: true,\n on: true,\n ...(has('params') ? { params: true as const } : {}),\n ...(has('select') ? { select: true as const } : {}),\n ...(has('when') ? { when: true as const } : {}),\n };\n return WidestDraftSchema.pick(keep).extend({ on }).strict().superRefine(reflexRules);\n};\n\nexport const ReflexDraftSchema = draftSchemaOf();\n\nexport type Selection = z.infer<typeof SelectionSchema>;\nexport type EffectRef = z.infer<typeof EffectRefSchema>;\nexport type Reflex = z.infer<typeof ReflexSchema>;\nexport type ReflexInput = z.input<typeof ReflexSchema>;\nexport type Timer = z.infer<typeof TimerSchema>;\n","const WEEKDAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] as const;\nconst WEEKDAY_WORDS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] as const;\nconst MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] as const;\n\ntype Day = { y: number; m: number; d: number };\n\nconst pad = (n: number): string => String(n).padStart(2, '0');\n// The date a text begins with, or undefined for one that does not exist (\"2026-02-30\").\nconst dayOf = (text: string): Day | undefined => {\n const found = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(text);\n if (found === null) return undefined;\n const day = { y: Number(found[1]), m: Number(found[2]), d: Number(found[3]) };\n const at = new Date(Date.UTC(day.y, day.m - 1, day.d));\n return at.getUTCFullYear() === day.y && at.getUTCMonth() === day.m - 1 && at.getUTCDate() === day.d ? day : undefined;\n};\n// Monday is 0: a week starts on Monday.\nconst weekdayOf = (day: Day): number => (new Date(Date.UTC(day.y, day.m - 1, day.d)).getUTCDay() + 6) % 7;\nconst plus = (day: Day, days: number): Day => {\n const at = new Date(Date.UTC(day.y, day.m - 1, day.d + days));\n return { y: at.getUTCFullYear(), m: at.getUTCMonth() + 1, d: at.getUTCDate() };\n};\nconst isoOf = (day: Day): string => `${String(day.y)}-${pad(day.m)}-${pad(day.d)}`;\nconst said = (day: Day): string => `${WEEKDAYS[weekdayOf(day)] ?? ''} ${isoOf(day)}`;\nconst days = (from: Day, first: number, last: number): string =>\n Array.from({ length: Math.max(0, last - first + 1) }, (_, at) => said(plus(from, first + at))).join(', ') || 'none';\n\n// One month on one line, each weekday once with its days.\nconst monthLine = (y: number, m: number): string => {\n const length = new Date(Date.UTC(y, m, 0)).getUTCDate();\n const byWeekday = WEEKDAYS.map((): number[] => []);\n for (let d = 1; d <= length; d++) byWeekday[weekdayOf({ y, m, d })]?.push(d);\n return `${MONTHS[m - 1] ?? ''} ${String(y)}: ${WEEKDAYS.map((weekday, at) => `${weekday} ${(byWeekday[at] ?? []).join(' ')}`).join(' | ')}`;\n};\n\n// What the agent reads a date off, written from the `now` it is handed: today with its weekday, the rest of this week\n// and the two after it, and this month and the next. A `now` that is no date and time says so instead.\nexport const whenItIs = (now: string): string => {\n const today = dayOf(now);\n const time = /^\\d{4}-\\d{2}-\\d{2}T([01]\\d|2[0-3]):[0-5]\\d/.test(now) ? now.slice(11, 16) : undefined;\n if (today === undefined || time === undefined) return 'TODAY — not known: ask for the date of anything not given as one.';\n const toSunday = 6 - weekdayOf(today);\n const next = today.m === 12 ? { y: today.y + 1, m: 1 } : { y: today.y, m: today.m + 1 };\n return [\n `TODAY — ${said(today)}, ${time}.`,\n `COMING DAYS — today: ${said(today)} | the rest of this week: ${days(today, 1, toSunday)} | next week: ${days(today, toSunday + 1, toSunday + 7)} | ` +\n `the week after: ${days(today, toSunday + 8, toSunday + 14)}`,\n `CALENDAR — ${monthLine(today.y, today.m)}; ${monthLine(next.y, next.m)}`,\n ].join('\\n');\n};\n\n// A weekday, as a word or abbreviated, then a date: \"Fri 2026-11-06\", \"Friday, 2026-11-06T14:30\", \"thurs 2026-11-05\".\nconst PAIRED = /\\b(mon|tue|wed|thu|fri|sat|sun)(?:day|sday|s|nesday|rsday|rs|urday)?\\.?,?\\s+(\\d{4}-\\d{2}-\\d{2})(?!\\d)/gi;\n\n// What is sent back: a date the reasoning writes beside the wrong weekday, or a date that does not exist. How the\n// reasoning words a date is its own: a draft is never sent back for that.\nexport const dateProblems = (reasoning: string | undefined): string[] => {\n const found = [...(reasoning ?? '').matchAll(PAIRED)].map((match) => ({\n text: match[2] ?? '',\n day: dayOf(match[2] ?? ''),\n named: WEEKDAYS.findIndex((weekday) => weekday.toLowerCase() === (match[1] ?? '').toLowerCase()),\n }));\n const none = found.flatMap(({ text, day }) => (day === undefined ? [`${text} is not a date. Look the date up in COMING DAYS or CALENDAR.`] : []));\n const pairs = found.flatMap(({ day, named }) => (day === undefined || named < 0 ? [] : [{ day, named }]));\n const wrong = pairs.flatMap(({ day, named }) => {\n const real = weekdayOf(day);\n if (real === named) return [];\n const after = plus(day, (named - real + 7) % 7);\n return [\n `${isoOf(day)} is a ${WEEKDAY_WORDS[real] ?? ''}, not a ${WEEKDAY_WORDS[named] ?? ''}: the ${WEEKDAY_WORDS[named] ?? ''}s around it are ` +\n `${said(plus(after, -7))} and ${said(after)}. Look the date up in COMING DAYS.`,\n ];\n });\n return [...none, ...wrong];\n};\n","import { z } from 'zod';\nimport type { ZodType } from 'zod';\nimport { defineAgent, type AgentDefinition, type Message } from '@niscorp/cortex';\nimport { draftSchemaOf, type DraftChoice, type ReflexDraft } from '../schemas';\nimport { dateProblems, whenItIs } from './dates';\n\nexport type OfferedEffect = { name: string; description: string; input: ZodType };\n\nexport const ReflexAgentInputSchema = z.object({\n intent: z.string().describe(\"The person's words — a request, or, later in the conversation, their reply to your question.\"),\n now: z\n .string()\n .describe('The current local date and time, \"YYYY-MM-DDTHH:MM\", in `tz` — what a date or a time of day in the request is read against.'),\n tz: z.string().describe('The IANA timezone the person is in. Every clock the reflex names uses it.'),\n});\n\nexport type ReflexAgentInput = z.infer<typeof ReflexAgentInputSchema>;\n\nexport const ReflexQuestionSchema = z\n .object({ question: z.string().min(1).describe(\"One short question in the person's language, naming what it chooses between.\") })\n .strict()\n .describe('Ask instead of writing a draft when the request can be read as different automations and nothing in its words or the conversation so far decides which.');\n\nexport const ReflexRefusalSchema = z\n .object({ refused: z.string().min(1).describe('Why none of the offered effects does it, in words for the person who asked.') })\n .strict()\n .describe('Refuse instead of writing a draft when none of the offered effects does what was asked. Only for that: a request that is unclear is a question, not a refusal.');\n\nexport type ReflexQuestion = z.infer<typeof ReflexQuestionSchema>;\nexport type ReflexRefusal = z.infer<typeof ReflexRefusalSchema>;\nexport type ReflexAnswer = ReflexDraft | ReflexQuestion | ReflexRefusal;\n\nexport const answerSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexAnswer> =>\n z.union([\n draftSchemaOf(choice).describe('Write the draft when the request — with the conversation so far — says what should happen and what sets it off.'),\n ReflexQuestionSchema,\n ReflexRefusalSchema,\n ]);\n\nexport const ReflexAnswerSchema = answerSchemaOf();\n\nexport const isDraft = (answer: ReflexAnswer): answer is ReflexDraft => 'effect' in answer;\n\nexport const reflexConversation = (conversation: {\n now: string;\n tz: string;\n earlier: readonly { request: string; answer: ReflexAnswer; reasoning?: string | undefined }[];\n latest: string;\n}): Message[] => [\n ...conversation.earlier.flatMap((turn): Message[] => [\n { role: 'user', content: JSON.stringify({ intent: turn.request, now: conversation.now, tz: conversation.tz }) },\n { role: 'assistant', content: JSON.stringify({ ...(turn.reasoning === undefined ? {} : { reasoning: turn.reasoning }), data: turn.answer }) },\n ]),\n { role: 'user', content: JSON.stringify({ intent: conversation.latest, now: conversation.now, tz: conversation.tz }) },\n];\n\nconst INSTRUCTIONS = `You are Tide's reflex agent. Somebody describes an automation; you answer with ONE of three things, as the OUTPUT SCHEMA describes: a reflex draft that does it (a trigger, exactly one of the offered effects, and its input), a question back, or a refusal.\n\nYour envelope's \\`data\\` is that answer. In \\`reasoning\\`, first restate the whole request as the conversation now has it; then decide. The answer must validate against the OUTPUT SCHEMA (its descriptions say what each part is); a draft must name one of the OFFERED EFFECTS and give it an input its schema accepts.\n\nTimes: a date is looked up in TODAY, COMING DAYS and CALENDAR, never counted. A weekday on its own is the coming one: the first of that weekday in COMING DAYS after today. In \\`reasoning\\`, write every date you draft or ask about as COMING DAYS writes it: the weekday's three letters, then the date. A date or a time that could still mean more than one moment is a question, never a guess — a day without its year, a time of day without morning or evening, today's own weekday (today, or a week from today), \"next\" before a weekday that could be this week's or next week's; a question about dates names them, as looked up. An automation happens once unless the person says it repeats. Never write a time that has already passed.\n\nA reply answers your last question: together with the request before it, it is one request — keep what the request said, and add what the reply decides.\n\nWhen you ask, ask about everything still undecided in one question, so one reply can settle it.\n\nEffects: when the request names something to be done that no offered effect does — a channel, a device, an action — refuse it; never put a different effect in its place.`;\n\n// What it is handed is a request, or a conversation whose last turn is the latest: either way `now` is in it.\nconst nowOf = (input: unknown): string | undefined => {\n const last = Array.isArray(input) ? input.at(-1) : undefined;\n const turn: unknown = typeof last === 'object' && last !== null && 'content' in last ? parsedJson(String(last.content)) : input;\n const parsed = ReflexAgentInputSchema.safeParse(turn);\n return parsed.success ? parsed.data.now : undefined;\n};\nconst parsedJson = (text: string): unknown => {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n};\n\n// Converted by the schema's own zod: a caller's schema may come from another copy.\nconst describeEffects = (effects: readonly OfferedEffect[]): string =>\n `OFFERED EFFECTS — a draft names exactly one, by \\`name\\`; choose by its \\`description\\`:\\n${JSON.stringify(\n effects.map((effect) => ({ name: effect.name, description: effect.description, input: effect.input['~standard'].jsonSchema.output({ target: 'draft-07' }) })),\n )}`;\n\nexport const effectProblem = (effects: readonly OfferedEffect[], reflex: Pick<ReflexDraft, 'effect'>): string | undefined => {\n const effect = effects.find((candidate) => candidate.name === reflex.effect.name);\n if (effect === undefined) return `The effect \"${reflex.effect.name}\" is not offered. Name one of: ${effects.map((candidate) => candidate.name).join(', ')}.`;\n const parsed = effect.input.safeParse(reflex.effect.input);\n if (parsed.success) return undefined;\n const issues = parsed.error.issues.map((issue) => `${issue.path.join('.') || 'input'}: ${issue.message}`).join('; ');\n return `The input for \"${effect.name}\" does not fit its schema — ${issues}.`;\n};\n\nexport const createReflexAgent = (config: { effects: readonly OfferedEffect[] } & DraftChoice): AgentDefinition<ReflexAnswer> =>\n defineAgent<ReflexAnswer>({\n id: 'tide.reflex',\n description: 'Answers what somebody wants automated with one tide reflex draft, a question back, or a refusal.',\n instructions: INSTRUCTIONS,\n context: [() => describeEffects(config.effects), ({ input }) => whenItIs(nowOf(input) ?? '')],\n output: {\n schema: answerSchemaOf(config),\n validate: (envelope) => {\n const effect = isDraft(envelope.data) ? effectProblem(config.effects, envelope.data) : undefined;\n const problems = [...(effect === undefined ? [] : [effect]), ...dateProblems(envelope.reasoning)];\n return problems.length === 0 ? { ok: true } : { retry: problems.join('\\n') };\n },\n },\n });\n"]}
1
+ {"version":3,"sources":["../src/schemas/trigger.schema.ts","../src/schemas/policy.schema.ts","../src/schemas/reflex.schema.ts","../src/agent/dates.ts","../src/agent/reflex-agent.ts"],"names":["z","WEEKDAYS","days","defineAgent"],"mappings":";;;;;;AAEO,IAAM,QAAA,GAAW,CAAC,KAAA,EAAO,KAAA,EAAO,OAAO,KAAA,EAAO,KAAA,EAAO,OAAO,KAAK,CAAA;AAExE,IAAM,IAAA,GAAO,2BAAA;AACb,IAAM,IAAA,GAAO,yCAAA;AACb,IAAM,cAAA,GAAiB,wDAAA;A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KAAW,CAAA,GAAI,EAAE,EAAA,EAAI,IAAA,EAAK,GAAI,EAAE,KAAA,EAAO,QAAA,CAAS,IAAA,CAAK,IAAI,CAAA,EAAE;AAAA,IAC7E;AAAA;AAEJ,CAAC","file":"agent.cjs","sourcesContent":["import { z } from 'zod';\n\nexport const WEEKDAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const;\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/;\nconst MMDD = /^(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$/;\nconst LOCAL_DATETIME = /^\\d{4}-\\d{2}-\\d{2}T([01]\\d|2[0-3]):[0-5]\\d(:[0-5]\\d)?$/;\n\nconst isKnownZone = (tz: string): boolean => {\n try {\n return new Intl.DateTimeFormat('en-US', { timeZone: tz }).resolvedOptions().timeZone !== '';\n } catch {\n return false;\n }\n};\n\nexport const TimeZoneSchema = z.string().refine(isKnownZone, { message: 'not a time zone Intl knows' }).describe('IANA timezone name.');\n\nexport const ClockUnitSchema = z.enum(['day', 'week', 'month', 'year']);\n\nexport const ClockRecurringSchema = z\n .object({\n every: ClockUnitSchema.describe('The calendar period it repeats on. A repeating clock fires on every such period until the reflex is removed — only for a request that says it repeats.'),\n on: z\n .union([z.number().int().min(1).max(31), z.enum(WEEKDAYS), z.array(z.enum(WEEKDAYS)).min(1), z.string().regex(MMDD)])\n .optional()\n .describe(\n 'week → a weekday, or a list of them: [\"mon\",\"tue\",\"wed\",\"thu\",\"fri\"] is every weekday; month → 1..31, where 31 is the last day of every month (a shorter month clamps to its end); year → \"MM-DD\". Omitted for day.',\n ),\n at: z.string().regex(HHMM).describe('Local wall-clock time, \"HH:MM\".'),\n tz: TimeZoneSchema,\n })\n .strict()\n .superRefine((clock, ctx) => {\n const fail = (message: string) => ctx.addIssue({ code: 'custom', message, path: ['on'] });\n if (clock.every === 'day' && clock.on !== undefined) fail('a daily clock takes no `on`');\n const weekday = (value: unknown): boolean => typeof value === 'string' && WEEKDAYS.some((d) => d === value);\n const weekdays = Array.isArray(clock.on) && clock.on.length > 0 && new Set(clock.on).size === clock.on.length;\n if (clock.every === 'week' && !weekday(clock.on) && !weekdays) fail('a weekly clock needs `on` as a weekday (mon..sun), or a list of different weekdays');\n if (clock.every !== 'week' && Array.isArray(clock.on)) fail('only a weekly clock takes a list of weekdays');\n if (clock.every === 'month' && typeof clock.on !== 'number') fail('a monthly clock needs `on` as a day number');\n if (clock.every === 'year' && !(typeof clock.on === 'string' && MMDD.test(clock.on)))\n fail('a yearly clock needs `on` as \"MM-DD\"');\n })\n .describe('Repeats: fires on every day, week, month or year, at a time of day, until the reflex is removed.');\n\nexport const ClockOnceSchema = z\n .object({\n at: z.string().regex(LOCAL_DATETIME).describe('A fixed local date and time, once: \"YYYY-MM-DDTHH:MM\" or, to the second, \"YYYY-MM-DDTHH:MM:SS\".'),\n tz: TimeZoneSchema,\n })\n .strict()\n .describe('Once: fires at one date and time, then never again.');\n\nexport const ClockTriggerSchema = z\n .object({ clock: z.union([ClockRecurringSchema, ClockOnceSchema]) })\n .strict()\n .describe('Fires on the calendar: once, at a date and time, or repeating at a time of day.');\n\nexport const OpSchema = z.enum(['insert', 'update', 'delete']);\n\nexport const WriteTriggerSchema = z\n .object({\n fact: z\n .object({\n entity: z.string().describe('The table or entity whose writes wake this reflex.'),\n op: OpSchema.optional().describe('Narrow to one op — \"only on create\" is op: \"insert\".'),\n })\n .strict(),\n })\n .strict()\n .describe('Fires when a row of an entity is written — created, changed or deleted.');\n\nexport const SignalTriggerSchema = z\n .object({ fact: z.object({ signal: z.string().describe('A named external intake.') }).strict() })\n .strict()\n .describe('Fires when an event arrives from outside, on a named intake.');\n\nexport const RunTriggerSchema = z\n .object({\n fact: z\n .object({ run: z.string().describe('A reflex id — fires when THAT reflex\\'s run settles. Fan-in and dependency.') })\n .strict(),\n })\n .strict()\n .describe('Fires when another reflex has run: one automation after another.');\n\nexport const ManualTriggerSchema = z\n .object({ manual: z.object({}).strict() })\n .strict()\n .describe('Fires only when somebody fires it by hand.');\n\nexport const TriggerSchema = z.union([\n ClockTriggerSchema,\n WriteTriggerSchema,\n SignalTriggerSchema,\n RunTriggerSchema,\n ManualTriggerSchema,\n]);\n\nexport type ClockRecurring = z.infer<typeof ClockRecurringSchema>;\nexport type ClockOnce = z.infer<typeof ClockOnceSchema>;\nexport type Clock = ClockRecurring | ClockOnce;\nexport type Trigger = z.infer<typeof TriggerSchema>;\nexport type Op = z.infer<typeof OpSchema>;\nexport type Weekday = (typeof WEEKDAYS)[number];\n\nexport const clockOf = (trigger: Trigger): Clock | undefined => ('clock' in trigger ? trigger.clock : undefined);\n\nexport const isRecurring = (clock: Clock): clock is ClockRecurring => 'every' in clock;\n\nexport const factOf = (\n trigger: Trigger,\n): { entity?: string; op?: Op; signal?: string; run?: string } | undefined =>\n 'fact' in trigger ? trigger.fact : undefined;\n\nexport const isManual = (trigger: Trigger): boolean => 'manual' in trigger;\n","import { z } from 'zod';\n\nexport const RetrySchema = z\n .object({\n max: z.number().int().min(0).default(3).describe('Attempts after the first before the task parks `failed`.'),\n backoff: z.enum(['fixed', 'exponential']).default('exponential'),\n baseMs: z.number().int().positive().default(60_000),\n })\n .strict();\n\nexport const PolicySchema = z\n .object({\n retry: RetrySchema.optional(),\n timeoutMs: z.number().int().positive().default(30_000),\n overlap: z.enum(['skip', 'allow']).default('skip'),\n catchUp: z.enum(['run', 'skip', 'latest']).default('run'),\n // Read by `catchUp: 'skip'` only. What `catchUp` opens still passes\n // `overlap`: occurrences missed together are repeats of one another, so\n // under `overlap: 'skip'` the oldest runs and the rest are skipped.\n lateMs: z.number().int().positive().default(3_600_000),\n order: z.enum(['any', 'serial']).default('any'),\n })\n .strict();\n\nexport type Retry = z.infer<typeof RetrySchema>;\nexport type Policy = z.infer<typeof PolicySchema>;\n\nexport const DEFAULT_POLICY: Policy = PolicySchema.parse({});\n","import { z } from 'zod';\nimport { ClockTriggerSchema, ManualTriggerSchema, RunTriggerSchema, SignalTriggerSchema, TriggerSchema, WriteTriggerSchema } from './trigger.schema';\nimport { DEFAULT_POLICY, PolicySchema } from './policy.schema';\n\nexport const SelectionSchema = z\n .object({\n query: z.unknown().describe('Handed to the `select` seam verbatim. Under moss: a vex { fingerprint, context } replay.'),\n mode: z\n .enum(['each', 'batch'])\n .default('each')\n .describe('each → one task per row; batch → one task carrying all rows (bounded sets only).'),\n unitKey: z.string().optional().describe('The row field keying a unit task. `each` mode only; duplicates fail the firing.'),\n })\n .strict();\n\nexport const EffectRefSchema = z\n .object({\n name: z.string().describe('A registered effect. The reflex names it; the registry supplies the handler.'),\n input: z.unknown().optional().describe('A template, evaluated per unit by the `transform` seam.'),\n })\n .strict();\n\nconst reflexFields = {\n id: z.string().min(1).describe(\"Unique. A tenant's reflex is the tenant's own row, with its own id.\"),\n intent: z.string().min(1).describe(\"One factual sentence — what this does, in the person's language.\"),\n on: TriggerSchema,\n as: z.string().optional().describe('The identity this runs under. Opaque to tide; the host resolves it.'),\n params: z.record(z.string(), z.unknown()).optional().describe('Authored knobs, visible to templates as $.params.'),\n select: SelectionSchema.optional().describe('Omitted = the trigger itself is the unit.'),\n when: z.unknown().optional().describe('A predicate template. FACT triggers only — a query belongs in `select`.'),\n effect: EffectRefSchema,\n policy: PolicySchema.default(DEFAULT_POLICY),\n enabled: z.boolean().default(true).describe('A switch on the row, not part of the definition — flipping it is not an edit.'),\n};\n\nconst reflexRules = (reflex: { on: object; when?: unknown; select?: { mode: string; unitKey?: string | undefined } | undefined }, ctx: z.RefinementCtx): void => {\n if (reflex.when !== undefined && !('fact' in reflex.on))\n ctx.addIssue({ code: 'custom', message: '`when` is for fact triggers; a clock condition belongs in `select`', path: ['when'] });\n if (reflex.select?.mode === 'each' && reflex.select.unitKey === undefined)\n ctx.addIssue({ code: 'custom', message: \"`each` mode needs a unitKey — it is the task's idempotency grain\", path: ['select', 'unitKey'] });\n};\n\nexport const ReflexSchema = z.object(reflexFields).strict().superRefine(reflexRules);\n\nexport const REFLEX_TRIGGERS = {\n clock: ClockTriggerSchema,\n write: WriteTriggerSchema,\n signal: SignalTriggerSchema,\n run: RunTriggerSchema,\n manual: ManualTriggerSchema,\n} as const;\nexport type ReflexTrigger = keyof typeof REFLEX_TRIGGERS;\n\nexport const reflexSchemaOf = (choice: { triggers?: readonly ReflexTrigger[] } = {}): z.ZodType<Reflex, ReflexInput> => {\n if (choice.triggers === undefined) return ReflexSchema;\n const [first, ...rest] = choice.triggers.map((kind): z.ZodType<Reflex['on'], ReflexInput['on']> => REFLEX_TRIGGERS[kind]);\n if (first === undefined) throw new Error('tide: a reflex needs at least one trigger kind');\n const on: z.ZodType<Reflex['on'], ReflexInput['on']> = rest.length === 0 ? first : z.union([first, ...rest]);\n return z.object({ ...reflexFields, on }).strict().superRefine(reflexRules);\n};\n\nexport const TimerSchema = z\n .object({\n hours: z.number().int().min(0).optional(),\n minutes: z.number().int().min(0).optional(),\n seconds: z.number().int().min(0).optional(),\n })\n .strict()\n .refine((timer) => (timer.hours ?? 0) + (timer.minutes ?? 0) + (timer.seconds ?? 0) > 0, { message: 'a timer needs a length' });\n\nexport const TimerTriggerSchema = z\n .object({ timer: TimerSchema.describe('A length of time from now, as hours, minutes and seconds (each optional, together more than zero). Fires once, that long after the reflex is saved — not after it is written. A clock is for a time of day or a date.') })\n .strict();\n\nexport const DRAFT_TRIGGERS = {\n clock: ClockTriggerSchema,\n timer: TimerTriggerSchema,\n write: WriteTriggerSchema,\n signal: SignalTriggerSchema,\n run: RunTriggerSchema,\n manual: ManualTriggerSchema,\n} as const;\nexport type DraftTrigger = keyof typeof DRAFT_TRIGGERS;\nconst ALL_DRAFT_TRIGGERS: readonly DraftTrigger[] = ['clock', 'timer', 'write', 'signal', 'run', 'manual'];\n\nexport type DraftField = 'params' | 'select' | 'when';\n\nexport type DraftChoice = { triggers?: readonly DraftTrigger[]; fields?: readonly DraftField[] };\n\nconst draftCore = {\n id: z.string().min(1).describe('A short name you make up from the request, like \"call-mum\". Never ask the person for it.'),\n intent: reflexFields.intent,\n effect: EffectRefSchema,\n};\n\nconst WidestDraftSchema = z\n .object({ ...draftCore, on: z.union([TriggerSchema, TimerTriggerSchema]), params: reflexFields.params, select: reflexFields.select, when: reflexFields.when })\n .strict();\nexport type ReflexDraft = z.infer<typeof WidestDraftSchema>;\n\nexport const draftSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexDraft> => {\n const [first, ...rest] = (choice.triggers ?? ALL_DRAFT_TRIGGERS).map((kind): z.ZodType<ReflexDraft['on']> => DRAFT_TRIGGERS[kind]);\n if (first === undefined) throw new Error('tide: a draft needs at least one trigger kind');\n const on: z.ZodType<ReflexDraft['on']> = rest.length === 0 ? first : z.union([first, ...rest]);\n const has = (field: DraftField): boolean => choice.fields?.includes(field) ?? false;\n const keep: { [key in keyof ReflexDraft]?: true } = {\n id: true,\n intent: true,\n effect: true,\n on: true,\n ...(has('params') ? { params: true as const } : {}),\n ...(has('select') ? { select: true as const } : {}),\n ...(has('when') ? { when: true as const } : {}),\n };\n return WidestDraftSchema.pick(keep).extend({ on }).strict().superRefine(reflexRules);\n};\n\nexport const ReflexDraftSchema = draftSchemaOf();\n\nexport type Selection = z.infer<typeof SelectionSchema>;\nexport type EffectRef = z.infer<typeof EffectRefSchema>;\nexport type Reflex = z.infer<typeof ReflexSchema>;\nexport type ReflexInput = z.input<typeof ReflexSchema>;\nexport type Timer = z.infer<typeof TimerSchema>;\n","const WEEKDAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] as const;\nconst WEEKDAY_WORDS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] as const;\nconst MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] as const;\n\ntype Day = { y: number; m: number; d: number };\n\nconst pad = (n: number): string => String(n).padStart(2, '0');\n// The date a text begins with, or undefined for one that does not exist (\"2026-02-30\").\nconst dayOf = (text: string): Day | undefined => {\n const found = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(text);\n if (found === null) return undefined;\n const day = { y: Number(found[1]), m: Number(found[2]), d: Number(found[3]) };\n const at = new Date(Date.UTC(day.y, day.m - 1, day.d));\n return at.getUTCFullYear() === day.y && at.getUTCMonth() === day.m - 1 && at.getUTCDate() === day.d ? day : undefined;\n};\n// Monday is 0: a week starts on Monday.\nconst weekdayOf = (day: Day): number => (new Date(Date.UTC(day.y, day.m - 1, day.d)).getUTCDay() + 6) % 7;\nconst plus = (day: Day, days: number): Day => {\n const at = new Date(Date.UTC(day.y, day.m - 1, day.d + days));\n return { y: at.getUTCFullYear(), m: at.getUTCMonth() + 1, d: at.getUTCDate() };\n};\nconst isoOf = (day: Day): string => `${String(day.y)}-${pad(day.m)}-${pad(day.d)}`;\nconst said = (day: Day): string => `${WEEKDAYS[weekdayOf(day)] ?? ''} ${isoOf(day)}`;\nconst days = (from: Day, first: number, last: number): string =>\n Array.from({ length: Math.max(0, last - first + 1) }, (_, at) => said(plus(from, first + at))).join(', ') || 'none';\n\n// One month on one line, each weekday once with its days.\nconst monthLine = (y: number, m: number): string => {\n const length = new Date(Date.UTC(y, m, 0)).getUTCDate();\n const byWeekday = WEEKDAYS.map((): number[] => []);\n for (let d = 1; d <= length; d++) byWeekday[weekdayOf({ y, m, d })]?.push(d);\n return `${MONTHS[m - 1] ?? ''} ${String(y)}: ${WEEKDAYS.map((weekday, at) => `${weekday} ${(byWeekday[at] ?? []).join(' ')}`).join(' | ')}`;\n};\n\n// What the agent reads a date off, written from the `now` it is handed: today with its weekday, the rest of this week\n// and the two after it, and this month and the next. A `now` that is no date and time says so instead.\nexport const whenItIs = (now: string): string => {\n const today = dayOf(now);\n const time = /^\\d{4}-\\d{2}-\\d{2}T([01]\\d|2[0-3]):[0-5]\\d/.test(now) ? now.slice(11, 16) : undefined;\n if (today === undefined || time === undefined) return 'TODAY — not known: ask for the date of anything not given as one.';\n const toSunday = 6 - weekdayOf(today);\n const next = today.m === 12 ? { y: today.y + 1, m: 1 } : { y: today.y, m: today.m + 1 };\n return [\n `TODAY — ${said(today)}, ${time}.`,\n `COMING DAYS — today: ${said(today)} | the rest of this week: ${days(today, 1, toSunday)} | next week: ${days(today, toSunday + 1, toSunday + 7)} | ` +\n `the week after: ${days(today, toSunday + 8, toSunday + 14)}`,\n `CALENDAR — ${monthLine(today.y, today.m)}; ${monthLine(next.y, next.m)}`,\n ].join('\\n');\n};\n\n// A one-shot clock on a date that does not exist loads and fires on the day it runs on to, which no person meant.\nexport const clockDateProblems = (at: string | undefined): string[] =>\n at === undefined || dayOf(at) !== undefined ? [] : [`The clock's date ${at.slice(0, 10)} is not a date. Look the date up in COMING DAYS or CALENDAR.`];\n\n// A weekday, as a word or abbreviated, then a date: \"Fri 2026-11-06\", \"Friday, 2026-11-06T14:30\", \"thurs 2026-11-05\".\nconst PAIRED = /\\b(mon|tue|wed|thu|fri|sat|sun)(?:day|sday|s|nesday|rsday|rs|urday)?\\.?,?\\s+(\\d{4}-\\d{2}-\\d{2})(?!\\d)/gi;\n\n// What is sent back: a date the reasoning writes beside the wrong weekday, or a date that does not exist. How the\n// reasoning words a date is its own: a draft is never sent back for that.\nexport const dateProblems = (reasoning: string | undefined): string[] => {\n const found = [...(reasoning ?? '').matchAll(PAIRED)].map((match) => ({\n text: match[2] ?? '',\n day: dayOf(match[2] ?? ''),\n named: WEEKDAYS.findIndex((weekday) => weekday.toLowerCase() === (match[1] ?? '').toLowerCase()),\n }));\n const none = found.flatMap(({ text, day }) => (day === undefined ? [`${text} is not a date. Look the date up in COMING DAYS or CALENDAR.`] : []));\n const pairs = found.flatMap(({ day, named }) => (day === undefined || named < 0 ? [] : [{ day, named }]));\n const wrong = pairs.flatMap(({ day, named }) => {\n const real = weekdayOf(day);\n if (real === named) return [];\n const after = plus(day, (named - real + 7) % 7);\n return [\n `${isoOf(day)} is a ${WEEKDAY_WORDS[real] ?? ''}, not a ${WEEKDAY_WORDS[named] ?? ''}: the ${WEEKDAY_WORDS[named] ?? ''}s around it are ` +\n `${said(plus(after, -7))} and ${said(after)}. Look the date up in COMING DAYS.`,\n ];\n });\n return [...none, ...wrong];\n};\n","import { z } from 'zod';\nimport type { ZodType } from 'zod';\nimport { defineAgent, type AgentDefinition, type Message } from '@niscorp/cortex';\nimport { draftSchemaOf, isRecurring, type DraftChoice, type ReflexDraft } from '../schemas';\nimport { clockDateProblems, dateProblems, whenItIs } from './dates';\n\nexport type OfferedEffect = { name: string; description: string; input: ZodType };\n\nexport const ReflexAgentInputSchema = z.object({\n intent: z.string().describe(\"The person's words — a request, or, later in the conversation, their reply to your question.\"),\n now: z\n .string()\n .describe('The current local date and time, \"YYYY-MM-DDTHH:MM\", in `tz` — what a date or a time of day in the request is read against.'),\n tz: z.string().describe('The IANA timezone the person is in. Every clock the reflex names uses it.'),\n});\n\nexport type ReflexAgentInput = z.infer<typeof ReflexAgentInputSchema>;\n\nexport const ReflexQuestionSchema = z\n .object({ question: z.string().min(1).describe(\"One short question in the person's language, naming what it chooses between.\") })\n .strict()\n .describe('Ask instead of writing a draft when the request can be read as different automations and nothing in its words or the conversation so far decides which.');\n\nexport const ReflexRefusalSchema = z\n .object({ refused: z.string().min(1).describe('Why none of the offered effects does it, in words for the person who asked.') })\n .strict()\n .describe('Refuse instead of writing a draft when none of the offered effects does what was asked. Only for that: a request that is unclear is a question, not a refusal.');\n\nexport type ReflexQuestion = z.infer<typeof ReflexQuestionSchema>;\nexport type ReflexRefusal = z.infer<typeof ReflexRefusalSchema>;\nexport type ReflexAnswer = ReflexDraft | ReflexQuestion | ReflexRefusal;\n\nexport const answerSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexAnswer> =>\n z.union([\n draftSchemaOf(choice).describe('Write the draft when the request — with the conversation so far — says what should happen and what sets it off.'),\n ReflexQuestionSchema,\n ReflexRefusalSchema,\n ]);\n\nexport const ReflexAnswerSchema = answerSchemaOf();\n\nexport const isDraft = (answer: ReflexAnswer): answer is ReflexDraft => 'effect' in answer;\n\nexport const reflexConversation = (conversation: {\n now: string;\n tz: string;\n earlier: readonly { request: string; answer: ReflexAnswer; reasoning?: string | undefined }[];\n latest: string;\n}): Message[] => [\n ...conversation.earlier.flatMap((turn): Message[] => [\n { role: 'user', content: JSON.stringify({ intent: turn.request, now: conversation.now, tz: conversation.tz }) },\n { role: 'assistant', content: JSON.stringify({ ...(turn.reasoning === undefined ? {} : { reasoning: turn.reasoning }), data: turn.answer }) },\n ]),\n { role: 'user', content: JSON.stringify({ intent: conversation.latest, now: conversation.now, tz: conversation.tz }) },\n];\n\nconst INSTRUCTIONS = `You are Tide's reflex agent. Somebody describes an automation; you answer with ONE of three things, as the OUTPUT SCHEMA describes: a reflex draft that does it (a trigger, exactly one of the offered effects, and its input), a question back, or a refusal.\n\nYour envelope's \\`data\\` is that answer. In \\`reasoning\\`, first restate the whole request as the conversation now has it; then decide. The answer must validate against the OUTPUT SCHEMA (its descriptions say what each part is); a draft must name one of the OFFERED EFFECTS and give it an input its schema accepts.\n\nTimes: a date is looked up in TODAY, COMING DAYS and CALENDAR, never counted. A weekday on its own is the coming one: the first of that weekday in COMING DAYS after today. In \\`reasoning\\`, write every date you draft or ask about as COMING DAYS writes it: the weekday's three letters, then the date. A date or a time that could still mean more than one moment is a question, never a guess — a day without its year, a time of day without morning or evening, today's own weekday (today, or a week from today), \"next\" before a weekday that could be this week's or next week's; a question about dates names them, as looked up. An automation happens once unless the person says it repeats. Never write a time that has already passed.\n\nA reply answers your last question: together with the request before it, it is one request — keep what the request said, and add what the reply decides.\n\nWhen you ask, ask about everything still undecided in one question, so one reply can settle it.\n\nEffects: when the request names something to be done that no offered effect does — a channel, a device, an action — refuse it; never put a different effect in its place.`;\n\n// What it is handed is a request, or a conversation whose last turn is the latest: either way `now` is in it.\nconst nowOf = (input: unknown): string | undefined => {\n const last = Array.isArray(input) ? input.at(-1) : undefined;\n const turn: unknown = typeof last === 'object' && last !== null && 'content' in last ? parsedJson(String(last.content)) : input;\n const parsed = ReflexAgentInputSchema.safeParse(turn);\n return parsed.success ? parsed.data.now : undefined;\n};\nconst parsedJson = (text: string): unknown => {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n};\n\n// Converted by the schema's own zod: a caller's schema may come from another copy.\nconst describeEffects = (effects: readonly OfferedEffect[]): string =>\n `OFFERED EFFECTS — a draft names exactly one, by \\`name\\`; choose by its \\`description\\`:\\n${JSON.stringify(\n effects.map((effect) => ({ name: effect.name, description: effect.description, input: effect.input['~standard'].jsonSchema.output({ target: 'draft-07' }) })),\n )}`;\n\nexport const effectProblem = (effects: readonly OfferedEffect[], reflex: Pick<ReflexDraft, 'effect'>): string | undefined => {\n const effect = effects.find((candidate) => candidate.name === reflex.effect.name);\n if (effect === undefined) return `The effect \"${reflex.effect.name}\" is not offered. Name one of: ${effects.map((candidate) => candidate.name).join(', ')}.`;\n const parsed = effect.input.safeParse(reflex.effect.input);\n if (parsed.success) return undefined;\n const issues = parsed.error.issues.map((issue) => `${issue.path.join('.') || 'input'}: ${issue.message}`).join('; ');\n return `The input for \"${effect.name}\" does not fit its schema — ${issues}.`;\n};\n\nconst oneShotAt = (answer: ReflexAnswer): string | undefined =>\n isDraft(answer) && 'clock' in answer.on && !isRecurring(answer.on.clock) ? answer.on.clock.at : undefined;\n\nexport const createReflexAgent = (config: { effects: readonly OfferedEffect[] } & DraftChoice): AgentDefinition<ReflexAnswer> =>\n defineAgent<ReflexAnswer>({\n id: 'tide.reflex',\n description: 'Answers what somebody wants automated with one tide reflex draft, a question back, or a refusal.',\n instructions: INSTRUCTIONS,\n context: [() => describeEffects(config.effects), ({ input }) => whenItIs(nowOf(input) ?? '')],\n output: {\n schema: answerSchemaOf(config),\n validate: (envelope) => {\n const effect = isDraft(envelope.data) ? effectProblem(config.effects, envelope.data) : undefined;\n const problems = [...(effect === undefined ? [] : [effect]), ...clockDateProblems(oneShotAt(envelope.data)), ...dateProblems(envelope.reasoning)];\n return problems.length === 0 ? { ok: true } : { retry: problems.join('\\n') };\n },\n },\n });\n"]}
package/dist/agent.js CHANGED
@@ -1,4 +1,4 @@
1
- import { draftSchemaOf } from './chunk-2HCRTQTB.js';
1
+ import { draftSchemaOf, isRecurring } from './chunk-SLLCUI65.js';
2
2
  import { z } from 'zod';
3
3
  import { defineAgent } from '@niscorp/cortex';
4
4
 
@@ -40,6 +40,7 @@ var whenItIs = (now) => {
40
40
  `CALENDAR \u2014 ${monthLine(today.y, today.m)}; ${monthLine(next.y, next.m)}`
41
41
  ].join("\n");
42
42
  };
43
+ var clockDateProblems = (at) => at === void 0 || dayOf(at) !== void 0 ? [] : [`The clock's date ${at.slice(0, 10)} is not a date. Look the date up in COMING DAYS or CALENDAR.`];
43
44
  var PAIRED = /\b(mon|tue|wed|thu|fri|sat|sun)(?:day|sday|s|nesday|rsday|rs|urday)?\.?,?\s+(\d{4}-\d{2}-\d{2})(?!\d)/gi;
44
45
  var dateProblems = (reasoning) => {
45
46
  const found = [...(reasoning ?? "").matchAll(PAIRED)].map((match) => ({
@@ -118,6 +119,7 @@ var effectProblem = (effects, reflex) => {
118
119
  const issues = parsed.error.issues.map((issue) => `${issue.path.join(".") || "input"}: ${issue.message}`).join("; ");
119
120
  return `The input for "${effect.name}" does not fit its schema \u2014 ${issues}.`;
120
121
  };
122
+ var oneShotAt = (answer) => isDraft(answer) && "clock" in answer.on && !isRecurring(answer.on.clock) ? answer.on.clock.at : void 0;
121
123
  var createReflexAgent = (config) => defineAgent({
122
124
  id: "tide.reflex",
123
125
  description: "Answers what somebody wants automated with one tide reflex draft, a question back, or a refusal.",
@@ -127,7 +129,7 @@ var createReflexAgent = (config) => defineAgent({
127
129
  schema: answerSchemaOf(config),
128
130
  validate: (envelope) => {
129
131
  const effect = isDraft(envelope.data) ? effectProblem(config.effects, envelope.data) : void 0;
130
- const problems = [...effect === void 0 ? [] : [effect], ...dateProblems(envelope.reasoning)];
132
+ const problems = [...effect === void 0 ? [] : [effect], ...clockDateProblems(oneShotAt(envelope.data)), ...dateProblems(envelope.reasoning)];
131
133
  return problems.length === 0 ? { ok: true } : { retry: problems.join("\n") };
132
134
  }
133
135
  }
package/dist/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/agent/dates.ts","../src/agent/reflex-agent.ts"],"names":["days"],"mappings":";;;;;AAAA,IAAM,QAAA,GAAW,CAAC,KAAA,EAAO,KAAA,EAAO,OAAO,KAAA,EAAO,KAAA,EAAO,OAAO,KAAK,CAAA;AACjE,IAAM,aAAA,GAAgB,CAAC,QAAA,EAAU,SAAA,EAAW,aAAa,UAAA,EAAY,QAAA,EAAU,YAAY,QAAQ,CAAA;AACnG,IAAM,MAAA,GAAS,CAAC,SAAA,EAAW,UAAA,EAAY,OAAA,EAAS,OAAA,EAAS,KAAA,EAAO,MAAA,EAAQ,MAAA,EAAQ,QAAA,EAAU,WAAA,EAAa,SAAA,EAAW,YAAY,UAAU,CAAA;AAIxI,IAAM,GAAA,GAAM,CAAC,CAAA,KAAsB,MAAA,CAAO,CAAC,CAAA,CAAE,QAAA,CAAS,GAAG,GAAG,CAAA;AAE5D,IAAM,KAAA,GAAQ,CAAC,IAAA,KAAkC;AAC/C,EAAA,MAAM,KAAA,GAAQ,0BAAA,CAA2B,IAAA,CAAK,IAAI,CAAA;AAClD,EAAA,IAAI,KAAA,KAAU,MAAM,OAAO,MAAA;AAC3B,EAAA,MAAM,MAAM,EAAE,CAAA,EAAG,OAAO,KAAA,CAAM,CAAC,CAAC,CAAA,EAAG,CAAA,EAAG,OAAO,KAAA,CAAM,CAAC,CAAC,CAAA,EAAG,CAAA,EAAG,OAAO,KAAA,CAAM,CAAC,CAAC,CAAA,EAAE;AAC5E,EAAA,MAAM,EAAA,GAAK,IAAI,IAAA,CAAK,IAAA,CAAK,GAAA,CAAI,GAAA,CAAI,CAAA,EAAG,GAAA,CAAI,CAAA,GAAI,CAAA,EAAG,GAAA,CAAI,CAAC,CAAC,CAAA;AACrD,EAAA,OAAO,GAAG,cAAA,EAAe,KAAM,GAAA,CAA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AO,CAAA,eAAA,EAAkB,MAAA,CAAO,IAAI,CAAA,iCAAA,EAA+B,MAAM,CAAA,CAAA,CAAA;AAC3E;AAEO,IAAM,iBAAA,GAAoB,CAAC,MAAA,KAChC,WAAA,CAA0B;AAAA,EACxB,EAAA,EAAI,aAAA;AAAA,EACJ,WAAA,EAAa,kGAAA;AAAA,EACb,YAAA,EAAc,YAAA;AAAA,EACd,SAAS,CAAC,MAAM,eAAA,CAAgB,MAAA,CAAO,OAAO,CAAA,EAAG,CAAC,EAAE,KAAA,OAAY,QAAA,CAAS,KAAA,CAAM,KAAK,CAAA,IAAK,EAAE,CAAC,CAAA;AAAA,EAC5F,MAAA,EAAQ;AAAA,IACN,MAAA,EAAQ,eAAe,MAAM,CAAA;AAAA,IAC7B,QAAA,EAAU,CAAC,QAAA,KAAa;AACtB,MAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,QAAA,CAAS,IAAI,CAAA,GAAI,cAAc,MAAA,CAAO,OAAA,EAAS,QAAA,CAAS,IAAI,CAAA,GAAI,MAAA;AACvF,MAAA,MAAM,QAAA,GAAW,CAAC,GAAI,MAAA,KAAW,SAAY,EAAC,GAAI,CAAC,MAAM,CAAA,EAAI,GAAG,YAAA,CAAa,QAAA,CAAS,SAAS,CAAC,CAAA;AAChG,MAAA,OAAO,QAAA,CAAS,MAAA,KAAW,CAAA,GAAI,EAAE,EAAA,EAAI,IAAA,EAAK,GAAI,EAAE,KAAA,EAAO,QAAA,CAAS,IAAA,CAAK,IAAI,CAAA,EAAE;AAAA,IAC7E;AAAA;AAEJ,CAAC","file":"agent.js","sourcesContent":["const WEEKDAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] as const;\nconst WEEKDAY_WORDS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] as const;\nconst MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] as const;\n\ntype Day = { y: number; m: number; d: number };\n\nconst pad = (n: number): string => String(n).padStart(2, '0');\n// The date a text begins with, or undefined for one that does not exist (\"2026-02-30\").\nconst dayOf = (text: string): Day | undefined => {\n const found = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(text);\n if (found === null) return undefined;\n const day = { y: Number(found[1]), m: Number(found[2]), d: Number(found[3]) };\n const at = new Date(Date.UTC(day.y, day.m - 1, day.d));\n return at.getUTCFullYear() === day.y && at.getUTCMonth() === day.m - 1 && at.getUTCDate() === day.d ? day : undefined;\n};\n// Monday is 0: a week starts on Monday.\nconst weekdayOf = (day: Day): number => (new Date(Date.UTC(day.y, day.m - 1, day.d)).getUTCDay() + 6) % 7;\nconst plus = (day: Day, days: number): Day => {\n const at = new Date(Date.UTC(day.y, day.m - 1, day.d + days));\n return { y: at.getUTCFullYear(), m: at.getUTCMonth() + 1, d: at.getUTCDate() };\n};\nconst isoOf = (day: Day): string => `${String(day.y)}-${pad(day.m)}-${pad(day.d)}`;\nconst said = (day: Day): string => `${WEEKDAYS[weekdayOf(day)] ?? ''} ${isoOf(day)}`;\nconst days = (from: Day, first: number, last: number): string =>\n Array.from({ length: Math.max(0, last - first + 1) }, (_, at) => said(plus(from, first + at))).join(', ') || 'none';\n\n// One month on one line, each weekday once with its days.\nconst monthLine = (y: number, m: number): string => {\n const length = new Date(Date.UTC(y, m, 0)).getUTCDate();\n const byWeekday = WEEKDAYS.map((): number[] => []);\n for (let d = 1; d <= length; d++) byWeekday[weekdayOf({ y, m, d })]?.push(d);\n return `${MONTHS[m - 1] ?? ''} ${String(y)}: ${WEEKDAYS.map((weekday, at) => `${weekday} ${(byWeekday[at] ?? []).join(' ')}`).join(' | ')}`;\n};\n\n// What the agent reads a date off, written from the `now` it is handed: today with its weekday, the rest of this week\n// and the two after it, and this month and the next. A `now` that is no date and time says so instead.\nexport const whenItIs = (now: string): string => {\n const today = dayOf(now);\n const time = /^\\d{4}-\\d{2}-\\d{2}T([01]\\d|2[0-3]):[0-5]\\d/.test(now) ? now.slice(11, 16) : undefined;\n if (today === undefined || time === undefined) return 'TODAY — not known: ask for the date of anything not given as one.';\n const toSunday = 6 - weekdayOf(today);\n const next = today.m === 12 ? { y: today.y + 1, m: 1 } : { y: today.y, m: today.m + 1 };\n return [\n `TODAY — ${said(today)}, ${time}.`,\n `COMING DAYS — today: ${said(today)} | the rest of this week: ${days(today, 1, toSunday)} | next week: ${days(today, toSunday + 1, toSunday + 7)} | ` +\n `the week after: ${days(today, toSunday + 8, toSunday + 14)}`,\n `CALENDAR — ${monthLine(today.y, today.m)}; ${monthLine(next.y, next.m)}`,\n ].join('\\n');\n};\n\n// A weekday, as a word or abbreviated, then a date: \"Fri 2026-11-06\", \"Friday, 2026-11-06T14:30\", \"thurs 2026-11-05\".\nconst PAIRED = /\\b(mon|tue|wed|thu|fri|sat|sun)(?:day|sday|s|nesday|rsday|rs|urday)?\\.?,?\\s+(\\d{4}-\\d{2}-\\d{2})(?!\\d)/gi;\n\n// What is sent back: a date the reasoning writes beside the wrong weekday, or a date that does not exist. How the\n// reasoning words a date is its own: a draft is never sent back for that.\nexport const dateProblems = (reasoning: string | undefined): string[] => {\n const found = [...(reasoning ?? '').matchAll(PAIRED)].map((match) => ({\n text: match[2] ?? '',\n day: dayOf(match[2] ?? ''),\n named: WEEKDAYS.findIndex((weekday) => weekday.toLowerCase() === (match[1] ?? '').toLowerCase()),\n }));\n const none = found.flatMap(({ text, day }) => (day === undefined ? [`${text} is not a date. Look the date up in COMING DAYS or CALENDAR.`] : []));\n const pairs = found.flatMap(({ day, named }) => (day === undefined || named < 0 ? [] : [{ day, named }]));\n const wrong = pairs.flatMap(({ day, named }) => {\n const real = weekdayOf(day);\n if (real === named) return [];\n const after = plus(day, (named - real + 7) % 7);\n return [\n `${isoOf(day)} is a ${WEEKDAY_WORDS[real] ?? ''}, not a ${WEEKDAY_WORDS[named] ?? ''}: the ${WEEKDAY_WORDS[named] ?? ''}s around it are ` +\n `${said(plus(after, -7))} and ${said(after)}. Look the date up in COMING DAYS.`,\n ];\n });\n return [...none, ...wrong];\n};\n","import { z } from 'zod';\nimport type { ZodType } from 'zod';\nimport { defineAgent, type AgentDefinition, type Message } from '@niscorp/cortex';\nimport { draftSchemaOf, type DraftChoice, type ReflexDraft } from '../schemas';\nimport { dateProblems, whenItIs } from './dates';\n\nexport type OfferedEffect = { name: string; description: string; input: ZodType };\n\nexport const ReflexAgentInputSchema = z.object({\n intent: z.string().describe(\"The person's words — a request, or, later in the conversation, their reply to your question.\"),\n now: z\n .string()\n .describe('The current local date and time, \"YYYY-MM-DDTHH:MM\", in `tz` — what a date or a time of day in the request is read against.'),\n tz: z.string().describe('The IANA timezone the person is in. Every clock the reflex names uses it.'),\n});\n\nexport type ReflexAgentInput = z.infer<typeof ReflexAgentInputSchema>;\n\nexport const ReflexQuestionSchema = z\n .object({ question: z.string().min(1).describe(\"One short question in the person's language, naming what it chooses between.\") })\n .strict()\n .describe('Ask instead of writing a draft when the request can be read as different automations and nothing in its words or the conversation so far decides which.');\n\nexport const ReflexRefusalSchema = z\n .object({ refused: z.string().min(1).describe('Why none of the offered effects does it, in words for the person who asked.') })\n .strict()\n .describe('Refuse instead of writing a draft when none of the offered effects does what was asked. Only for that: a request that is unclear is a question, not a refusal.');\n\nexport type ReflexQuestion = z.infer<typeof ReflexQuestionSchema>;\nexport type ReflexRefusal = z.infer<typeof ReflexRefusalSchema>;\nexport type ReflexAnswer = ReflexDraft | ReflexQuestion | ReflexRefusal;\n\nexport const answerSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexAnswer> =>\n z.union([\n draftSchemaOf(choice).describe('Write the draft when the request — with the conversation so far — says what should happen and what sets it off.'),\n ReflexQuestionSchema,\n ReflexRefusalSchema,\n ]);\n\nexport const ReflexAnswerSchema = answerSchemaOf();\n\nexport const isDraft = (answer: ReflexAnswer): answer is ReflexDraft => 'effect' in answer;\n\nexport const reflexConversation = (conversation: {\n now: string;\n tz: string;\n earlier: readonly { request: string; answer: ReflexAnswer; reasoning?: string | undefined }[];\n latest: string;\n}): Message[] => [\n ...conversation.earlier.flatMap((turn): Message[] => [\n { role: 'user', content: JSON.stringify({ intent: turn.request, now: conversation.now, tz: conversation.tz }) },\n { role: 'assistant', content: JSON.stringify({ ...(turn.reasoning === undefined ? {} : { reasoning: turn.reasoning }), data: turn.answer }) },\n ]),\n { role: 'user', content: JSON.stringify({ intent: conversation.latest, now: conversation.now, tz: conversation.tz }) },\n];\n\nconst INSTRUCTIONS = `You are Tide's reflex agent. Somebody describes an automation; you answer with ONE of three things, as the OUTPUT SCHEMA describes: a reflex draft that does it (a trigger, exactly one of the offered effects, and its input), a question back, or a refusal.\n\nYour envelope's \\`data\\` is that answer. In \\`reasoning\\`, first restate the whole request as the conversation now has it; then decide. The answer must validate against the OUTPUT SCHEMA (its descriptions say what each part is); a draft must name one of the OFFERED EFFECTS and give it an input its schema accepts.\n\nTimes: a date is looked up in TODAY, COMING DAYS and CALENDAR, never counted. A weekday on its own is the coming one: the first of that weekday in COMING DAYS after today. In \\`reasoning\\`, write every date you draft or ask about as COMING DAYS writes it: the weekday's three letters, then the date. A date or a time that could still mean more than one moment is a question, never a guess — a day without its year, a time of day without morning or evening, today's own weekday (today, or a week from today), \"next\" before a weekday that could be this week's or next week's; a question about dates names them, as looked up. An automation happens once unless the person says it repeats. Never write a time that has already passed.\n\nA reply answers your last question: together with the request before it, it is one request — keep what the request said, and add what the reply decides.\n\nWhen you ask, ask about everything still undecided in one question, so one reply can settle it.\n\nEffects: when the request names something to be done that no offered effect does — a channel, a device, an action — refuse it; never put a different effect in its place.`;\n\n// What it is handed is a request, or a conversation whose last turn is the latest: either way `now` is in it.\nconst nowOf = (input: unknown): string | undefined => {\n const last = Array.isArray(input) ? input.at(-1) : undefined;\n const turn: unknown = typeof last === 'object' && last !== null && 'content' in last ? parsedJson(String(last.content)) : input;\n const parsed = ReflexAgentInputSchema.safeParse(turn);\n return parsed.success ? parsed.data.now : undefined;\n};\nconst parsedJson = (text: string): unknown => {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n};\n\n// Converted by the schema's own zod: a caller's schema may come from another copy.\nconst describeEffects = (effects: readonly OfferedEffect[]): string =>\n `OFFERED EFFECTS — a draft names exactly one, by \\`name\\`; choose by its \\`description\\`:\\n${JSON.stringify(\n effects.map((effect) => ({ name: effect.name, description: effect.description, input: effect.input['~standard'].jsonSchema.output({ target: 'draft-07' }) })),\n )}`;\n\nexport const effectProblem = (effects: readonly OfferedEffect[], reflex: Pick<ReflexDraft, 'effect'>): string | undefined => {\n const effect = effects.find((candidate) => candidate.name === reflex.effect.name);\n if (effect === undefined) return `The effect \"${reflex.effect.name}\" is not offered. Name one of: ${effects.map((candidate) => candidate.name).join(', ')}.`;\n const parsed = effect.input.safeParse(reflex.effect.input);\n if (parsed.success) return undefined;\n const issues = parsed.error.issues.map((issue) => `${issue.path.join('.') || 'input'}: ${issue.message}`).join('; ');\n return `The input for \"${effect.name}\" does not fit its schema — ${issues}.`;\n};\n\nexport const createReflexAgent = (config: { effects: readonly OfferedEffect[] } & DraftChoice): AgentDefinition<ReflexAnswer> =>\n defineAgent<ReflexAnswer>({\n id: 'tide.reflex',\n description: 'Answers what somebody wants automated with one tide reflex draft, a question back, or a refusal.',\n instructions: INSTRUCTIONS,\n context: [() => describeEffects(config.effects), ({ input }) => whenItIs(nowOf(input) ?? '')],\n output: {\n schema: answerSchemaOf(config),\n validate: (envelope) => {\n const effect = isDraft(envelope.data) ? effectProblem(config.effects, envelope.data) : undefined;\n const problems = [...(effect === undefined ? [] : [effect]), ...dateProblems(envelope.reasoning)];\n return problems.length === 0 ? { ok: true } : { retry: problems.join('\\n') };\n },\n },\n });\n"]}
1
+ {"version":3,"sources":["../src/agent/dates.ts","../src/agent/reflex-agent.ts"],"names":["days"],"mappings":";;;;;AAAA,IAAM,QAAA,GAAW,CAAC,KAAA,EAAO,KAAA,EAAO,OAAO,KAAA,EAAO,KAAA,EAAO,OAAO,KAAK,CAAA;AACjE,IAAM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st WEEKDAY_WORDS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] as const;\nconst MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] as const;\n\ntype Day = { y: number; m: number; d: number };\n\nconst pad = (n: number): string => String(n).padStart(2, '0');\n// The date a text begins with, or undefined for one that does not exist (\"2026-02-30\").\nconst dayOf = (text: string): Day | undefined => {\n const found = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(text);\n if (found === null) return undefined;\n const day = { y: Number(found[1]), m: Number(found[2]), d: Number(found[3]) };\n const at = new Date(Date.UTC(day.y, day.m - 1, day.d));\n return at.getUTCFullYear() === day.y && at.getUTCMonth() === day.m - 1 && at.getUTCDate() === day.d ? day : undefined;\n};\n// Monday is 0: a week starts on Monday.\nconst weekdayOf = (day: Day): number => (new Date(Date.UTC(day.y, day.m - 1, day.d)).getUTCDay() + 6) % 7;\nconst plus = (day: Day, days: number): Day => {\n const at = new Date(Date.UTC(day.y, day.m - 1, day.d + days));\n return { y: at.getUTCFullYear(), m: at.getUTCMonth() + 1, d: at.getUTCDate() };\n};\nconst isoOf = (day: Day): string => `${String(day.y)}-${pad(day.m)}-${pad(day.d)}`;\nconst said = (day: Day): string => `${WEEKDAYS[weekdayOf(day)] ?? ''} ${isoOf(day)}`;\nconst days = (from: Day, first: number, last: number): string =>\n Array.from({ length: Math.max(0, last - first + 1) }, (_, at) => said(plus(from, first + at))).join(', ') || 'none';\n\n// One month on one line, each weekday once with its days.\nconst monthLine = (y: number, m: number): string => {\n const length = new Date(Date.UTC(y, m, 0)).getUTCDate();\n const byWeekday = WEEKDAYS.map((): number[] => []);\n for (let d = 1; d <= length; d++) byWeekday[weekdayOf({ y, m, d })]?.push(d);\n return `${MONTHS[m - 1] ?? ''} ${String(y)}: ${WEEKDAYS.map((weekday, at) => `${weekday} ${(byWeekday[at] ?? []).join(' ')}`).join(' | ')}`;\n};\n\n// What the agent reads a date off, written from the `now` it is handed: today with its weekday, the rest of this week\n// and the two after it, and this month and the next. A `now` that is no date and time says so instead.\nexport const whenItIs = (now: string): string => {\n const today = dayOf(now);\n const time = /^\\d{4}-\\d{2}-\\d{2}T([01]\\d|2[0-3]):[0-5]\\d/.test(now) ? now.slice(11, 16) : undefined;\n if (today === undefined || time === undefined) return 'TODAY — not known: ask for the date of anything not given as one.';\n const toSunday = 6 - weekdayOf(today);\n const next = today.m === 12 ? { y: today.y + 1, m: 1 } : { y: today.y, m: today.m + 1 };\n return [\n `TODAY — ${said(today)}, ${time}.`,\n `COMING DAYS — today: ${said(today)} | the rest of this week: ${days(today, 1, toSunday)} | next week: ${days(today, toSunday + 1, toSunday + 7)} | ` +\n `the week after: ${days(today, toSunday + 8, toSunday + 14)}`,\n `CALENDAR — ${monthLine(today.y, today.m)}; ${monthLine(next.y, next.m)}`,\n ].join('\\n');\n};\n\n// A one-shot clock on a date that does not exist loads and fires on the day it runs on to, which no person meant.\nexport const clockDateProblems = (at: string | undefined): string[] =>\n at === undefined || dayOf(at) !== undefined ? [] : [`The clock's date ${at.slice(0, 10)} is not a date. Look the date up in COMING DAYS or CALENDAR.`];\n\n// A weekday, as a word or abbreviated, then a date: \"Fri 2026-11-06\", \"Friday, 2026-11-06T14:30\", \"thurs 2026-11-05\".\nconst PAIRED = /\\b(mon|tue|wed|thu|fri|sat|sun)(?:day|sday|s|nesday|rsday|rs|urday)?\\.?,?\\s+(\\d{4}-\\d{2}-\\d{2})(?!\\d)/gi;\n\n// What is sent back: a date the reasoning writes beside the wrong weekday, or a date that does not exist. How the\n// reasoning words a date is its own: a draft is never sent back for that.\nexport const dateProblems = (reasoning: string | undefined): string[] => {\n const found = [...(reasoning ?? '').matchAll(PAIRED)].map((match) => ({\n text: match[2] ?? '',\n day: dayOf(match[2] ?? ''),\n named: WEEKDAYS.findIndex((weekday) => weekday.toLowerCase() === (match[1] ?? '').toLowerCase()),\n }));\n const none = found.flatMap(({ text, day }) => (day === undefined ? [`${text} is not a date. Look the date up in COMING DAYS or CALENDAR.`] : []));\n const pairs = found.flatMap(({ day, named }) => (day === undefined || named < 0 ? [] : [{ day, named }]));\n const wrong = pairs.flatMap(({ day, named }) => {\n const real = weekdayOf(day);\n if (real === named) return [];\n const after = plus(day, (named - real + 7) % 7);\n return [\n `${isoOf(day)} is a ${WEEKDAY_WORDS[real] ?? ''}, not a ${WEEKDAY_WORDS[named] ?? ''}: the ${WEEKDAY_WORDS[named] ?? ''}s around it are ` +\n `${said(plus(after, -7))} and ${said(after)}. Look the date up in COMING DAYS.`,\n ];\n });\n return [...none, ...wrong];\n};\n","import { z } from 'zod';\nimport type { ZodType } from 'zod';\nimport { defineAgent, type AgentDefinition, type Message } from '@niscorp/cortex';\nimport { draftSchemaOf, isRecurring, type DraftChoice, type ReflexDraft } from '../schemas';\nimport { clockDateProblems, dateProblems, whenItIs } from './dates';\n\nexport type OfferedEffect = { name: string; description: string; input: ZodType };\n\nexport const ReflexAgentInputSchema = z.object({\n intent: z.string().describe(\"The person's words — a request, or, later in the conversation, their reply to your question.\"),\n now: z\n .string()\n .describe('The current local date and time, \"YYYY-MM-DDTHH:MM\", in `tz` — what a date or a time of day in the request is read against.'),\n tz: z.string().describe('The IANA timezone the person is in. Every clock the reflex names uses it.'),\n});\n\nexport type ReflexAgentInput = z.infer<typeof ReflexAgentInputSchema>;\n\nexport const ReflexQuestionSchema = z\n .object({ question: z.string().min(1).describe(\"One short question in the person's language, naming what it chooses between.\") })\n .strict()\n .describe('Ask instead of writing a draft when the request can be read as different automations and nothing in its words or the conversation so far decides which.');\n\nexport const ReflexRefusalSchema = z\n .object({ refused: z.string().min(1).describe('Why none of the offered effects does it, in words for the person who asked.') })\n .strict()\n .describe('Refuse instead of writing a draft when none of the offered effects does what was asked. Only for that: a request that is unclear is a question, not a refusal.');\n\nexport type ReflexQuestion = z.infer<typeof ReflexQuestionSchema>;\nexport type ReflexRefusal = z.infer<typeof ReflexRefusalSchema>;\nexport type ReflexAnswer = ReflexDraft | ReflexQuestion | ReflexRefusal;\n\nexport const answerSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexAnswer> =>\n z.union([\n draftSchemaOf(choice).describe('Write the draft when the request — with the conversation so far — says what should happen and what sets it off.'),\n ReflexQuestionSchema,\n ReflexRefusalSchema,\n ]);\n\nexport const ReflexAnswerSchema = answerSchemaOf();\n\nexport const isDraft = (answer: ReflexAnswer): answer is ReflexDraft => 'effect' in answer;\n\nexport const reflexConversation = (conversation: {\n now: string;\n tz: string;\n earlier: readonly { request: string; answer: ReflexAnswer; reasoning?: string | undefined }[];\n latest: string;\n}): Message[] => [\n ...conversation.earlier.flatMap((turn): Message[] => [\n { role: 'user', content: JSON.stringify({ intent: turn.request, now: conversation.now, tz: conversation.tz }) },\n { role: 'assistant', content: JSON.stringify({ ...(turn.reasoning === undefined ? {} : { reasoning: turn.reasoning }), data: turn.answer }) },\n ]),\n { role: 'user', content: JSON.stringify({ intent: conversation.latest, now: conversation.now, tz: conversation.tz }) },\n];\n\nconst INSTRUCTIONS = `You are Tide's reflex agent. Somebody describes an automation; you answer with ONE of three things, as the OUTPUT SCHEMA describes: a reflex draft that does it (a trigger, exactly one of the offered effects, and its input), a question back, or a refusal.\n\nYour envelope's \\`data\\` is that answer. In \\`reasoning\\`, first restate the whole request as the conversation now has it; then decide. The answer must validate against the OUTPUT SCHEMA (its descriptions say what each part is); a draft must name one of the OFFERED EFFECTS and give it an input its schema accepts.\n\nTimes: a date is looked up in TODAY, COMING DAYS and CALENDAR, never counted. A weekday on its own is the coming one: the first of that weekday in COMING DAYS after today. In \\`reasoning\\`, write every date you draft or ask about as COMING DAYS writes it: the weekday's three letters, then the date. A date or a time that could still mean more than one moment is a question, never a guess — a day without its year, a time of day without morning or evening, today's own weekday (today, or a week from today), \"next\" before a weekday that could be this week's or next week's; a question about dates names them, as looked up. An automation happens once unless the person says it repeats. Never write a time that has already passed.\n\nA reply answers your last question: together with the request before it, it is one request — keep what the request said, and add what the reply decides.\n\nWhen you ask, ask about everything still undecided in one question, so one reply can settle it.\n\nEffects: when the request names something to be done that no offered effect does — a channel, a device, an action — refuse it; never put a different effect in its place.`;\n\n// What it is handed is a request, or a conversation whose last turn is the latest: either way `now` is in it.\nconst nowOf = (input: unknown): string | undefined => {\n const last = Array.isArray(input) ? input.at(-1) : undefined;\n const turn: unknown = typeof last === 'object' && last !== null && 'content' in last ? parsedJson(String(last.content)) : input;\n const parsed = ReflexAgentInputSchema.safeParse(turn);\n return parsed.success ? parsed.data.now : undefined;\n};\nconst parsedJson = (text: string): unknown => {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n};\n\n// Converted by the schema's own zod: a caller's schema may come from another copy.\nconst describeEffects = (effects: readonly OfferedEffect[]): string =>\n `OFFERED EFFECTS — a draft names exactly one, by \\`name\\`; choose by its \\`description\\`:\\n${JSON.stringify(\n effects.map((effect) => ({ name: effect.name, description: effect.description, input: effect.input['~standard'].jsonSchema.output({ target: 'draft-07' }) })),\n )}`;\n\nexport const effectProblem = (effects: readonly OfferedEffect[], reflex: Pick<ReflexDraft, 'effect'>): string | undefined => {\n const effect = effects.find((candidate) => candidate.name === reflex.effect.name);\n if (effect === undefined) return `The effect \"${reflex.effect.name}\" is not offered. Name one of: ${effects.map((candidate) => candidate.name).join(', ')}.`;\n const parsed = effect.input.safeParse(reflex.effect.input);\n if (parsed.success) return undefined;\n const issues = parsed.error.issues.map((issue) => `${issue.path.join('.') || 'input'}: ${issue.message}`).join('; ');\n return `The input for \"${effect.name}\" does not fit its schema — ${issues}.`;\n};\n\nconst oneShotAt = (answer: ReflexAnswer): string | undefined =>\n isDraft(answer) && 'clock' in answer.on && !isRecurring(answer.on.clock) ? answer.on.clock.at : undefined;\n\nexport const createReflexAgent = (config: { effects: readonly OfferedEffect[] } & DraftChoice): AgentDefinition<ReflexAnswer> =>\n defineAgent<ReflexAnswer>({\n id: 'tide.reflex',\n description: 'Answers what somebody wants automated with one tide reflex draft, a question back, or a refusal.',\n instructions: INSTRUCTIONS,\n context: [() => describeEffects(config.effects), ({ input }) => whenItIs(nowOf(input) ?? '')],\n output: {\n schema: answerSchemaOf(config),\n validate: (envelope) => {\n const effect = isDraft(envelope.data) ? effectProblem(config.effects, envelope.data) : undefined;\n const problems = [...(effect === undefined ? [] : [effect]), ...clockDateProblems(oneShotAt(envelope.data)), ...dateProblems(envelope.reasoning)];\n return problems.length === 0 ? { ok: true } : { retry: problems.join('\\n') };\n },\n },\n });\n"]}
@@ -5,14 +5,14 @@ var WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
5
5
  var HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
6
6
  var MMDD = /^(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
7
7
  var LOCAL_DATETIME = /^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/;
8
- var knownZone = (tz) => {
8
+ var isKnownZone = (tz) => {
9
9
  try {
10
10
  return new Intl.DateTimeFormat("en-US", { timeZone: tz }).resolvedOptions().timeZone !== "";
11
11
  } catch {
12
12
  return false;
13
13
  }
14
14
  };
15
- var TimeZoneSchema = z.string().refine(knownZone, { message: "not a time zone Intl knows" }).describe("IANA timezone name.");
15
+ var TimeZoneSchema = z.string().refine(isKnownZone, { message: "not a time zone Intl knows" }).describe("IANA timezone name.");
16
16
  var ClockUnitSchema = z.enum(["day", "week", "month", "year"]);
17
17
  var ClockRecurringSchema = z.object({
18
18
  every: ClockUnitSchema.describe("The calendar period it repeats on. A repeating clock fires on every such period until the reflex is removed \u2014 only for a request that says it repeats."),
@@ -213,5 +213,5 @@ var draftSchemaOf = (choice = {}) => {
213
213
  var ReflexDraftSchema = draftSchemaOf();
214
214
 
215
215
  export { ClockOnceSchema, ClockRecurringSchema, ClockTriggerSchema, ClockUnitSchema, DRAFT_TRIGGERS, EffectRefSchema, FactInputSchema, FactKindSchema, ManualTriggerSchema, OpSchema, PolicySchema, REFLEX_TRIGGERS, ReflexDraftSchema, ReflexSchema, RetrySchema, RunTriggerSchema, SelectionSchema, SignalTriggerSchema, TimeZoneSchema, TimerSchema, TimerTriggerSchema, TriggerSchema, WEEKDAYS, WriteTriggerSchema, clockOf, draftSchemaOf, factOf, isManual, isRecurring, reflexSchemaOf };
216
- //# sourceMappingURL=chunk-2HCRTQTB.js.map
217
- //# sourceMappingURL=chunk-2HCRTQTB.js.map
216
+ //# sourceMappingURL=chunk-SLLCUI65.js.map
217
+ //# sourceMappingURL=chunk-SLLCUI65.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schemas/trigger.schema.ts","../src/schemas/policy.schema.ts","../src/schemas/fact.schema.ts","../src/schemas/reflex.schema.ts"],"names":["z","require"],"mappings":";;;AAEO,IAAM,QAAA,GAAW,CAAC,KAAA,EAAO,KAAA,EAAO,OAAO,KAAA,EAAO,KAAA,EAAO,OAAO,KAAK;AAExE,IAAM,IAAA,GAAO,2BAAA;AACb,IAAM,IAAA,GAAO,yCAAA;AACb,IAAM,cAAA,GAAiB,wDAAA;AAEvB,IAAM,WAAA,GAAc,CAAC,EAAA,KAAwB;AAC3C,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,IAAA,CAAK,cAAA,CAAe,OAAA,EAAS,EAAE,QAAA,EAAU,EAAA,EAAI,CAAA,CAAE,eAAA,EAAgB,CAAE,QAAA,KAAa,EAAA;AAAA,EAC3F,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF,CAAA;AAEO,IAAM,cAAA,GAAiB,CAAA,CAAE,MAAA,EAAO,CAAE,MAAA,CAAO,WAAA,EAAa,EAAE,OAAA,EAAS,4BAAA,EAA8B,CAAA,CAAE,QAAA,CAAS,qBAAqB;AAE/H,IAAM,eAAA,GAAkB,EAAE,IAAA,CAAK,CAAC,OAAO,MAAA,EAAQ,OAAA,EAAS,MAAM,CAAC;AAE/D,IAAM,oBAAA,GAAuB,EACjC,MAAA,CAAO;AAAA,EACN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I,CAAA,CAAE,MAAA,EAAO,CAAE,WAAA,CAAY,WAAW,CAAA;AACrF;AAEO,IAAM,oBAAoB,aAAA","file":"chunk-SLLCUI65.js","sourcesContent":["import { z } from 'zod';\n\nexport const WEEKDAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const;\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/;\nconst MMDD = /^(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$/;\nconst LOCAL_DATETIME = /^\\d{4}-\\d{2}-\\d{2}T([01]\\d|2[0-3]):[0-5]\\d(:[0-5]\\d)?$/;\n\nconst isKnownZone = (tz: string): boolean => {\n try {\n return new Intl.DateTimeFormat('en-US', { timeZone: tz }).resolvedOptions().timeZone !== '';\n } catch {\n return false;\n }\n};\n\nexport const TimeZoneSchema = z.string().refine(isKnownZone, { message: 'not a time zone Intl knows' }).describe('IANA timezone name.');\n\nexport const ClockUnitSchema = z.enum(['day', 'week', 'month', 'year']);\n\nexport const ClockRecurringSchema = z\n .object({\n every: ClockUnitSchema.describe('The calendar period it repeats on. A repeating clock fires on every such period until the reflex is removed — only for a request that says it repeats.'),\n on: z\n .union([z.number().int().min(1).max(31), z.enum(WEEKDAYS), z.array(z.enum(WEEKDAYS)).min(1), z.string().regex(MMDD)])\n .optional()\n .describe(\n 'week → a weekday, or a list of them: [\"mon\",\"tue\",\"wed\",\"thu\",\"fri\"] is every weekday; month → 1..31, where 31 is the last day of every month (a shorter month clamps to its end); year → \"MM-DD\". Omitted for day.',\n ),\n at: z.string().regex(HHMM).describe('Local wall-clock time, \"HH:MM\".'),\n tz: TimeZoneSchema,\n })\n .strict()\n .superRefine((clock, ctx) => {\n const fail = (message: string) => ctx.addIssue({ code: 'custom', message, path: ['on'] });\n if (clock.every === 'day' && clock.on !== undefined) fail('a daily clock takes no `on`');\n const weekday = (value: unknown): boolean => typeof value === 'string' && WEEKDAYS.some((d) => d === value);\n const weekdays = Array.isArray(clock.on) && clock.on.length > 0 && new Set(clock.on).size === clock.on.length;\n if (clock.every === 'week' && !weekday(clock.on) && !weekdays) fail('a weekly clock needs `on` as a weekday (mon..sun), or a list of different weekdays');\n if (clock.every !== 'week' && Array.isArray(clock.on)) fail('only a weekly clock takes a list of weekdays');\n if (clock.every === 'month' && typeof clock.on !== 'number') fail('a monthly clock needs `on` as a day number');\n if (clock.every === 'year' && !(typeof clock.on === 'string' && MMDD.test(clock.on)))\n fail('a yearly clock needs `on` as \"MM-DD\"');\n })\n .describe('Repeats: fires on every day, week, month or year, at a time of day, until the reflex is removed.');\n\nexport const ClockOnceSchema = z\n .object({\n at: z.string().regex(LOCAL_DATETIME).describe('A fixed local date and time, once: \"YYYY-MM-DDTHH:MM\" or, to the second, \"YYYY-MM-DDTHH:MM:SS\".'),\n tz: TimeZoneSchema,\n })\n .strict()\n .describe('Once: fires at one date and time, then never again.');\n\nexport const ClockTriggerSchema = z\n .object({ clock: z.union([ClockRecurringSchema, ClockOnceSchema]) })\n .strict()\n .describe('Fires on the calendar: once, at a date and time, or repeating at a time of day.');\n\nexport const OpSchema = z.enum(['insert', 'update', 'delete']);\n\nexport const WriteTriggerSchema = z\n .object({\n fact: z\n .object({\n entity: z.string().describe('The table or entity whose writes wake this reflex.'),\n op: OpSchema.optional().describe('Narrow to one op — \"only on create\" is op: \"insert\".'),\n })\n .strict(),\n })\n .strict()\n .describe('Fires when a row of an entity is written — created, changed or deleted.');\n\nexport const SignalTriggerSchema = z\n .object({ fact: z.object({ signal: z.string().describe('A named external intake.') }).strict() })\n .strict()\n .describe('Fires when an event arrives from outside, on a named intake.');\n\nexport const RunTriggerSchema = z\n .object({\n fact: z\n .object({ run: z.string().describe('A reflex id — fires when THAT reflex\\'s run settles. Fan-in and dependency.') })\n .strict(),\n })\n .strict()\n .describe('Fires when another reflex has run: one automation after another.');\n\nexport const ManualTriggerSchema = z\n .object({ manual: z.object({}).strict() })\n .strict()\n .describe('Fires only when somebody fires it by hand.');\n\nexport const TriggerSchema = z.union([\n ClockTriggerSchema,\n WriteTriggerSchema,\n SignalTriggerSchema,\n RunTriggerSchema,\n ManualTriggerSchema,\n]);\n\nexport type ClockRecurring = z.infer<typeof ClockRecurringSchema>;\nexport type ClockOnce = z.infer<typeof ClockOnceSchema>;\nexport type Clock = ClockRecurring | ClockOnce;\nexport type Trigger = z.infer<typeof TriggerSchema>;\nexport type Op = z.infer<typeof OpSchema>;\nexport type Weekday = (typeof WEEKDAYS)[number];\n\nexport const clockOf = (trigger: Trigger): Clock | undefined => ('clock' in trigger ? trigger.clock : undefined);\n\nexport const isRecurring = (clock: Clock): clock is ClockRecurring => 'every' in clock;\n\nexport const factOf = (\n trigger: Trigger,\n): { entity?: string; op?: Op; signal?: string; run?: string } | undefined =>\n 'fact' in trigger ? trigger.fact : undefined;\n\nexport const isManual = (trigger: Trigger): boolean => 'manual' in trigger;\n","import { z } from 'zod';\n\nexport const RetrySchema = z\n .object({\n max: z.number().int().min(0).default(3).describe('Attempts after the first before the task parks `failed`.'),\n backoff: z.enum(['fixed', 'exponential']).default('exponential'),\n baseMs: z.number().int().positive().default(60_000),\n })\n .strict();\n\nexport const PolicySchema = z\n .object({\n retry: RetrySchema.optional(),\n timeoutMs: z.number().int().positive().default(30_000),\n overlap: z.enum(['skip', 'allow']).default('skip'),\n catchUp: z.enum(['run', 'skip', 'latest']).default('run'),\n // Read by `catchUp: 'skip'` only. What `catchUp` opens still passes\n // `overlap`: occurrences missed together are repeats of one another, so\n // under `overlap: 'skip'` the oldest runs and the rest are skipped.\n lateMs: z.number().int().positive().default(3_600_000),\n order: z.enum(['any', 'serial']).default('any'),\n })\n .strict();\n\nexport type Retry = z.infer<typeof RetrySchema>;\nexport type Policy = z.infer<typeof PolicySchema>;\n\nexport const DEFAULT_POLICY: Policy = PolicySchema.parse({});\n","import { z } from 'zod';\nimport { OpSchema } from './trigger.schema';\n\nexport const FactKindSchema = z.enum(['write', 'signal', 'manual', 'run']);\n\nexport const FactInputSchema = z\n .object({\n kind: FactKindSchema,\n\n entity: z.string().optional().describe('Which table or entity was written.'),\n op: OpSchema.optional().describe('Ops are distinct stimuli — \"only on create\" is op: \"insert\".'),\n row: z.record(z.string(), z.unknown()).optional().describe('The row, as the write returned it.'),\n\n name: z.string().optional().describe('Which named intake this arrived on.'),\n payload: z.unknown().optional().describe('The event body — validated at the HOST boundary before it gets here.'),\n\n reflex: z.string().optional(),\n runId: z.string().optional(),\n occurrence: z.string().optional().describe('The calendar key, when the clock was the cause.'),\n stats: z\n .object({ total: z.number().int(), done: z.number().int(), failed: z.number().int() })\n .strict()\n .optional(),\n\n target: z.string().optional().describe('The one reflex a manual fact is aimed at.'),\n by: z.string().optional().describe('Who fired it — recorded on the firing as manual:<who>.'),\n\n at: z.number().int().describe('Supplied by the caller. Tide reads no clocks.'),\n notBefore: z.number().int().optional().describe('A delayed fact — timers as data, visible and queryable.'),\n dedupeKey: z.string().optional().describe('Provider event ids. A repeat is refused and announced as fact.deduped; it is not an error.'),\n cause: z.string().optional().describe('Set by tide when an effect emits — the causality chain.'),\n })\n .strict()\n .superRefine((fact, ctx) => {\n const require = (field: keyof typeof fact, why: string) => {\n if (fact[field] === undefined)\n ctx.addIssue({ code: 'custom', message: `a ${fact.kind} fact needs \\`${String(field)}\\` — ${why}`, path: [field] });\n };\n const refuse = (field: keyof typeof fact) => {\n if (fact[field] !== undefined)\n ctx.addIssue({ code: 'custom', message: `\\`${String(field)}\\` is not part of a ${fact.kind} fact`, path: [field] });\n };\n\n if (fact.kind === 'write') {\n require('entity', 'it is what a write trigger matches on');\n refuse('name');\n refuse('target');\n refuse('runId');\n }\n if (fact.kind === 'signal') {\n require('name', 'it is which named intake this arrived on');\n refuse('entity');\n refuse('op');\n refuse('target');\n refuse('runId');\n }\n if (fact.kind === 'manual') {\n require('target', 'a manual fact is aimed at exactly one reflex');\n refuse('entity');\n refuse('name');\n refuse('runId');\n }\n if (fact.kind === 'run') {\n require('reflex', 'it is whose run settled');\n require('runId', 'it is which run settled');\n refuse('entity');\n refuse('name');\n refuse('target');\n }\n });\n\nexport type FactInput = z.infer<typeof FactInputSchema>;\nexport type FactKind = z.infer<typeof FactKindSchema>;\n","import { z } from 'zod';\nimport { ClockTriggerSchema, ManualTriggerSchema, RunTriggerSchema, SignalTriggerSchema, TriggerSchema, WriteTriggerSchema } from './trigger.schema';\nimport { DEFAULT_POLICY, PolicySchema } from './policy.schema';\n\nexport const SelectionSchema = z\n .object({\n query: z.unknown().describe('Handed to the `select` seam verbatim. Under moss: a vex { fingerprint, context } replay.'),\n mode: z\n .enum(['each', 'batch'])\n .default('each')\n .describe('each → one task per row; batch → one task carrying all rows (bounded sets only).'),\n unitKey: z.string().optional().describe('The row field keying a unit task. `each` mode only; duplicates fail the firing.'),\n })\n .strict();\n\nexport const EffectRefSchema = z\n .object({\n name: z.string().describe('A registered effect. The reflex names it; the registry supplies the handler.'),\n input: z.unknown().optional().describe('A template, evaluated per unit by the `transform` seam.'),\n })\n .strict();\n\nconst reflexFields = {\n id: z.string().min(1).describe(\"Unique. A tenant's reflex is the tenant's own row, with its own id.\"),\n intent: z.string().min(1).describe(\"One factual sentence — what this does, in the person's language.\"),\n on: TriggerSchema,\n as: z.string().optional().describe('The identity this runs under. Opaque to tide; the host resolves it.'),\n params: z.record(z.string(), z.unknown()).optional().describe('Authored knobs, visible to templates as $.params.'),\n select: SelectionSchema.optional().describe('Omitted = the trigger itself is the unit.'),\n when: z.unknown().optional().describe('A predicate template. FACT triggers only — a query belongs in `select`.'),\n effect: EffectRefSchema,\n policy: PolicySchema.default(DEFAULT_POLICY),\n enabled: z.boolean().default(true).describe('A switch on the row, not part of the definition — flipping it is not an edit.'),\n};\n\nconst reflexRules = (reflex: { on: object; when?: unknown; select?: { mode: string; unitKey?: string | undefined } | undefined }, ctx: z.RefinementCtx): void => {\n if (reflex.when !== undefined && !('fact' in reflex.on))\n ctx.addIssue({ code: 'custom', message: '`when` is for fact triggers; a clock condition belongs in `select`', path: ['when'] });\n if (reflex.select?.mode === 'each' && reflex.select.unitKey === undefined)\n ctx.addIssue({ code: 'custom', message: \"`each` mode needs a unitKey — it is the task's idempotency grain\", path: ['select', 'unitKey'] });\n};\n\nexport const ReflexSchema = z.object(reflexFields).strict().superRefine(reflexRules);\n\nexport const REFLEX_TRIGGERS = {\n clock: ClockTriggerSchema,\n write: WriteTriggerSchema,\n signal: SignalTriggerSchema,\n run: RunTriggerSchema,\n manual: ManualTriggerSchema,\n} as const;\nexport type ReflexTrigger = keyof typeof REFLEX_TRIGGERS;\n\nexport const reflexSchemaOf = (choice: { triggers?: readonly ReflexTrigger[] } = {}): z.ZodType<Reflex, ReflexInput> => {\n if (choice.triggers === undefined) return ReflexSchema;\n const [first, ...rest] = choice.triggers.map((kind): z.ZodType<Reflex['on'], ReflexInput['on']> => REFLEX_TRIGGERS[kind]);\n if (first === undefined) throw new Error('tide: a reflex needs at least one trigger kind');\n const on: z.ZodType<Reflex['on'], ReflexInput['on']> = rest.length === 0 ? first : z.union([first, ...rest]);\n return z.object({ ...reflexFields, on }).strict().superRefine(reflexRules);\n};\n\nexport const TimerSchema = z\n .object({\n hours: z.number().int().min(0).optional(),\n minutes: z.number().int().min(0).optional(),\n seconds: z.number().int().min(0).optional(),\n })\n .strict()\n .refine((timer) => (timer.hours ?? 0) + (timer.minutes ?? 0) + (timer.seconds ?? 0) > 0, { message: 'a timer needs a length' });\n\nexport const TimerTriggerSchema = z\n .object({ timer: TimerSchema.describe('A length of time from now, as hours, minutes and seconds (each optional, together more than zero). Fires once, that long after the reflex is saved — not after it is written. A clock is for a time of day or a date.') })\n .strict();\n\nexport const DRAFT_TRIGGERS = {\n clock: ClockTriggerSchema,\n timer: TimerTriggerSchema,\n write: WriteTriggerSchema,\n signal: SignalTriggerSchema,\n run: RunTriggerSchema,\n manual: ManualTriggerSchema,\n} as const;\nexport type DraftTrigger = keyof typeof DRAFT_TRIGGERS;\nconst ALL_DRAFT_TRIGGERS: readonly DraftTrigger[] = ['clock', 'timer', 'write', 'signal', 'run', 'manual'];\n\nexport type DraftField = 'params' | 'select' | 'when';\n\nexport type DraftChoice = { triggers?: readonly DraftTrigger[]; fields?: readonly DraftField[] };\n\nconst draftCore = {\n id: z.string().min(1).describe('A short name you make up from the request, like \"call-mum\". Never ask the person for it.'),\n intent: reflexFields.intent,\n effect: EffectRefSchema,\n};\n\nconst WidestDraftSchema = z\n .object({ ...draftCore, on: z.union([TriggerSchema, TimerTriggerSchema]), params: reflexFields.params, select: reflexFields.select, when: reflexFields.when })\n .strict();\nexport type ReflexDraft = z.infer<typeof WidestDraftSchema>;\n\nexport const draftSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexDraft> => {\n const [first, ...rest] = (choice.triggers ?? ALL_DRAFT_TRIGGERS).map((kind): z.ZodType<ReflexDraft['on']> => DRAFT_TRIGGERS[kind]);\n if (first === undefined) throw new Error('tide: a draft needs at least one trigger kind');\n const on: z.ZodType<ReflexDraft['on']> = rest.length === 0 ? first : z.union([first, ...rest]);\n const has = (field: DraftField): boolean => choice.fields?.includes(field) ?? false;\n const keep: { [key in keyof ReflexDraft]?: true } = {\n id: true,\n intent: true,\n effect: true,\n on: true,\n ...(has('params') ? { params: true as const } : {}),\n ...(has('select') ? { select: true as const } : {}),\n ...(has('when') ? { when: true as const } : {}),\n };\n return WidestDraftSchema.pick(keep).extend({ on }).strict().superRefine(reflexRules);\n};\n\nexport const ReflexDraftSchema = draftSchemaOf();\n\nexport type Selection = z.infer<typeof SelectionSchema>;\nexport type EffectRef = z.infer<typeof EffectRefSchema>;\nexport type Reflex = z.infer<typeof ReflexSchema>;\nexport type ReflexInput = z.input<typeof ReflexSchema>;\nexport type Timer = z.infer<typeof TimerSchema>;\n"]}