@niscorp/tide 0.1.9 → 0.1.11

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @niscorp/tide
2
2
 
3
+ ## 0.1.11
4
+
5
+ ### Patch Changes
6
+
7
+ - 5b2538d: A load can leave out each bad reflex alone (`isolate`), a clock's zone is checked, and a timer in the hour a clock turns back fires when it was set to.
8
+ - **`load(reflexes, { isolate: true })`** leaves out each reflex that would refuse the load — one that does not parse, a duplicate id, an unregistered effect, every reflex on an unguarded cycle, and one left watching the run of a reflex left out — and loads the rest. The report's new `refused` lists each, as `{ reflexId, code, message }`. Without `isolate` a load refuses whole, as before. It is for a host whose reflexes are its people's rows: in an app that keeps them that way, a member who wrote a reflex waking on every write to a table its own effect writes stopped every person's automations until the next boot, and the boot with it.
9
+ - **A clock's `tz` is a zone `Intl` knows** (`TimeZoneSchema`), refused where the reflex is parsed. One it did not know was accepted, and then every `advance` and `nextDue` threw, for everybody: DOCS promised an advance does not crash because one reflex is broken. No document changes: a reflex with such a zone could never fire.
10
+ - **`reflexSchemaOf({ triggers })`** parses a stored reflex with only the trigger kinds a host offers (`REFLEX_TRIGGERS`), as `draftSchemaOf` does for a draft. `reflexSchemaOf()` is `ReflexSchema`.
11
+ - **`anchorDraft` keeps a timer in `UTC` where the host's local time would name another instant.** In the hour a clock turns back, the local time is shown twice and was read as its first pass: a ten-minute timer saved at 02:55 CEST in Vienna on the last Sunday of October fired an hour early — before it was saved, so in fact never. Everywhere else it is kept in the host's zone, as before.
12
+ - `GraphReport`'s refusals name the `reflexIds` each is about (`GraphRefusal`).
13
+ - `isolate` keeps one tenant's bad reflex from stopping another's only where the host owns the ids (a duplicate leaves out every reflex after the first) and one tenant's triggers never wake on another's writes (every reflex on an unguarded cycle is left out, whoever's it is).
14
+
15
+ **What to change:** nothing. A host whose reflexes are its people's rows passes `isolate: true` and logs `refused`.
16
+
17
+ ## 0.1.10
18
+
19
+ ### Patch Changes
20
+
21
+ - 2fc1bf0: The docs name the identity seam `actor`, say a fact kind refuses only the other kinds' key fields, list everything load refuses and `graph()`'s `refusals`, and show `migrations/` in the file layout.
22
+
23
+ **What to change:** nothing. Documentation only.
24
+
3
25
  ## 0.1.9
4
26
 
5
27
  ### Patch Changes
package/DESIGN.md CHANGED
@@ -64,7 +64,7 @@ of those properties. Tide exists so that piece never has to be written.
64
64
 
65
65
  5. **Identity-blind.** Tide never learns what a principal is. Every reflex names an
66
66
  `as`; the host resolves it to whatever authority means there (under moss: a
67
- charter-resolved, engine-enforced `ActorContext`) and tide threads it through to
67
+ charter-resolved, engine-enforced principal) and tide threads it through to
68
68
  effects untouched. It is also *written down* on every run, so a host can scope its
69
69
  own ledger by it without tide knowing what it scoped. The same blindness charter
70
70
  has toward universes, tide has toward identity — and for the same reason:
