@niscorp/tide 0.1.8 → 0.1.10

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,25 @@
1
1
  # @niscorp/tide
2
2
 
3
+ ## 0.1.10
4
+
5
+ ### Patch Changes
6
+
7
+ - 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.
8
+
9
+ **What to change:** nothing. Documentation only.
10
+
11
+ ## 0.1.9
12
+
13
+ ### Patch Changes
14
+
15
+ - 4e1a905: The reflex agent is shown the dates to look up instead of counting them, and a date it writes beside the wrong weekday is sent back.
16
+ - **What it is told:** from the `now` it is handed (which must begin `YYYY-MM-DDTHH:MM`; otherwise it is told today is not known), today with its weekday, the coming days — today, the rest of this week, and the two weeks after it, a week running Monday to Sunday — and this month and the next.
17
+ - **What a weekday means, as it is told:** a weekday on its own is the coming one (0.1.8 told it to ask about a weekday whose week is not said: it guessed a wrong day instead). Today's own weekday, and "next" before a weekday that could be this week's or next week's, are to be asked about, naming the dates as looked up. Nothing checks this: the check sees the agent's answer, not the request.
18
+ - **What is checked:** it is told to write every date it drafts or asks about with its weekday ("Fri 2026-11-06"). A date its reasoning writes beside the wrong weekday is sent back in the same run, with the weekday it is and the two dates of the named weekday around it; so is a date that does not exist, as not a date. How the reasoning words a date is its own: a draft is never sent back for that (asking for the weekday beside every drafted date, measured, refused correct edits worded "Wed 4 Nov" until the run failed), so a date written some other way is not checked.
19
+ - **Measured** with gpt-oss-120b at low reasoning, 8 runs each, today a Tuesday: "Friday at 14:30" was drafted on the coming Friday 8 of 8 times (before: once, besides a Wednesday and questions); "tomorrow at 9" 8 of 8, as before; "the last Friday of November" 6 of 8 (before: 2), once on Sunday the 29th, written as a Sunday, so nothing sent it back, and once answered `{ refused }`, which is a failure. "next Wednesday" was asked about 7 of 8 times and drafted next week's once (before: a Sunday or a Monday, never asked). "Tuesday at 17:00", said on a Tuesday, was drafted for today 7 of 8 times and next week's once, never asked: the line about today's weekday is kept as the decision it records, and is a known gap. A run took 1.05 model calls. In an app's set of automations asked by chat, 8 runs each: new ones 109 of 112 right ("Friday at 14:30" 8 of 8, from 0; "next Wednesday" asked 8 of 8, from wrong 8 of 8), and changes to one 61 of 64, run one at a time as before the change (60 of 64), none ended by the date check.
20
+
21
+ **What to change:** nothing. The answer's shape is as before.
22
+
3
23
  ## 0.1.8
4
24
 
5
25
  ### 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,9 @@ 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. The verification is only as good as the
676
679
  effects' `writes`: under moss they are *derived* (from `mutationEffect` on the vex
677
680
  mutation behind each effect), so an edge is never guessed; a plain host declares
678
681
  them or forgoes the check, and an effect with none is reported as a **blind** edge,
@@ -746,7 +749,7 @@ the argument that tide is a *nisc* library and not a scheduler with JSON config:
746
749
  | `transform` | `(config, source) => value` | Prism's `evaluate`, or anything | **nova's exact socket** — nova doesn't know Prism; neither does tide |
747
750
  | `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
751
  | `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 |
752
+ | `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
753
 
751
754
  Plus the driver-facing edges, contracts rather than injections: **`ingest(fact)`**
752
755
  in, **`advance({ now, limit })`** to run one committed increment, and
@@ -822,7 +825,7 @@ Moss fills every seam but the store, which is tide's own:
822
825
  | `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
826
  | `effects` | every seeded vex **mutation** auto-registered under its fingerprint (with `writes` *derived* from `mutationEffect`) + the app's `effects(actor)` |
824
827
  | `transform` | prism — the same wiring the shell's transform socket already gets |
825
- | `ctx` | `ActorContext`: the charter-resolved, engine-enforced, no-shell principal |
828
+ | `actor` | the principal a run's `as` names: charter-resolved, engine-enforced, no shell |
826
829
  | the ledger | ordinary vex entries over `tide_run`, scoped by the host on the identity the run declared |
827
830
 
