@yaks/wake 0.0.0-stage → 0.2.36

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.
Files changed (85) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +325 -2
  3. package/_dist/cloudflare.d.ts +68 -0
  4. package/_dist/cloudflare.d.ts.map +1 -0
  5. package/_dist/comp.d.ts +59 -0
  6. package/_dist/comp.d.ts.map +1 -0
  7. package/_dist/deno.d.ts +40 -0
  8. package/_dist/deno.d.ts.map +1 -0
  9. package/_dist/due.d.ts +96 -0
  10. package/_dist/due.d.ts.map +1 -0
  11. package/_dist/every.d.ts +65 -0
  12. package/_dist/every.d.ts.map +1 -0
  13. package/_dist/graph.d.ts +4 -0
  14. package/_dist/graph.d.ts.map +1 -0
  15. package/_dist/held.d.ts +9 -0
  16. package/_dist/held.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +59 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/plugin.d.ts +20 -0
  20. package/_dist/plugin.d.ts.map +1 -0
  21. package/_dist/run.d.ts +24 -0
  22. package/_dist/run.d.ts.map +1 -0
  23. package/_dist/service.d.ts +9 -0
  24. package/_dist/service.d.ts.map +1 -0
  25. package/_dist/tick.d.ts +36 -0
  26. package/_dist/tick.d.ts.map +1 -0
  27. package/_dist/tools.d.ts +6 -0
  28. package/_dist/tools.d.ts.map +1 -0
  29. package/_dist/vocab.d.ts +7 -0
  30. package/_dist/vocab.d.ts.map +1 -0
  31. package/_dist/watch.d.ts +58 -0
  32. package/_dist/watch.d.ts.map +1 -0
  33. package/_dist/while.d.ts +43 -0
  34. package/_dist/while.d.ts.map +1 -0
  35. package/cloudflare.js +80 -0
  36. package/cloudflare.js.map +1 -0
  37. package/cloudflare.ts +113 -0
  38. package/comp.js +59 -0
  39. package/comp.js.map +1 -0
  40. package/comp.ts +139 -0
  41. package/deno.js +57 -0
  42. package/deno.js.map +1 -0
  43. package/deno.json +1 -0
  44. package/deno.ts +78 -0
  45. package/due.js +147 -0
  46. package/due.js.map +1 -0
  47. package/due.ts +180 -0
  48. package/every.js +203 -0
  49. package/every.js.map +1 -0
  50. package/every.ts +223 -0
  51. package/graph.js +10 -0
  52. package/graph.js.map +1 -0
  53. package/graph.ts +11 -0
  54. package/held.js +29 -0
  55. package/held.js.map +1 -0
  56. package/held.ts +42 -0
  57. package/mod.js +59 -0
  58. package/mod.js.map +1 -0
  59. package/mod.ts +60 -0
  60. package/package.json +49 -4
  61. package/plugin.js +87 -0
  62. package/plugin.js.map +1 -0
  63. package/plugin.ts +94 -0
  64. package/run.js +124 -0
  65. package/run.js.map +1 -0
  66. package/run.ts +117 -0
  67. package/service.js +28 -0
  68. package/service.js.map +1 -0
  69. package/service.ts +42 -0
  70. package/tick.js +168 -0
  71. package/tick.js.map +1 -0
  72. package/tick.ts +181 -0
  73. package/tools.js +83 -0
  74. package/tools.js.map +1 -0
  75. package/tools.ts +76 -0
  76. package/vocab.js +14 -0
  77. package/vocab.js.map +1 -0
  78. package/vocab.json +270 -0
  79. package/vocab.ts +16 -0
  80. package/watch.js +175 -0
  81. package/watch.js.map +1 -0
  82. package/watch.ts +193 -0
  83. package/while.js +159 -0
  84. package/while.js.map +1 -0
  85. package/while.ts +176 -0