@@ -281,7 +281,9 @@ drive tide; nothing else about the producer is tide's business.
281
281
  ```
282
282
 
283
283
  **The union is enforced, and ⟲ it was not.** Each kind requires the fields that make it
284
- addressable and refuses the fields belonging to the others. `{ kind: 'write' }` with no
284
+ addressable and refuses the key fields of the others (`entity`, `name`, `target`,
285
+ `runId`; a `signal` also refuses `op`). The rest are not checked by kind: a `write`
286
+ accepts `payload`, `reflex`, `stats` and `by`. `{ kind: 'write' }` with no
285
287
  entity used to parse, store, match nothing, get marked delivered, and vanish — a
286
288
  producer with no way to learn its fact was never going to wake anything. An
287
289
  unenforced union is worse than none, because it is documented.
@@ -671,8 +673,12 @@ cannot count it:
671
673
  Releasing a parked fact **records** the override; **⟲** clearing the park alone was a
672
674
  ping-pong, because the depth that parked it had not changed and never would.
673
675
 
674
- Load **refuses** outright: an unguarded cycle, a reflex naming an unregistered
675
- effect, a `when` on a non-fact trigger. The verification is only as good as the
676
+ Load **refuses** outright: a reflex that does not parse, a duplicate id, a reflex
677
+ naming an unregistered effect, a `when` on a non-fact trigger, `each` mode with no
678
+ `unitKey`, a run subscription to a reflex that is not loaded, an unguarded cycle. A host
679
+ whose reflexes are its people's rows loads with `isolate`: then each such reflex is left
680
+ out alone and reported, because one person's bad row refusing the load stopped everybody
681
+ else's. The verification is only as good as the
676
682
  effects' `writes`: under moss they are *derived* (from `mutationEffect` on the vex
677
683
  mutation behind each effect), so an edge is never guessed; a plain host declares
678
684
  them or forgoes the check, and an effect with none is reported as a **blind** edge,
@@ -746,7 +752,7 @@ the argument that tide is a *nisc* library and not a scheduler with JSON config:
746
752
  | `transform` | `(config, source) => value` | Prism's `evaluate`, or anything | **nova's exact socket** — nova doesn't know Prism; neither does tide |
747
753
  | `select` | `(query, ctx) => AsyncIterable<row>` — the query blob is opaque | vex replay under the actor's policy; or raw SQL; or an array | vex's `generateDsl` / `mapToShape` |
748
754
  | `effects` | `name → { run(input, ctx), writes?, preview? }` | vex mutation replays, fns, cortex agents; or plain functions | moss's `functions` seam |
749
- | `ctx` | opaque, threaded through to `select` and `effects`; carries `taskKey`, `emit`, `now` | moss: `ActorContext` (principal, policy, wire) | charter's universe-blindness, applied to identity |
755
+ | `actor` | `(as) => unknown`; its answer is threaded opaque into `select` and `effects` as `ctx.actor` | moss: the principal `as` names (policy, wire) | charter's universe-blindness, applied to identity |
750
756
 
751
757
  Plus the driver-facing edges, contracts rather than injections: **`ingest(fact)`**
752
758
  in, **`advance({ now, limit })`** to run one committed increment, and
@@ -822,7 +828,7 @@ Moss fills every seam but the store, which is tide's own:
822
828
  | `select` | vex replay **through the actor's own wire** — selection inherits replay-only, scoped, cached, inspectable; the tenant filter is in the SQL, engine-injected, unforgeable |
823
829
  | `effects` | every seeded vex **mutation** auto-registered under its fingerprint (with `writes` *derived* from `mutationEffect`) + the app's `effects(actor)` |
824
830
  | `transform` | prism — the same wiring the shell's transform socket already gets |
825
- | `ctx` | `ActorContext`: the charter-resolved, engine-enforced, no-shell principal |
831
+ | `actor` | the principal a run's `as` names: charter-resolved, engine-enforced, no shell |
826
832
  | the ledger | ordinary vex entries over `tide_run`, scoped by the host on the identity the run declared |
827
833
 
828
834
  **The engine's writes do not go through vex's mutation pipeline, and the reason is
@@ -886,6 +892,9 @@ src/
886
892
  types.ts ledger rows, seam types, TideStore, UNIQUE_BY, reports
887
893
  errors.ts TideError (code + details)
888
894
 
895
+ migrations/
896
+ index.ts TIDE_GRAMMAR, TIDE_SCHEMAS — a reflex or a draft as a stored document (the ./migrations entry)
897
+
889
898
  schemas/
890
899
  reflex.schema.ts ReflexSchema — trigger, select, effect, policy, enabled; the draft schemas and the timer
891
900
  trigger.schema.ts clock | fact | manual, with narrowing helpers
@@ -909,7 +918,7 @@ src/
909
918
 
910
919
  store/
911
920
  memory.ts createMemoryStore — the reference implementation + snapshot()
912
- postgres/ the Postgres store — the ./postgres entry; the only directory that imports strata
921
+ postgres/ the Postgres store — the ./postgres entry; with migrations/, the only code that imports strata
913
922
  index.ts the door: createTideStore, TIDE_SEQUENCE, TIDE_TABLES, TIDE_DDL, TidePool
914
923
  pool.ts the pool the store runs on, as much of one as it uses
915
924
  tables.ts the four tables, and the strata sequence that makes them
@@ -1031,7 +1040,7 @@ a host can do: turning its own writes into facts.
1031
1040
  truthiness rather than a second reading of it.
1032
1041
 
1033
1042
  13. **Identity is the host's, entirely — and written down.** Tide threads an opaque
1034
- `ctx`; moss's `ActorContext` supplies principal, compiled policy and tenancy. An
1043
+ `actor`, what the host's `actor(as)` returns: principal, compiled policy and tenancy. An
1035
1044
  automation that "runs as root" is unbuildable through this seam, because tide has
1036
1045
  no root to offer. Recording `as` on the run is what lets a host scope the ledger
1037
1046
  without tide learning what it scoped.
@@ -1063,7 +1072,7 @@ The wishlist, answered — including its own open questions:
1063
1072
  | Idempotency before the effect | task insert refused by `UNIQUE(runId, unit)`; task key in `ctx` for downstream |
1064
1073
  | Retry vs terminal | throw vs return (§ decision 6); `retry()` for the parked, and it rewinds the run |
1065
1074
  | Concurrency, overlap, ordering, partial failure, timeout, catch-up | leased claims + fencing, `overlap`, `order: 'serial'` inside the claim, task-per-unit, `timeoutMs`, `catchUp` |
1066
- | Scoped no-session identity, tenant-bounded | `ctx` seam ← moss's `ActorContext`; engine-side enforcement, unchanged |
1075
+ | Scoped no-session identity, tenant-bounded | `actor` seam ← the host's `actor(as)`; engine-side enforcement, unchanged |
1067
1076
  | Run ledger, dry run, preview with names, silence alerting, ledger-as-data | facts/runs/tasks; `preview()`; materialized-ahead pending rows; host-readable tables with a retention policy |
1068
1077
  | Per-tenant config, instant disarm, versioning across runs | reflexes are tenant rows; disarming is the host's row write + `load` (§ decision 11); content-hash versions (§ decision 14) |
1069
1078
  | Host-agnostic wake-up; serverless and local both | `advance({ now })` + `nextDue(now)`: the driver wakes on ingest and sleeps until the next due instant; its janitor beat is recovery, not pacing |
@@ -1071,7 +1080,7 @@ The wishlist, answered — including its own open questions:
1071
1080
  | Durable across restarts | `createTideStore(pool)`, `@niscorp/tide/postgres`; the memory store remains the reference and the check harness |
1072
1081
  | Wishlist: dependency between automations | run facts — `on: { fact: { run: 'A' } }` with `when` on the stats |
1073
1082
  | **Open: one library or two?** | one, standalone — "react to a change" is a fact reflex; same machine |
1074
- | **Open: does the identity belong here?** | no — moss's `ActorContext`, consumed through an opaque seam |
1083
+ | **Open: does the identity belong here?** | no — the host's, consumed through the opaque `actor` seam |
1075
1084
  | **Open: how much effect vocabulary is closed?** | the seam is closed (one shape), the vocabulary is open (registered handlers) |
1076
1085
  | **Open: what does versioning mean?** | content hash pinned by the ledger; `enabled` is the host's field, so pausing isn't a version |
1077
1086
  | **Open: do notifications belong here?** | no — an automation writes rows; whatever notifies is another consumer of rows |
package/DOCS.md CHANGED
@@ -107,16 +107,39 @@ applied — `policy`, `enabled` and `select.mode` may be omitted). The parts are
107
107
  exported too: `SelectionSchema`, `EffectRefSchema`, `TriggerSchema` and its
108
108
  members (`ClockTriggerSchema`, `ClockRecurringSchema`, `ClockOnceSchema`,
109
109
  `WriteTriggerSchema`, `SignalTriggerSchema`, `RunTriggerSchema`,
110
- `ManualTriggerSchema`), `ClockUnitSchema`, `OpSchema`, `WEEKDAYS`,
110
+ `ManualTriggerSchema`), `ClockUnitSchema`, `TimeZoneSchema`, `OpSchema`, `WEEKDAYS`,
111
111
  `PolicySchema`, `RetrySchema`, `FactInputSchema` and `FactKindSchema`, with the
112
112
  types `Selection`, `EffectRef`, `Trigger`, `Clock`, `ClockRecurring`,
113
113
  `ClockOnce`, `Op`, `Weekday`, `Policy`, `Retry`, `FactInput` and `FactKind`.
114
114
 
115
+ A clock's `tz` is a zone `Intl` knows (`TimeZoneSchema`) — an IANA name, in any
116
+ case, or an offset such as `+01:00`: any other is refused where the reflex is
117
+ parsed, since it would throw wherever the clock is read.
118
+
119
+ A host that keeps reflexes its people wrote parses them with only the trigger
120
+ kinds it offers, as a draft is parsed:
121
+
122
+ ```typescript
123
+ reflexSchemaOf(choice?: { triggers?: readonly ReflexTrigger[] }): z.ZodType<Reflex, ReflexInput>
124
+ REFLEX_TRIGGERS // 'clock' | 'write' | 'signal' | 'run' | 'manual' → its schema
125
+ ```
126
+
127
+ `reflexSchemaOf()` is `ReflexSchema`; it throws a plain `Error` on an empty
128
+ `triggers` list, and keeps the reflex's own rules.
129
+
115
130
  **Load refuses**, in one pass: a reflex that does not parse, a duplicate id, an
116
131
  unregistered effect, `when` on a non-fact trigger, `each` mode with no
117
132
  `unitKey`, a run subscription to a reflex that is not
118
133
  loaded, and an **unguarded cycle** — a loop on which no reflex has a `select`
119
- or a `when`.
134
+ or a `when`. By default one such reflex refuses the whole load. With
135
+ `load(reflexes, { isolate: true })` each is left out alone — with every reflex on
136
+ an unguarded cycle, and any reflex left watching the run of one left out — and
137
+ the rest load; the report's `refused` says which, and why (`LoadRefusal`). That
138
+ is for a host whose reflexes are its people's rows. It keeps one person's bad
139
+ reflex from stopping another's only where the host owns the ids (a duplicate
140
+ leaves out every reflex after the first) and one person's triggers never wake on
141
+ another's writes (every reflex on an unguarded cycle is left out, whoever's it
142
+ is).
120
143
 
121
144
  **`enabled` is the host's.** Tide reads it off the reflex it is handed and
122
145
  holds no copy. To pause an automation, write your own row and `load` again.
@@ -206,8 +229,10 @@ timerMs(timer: Timer): number
206
229
 
207
230
  `anchorDraft` turns a draft into a stored reflex at the moment it is saved. A
208
231
  `timer` becomes a one-shot clock at `anchor.at` plus its length, rounded **up**
209
- to the whole second, as a local date-time in `anchor.tz`; any other trigger
210
- passes through. The result is parsed by `ReflexSchema`, so defaults are applied
232
+ to the whole second, as a local date-time in `anchor.tz` — or, where that local
233
+ time names another instant (the hour a clock turns back shows twice, and a local
234
+ time there names its first pass), in `UTC`, which names every instant once. Any
235
+ other trigger passes through. The result is parsed by `ReflexSchema`, so defaults are applied
211
236
  and a bad draft throws. The host adds `as` afterwards.
212
237
 
213
238
  ---
@@ -313,7 +338,9 @@ type FactInput = {
313
338
 
314
339
  **The union is enforced end to end.** A `write` needs an `entity`, a `signal` a
315
340
  `name`, a `manual` a `target`, a `run` both `reflex` and `runId` — and each
316
- refuses the fields belonging to the others. `{ kind: 'write' }` with no entity
341
+ refuses the key fields of the others (`entity`, `name`, `target`, `runId`; a
342
+ `signal` also refuses `op`). The rest are not checked by kind: a `write`
343
+ accepts `payload`, `reflex`, `stats` and `by`. `{ kind: 'write' }` with no entity
317
344
  used to parse, store, match nothing, get marked delivered and vanish, with no
318
345
  way for the producer to learn its fact was never going to wake anything.
319
346
 
@@ -337,13 +364,15 @@ not duplicates of each other, and without it one of them loses its rows.
337
364
  ## Verbs
338
365
 
339
366
  ```typescript