828
831
  **The engine's writes do not go through vex's mutation pipeline, and the reason is
@@ -886,6 +889,9 @@ src/
886
889
  types.ts ledger rows, seam types, TideStore, UNIQUE_BY, reports
887
890
  errors.ts TideError (code + details)
888
891
 
892
+ migrations/
893
+ index.ts TIDE_GRAMMAR, TIDE_SCHEMAS — a reflex or a draft as a stored document (the ./migrations entry)
894
+
889
895
  schemas/
890
896
  reflex.schema.ts ReflexSchema — trigger, select, effect, policy, enabled; the draft schemas and the timer
891
897
  trigger.schema.ts clock | fact | manual, with narrowing helpers
@@ -909,7 +915,7 @@ src/
909
915
 
910
916
  store/
911
917
  memory.ts createMemoryStore — the reference implementation + snapshot()
912
- postgres/ the Postgres store — the ./postgres entry; the only directory that imports strata
918
+ postgres/ the Postgres store — the ./postgres entry; with migrations/, the only code that imports strata
913
919
  index.ts the door: createTideStore, TIDE_SEQUENCE, TIDE_TABLES, TIDE_DDL, TidePool
914
920
  pool.ts the pool the store runs on, as much of one as it uses
915
921
  tables.ts the four tables, and the strata sequence that makes them
@@ -920,6 +926,7 @@ src/
920
926
 
921
927
  agent/
922
928
  reflex-agent.ts createReflexAgent — the ./agent entry; the only file that imports cortex
929
+ dates.ts what the agent reads a date off (today, the coming days, two months) and the date check
923
930
  index.ts
924
931
 
925
932
  test/
@@ -934,7 +941,7 @@ test/
934
941
  baselines.test.ts the checksum of each migration of TIDE_SEQUENCE, pinned
935
942
  driver.test.ts the driver: stopping, and a wait longer than a timer holds
936
943
  anchor.test.ts a draft's timer, anchored when it is saved
937
- agent.test.ts the reflex agent — its answer schemas, effect check and conversation turns
944
+ agent.test.ts the reflex agent — its answer schemas, effect check, conversation turns, and dates looked up and checked
938
945
  support.ts shared fixtures
939
946
  ```
940
947
 
@@ -1030,7 +1037,7 @@ a host can do: turning its own writes into facts.
1030
1037
  truthiness rather than a second reading of it.
1031
1038
 
1032
1039
  13. **Identity is the host's, entirely — and written down.** Tide threads an opaque
1033
- `ctx`; moss's `ActorContext` supplies principal, compiled policy and tenancy. An
1040
+ `actor`, what the host's `actor(as)` returns: principal, compiled policy and tenancy. An
1034
1041
  automation that "runs as root" is unbuildable through this seam, because tide has
1035
1042
  no root to offer. Recording `as` on the run is what lets a host scope the ledger
1036
1043
  without tide learning what it scoped.
@@ -1062,7 +1069,7 @@ The wishlist, answered — including its own open questions:
1062
1069
  | Idempotency before the effect | task insert refused by `UNIQUE(runId, unit)`; task key in `ctx` for downstream |
1063
1070
  | Retry vs terminal | throw vs return (§ decision 6); `retry()` for the parked, and it rewinds the run |
1064
1071
  | Concurrency, overlap, ordering, partial failure, timeout, catch-up | leased claims + fencing, `overlap`, `order: 'serial'` inside the claim, task-per-unit, `timeoutMs`, `catchUp` |
1065
- | Scoped no-session identity, tenant-bounded | `ctx` seam ← moss's `ActorContext`; engine-side enforcement, unchanged |
1072
+ | Scoped no-session identity, tenant-bounded | `actor` seam ← the host's `actor(as)`; engine-side enforcement, unchanged |
1066
1073
  | 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 |
1067
1074
  | 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) |
1068
1075
  | 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 |
@@ -1070,7 +1077,7 @@ The wishlist, answered — including its own open questions:
1070
1077
  | Durable across restarts | `createTideStore(pool)`, `@niscorp/tide/postgres`; the memory store remains the reference and the check harness |
1071
1078
  | Wishlist: dependency between automations | run facts — `on: { fact: { run: 'A' } }` with `when` on the stats |
1072
1079
  | **Open: one library or two?** | one, standalone — "react to a change" is a fact reflex; same machine |
1073
- | **Open: does the identity belong here?** | no — moss's `ActorContext`, consumed through an opaque seam |
1080
+ | **Open: does the identity belong here?** | no — the host's, consumed through the opaque `actor` seam |
1074
1081
  | **Open: how much effect vocabulary is closed?** | the seam is closed (one shape), the vocabulary is open (registered handlers) |
1075
1082
  | **Open: what does versioning mean?** | content hash pinned by the ledger; `enabled` is the host's field, so pausing isn't a version |
1076
1083
  | **Open: do notifications belong here?** | no — an automation writes rows; whatever notifies is another consumer of rows |
package/DOCS.md CHANGED
@@ -313,7 +313,9 @@ type FactInput = {
313
313
 
314
314
  **The union is enforced end to end.** A `write` needs an `entity`, a `signal` a
315
315
  `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