package/held.ts ADDED
@@ -0,0 +1,42 @@
1
+ // One person's wakes: those set for them (`wake.for`), which run as them and
2
+ // are theirs to list and cancel. A host that serves several people from one
3
+ // graph (the space's Operator on yaks.app) lists and cancels by these, so one
4
+ // person never sees or ends another's.
5
+
6
+ import { addressed, type Bundle, type Eid, type Graph } from '@yaks/graph'
7
+ import { line } from '@yaks/query'
8
+ import { WAKE } from './comp.js'
9
+
10
+ type G = Pick<Graph, 'read' | 'get' | 'apply' | 'address'>
11
+
12
+ /** The wakes set for `person` that will fire again, soonest first, whole. */
13
+ export let held = (g: Pick<Graph, 'read'>, person: Eid): Promise<Bundle[]> =>
14
+ Promise.resolve(
15
+ g.read(line`.${WAKE}.for=${person}&.${WAKE}.at&.order=${WAKE}.at&*`),
16
+ )
17
+
18
+ /** The wake `id` names (an eid, a short `#id` or a `W-` number) when it is
19
+ * set for `person`, else `undefined`. */
20
+ export let theirs = async (
21
+ g: Pick<G, 'get' | 'address'>,
22
+ person: Eid,
23
+ id: string,
24
+ ): Promise<Bundle | undefined> => {
25
+ let [row] = id ? await g.get(await addressed(g, [id])) : []
26
+ let wake = row?.[WAKE] as { for?: Eid } | undefined
27
+ return wake?.for == person ? row : undefined
28
+ }
29
+
30
+ /** Cancel the wake `id` names when it is set for `person`: it is deleted, so
31
+ * it never fires again. Answers the wake cancelled, or `undefined` when
32
+ * `person` has no such wake. */
33
+ export let cancel = async (
34
+ g: Pick<G, 'get' | 'address' | 'apply'>,
35
+ person: Eid,
36
+ id: string,
37
+ opts: Parameters<Graph['apply']>[1] = {},
38
+ ): Promise<Bundle | undefined> => {
39
+ let row = await theirs(g, person, id)
40
+ if (row) await g.apply([{ entity: row.entity, $delete: true }], opts)
41
+ return row
42
+ }
package/mod.js ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @yaks/wake — schedules as graph rows, shared by Deno, Workers and browsers.
3
+ * A wake records when to come back to something; firing it writes `fired{at}`
4
+ * on the same entity. The graph's rules decide what follows that write.
5
+ *
6
+ * - `wake{at, every, while, target, note}` — the next instant, optional
7
+ * recurrence, the conditions it recurs under, what it is about, and why.
8
+ * - `fired{at}` — the most recent firing.
9
+ * - `watch{query, local, seen, changes}` — a query whose change it fires on.
10
+ * - `occurrence{wake, at, call, error}` — one firing that ran a call
11
+ * (`@yaks/wake/run`).
12
+ *
13
+ * `wake.for` is whom a wake was set for: it runs as them, and `held` and
14
+ * `cancel` are their own wakes.
15
+ *
16
+ * ```ts
17
+ * import { next, tick } from '@yaks/wake'
18
+ *
19
+ * let at = next('20 4 * * * America/Detroit', Date.now())
20
+ * // await graph.apply([{ entity: { eid: 'cleanup' }, wake: { at }, sweep: {} }])
21
+ * // await tick(graph, Date.now())
22
+ * ```
23
+ *
24
+ * `tick` finds the due wakes and applies one transaction per wake, each with a
25
+ * precondition on what it read: `fired` plus the next `wake.at`, or a cleared
26
+ * `at` for a one-shot. One rejected transaction leaves that wake due and lets
27
+ * the others fire. Occurrences missed during an outage collapse into one
28
+ * firing, which then advances past now.
29
+ *
30
+ * A rule such as `.wake, *fired, .sweep` runs through the graph's own phases.
31
+ * `produce` is the declarative case; `run` is code. `#Now` is the tick's
32
+ * instant and `#Actor` is the actor of the write, as in every graph write.
33
+ *
34
+ * A duration (`30m`, `every 3 days`) keeps its original cadence. Five cron
35
+ * fields (`0 9 * * 1-5`) or `@hourly`, `@daily`, `@weekly`, `@monthly` name
36
+ * calendar positions. An optional trailing IANA time zone is stored in the same
37
+ * property; with none, UTC is used. Croner uses Intl, with no build step.
38
+ *
39
+ * A wake that watches a query (`watch`) fires only when the query's rows
40
+ * changed since it last looked; a look that finds nothing new moves it on.
41
+ *
42
+ * `while` makes a recurrence conditional: `{match, every}` in order, the first
43
+ * whose query finds anything setting the cadence at each firing. A wake none
44
+ * holds sleeps, and `rouse` arms it again once a write makes one hold.
45
+ *
46
+ * This module starts no timer and imports no platform API. The program running
47
+ * it calls `tick` when its own clock fires, and `rouse` after its writes
48
+ * commit.
49
+ *
50
+ * @module
51
+ */ export * from "./comp.js";
52
+ export * from "./every.js";
53
+ export * from "./due.js";
54
+ export * from "./held.js";
55
+ export * from "./plugin.js";
56
+ export * from "./tick.js";
57
+ export * from "./watch.js";
58
+ export * from "./while.js";
59
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkDC,GAED,0BAAyB;AACzB,2BAA0B;AAC1B,yBAAwB;AACxB,0BAAyB;AACzB,4BAA2B;AAC3B,0BAAyB;AACzB,2BAA0B;AAC1B,2BAA0B"}
package/mod.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @yaks/wake — schedules as graph rows, shared by Deno, Workers and browsers.
3
+ * A wake records when to come back to something; firing it writes `fired{at}`
4
+ * on the same entity. The graph's rules decide what follows that write.
5
+ *
6
+ * - `wake{at, every, while, target, note}` — the next instant, optional
7
+ * recurrence, the conditions it recurs under, what it is about, and why.
8
+ * - `fired{at}` — the most recent firing.
9
+ * - `watch{query, local, seen, changes}` — a query whose change it fires on.
10
+ * - `occurrence{wake, at, call, error}` — one firing that ran a call
11
+ * (`@yaks/wake/run`).
12
+ *
13
+ * `wake.for` is whom a wake was set for: it runs as them, and `held` and
14
+ * `cancel` are their own wakes.
15
+ *
16
+ * ```ts
17
+ * import { next, tick } from '@yaks/wake'
18
+ *
19
+ * let at = next('20 4 * * * America/Detroit', Date.now())
20
+ * // await graph.apply([{ entity: { eid: 'cleanup' }, wake: { at }, sweep: {} }])
21
+ * // await tick(graph, Date.now())
22
+ * ```
23
+ *
24
+ * `tick` finds the due wakes and applies one transaction per wake, each with a
25
+ * precondition on what it read: `fired` plus the next `wake.at`, or a cleared
26
+ * `at` for a one-shot. One rejected transaction leaves that wake due and lets
27
+ * the others fire. Occurrences missed during an outage collapse into one
28
+ * firing, which then advances past now.
29
+ *
30
+ * A rule such as `.wake, *fired, .sweep` runs through the graph's own phases.
31
+ * `produce` is the declarative case; `run` is code. `#Now` is the tick's
32
+ * instant and `#Actor` is the actor of the write, as in every graph write.
33
+ *
34
+ * A duration (`30m`, `every 3 days`) keeps its original cadence. Five cron
35
+ * fields (`0 9 * * 1-5`) or `@hourly`, `@daily`, `@weekly`, `@monthly` name
36
+ * calendar positions. An optional trailing IANA time zone is stored in the same
37
+ * property; with none, UTC is used. Croner uses Intl, with no build step.
38
+ *
39
+ * A wake that watches a query (`watch`) fires only when the query's rows
40
+ * changed since it last looked; a look that finds nothing new moves it on.
41
+ *
42
+ * `while` makes a recurrence conditional: `{match, every}` in order, the first
43
+ * whose query finds anything setting the cadence at each firing. A wake none
44
+ * holds sleeps, and `rouse` arms it again once a write makes one hold.
45
+ *
46
+ * This module starts no timer and imports no platform API. The program running
47
+ * it calls `tick` when its own clock fires, and `rouse` after its writes
48
+ * commit.
49
+ *
50
+ * @module
51
+ */
52
+
53
+ export * from './comp.js'
54
+ export * from './every.js'
55
+ export * from './due.js'
56
+ export * from './held.js'
57
+ export * from './plugin.js'
58
+ export * from './tick.js'
59
+ export * from './watch.js'
60
+ export * from './while.js'
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@yaks/wake",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/wake",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./cloudflare": {
12
+ "types": "./_dist/cloudflare.d.ts",
13
+ "default": "./cloudflare.js"
14
+ },
15
+ "./deno": {
16
+ "types": "./_dist/deno.d.ts",
17
+ "default": "./deno.js"
18
+ },
19
+ "./vocab": {
20
+ "types": "./_dist/vocab.d.ts",
21
+ "default": "./vocab.js"
22
+ },
23
+ "./graph": {
24
+ "types": "./_dist/graph.d.ts",
25
+ "default": "./graph.js"
26
+ },
27
+ "./tools": {
28
+ "types": "./_dist/tools.d.ts",
29
+ "default": "./tools.js"
30
+ },
31
+ "./service": {
32
+ "types": "./_dist/service.d.ts",
33
+ "default": "./service.js"
34
+ },
35
+ "./run": {
36
+ "types": "./_dist/run.d.ts",
37
+ "default": "./run.js"
38
+ }
39
+ },
40
+ "license": "Apache-2.0",
41
+ "dependencies": {
42
+ "@yaks/fp": "0.2.36",
43
+ "@yaks/graph": "0.2.36",
44
+ "@yaks/query": "0.2.36",
45
+ "@yaks/tools": "0.2.36",
46
+ "@yaks/vocab": "0.2.36",
47
+ "croner": "10.0.1"
48
+ },
49
+ "description": "Stores one-shot and recurring schedules as graph components, marking due wakes as fired and advancing their next scheduled times.",
50
+ "repository": "https://github.com/yak-sh/yak.git"
51
+ }
package/plugin.js ADDED
@@ -0,0 +1,87 @@
1
+ // The package as a graph plugin: the two components, one convenience on the
2
+ // way in, and one check.
3
+ //
4
+ // A wake written as a cadence alone — `{ every: '@daily' }`, with no `at` — is
5
+ // a schedule nobody would call wrong, and it would never fire: `due` tests
6
+ // whether `at` has passed, and a property that is absent never has. So
7
+ // `beforeWrite` gives a new cadence its first instant inside the transaction,
8
+ // leaving an existing schedule (including a paused one) unchanged.
9
+ //
10
+ // The check is `precondition`'s: a `while` condition is a query, and a query
11
+ // that does not parse, or names a word the graph does not speak, is refused
12
+ // when it is written rather than found out at a firing (./while.ts
13
+ // `conditions`).
14
+ //
15
+ // The plugin starts no timer. The application calls `tick`, which writes
16
+ // `fired` on each due wake; graph rules matching that write decide what
17
+ // follows. An effect observing a new or moved wake can set the application's
18
+ // timer or alarm.
19
+ import { after } from "@yaks/fp";
20
+ import { hook } from "@yaks/graph/plugin";
21
+ import { wakeOf } from "./due.js";
22
+ import { recur } from "./every.js";
23
+ import { WAKE, wakeDoc } from "./comp.js";
24
+ import { conditions } from "./while.js";
25
+ /**
26
+ * The `beforeWrite` hook: a new cadence without a first instant gets one.
27
+ * An existing recurrence without `at` is paused; omission in a patch or a
28
+ * replayed read must leave it paused. Likewise, cadence edits retain an
29
+ * existing instant. Exported for graphs that load the vocabulary separately.
30
+ */ export let starting = (opts = {})=>(bundles, tx)=>after(tx.get(bundles.filter((b)=>{
31
+ let w = wakeOf(b);
32
+ return w?.every && w.at === undefined;
33
+ }).map((b)=>b.entity.eid)), (held)=>{
34
+ let prior = new Map(held.map((b)=>[
35
+ b.entity.eid,
36
+ wakeOf(b)
37
+ ]));
38
+ return bundles.map((b)=>{
39
+ let w = wakeOf(b);
40
+ let was = prior.get(b.entity.eid);
41
+ if (!w?.every || w.at !== undefined || was?.every || was?.at) return b;
42
+ let now = (opts.now ?? Date.now)();
43
+ let at = recur(w.every, now, now, opts.tz);
44
+ return at == null ? b : {
45
+ ...b,
46
+ [WAKE]: {
47
+ ...w,
48
+ at: new Date(at).toISOString()
49
+ }
50
+ };
51
+ });
52
+ });
53
+ /**
54
+ * The wake plugin: the `wake` and `fired` components, and the two hooks
55
+ * above.
56
+ *
57
+ * The application calls `tick(graph, now)` to fire due wakes. Rules matching
58
+ * `.wake, *fired` run in their declared phases; the driver itself calls no
59
+ * handler.
60
+ */ /// let { loadVocab } = await import('@yaks/vocab')
61
+ /// let { graph } = await import('@yaks/graph')
62
+ /// let { ram } = await import('@yaks/ram')
63
+ /// let { wakeDoc } = await import('./comp.ts')
64
+ /// let vocab = loadVocab([wakeDoc])
65
+ /// let now = () => Date.parse('2026-01-01T09:17:00Z')
66
+ /// let storage = ram(vocab)
67
+ /// let g = graph({ storage, vocab, plugins: [wakes({ now })] })
68
+ /// (await g.apply([{ entity: { eid: 'w1' }, wake: { every: '@daily', note: 'water the plants' } }]))[0].wake.at -> '2026-01-02T00:00:00.000Z'
69
+ export let wakes = (opts = {})=>({
70
+ name: '@yaks/wake',
71
+ admission: ()=>true,
72
+ vocab: [
73
+ wakeDoc
74
+ ],
75
+ beforeWrite: (bundles)=>bundles.some((b)=>{
76
+ let w = wakeOf(b);
77
+ return w?.every && w.at === undefined;
78
+ }) ? hook([
79
+ WAKE
80
+ ], starting(opts)) : undefined,
81
+ hooks: {
82
+ precondition: hook([
83
+ WAKE
84
+ ], conditions)
85
+ }
86
+ });
87
+ //# sourceMappingURL=plugin.js.map
package/plugin.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sources":["./plugin.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,yBAAyB;AACzB,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC3E,uEAAuE;AACvE,8EAA8E;AAC9E,mEAAmE;AACnE,EAAE;AACF,6EAA6E;AAC7E,4EAA4E;AAC5E,mEAAmE;AACnE,i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4BAA4B;AAC5B,gEAAgE;AAChE,8IAA8I;AAC9I,OAAO,IAAI,QAAQ,CAAC,OAAa,CAAC,CAAC,GAAa,CAAC;IAC/C,MAAM;IACN,WAAW,IAAM;IACjB,OAAO;MAAC;KAAQ;IAChB,aAAa,CAAC,UACZ,QAAQ,IAAI,CAAC,CAAC;QACV,IAAI,IAAI,OAAO;QACf,OAAO,GAAG,SAAS,EAAE,EAAE,KAAK;MAC9B,KACE,KAAK;QAAC;OAAK,EAAE,SAAS,SACtB;IACN,OAAO;MACL,cAAc,KAAK;QAAC;OAAK,EAAE;IAC7B;EACF,CAAC,EAAC"}
package/plugin.ts ADDED
@@ -0,0 +1,94 @@
1
+ // The package as a graph plugin: the two components, one convenience on the
2
+ // way in, and one check.
3
+ //
4
+ // A wake written as a cadence alone — `{ every: '@daily' }`, with no `at` — is
5
+ // a schedule nobody would call wrong, and it would never fire: `due` tests
6
+ // whether `at` has passed, and a property that is absent never has. So
7
+ // `beforeWrite` gives a new cadence its first instant inside the transaction,
8
+ // leaving an existing schedule (including a paused one) unchanged.
9
+ //
10
+ // The check is `precondition`'s: a `while` condition is a query, and a query
11
+ // that does not parse, or names a word the graph does not speak, is refused
12
+ // when it is written rather than found out at a firing (./while.ts
13
+ // `conditions`).
14
+ //
15
+ // The plugin starts no timer. The application calls `tick`, which writes
16
+ // `fired` on each due wake; graph rules matching that write decide what
17
+ // follows. An effect observing a new or moved wake can set the application's
18
+ // timer or alarm.
19
+
20
+ import { after } from '@yaks/fp'
21
+ import type { Bundle } from 'jsr:@yaks/graph@0.2.36/bundle'
22
+ import { type Hook, hook, type Plugin } from '@yaks/graph/plugin'
23
+ import { type Clock, wakeOf } from './due.js'
24
+ import { recur } from './every.js'
25
+ import { WAKE, wakeDoc } from './comp.js'
26
+ import { conditions } from './while.js'
27
+
28
+ /** How the plugin reads a schedule, and where it gets the current time. */
29
+ export type Opts = Clock & {
30
+ /** the clock, replaceable in tests (default `Date.now`) */
31
+ now?: () => number
32
+ }
33
+
34
+ /**
35
+ * The `beforeWrite` hook: a new cadence without a first instant gets one.
36
+ * An existing recurrence without `at` is paused; omission in a patch or a
37
+ * replayed read must leave it paused. Likewise, cadence edits retain an
38
+ * existing instant. Exported for graphs that load the vocabulary separately.
39
+ */
40
+ export let starting = (opts: Opts = {}): Hook => (bundles, tx) =>
41
+ after(
42
+ tx.get(
43
+ bundles.filter((b) => {
44
+ let w = wakeOf(b)
45
+ return w?.every && w.at === undefined
46
+ }).map((b) => b.entity.eid),
47
+ ),
48
+ (held) => {
49
+ let prior = new Map(held.map((b) => [b.entity.eid, wakeOf(b)]))
50
+ return bundles.map((b: Bundle): Bundle => {
51
+ let w = wakeOf(b)
52
+ let was = prior.get(b.entity.eid)
53
+ if (!w?.every || w.at !== undefined || was?.every || was?.at) return b
54
+ let now = (opts.now ?? Date.now)()
55
+ let at = recur(w.every, now, now, opts.tz)
56
+ return at == null
57
+ ? b
58
+ : { ...b, [WAKE]: { ...w, at: new Date(at).toISOString() } }
59
+ })
60
+ },
61
+ )
62
+
63
+ /**
64
+ * The wake plugin: the `wake` and `fired` components, and the two hooks
65
+ * above.
66
+ *
67
+ * The application calls `tick(graph, now)` to fire due wakes. Rules matching
68
+ * `.wake, *fired` run in their declared phases; the driver itself calls no
69
+ * handler.
70
+ */
71
+ /// let { loadVocab } = await import('@yaks/vocab')
72
+ /// let { graph } = await import('@yaks/graph')
73
+ /// let { ram } = await import('@yaks/ram')
74
+ /// let { wakeDoc } = await import('./comp.ts')
75
+ /// let vocab = loadVocab([wakeDoc])
76
+ /// let now = () => Date.parse('2026-01-01T09:17:00Z')
77
+ /// let storage = ram(vocab)
78
+ /// let g = graph({ storage, vocab, plugins: [wakes({ now })] })
79
+ /// (await g.apply([{ entity: { eid: 'w1' }, wake: { every: '@daily', note: 'water the plants' } }]))[0].wake.at -> '2026-01-02T00:00:00.000Z'
80
+ export let wakes = (opts: Opts = {}): Plugin => ({
81
+ name: '@yaks/wake',
82
+ admission: () => true,
83
+ vocab: [wakeDoc],
84
+ beforeWrite: (bundles) =>
85
+ bundles.some((b) => {
86
+ let w = wakeOf(b)
87
+ return w?.every && w.at === undefined
88
+ })
89
+ ? hook([WAKE], starting(opts))
90
+ : undefined,
91
+ hooks: {
92
+ precondition: hook([WAKE], conditions),
93
+ },
94
+ })
package/run.js ADDED
@@ -0,0 +1,124 @@
1
+ // A wake set for a person that carries a tool call (`call{to, args}`, from
2
+ // @yaks/tools) runs it at each firing with no model turn, as that person, and
3
+ // keeps a record of the run: an `occurrence{wake, at, call, error}` entity,
4
+ // one a firing, whose eid is derived from the wake and the instant it fired,
5
+ // so a replay of the same firing, or a second driver, finds it and runs
6
+ // nothing twice. The call is its own entity, derived from the occurrence, and
7
+ // @yaks/tools keeps its answer, so a retry reuses an answer already recorded.
8
+ //
9
+ // The host lends what only it has: a runner over the tools the person may use
10
+ // as they stand when it fires (their permissions are read then, not when the
11
+ // wake was set), and anything else the occurrence is written with (the
12
+ // Operator's is also the session its helper runs in). How the occurrence ends
13
+ // is the host's to mark, `completed` or `failed`, since a helper given the
14
+ // wake's brief may still be checking it.
15
+ //
16
+ // This entry point imports @yaks/tools; the core (`@yaks/wake`) does not.
17
+ import { derivedEid } from "@yaks/graph";
18
+ import { answerOf, faulted, worded } from "@yaks/tools";
19
+ import { OCCURRENCE } from "./comp.js";
20
+ /** The most characters of a call's answer an occurrence says. */ export let SAID = 16_384;
21
+ /** The occurrence a wake's firing at `at` records. */ export let occurrenceOf = (wake, at)=>derivedEid(`occurrence ${wake} ${at}`);
22
+ // A call that answered may still report a failure inside its answer: a
23
+ // script's error, or a nested call that failed or had not finished (code_mode
24
+ // answers with its receipts).
25
+ let inner = (out)=>{
26
+ for (let answer of out){
27
+ let outer = answer.output?.value;
28
+ let value = outer?.structuredContent ?? outer;
29
+ let calls = value?.calls;
30
+ if (value?.error || calls?.some((c)=>c.isError || c.pending)) {
31
+ return String(value?.error ?? 'A nested call failed or has not finished.');
32
+ }
33
+ }
34
+ };
35
+ /**
36
+ * Record a wake's firing at `at` and run the call it carries, once: answers
37
+ * the occurrence and what the call said, with its failure, or `undefined`
38
+ * when the occurrence already ended. A wake with no call is recorded and
39
+ * answers that nothing was called.
40
+ */ export let run = async (g, wake, at, host)=>{
41
+ let id = occurrenceOf(wake.entity.eid, at);
42
+ let [held] = await g.get([
43
+ id
44
+ ]);
45
+ if (held?.completed || held?.failed) return;
46
+ let asked = wake.call;
47
+ let call = asked ? derivedEid(`call ${id}`) : undefined;
48
+ if (!held) {
49
+ let occurrence = {
50
+ wake: wake.entity.eid,
51
+ at,
52
+ ...call ? {
53
+ call
54
+ } : {}
55
+ };
56
+ await g.apply([
57
+ {
58
+ entity: {
59
+ eid: id
60
+ },
61
+ ...host.with,
62
+ [OCCURRENCE]: occurrence
63
+ }
64
+ ], {
65
+ trusted: true
66
+ });
67
+ }
68
+ if (!call) return {
69
+ occurrence: id,
70
+ text: 'Nothing was called.'
71
+ };
72
+ let text, error;
73
+ try {
74
+ let answered = await (await host.runner(id)).call({
75
+ entity: {
76
+ eid: call
77
+ },
78
+ call: {
79
+ ...asked,
80
+ source: id
81
+ },
82
+ $actor: {
83
+ ...host.by ? {
84
+ by: host.by
85
+ } : {},
86
+ via: id
87
+ }
88
+ });
89
+ let out = answerOf(answered, call);
90
+ text = worded(out, SAID);
91
+ let [stored] = await g.get([
92
+ call
93
+ ]);
94
+ if (faulted([
95
+ stored,
96
+ ...answered
97
+ ], call)) error = text;
98
+ error = inner(out) ?? error;
99
+ } catch (e) {
100
+ text = error = e instanceof Error ? e.message : String(e);
101
+ }
102
+ if (error) {
103
+ await g.apply([
104
+ {
105
+ entity: {
106
+ eid: id
107
+ },
108
+ [OCCURRENCE]: {
109
+ error
110
+ }
111
+ }
112
+ ], {
113
+ trusted: true
114
+ });
115
+ }
116
+ return {
117
+ occurrence: id,
118
+ text,
119
+ ...error ? {
120
+ error
121
+ } : {}
122
+ };
123
+ };
124
+ //# sourceMappingURL=run.js.map
package/run.js.map ADDED
@@ -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`call{to, args}`, from
2
+ // @yaks/tools) runs it at each firing with no model turn, as that person, and
3
+ // keeps a record of the run: an `occurrence{wake, at, call, error}` entity,
4
+ // one a firing, whose eid is derived from the wake and the instant it fired,
5
+ // so a replay of the same firing, or a second driver, finds it and runs
6
+ // nothing twice. The call is its own entity, derived from the occurrence, and
7
+ // @yaks/tools keeps its answer, so a retry reuses an answer already recorded.
8
+ //
9
+ // The host lends what only it has: a runner over the tools the person may use
10
+ // as they stand when it fires (their permissions are read then, not when the
11
+ // wake was set), and anything else the occurrence is written with (the
12
+ // Operator's is also the session its helper runs in). How the occurrence ends
13
+ // is the host's to mark, `completed` or `failed`, since a helper given the
14
+ // wake's brief may still be checking it.
15
+ //
16
+ // This entry point imports @yaks/tools; the core (`@yaks/wake`) does not.
17
+
18
+ import {
19
+ type Bundle,
20
+ type Comp,
21
+ derivedEid,
22
+ type Eid,
23
+ type Graph,
24
+ } from '@yaks/graph'
25
+ import { answerOf, faulted, type Runner, worded } from '@yaks/tools'
26
+ import { OCCURRENCE, type Occurrence } from './comp.js'
27
+
28
+ type G = Pick<Graph, 'get' | 'apply'>
29
+
30
+ /** The most characters of a call's answer an occurrence says. */
31
+ export let SAID = 16_384
32
+
33
+ /** The occurrence a wake's firing at `at` records. */
34
+ export let occurrenceOf = (wake: Eid, at: string): Eid =>
35
+ derivedEid(`occurrence ${wake} ${at}`)
36
+
37
+ /** What one firing's call came to: its occurrence, the answer in words, and
38
+ * the failure where it failed. */
39
+ export type Ran = { occurrence: Eid; text: string; error?: string }
40
+
41
+ /** What the host lends a firing. */
42
+ export type Host = {
43
+ /** the runner the call is made through, over the person's tools as they
44
+ * stand now; given the occurrence the call is made for */
45
+ runner: (occurrence: Eid) => Runner | Promise<Runner>
46
+ /** what else the occurrence is written with */
47
+ with?: Omit<Bundle, 'entity'>
48
+ /** whom the call is made by; it comes in through its occurrence */
49
+ by?: string
50
+ }
51
+
52
+ // A call that answered may still report a failure inside its answer: a
53
+ // script's error, or a nested call that failed or had not finished (code_mode
54
+ // answers with its receipts).
55
+ let inner = (out: Bundle[]): string | undefined => {
56
+ for (let answer of out) {
57
+ let outer = (answer.output as Comp | undefined)?.value as Comp | undefined
58
+ let value = (outer?.structuredContent ?? outer) as Comp | undefined
59
+ let calls = value?.calls as Comp[] | undefined
60
+ if (value?.error || calls?.some((c) => c.isError || c.pending)) {
61
+ return String(value?.error ?? 'A nested call failed or has not finished.')
62
+ }
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Record a wake's firing at `at` and run the call it carries, once: answers
68
+ * the occurrence and what the call said, with its failure, or `undefined`
69
+ * when the occurrence already ended. A wake with no call is recorded and
70
+ * answers that nothing was called.
71
+ */
72
+ export let run = async (
73
+ g: G,
74
+ wake: Bundle,
75
+ at: string,
76
+ host: Host,
77
+ ): Promise<Ran | undefined> => {
78
+ let id = occurrenceOf(wake.entity.eid, at)
79
+ let [held] = await g.get([id])
80
+ if (held?.completed || held?.failed) return
81
+ let asked = wake.call as Comp | undefined
82
+ let call = asked ? derivedEid(`call ${id}`) : undefined
83
+ if (!held) {
84
+ let occurrence: Occurrence = {
85
+ wake: wake.entity.eid,
86
+ at,
87
+ ...call ? { call } : {},
88
+ }
89
+ await g.apply([{
90
+ entity: { eid: id },
91
+ ...host.with,
92
+ [OCCURRENCE]: occurrence,
93
+ }], { trusted: true })
94
+ }
95
+ if (!call) return { occurrence: id, text: 'Nothing was called.' }
96
+ let text: string, error: string | undefined
97
+ try {
98
+ let answered = await (await host.runner(id)).call({
99
+ entity: { eid: call },
100
+ call: { ...asked, source: id },
101
+ $actor: { ...host.by ? { by: host.by } : {}, via: id },
102
+ })
103
+ let out = answerOf(answered, call)
104
+ text = worded(out, SAID)
105
+ let [stored] = await g.get([call])
106
+ if (faulted([stored, ...answered], call)) error = text
107
+ error = inner(out) ?? error
108
+ } catch (e) {
109
+ text = error = e instanceof Error ? e.message : String(e)
110
+ }
111
+ if (error) {
112
+ await g.apply([{ entity: { eid: id }, [OCCURRENCE]: { error } }], {
113
+ trusted: true,
114
+ })
115
+ }
116
+ return { occurrence: id, text, ...error ? { error } : {} }
117
+ }