340
- load(reflexes, options?: { at?: number }): Promise<LoadReport>
367
+ load(reflexes, options?: { at?: number; isolate?: boolean }): Promise<LoadReport>
341
368
  ```
342
369
  Validates, hashes versions, derives and verifies the graph, and arms. `at` is
343
370
  the host's boot time; arming persists, so a restart does not reopen the past.
344
- `LoadReport` carries `{ loaded, cycles, blind, warnings }` — guarded
371
+ `LoadReport` carries `{ loaded, cycles, blind, warnings, refused }` — guarded
345
372
  cycles are legal and reported; effects with no `writes` are reported as
346
- blind edges. Calling it again is how a host changes what is running,
373
+ blind edges; `refused` is each reflex `isolate` left out, as
374
+ `{ reflexId, code, message }` (`reflexId` is undefined for one that had none),
375
+ and is empty without it. Calling it again is how a host changes what is running,
347
376
  including turning one off.
348
377
 
349
378
  ```typescript
@@ -442,7 +471,7 @@ the same `now` may create no run. `fired` is `false`, with a `reason`, when
442
471
  throws, a unit key repeats); `true` does not say a run is due.
443
472
 
444
473
  ```typescript
445
- graph(): GraphReport // { edges: { from, to, via }[], cycles, blind, errors, warnings } over what is loaded
474
+ graph(): GraphReport // { edges: { from, to, via }[], cycles, blind, errors, refusals, warnings } over what is loaded
446
475
  sweep(now, retention): Promise<number> // { facts?, runs?, tasks? } horizons in ms
447
476
  ```