316
+ refuses the key fields of the others (`entity`, `name`, `target`, `runId`; a
317
+ `signal` also refuses `op`). The rest are not checked by kind: a `write`
318
+ accepts `payload`, `reflex`, `stats` and `by`. `{ kind: 'write' }` with no entity
317
319
  used to parse, store, match nothing, get marked delivered and vanish, with no
318
320
  way for the producer to learn its fact was never going to wake anything.
319
321
 
@@ -442,7 +444,7 @@ the same `now` may create no run. `fired` is `false`, with a `reason`, when
442
444
  throws, a unit key repeats); `true` does not say a run is due.
443
445
 
444
446
  ```typescript
445
- graph(): GraphReport // { edges: { from, to, via }[], cycles, blind, errors, warnings } over what is loaded
447
+ graph(): GraphReport // { edges: { from, to, via }[], cycles, blind, errors, refusals, warnings } over what is loaded
446
448
  sweep(now, retention): Promise<number> // { facts?, runs?, tasks? } horizons in ms
447
449
  ```
448
450
 
@@ -766,6 +768,18 @@ type ReflexRefusal = { refused: string };
766
768
  draft naming an effect that is not offered, or an input that effect's schema
767
769
  refuses, is sent back to the model to correct within the same run.
768
770
 
771
+ Dates are looked up, never counted. From the `now` it is handed — which must
772
+ begin `YYYY-MM-DDTHH:MM` for this — the agent is told today with its weekday,
773
+ the coming days (the rest of this week, Monday to Sunday, and the two weeks
774
+ after it), and this month and the next. It is told that a weekday on its own is
775
+ the coming one, and to ask about today's own weekday and about "next" before one
776
+ that could be this week's or next week's; nothing checks that it does, and it
777
+ often does not. It is told to write every date it drafts or asks about with
778
+ its weekday ("Fri 2026-11-06"), and a date its reasoning writes beside the wrong
779
+ weekday is sent back in the same run with the weekday it is, as is a date that
780
+ does not exist. How it words a date is its own: a draft is never sent back for
781
+ that, so a date it writes some other way is not checked.
782
+
769
783
  ```typescript
770
784
  const agent = createReflexAgent({ effects, triggers: ['clock', 'timer'] });
771
785
  const result = await agent.run({ intent, now, tz }, { llm }).result;
package/README.md CHANGED
@@ -130,7 +130,7 @@ A model can WRITE a reflex; it never runs one. `createReflexAgent({ effects, tri
130
130
 
131
131
  The draft's shape is built from that choice (`draftSchemaOf`, from tide's own schemas, each with its description) — it is what the model is shown and what it is held to. A draft never carries who it runs as, its policy or whether it is enabled: those are the host's, and `anchorDraft` completes them. Its `id` is only a short name the model makes up, and never asks for — the host may give the stored reflex its own id when it is saved; and a `run` trigger names another reflex's id, so a host that offers it must tell the model which reflexes exist.
132
132
 
133
- It answers with ONE of three things (`answerSchemaOf`): a reflex draft; a `{ question }` back, when the request can be read as different automations and nothing in the conversation decides which; or a `{ refused }`, when no offered effect does what was asked. A question ends the run like any answer — nothing waits. When the person answers it, or corrects a draft they have not saved, the host runs the agent again over the conversation: `reflexConversation({ now, tz, earlier, latest })` turns the earlier requests and the agent's answers to them — as it gave them, reasoning first — and the latest words into the turns of a chat. A draft naming an effect that is not offered, or an input that effect's schema refuses, goes back to the model to correct in the same run (`effectProblem`). The host shows it, and when somebody saves it, anchors it (`anchorDraft`) and decides who it runs as (`as`); from then on it runs with no model at all. Cortex is an optional peer, used only by this subpath.
133
+ It answers with ONE of three things (`answerSchemaOf`): a reflex draft; a `{ question }` back, when the request can be read as different automations and nothing in the conversation decides which; or a `{ refused }`, when no offered effect does what was asked. A question ends the run like any answer — nothing waits. When the person answers it, or corrects a draft they have not saved, the host runs the agent again over the conversation: `reflexConversation({ now, tz, earlier, latest })` turns the earlier requests and the agent's answers to them — as it gave them, reasoning first — and the latest words into the turns of a chat. A draft naming an effect that is not offered, or an input that effect's schema refuses, goes back to the model to correct in the same run (`effectProblem`). So does a date that is not the weekday the agent says it is: it is told today, the coming days and two months, written from `now`, to look dates up there rather than count them. A date written beside the wrong weekday, or one that does not exist, is all that is sent back: how the agent words a date is its own. The host shows it, and when somebody saves it, anchors it (`anchorDraft`) and decides who it runs as (`as`); from then on it runs with no model at all. Cortex is an optional peer, used only by this subpath.
134
134
 
135
135
  A draft's trigger may be a **timer** — `{ "timer": { "minutes": 5 } }`, "this long from now". A timer is sugar and is never stored: `anchorDraft(draft, { at, tz })` fixes it to a one-shot clock at the moment of saving plus its length, to the second (rounded up — never short), so time spent reading the draft is not taken off it, and a restart re-loads the same instant.
136
136
 
package/dist/agent.cjs CHANGED
@@ -135,6 +135,64 @@ var draftSchemaOf = (choice = {}) => {
135
135
  };
136
136
  draftSchemaOf();
137
137
 
138
+ // src/agent/dates.ts
139
+ var WEEKDAYS2 = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
140
+ var WEEKDAY_WORDS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
141
+ var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
142
+ var pad = (n) => String(n).padStart(2, "0");
143
+ var dayOf = (text) => {
144
+ const found = /^(\d{4})-(\d{2})-(\d{2})/.exec(text);
145
+ if (found === null) return void 0;
146
+ const day = { y: Number(found[1]), m: Number(found[2]), d: Number(found[3]) };
147
+ const at = new Date(Date.UTC(day.y, day.m - 1, day.d));
148
+ return at.getUTCFullYear() === day.y && at.getUTCMonth() === day.m - 1 && at.getUTCDate() === day.d ? day : void 0;
149
+ };
150
+ var weekdayOf = (day) => (new Date(Date.UTC(day.y, day.m - 1, day.d)).getUTCDay() + 6) % 7;
151
+ var plus = (day, days2) => {
152
+ const at = new Date(Date.UTC(day.y, day.m - 1, day.d + days2));
153
+ return { y: at.getUTCFullYear(), m: at.getUTCMonth() + 1, d: at.getUTCDate() };
154
+ };
155
+ var isoOf = (day) => `${String(day.y)}-${pad(day.m)}-${pad(day.d)}`;
156
+ var said = (day) => `${WEEKDAYS2[weekdayOf(day)] ?? ""} ${isoOf(day)}`;
157
+ var days = (from, first, last) => Array.from({ length: Math.max(0, last - first + 1) }, (_, at) => said(plus(from, first + at))).join(", ") || "none";
158
+ var monthLine = (y, m) => {
159
+ const length = new Date(Date.UTC(y, m, 0)).getUTCDate();
160
+ const byWeekday = WEEKDAYS2.map(() => []);
161
+ for (let d = 1; d <= length; d++) byWeekday[weekdayOf({ y, m, d })]?.push(d);
162
+ return `${MONTHS[m - 1] ?? ""} ${String(y)}: ${WEEKDAYS2.map((weekday, at) => `${weekday} ${(byWeekday[at] ?? []).join(" ")}`).join(" | ")}`;
163
+ };
164
+ var whenItIs = (now) => {
165
+ const today = dayOf(now);
166
+ const time = /^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d/.test(now) ? now.slice(11, 16) : void 0;
167
+ if (today === void 0 || time === void 0) return "TODAY \u2014 not known: ask for the date of anything not given as one.";
168
+ const toSunday = 6 - weekdayOf(today);
169
+ const next = today.m === 12 ? { y: today.y + 1, m: 1 } : { y: today.y, m: today.m + 1 };
170
+ return [
171
+ `TODAY \u2014 ${said(today)}, ${time}.`,
172
+ `COMING DAYS \u2014 today: ${said(today)} | the rest of this week: ${days(today, 1, toSunday)} | next week: ${days(today, toSunday + 1, toSunday + 7)} | the week after: ${days(today, toSunday + 8, toSunday + 14)}`,
173
+ `CALENDAR \u2014 ${monthLine(today.y, today.m)}; ${monthLine(next.y, next.m)}`
174
+ ].join("\n");
175
+ };
176
+ 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;
177
+ var dateProblems = (reasoning) => {
178
+ const found = [...(reasoning ?? "").matchAll(PAIRED)].map((match) => ({
179
+ text: match[2] ?? "",
180
+ day: dayOf(match[2] ?? ""),
181
+ named: WEEKDAYS2.findIndex((weekday) => weekday.toLowerCase() === (match[1] ?? "").toLowerCase())
182
+ }));
183
+ const none = found.flatMap(({ text, day }) => day === void 0 ? [`${text} is not a date. Look the date up in COMING DAYS or CALENDAR.`] : []);
184
+ const pairs = found.flatMap(({ day, named }) => day === void 0 || named < 0 ? [] : [{ day, named }]);
185
+ const wrong = pairs.flatMap(({ day, named }) => {
186
+ const real = weekdayOf(day);
187
+ if (real === named) return [];
188
+ const after = plus(day, (named - real + 7) % 7);
189
+ return [
190
+ `${isoOf(day)} is a ${WEEKDAY_WORDS[real] ?? ""}, not a ${WEEKDAY_WORDS[named] ?? ""}: the ${WEEKDAY_WORDS[named] ?? ""}s around it are ${said(plus(after, -7))} and ${said(after)}. Look the date up in COMING DAYS.`
191
+ ];
192
+ });
193
+ return [...none, ...wrong];
194
+ };
195
+
138
196
  // src/agent/reflex-agent.ts
139
197
  var ReflexAgentInputSchema = zod.z.object({
140
198
  intent: zod.z.string().describe("The person's words \u2014 a request, or, later in the conversation, their reply to your question."),
@@ -161,13 +219,26 @@ var INSTRUCTIONS = `You are Tide's reflex agent. Somebody describes an automatio
161
219
 
162
220
  Your 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.
163
221
 
164
- Times: a date or a time that could mean more than one moment is a question, never a guess \u2014 a day without its year, a time of day without morning or evening, a weekday whose week is not said. An automation happens once unless the person says it repeats. Never write a time that has already passed.
222
+ Times: 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 \u2014 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.
165
223
 
166
224
  A reply answers your last question: together with the request before it, it is one request \u2014 keep what the request said, and add what the reply decides.
167
225
 
168
226
  When you ask, ask about everything still undecided in one question, so one reply can settle it.
169
227
 
170
228
  Effects: when the request names something to be done that no offered effect does \u2014 a channel, a device, an action \u2014 refuse it; never put a different effect in its place.`;
229
+ var nowOf = (input) => {
230
+ const last = Array.isArray(input) ? input.at(-1) : void 0;
231
+ const turn = typeof last === "object" && last !== null && "content" in last ? parsedJson(String(last.content)) : input;
232
+ const parsed = ReflexAgentInputSchema.safeParse(turn);
233
+ return parsed.success ? parsed.data.now : void 0;
234
+ };
235
+ var parsedJson = (text) => {
236
+ try {
237
+ return JSON.parse(text);
238
+ } catch {
239
+ return void 0;
240
+ }
241
+ };
171
242
  var describeEffects = (effects) => `OFFERED EFFECTS \u2014 a draft names exactly one, by \`name\`; choose by its \`description\`:
172
243
  ${JSON.stringify(
173
244
  effects.map((effect) => ({ name: effect.name, description: effect.description, input: effect.input["~standard"].jsonSchema.output({ target: "draft-07" }) }))
@@ -184,13 +255,13 @@ var createReflexAgent = (config) => cortex.defineAgent({
184
255
  id: "tide.reflex",
185
256
  description: "Answers what somebody wants automated with one tide reflex draft, a question back, or a refusal.",
186
257
  instructions: INSTRUCTIONS,
187
- context: [() => describeEffects(config.effects)],
258
+ context: [() => describeEffects(config.effects), ({ input }) => whenItIs(nowOf(input) ?? "")],
188
259
  output: {
189
260
  schema: answerSchemaOf(config),
190
261
  validate: (envelope) => {
191
- if (!isDraft(envelope.data)) return { ok: true };
192
- const problem = effectProblem(config.effects, envelope.data);
193
- return problem === void 0 ? { ok: true } : { retry: problem };
262
+ const effect = isDraft(envelope.data) ? effectProblem(config.effects, envelope.data) : void 0;
263
+ const problems = [...effect === void 0 ? [] : [effect], ...dateProblems(envelope.reasoning)];
264
+ return problems.length === 0 ? { ok: true } : { retry: problems.join("\n") };
194
265
  }
195
266
  }
196
267
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schemas/trigger.schema.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\\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","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';\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 or a time that could mean more than one moment is a question, never a guess — a day without its year, a time of day without morning or evening, a weekday whose week is not said. 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// 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)],\n output: {\n schema: answerSchemaOf(config),\n validate: (envelope) => {\n if (!isDraft(envelope.data)) return { ok: true };\n const problem = effectProblem(config.effects, envelope.data);\n return problem === undefined ? { ok: true } : { retry: problem };\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;AAEhB,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,CAAE,GAAA,CAAI,EAAE,CAAA,EAAGA,KAAA,CAAE,KAAK,QAAQ,CAAA,EAAGA,KAAA,CAAE,KAAA,CAAMA,MAAE,IAAA,CAAK,QAAQ,CAAC,CAAA,CAAE,IAAI,CAAC,CAAA,EAAGA,KAAA,CAAE,MAAA,GAAS,KAAA,CAAM,IAAI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s","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"]}
package/dist/agent.js CHANGED
@@ -2,6 +2,65 @@ import { draftSchemaOf } from './chunk-ZEEJLISU.js';
2
2
  import { z } from 'zod';
3
3
  import { defineAgent } from '@niscorp/cortex';
4
4
 
5
+ // src/agent/dates.ts
6
+ var WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
7
+ var WEEKDAY_WORDS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
8
+ var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
9
+ var pad = (n) => String(n).padStart(2, "0");
10
+ var dayOf = (text) => {
11
+ const found = /^(\d{4})-(\d{2})-(\d{2})/.exec(text);
12
+ if (found === null) return void 0;
13
+ const day = { y: Number(found[1]), m: Number(found[2]), d: Number(found[3]) };
14
+ const at = new Date(Date.UTC(day.y, day.m - 1, day.d));
15
+ return at.getUTCFullYear() === day.y && at.getUTCMonth() === day.m - 1 && at.getUTCDate() === day.d ? day : void 0;
16
+ };
17
+ var weekdayOf = (day) => (new Date(Date.UTC(day.y, day.m - 1, day.d)).getUTCDay() + 6) % 7;
18
+ var plus = (day, days2) => {
19
+ const at = new Date(Date.UTC(day.y, day.m - 1, day.d + days2));
20
+ return { y: at.getUTCFullYear(), m: at.getUTCMonth() + 1, d: at.getUTCDate() };
21
+ };
22
+ var isoOf = (day) => `${String(day.y)}-${pad(day.m)}-${pad(day.d)}`;
23
+ var said = (day) => `${WEEKDAYS[weekdayOf(day)] ?? ""} ${isoOf(day)}`;
24
+ var days = (from, first, last) => Array.from({ length: Math.max(0, last - first + 1) }, (_, at) => said(plus(from, first + at))).join(", ") || "none";
25
+ var monthLine = (y, m) => {
26
+ const length = new Date(Date.UTC(y, m, 0)).getUTCDate();
27
+ const byWeekday = WEEKDAYS.map(() => []);
28
+ for (let d = 1; d <= length; d++) byWeekday[weekdayOf({ y, m, d })]?.push(d);
29
+ return `${MONTHS[m - 1] ?? ""} ${String(y)}: ${WEEKDAYS.map((weekday, at) => `${weekday} ${(byWeekday[at] ?? []).join(" ")}`).join(" | ")}`;
30
+ };
31
+ var whenItIs = (now) => {
32
+ const today = dayOf(now);
33
+ const time = /^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d/.test(now) ? now.slice(11, 16) : void 0;
34
+ if (today === void 0 || time === void 0) return "TODAY \u2014 not known: ask for the date of anything not given as one.";
35
+ const toSunday = 6 - weekdayOf(today);
36
+ const next = today.m === 12 ? { y: today.y + 1, m: 1 } : { y: today.y, m: today.m + 1 };
37
+ return [
38
+ `TODAY \u2014 ${said(today)}, ${time}.`,
39
+ `COMING DAYS \u2014 today: ${said(today)} | the rest of this week: ${days(today, 1, toSunday)} | next week: ${days(today, toSunday + 1, toSunday + 7)} | the week after: ${days(today, toSunday + 8, toSunday + 14)}`,
40
+ `CALENDAR \u2014 ${monthLine(today.y, today.m)}; ${monthLine(next.y, next.m)}`
41
+ ].join("\n");
42
+ };
43
+ 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
+ var dateProblems = (reasoning) => {
45
+ const found = [...(reasoning ?? "").matchAll(PAIRED)].map((match) => ({
46
+ text: match[2] ?? "",
47
+ day: dayOf(match[2] ?? ""),
48
+ named: WEEKDAYS.findIndex((weekday) => weekday.toLowerCase() === (match[1] ?? "").toLowerCase())
49
+ }));
50
+ const none = found.flatMap(({ text, day }) => day === void 0 ? [`${text} is not a date. Look the date up in COMING DAYS or CALENDAR.`] : []);
51
+ const pairs = found.flatMap(({ day, named }) => day === void 0 || named < 0 ? [] : [{ day, named }]);
52
+ const wrong = pairs.flatMap(({ day, named }) => {
53
+ const real = weekdayOf(day);
54
+ if (real === named) return [];
55
+ const after = plus(day, (named - real + 7) % 7);
56
+ return [
57
+ `${isoOf(day)} is a ${WEEKDAY_WORDS[real] ?? ""}, not a ${WEEKDAY_WORDS[named] ?? ""}: the ${WEEKDAY_WORDS[named] ?? ""}s around it are ${said(plus(after, -7))} and ${said(after)}. Look the date up in COMING DAYS.`
58
+ ];
59
+ });
60
+ return [...none, ...wrong];
61
+ };
62
+
63
+ // src/agent/reflex-agent.ts
5
64
  var ReflexAgentInputSchema = z.object({
6
65
  intent: z.string().describe("The person's words \u2014 a request, or, later in the conversation, their reply to your question."),
7
66
  now: z.string().describe('The current local date and time, "YYYY-MM-DDTHH:MM", in `tz` \u2014 what a date or a time of day in the request is read against.'),
@@ -27,13 +86,26 @@ var INSTRUCTIONS = `You are Tide's reflex agent. Somebody describes an automatio
27
86
 
28
87
  Your 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.
29
88
 
30
- Times: a date or a time that could mean more than one moment is a question, never a guess \u2014 a day without its year, a time of day without morning or evening, a weekday whose week is not said. An automation happens once unless the person says it repeats. Never write a time that has already passed.
89
+ Times: 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 \u2014 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.
31
90
 
32
91
  A reply answers your last question: together with the request before it, it is one request \u2014 keep what the request said, and add what the reply decides.
33
92
 
34
93
  When you ask, ask about everything still undecided in one question, so one reply can settle it.
35
94
 
36
95
  Effects: when the request names something to be done that no offered effect does \u2014 a channel, a device, an action \u2014 refuse it; never put a different effect in its place.`;
96
+ var nowOf = (input) => {
97
+ const last = Array.isArray(input) ? input.at(-1) : void 0;
98
+ const turn = typeof last === "object" && last !== null && "content" in last ? parsedJson(String(last.content)) : input;
99
+ const parsed = ReflexAgentInputSchema.safeParse(turn);
100
+ return parsed.success ? parsed.data.now : void 0;
101
+ };
102
+ var parsedJson = (text) => {
103
+ try {
104
+ return JSON.parse(text);
105
+ } catch {
106
+ return void 0;
107
+ }
108
+ };
37
109
  var describeEffects = (effects) => `OFFERED EFFECTS \u2014 a draft names exactly one, by \`name\`; choose by its \`description\`:
38
110
  ${JSON.stringify(
39
111
  effects.map((effect) => ({ name: effect.name, description: effect.description, input: effect.input["~standard"].jsonSchema.output({ target: "draft-07" }) }))
@@ -50,13 +122,13 @@ var createReflexAgent = (config) => defineAgent({
50
122
  id: "tide.reflex",
51
123
  description: "Answers what somebody wants automated with one tide reflex draft, a question back, or a refusal.",
52
124
  instructions: INSTRUCTIONS,
53
- context: [() => describeEffects(config.effects)],
125
+ context: [() => describeEffects(config.effects), ({ input }) => whenItIs(nowOf(input) ?? "")],
54
126
  output: {
55
127
  schema: answerSchemaOf(config),
56
128
  validate: (envelope) => {
57
- if (!isDraft(envelope.data)) return { ok: true };
58
- const problem = effectProblem(config.effects, envelope.data);
59
- return problem === void 0 ? { ok: true } : { retry: problem };
129
+ const effect = isDraft(envelope.data) ? effectProblem(config.effects, envelope.data) : void 0;
130
+ const problems = [...effect === void 0 ? [] : [effect], ...dateProblems(envelope.reasoning)];
131
+ return problems.length === 0 ? { ok: true } : { retry: problems.join("\n") };
60
132
  }
61
133
  }
62
134
  });
package/dist/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/agent/reflex-agent.ts"],"names":[],"mappings":";;;;AAOO,IAAM,sBAAA,GAAyB,EAAE,MAAA,CAAO;AAAA,EAC7C,MAAA,EAAQ,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,mGAA8F,CAAA;AAAA,EAC1H,GAAA,EAAK,CAAA,CACF,MAAA,EAAO,CAC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MAAA,GAAS,OAAO,KAAA,CAAM,MAAA,CAAO,IAAI,CAAC,KAAA,KAAU,GAAG,KAAA,CAAM,IAAA,CAAK,KAAK,GAAG,CAAA,IAAK,OAAO,CAAA,EAAA,EAAK,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA,CAAE,KAAK,IAAI,CAAA;AACnH,EAAA,OAAO,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,CAAC,CAAA;AAAA,EAC/C,MAAA,EAAQ;AAAA,IACN,MAAA,EAAQ,eAAe,MAAM,CAAA;AAAA,IAC7B,QAAA,EAAU,CAAC,QAAA,KAAa;AACtB,MAAA,IAAI,CAAC,QAAQ,QAAA,CAAS,IAAI,GAAG,OAAO,EAAE,IAAI,IAAA,EAAK;AAC/C,MAAA,MAAM,OAAA,GAAU,aAAA,CAAc,MAAA,CAAO,OAAA,EAAS,SAAS,IAAI,CAAA;AAC3D,MAAA,OAAO,OAAA,KAAY,SAAY,EAAE,EAAA,EAAI,MAAK,GAAI,EAAE,OAAO,OAAA,EAAQ;AAAA,IACjE;AAAA;AAEJ,CAAC","file":"agent.js","sourcesContent":["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';\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 or a time that could mean more than one moment is a question, never a guess — a day without its year, a time of day without morning or evening, a weekday whose week is not said. 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// 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)],\n output: {\n schema: answerSchemaOf(config),\n validate: (envelope) => {\n if (!isDraft(envelope.data)) return { ok: true };\n const problem = effectProblem(config.effects, envelope.data);\n return problem === undefined ? { ok: true } : { retry: problem };\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,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,GAA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AK,IAAI,CAAA;AACnH,EAAA,OAAO,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@niscorp/tide",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
4
4
  "description": "Host-blind automation engine — a reflex turns the clock and the fact into one named effect, through a durable ledger.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -76,8 +76,8 @@
76
76
  },
77
77
  "peerDependencies": {
78
78
  "zod": "^4.2.0",
79
- "@niscorp/cortex": "^0.1.4",
80
- "@niscorp/strata": "^0.1.7"
79
+ "@niscorp/cortex": "^0.1.6",
80
+ "@niscorp/strata": "^0.1.9"
81
81
  },
82
82
  "devDependencies": {
83
83
  "@electric-sql/pglite": "^0.5.1",
@@ -86,8 +86,8 @@
86
86
  "typescript": "^6.0.2",
87
87
  "vitest": "^4.1.2",
88
88
  "zod": "^4.6.5",
89
- "@niscorp/strata": "^0.1.7",
90
- "@niscorp/cortex": "^0.1.4"
89
+ "@niscorp/strata": "^0.1.9",
90
+ "@niscorp/cortex": "^0.1.6"
91
91
  },
92
92
  "peerDependenciesMeta": {
93
93
  "@niscorp/cortex": {