448
477
 
@@ -818,8 +847,9 @@ if (result.ok && isDraft(result.output.data)) {
818
847
  | `store` | a selection exists but no `select` seam is wired |
819
848
 
820
849
  `load` checks the whole graph in one pass. When it refuses, `details.errors`
821
- lists every reason and `details.refusals` gives each with its own code; the
822
- error's `code` is the first one's.
850
+ lists every reason and `details.refusals` gives each with its own code and the
851
+ `reflexIds` it is about (`GraphRefusal`, as `graph().refusals` gives them); the error's `code` is the first one's. Under `isolate`
852
+ nothing is thrown for these: they are in the report's `refused`.
823
853
 
824
854
  Runtime failures are **not** exceptions: a handler that throws becomes a
825
855
  recorded attempt, a `when` that throws becomes a recorded non-match, and an `advance`
package/dist/agent.cjs CHANGED
@@ -8,6 +8,14 @@ var WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
8
8
  var HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
9
9
  var MMDD = /^(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
10
10
  var LOCAL_DATETIME = /^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/;
11
+ var knownZone = (tz) => {
12
+ try {
13
+ return new Intl.DateTimeFormat("en-US", { timeZone: tz }).resolvedOptions().timeZone !== "";
14
+ } catch {
15
+ return false;
16
+ }
17
+ };
18
+ var TimeZoneSchema = zod.z.string().refine(knownZone, { message: "not a time zone Intl knows" }).describe("IANA timezone name.");
11
19
  var ClockUnitSchema = zod.z.enum(["day", "week", "month", "year"]);
12
20
  var ClockRecurringSchema = zod.z.object({
13
21
  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."),
@@ -15,7 +23,7 @@ var ClockRecurringSchema = zod.z.object({
15
23
  'week \u2192 a weekday, or a list of them: ["mon","tue","wed","thu","fri"] is every weekday; month \u2192 1..31, where 31 is the last day of every month (a shorter month clamps to its end); year \u2192 "MM-DD". Omitted for day.'
16
24
  ),
17
25
  at: zod.z.string().regex(HHMM).describe('Local wall-clock time, "HH:MM".'),
18
- tz: zod.z.string().describe("IANA timezone name.")
26
+ tz: TimeZoneSchema
19
27
  }).strict().superRefine((clock, ctx) => {
20
28
  const fail = (message) => ctx.addIssue({ code: "custom", message, path: ["on"] });
21
29
  if (clock.every === "day" && clock.on !== void 0) fail("a daily clock takes no `on`");
@@ -29,7 +37,7 @@ var ClockRecurringSchema = zod.z.object({
29
37
  }).describe("Repeats: fires on every day, week, month or year, at a time of day, until the reflex is removed.");
30
38
  var ClockOnceSchema = zod.z.object({
31
39
  at: zod.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".'),
32
- tz: zod.z.string().describe("IANA timezone name.")
40
+ tz: TimeZoneSchema
33
41
  }).strict().describe("Once: fires at one date and time, then never again.");
34
42
  var ClockTriggerSchema = zod.z.object({ clock: zod.z.union([ClockRecurringSchema, ClockOnceSchema]) }).strict().describe("Fires on the calendar: once, at a date and time, or repeating at a time of day.");
35
43
  var OpSchema = zod.z.enum(["insert", "update", "delete"]);
@@ -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/re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AAa,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.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\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: z.string().describe('IANA timezone name.'),\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: z.string().describe('IANA timezone name.'),\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 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,wDAA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oB,CAAC,MAAA,KAChCG,kBAAA,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.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"]}
package/dist/agent.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ZodType, z } from 'zod';
2
2
  import { AgentDefinition, Message } from '@niscorp/cortex';
3
- import { b as ReflexDraft, c as DraftChoice } from './reflex.schema-DW1znJfS.cjs';
3
+ import { b as ReflexDraft, c as DraftChoice } from './reflex.schema-wJ0MHKQn.cjs';
4
4
 
5
5
  type OfferedEffect = {
6
6
  name: string;
package/dist/agent.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ZodType, z } from 'zod';
2
2
  import { AgentDefinition, Message } from '@niscorp/cortex';
3
- import { b as ReflexDraft, c as DraftChoice } from './reflex.schema-DW1znJfS.js';
3
+ import { b as ReflexDraft, c as DraftChoice } from './reflex.schema-wJ0MHKQn.js';
4
4
 
5
5
  type OfferedEffect = {
6
6
  name: string;
package/dist/agent.js CHANGED
@@ -1,4 +1,4 @@
1
- import { draftSchemaOf } from './chunk-ZEEJLISU.js';
1
+ import { draftSchemaOf } from './chunk-2HCRTQTB.js';
2
2
  import { z } from 'zod';
3
3
  import { defineAgent } from '@niscorp/cortex';
4
4
 
@@ -5,6 +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) => {
9
+ try {
10
+ return new Intl.DateTimeFormat("en-US", { timeZone: tz }).resolvedOptions().timeZone !== "";
11
+ } catch {
12
+ return false;
13
+ }
14
+ };
15
+ var TimeZoneSchema = z.string().refine(knownZone, { message: "not a time zone Intl knows" }).describe("IANA timezone name.");
8
16
  var ClockUnitSchema = z.enum(["day", "week", "month", "year"]);
9
17
  var ClockRecurringSchema = z.object({
10
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."),
@@ -12,7 +20,7 @@ var ClockRecurringSchema = z.object({
12
20
  'week \u2192 a weekday, or a list of them: ["mon","tue","wed","thu","fri"] is every weekday; month \u2192 1..31, where 31 is the last day of every month (a shorter month clamps to its end); year \u2192 "MM-DD". Omitted for day.'
13
21
  ),
14
22
  at: z.string().regex(HHMM).describe('Local wall-clock time, "HH:MM".'),
15
- tz: z.string().describe("IANA timezone name.")
23
+ tz: TimeZoneSchema
16
24
  }).strict().superRefine((clock, ctx) => {
17
25
  const fail = (message) => ctx.addIssue({ code: "custom", message, path: ["on"] });
18
26
  if (clock.every === "day" && clock.on !== void 0) fail("a daily clock takes no `on`");
@@ -26,7 +34,7 @@ var ClockRecurringSchema = z.object({
26
34
  }).describe("Repeats: fires on every day, week, month or year, at a time of day, until the reflex is removed.");
27
35
  var ClockOnceSchema = z.object({
28
36
  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".'),
29
- tz: z.string().describe("IANA timezone name.")
37
+ tz: TimeZoneSchema
30
38
  }).strict().describe("Once: fires at one date and time, then never again.");
31
39
  var ClockTriggerSchema = z.object({ clock: z.union([ClockRecurringSchema, ClockOnceSchema]) }).strict().describe("Fires on the calendar: once, at a date and time, or repeating at a time of day.");
32
40
  var OpSchema = z.enum(["insert", "update", "delete"]);
@@ -151,6 +159,20 @@ var reflexRules = (reflex, ctx) => {
151
159
  ctx.addIssue({ code: "custom", message: "`each` mode needs a unitKey \u2014 it is the task's idempotency grain", path: ["select", "unitKey"] });
152
160
  };
153
161
  var ReflexSchema = z.object(reflexFields).strict().superRefine(reflexRules);
162
+ var REFLEX_TRIGGERS = {
163
+ clock: ClockTriggerSchema,
164
+ write: WriteTriggerSchema,
165
+ signal: SignalTriggerSchema,
166
+ run: RunTriggerSchema,
167
+ manual: ManualTriggerSchema
168
+ };
169
+ var reflexSchemaOf = (choice = {}) => {
170
+ if (choice.triggers === void 0) return ReflexSchema;
171
+ const [first, ...rest] = choice.triggers.map((kind) => REFLEX_TRIGGERS[kind]);
172
+ if (first === void 0) throw new Error("tide: a reflex needs at least one trigger kind");
173
+ const on = rest.length === 0 ? first : z.union([first, ...rest]);
174
+ return z.object({ ...reflexFields, on }).strict().superRefine(reflexRules);
175
+ };
154
176
  var TimerSchema = z.object({
155
177
  hours: z.number().int().min(0).optional(),
156
178
  minutes: z.number().int().min(0).optional(),
@@ -190,6 +212,6 @@ var draftSchemaOf = (choice = {}) => {
190
212
  };
191
213
  var ReflexDraftSchema = draftSchemaOf();
192
214
 
193
- export { ClockOnceSchema, ClockRecurringSchema, ClockTriggerSchema, ClockUnitSchema, DRAFT_TRIGGERS, EffectRefSchema, FactInputSchema, FactKindSchema, ManualTriggerSchema, OpSchema, PolicySchema, ReflexDraftSchema, ReflexSchema, RetrySchema, RunTriggerSchema, SelectionSchema, SignalTriggerSchema, TimerSchema, TimerTriggerSchema, TriggerSchema, WEEKDAYS, WriteTriggerSchema, clockOf, draftSchemaOf, factOf, isManual, isRecurring };
194
- //# sourceMappingURL=chunk-ZEEJLISU.js.map
195
- //# sourceMappingURL=chunk-ZEEJLISU.js.map
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