@dxos/brain 0.0.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/LICENSE +105 -0
  2. package/README.md +32 -1
  3. package/dist/lib/Builtins.mjs +184 -0
  4. package/dist/lib/Builtins.mjs.map +1 -0
  5. package/dist/lib/CompilePrompt.mjs +305 -0
  6. package/dist/lib/CompilePrompt.mjs.map +1 -0
  7. package/dist/lib/Compiler.mjs +212 -0
  8. package/dist/lib/Compiler.mjs.map +1 -0
  9. package/dist/lib/Encoding.mjs +116 -0
  10. package/dist/lib/Encoding.mjs.map +1 -0
  11. package/dist/lib/GoalRules.mjs +245 -0
  12. package/dist/lib/GoalRules.mjs.map +1 -0
  13. package/dist/lib/Vocabulary.mjs +92 -0
  14. package/dist/lib/Vocabulary.mjs.map +1 -0
  15. package/dist/lib/chunk-rolldown-runtime.mjs +13 -0
  16. package/dist/lib/index.mjs +7 -0
  17. package/dist/lib/testing.mjs +831 -0
  18. package/dist/lib/testing.mjs.map +1 -0
  19. package/dist/types/src/Builtins.d.ts +61 -0
  20. package/dist/types/src/Builtins.d.ts.map +1 -0
  21. package/dist/types/src/Builtins.test.d.ts +2 -0
  22. package/dist/types/src/Builtins.test.d.ts.map +1 -0
  23. package/dist/types/src/CompilePrompt.d.ts +107 -0
  24. package/dist/types/src/CompilePrompt.d.ts.map +1 -0
  25. package/dist/types/src/CompilePrompt.test.d.ts +2 -0
  26. package/dist/types/src/CompilePrompt.test.d.ts.map +1 -0
  27. package/dist/types/src/Compiler.d.ts +76 -0
  28. package/dist/types/src/Compiler.d.ts.map +1 -0
  29. package/dist/types/src/Compiler.test.d.ts +2 -0
  30. package/dist/types/src/Compiler.test.d.ts.map +1 -0
  31. package/dist/types/src/Encoding.d.ts +42 -0
  32. package/dist/types/src/Encoding.d.ts.map +1 -0
  33. package/dist/types/src/Encoding.test.d.ts +2 -0
  34. package/dist/types/src/Encoding.test.d.ts.map +1 -0
  35. package/dist/types/src/GoalRules.d.ts +125 -0
  36. package/dist/types/src/GoalRules.d.ts.map +1 -0
  37. package/dist/types/src/GoalRules.test.d.ts +2 -0
  38. package/dist/types/src/GoalRules.test.d.ts.map +1 -0
  39. package/dist/types/src/Vocabulary.d.ts +31 -0
  40. package/dist/types/src/Vocabulary.d.ts.map +1 -0
  41. package/dist/types/src/Vocabulary.test.d.ts +2 -0
  42. package/dist/types/src/Vocabulary.test.d.ts.map +1 -0
  43. package/dist/types/src/index.d.ts +7 -0
  44. package/dist/types/src/index.d.ts.map +1 -0
  45. package/dist/types/src/testing/index.d.ts +4 -0
  46. package/dist/types/src/testing/index.d.ts.map +1 -0
  47. package/dist/types/src/testing/reference.d.ts +9 -0
  48. package/dist/types/src/testing/reference.d.ts.map +1 -0
  49. package/dist/types/src/testing/scenarios.d.ts +73 -0
  50. package/dist/types/src/testing/scenarios.d.ts.map +1 -0
  51. package/dist/types/src/testing/simulate.d.ts +31 -0
  52. package/dist/types/src/testing/simulate.d.ts.map +1 -0
  53. package/dist/types/tsconfig.tsbuildinfo +1 -0
  54. package/package.json +74 -5
  55. package/src/Builtins.test.ts +45 -0
  56. package/src/Builtins.ts +284 -0
  57. package/src/CompilePrompt.test.ts +117 -0
  58. package/src/CompilePrompt.ts +376 -0
  59. package/src/Compiler.test.ts +85 -0
  60. package/src/Compiler.ts +234 -0
  61. package/src/Encoding.test.ts +79 -0
  62. package/src/Encoding.ts +99 -0
  63. package/src/GoalRules.test.ts +186 -0
  64. package/src/GoalRules.ts +306 -0
  65. package/src/Vocabulary.test.ts +48 -0
  66. package/src/Vocabulary.ts +88 -0
  67. package/src/index.ts +10 -0
  68. package/src/testing/index.ts +7 -0
  69. package/src/testing/reference.ts +91 -0
  70. package/src/testing/scenarios.ts +604 -0
  71. package/src/testing/simulate.ts +127 -0
package/LICENSE ADDED
@@ -0,0 +1,105 @@
1
+ # Functional Source License, Version 1.1, ALv2 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-Apache-2.0
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 DXOS
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following
93
+ will apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,34 @@
1
1
  # @dxos/brain
2
2
 
3
- Placeholder release that registers the package name. See https://github.com/dxos/dxos.
3
+ The agent brain's rule layer: pipeline-rdf facts encoded as Datalog relations, a canonical predicate
4
+ vocabulary, the goal built-ins, and an incremental evaluator that decides when a goal wakes. Rules
5
+ run on [`@dxos/datalog`](../../../common/datalog), so the same code runs in plugin-agent and in the
6
+ EDGE Durable Object. Design: `packages/plugins/plugin-agent/docs/BRAIN.md`.
7
+
8
+ ## Modules
9
+
10
+ - **`Encoding`** — encodes a pipeline-rdf `RDF.Fact` as `fact(F, S, P, O)` plus metadata relations keyed by `F` (`speaker`, `force`,
11
+ `polarity`, `mood`, `factuality`, `saidAt`, `source`, `surface`, …) and the goal relations
12
+ (`subgoal`, `status`, `action`, `actionArg`).
13
+ - **`Vocabulary`** — canonical predicates and their surface synonyms. Extraction stores the canonical
14
+ predicate and keeps the original as `surface(F, …)`.
15
+ - **`Builtins`** — `about(F, Text)` and `concerns(F, Entity)` (both may bind `F`, behind `TextIndex` /
16
+ `EntityIndex` so a semantic index can replace the keyword one), `elapsed`, `every`, `due`,
17
+ `weekday` and `hour` against an injected clock.
18
+ - **`Compiler`** — parses goal rules, expands shorthand for canonical predicates
19
+ (`helps_with(dima, X)` → `fact(_, dima, helps_with, X)`; `helps_with(F, dima, X)` exposes the id),
20
+ rejects synonyms and misspellings, checks goal heads, then runs the engine's static checks.
21
+ - **`GoalRules`** — evaluates one goal over a fact stream and clock ticks. It wakes when a wake rule
22
+ gains a new binding, when `achieved(goal)` first holds, and when a sub-goal changes status, and
23
+ reports the fact ids behind each wake. `checkAction` evaluates `blocks` rules for a proposed action.
24
+
25
+ ```ts
26
+ const rules = GoalRules.make({ source, createdAt: Date.now() });
27
+ const { wakes, achieved } = rules.update({ at: Date.now(), facts: [fact] });
28
+ ```
29
+
30
+ ## Testing
31
+
32
+ `@dxos/brain/testing` holds the eight BRAIN.md example scenarios, their reference compilations and
33
+ plausible wrong ones, and `simulate`, which replays a scenario against compiled rules — the replay gate
34
+ a compilation must pass before its goal goes active.
@@ -0,0 +1,184 @@
1
+ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
+ import * as Builtin from "@dxos/datalog/Builtin";
3
+ //#region src/Builtins.ts
4
+ var Builtins_exports = /* @__PURE__ */ __exportAll({
5
+ KeywordIndex: () => KeywordIndex,
6
+ MemoryEntityIndex: () => MemoryEntityIndex,
7
+ emptyContext: () => emptyContext,
8
+ keywordMatch: () => keywordMatch,
9
+ make: () => make,
10
+ parseDuration: () => parseDuration
11
+ });
12
+ var STOP_WORDS = /* @__PURE__ */ new Set([
13
+ "the",
14
+ "a",
15
+ "an",
16
+ "of",
17
+ "to",
18
+ "on",
19
+ "in",
20
+ "for",
21
+ "and",
22
+ "or",
23
+ "with",
24
+ "about",
25
+ "is",
26
+ "my",
27
+ "me",
28
+ "this",
29
+ "that",
30
+ "at",
31
+ "by",
32
+ "it"
33
+ ]);
34
+ var stem = (word) => {
35
+ let stemmed = word.toLowerCase();
36
+ if (stemmed.length > 4 && stemmed.endsWith("ing")) stemmed = stemmed.slice(0, -3);
37
+ else if (stemmed.length > 3 && (stemmed.endsWith("ed") || stemmed.endsWith("es"))) stemmed = stemmed.slice(0, -2);
38
+ else if (stemmed.length > 2 && stemmed.endsWith("s")) stemmed = stemmed.slice(0, -1);
39
+ if (stemmed.length > 3 && stemmed.at(-1) === stemmed.at(-2)) stemmed = stemmed.slice(0, -1);
40
+ return stemmed;
41
+ };
42
+ var words = (text) => text.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
43
+ /** True if every non-stop keyword of `query` (stemmed, prefix-tolerant) occurs in `text`. */
44
+ var keywordMatch = (text, query) => {
45
+ const stems = new Set(words(text).map(stem));
46
+ const keywords = words(query).filter((word) => !STOP_WORDS.has(word)).map(stem);
47
+ return keywords.length > 0 && keywords.every((keyword) => [...stems].some((candidate) => candidate === keyword || keyword.length >= 4 && candidate.startsWith(keyword) || candidate.length >= 4 && keyword.startsWith(candidate)));
48
+ };
49
+ /** Keyword stand-in for a semantic index. */
50
+ var KeywordIndex = class {
51
+ #texts = /* @__PURE__ */ new Map();
52
+ add(factId, text) {
53
+ this.#texts.set(factId, text);
54
+ }
55
+ remove(factId) {
56
+ this.#texts.delete(factId);
57
+ }
58
+ matches(factId, query) {
59
+ return keywordMatch(this.#texts.get(factId) ?? "", query);
60
+ }
61
+ *search(query) {
62
+ for (const [factId, text] of this.#texts) if (keywordMatch(text, query)) yield factId;
63
+ }
64
+ };
65
+ /** In-memory entity index. */
66
+ var MemoryEntityIndex = class {
67
+ #byFact = /* @__PURE__ */ new Map();
68
+ add(factId, entities) {
69
+ this.#byFact.set(factId, entities);
70
+ }
71
+ remove(factId) {
72
+ this.#byFact.delete(factId);
73
+ }
74
+ concerns(factId) {
75
+ return this.#byFact.get(factId) ?? [];
76
+ }
77
+ *facts(entity) {
78
+ for (const [factId, entities] of this.#byFact) if (entities.includes(entity)) yield factId;
79
+ }
80
+ };
81
+ var DURATION_UNITS = {
82
+ s: 1e3,
83
+ m: 6e4,
84
+ h: 36e5,
85
+ d: 864e5,
86
+ w: 6048e5
87
+ };
88
+ /** Parses `30s`, `5m`, `2h`, `2d`, `1w` (optionally ISO-prefixed `P`/`PT`) to milliseconds. */
89
+ var parseDuration = (duration) => {
90
+ const match = /^P?T?(\d+(?:\.\d+)?)\s*([smhdw])$/i.exec(String(duration).trim());
91
+ const unit = match ? DURATION_UNITS[match[2].toLowerCase()] : void 0;
92
+ return match && unit !== void 0 ? Number(match[1]) * unit : void 0;
93
+ };
94
+ var WEEKDAYS = [
95
+ "sunday",
96
+ "monday",
97
+ "tuesday",
98
+ "wednesday",
99
+ "thursday",
100
+ "friday",
101
+ "saturday"
102
+ ];
103
+ var parseTime = (value) => {
104
+ const time = typeof value === "number" ? value : Date.parse(value);
105
+ return Number.isNaN(time) ? void 0 : time;
106
+ };
107
+ /**
108
+ * The goal built-ins: `about(F, Text)` and `concerns(F, Entity)` (both may bind `F`),
109
+ * `elapsed(Ref, Duration)` (`Ref` is `goal`, a fact id or a time), `every(Duration)` (a period
110
+ * boundary passed since the previous evaluation), `due(Time, Lead)`, `weekday(Time, Day)` and
111
+ * `hour(Time, Hour)` (UTC).
112
+ */
113
+ var make = ({ clock, text, entities }) => {
114
+ const reference = (value) => value === "goal" ? clock.createdAt : clock.saidAt(String(value)) ?? parseTime(value);
115
+ return Builtin.registry(Builtin.make({
116
+ name: "about",
117
+ arity: 2,
118
+ modes: ["fb"],
119
+ evaluate: ([factId, query]) => {
120
+ if (query === void 0) return [];
121
+ if (factId === void 0) return [...text.search(String(query))].map((id) => [id, query]);
122
+ return text.matches(String(factId), String(query)) ? [[factId, query]] : [];
123
+ }
124
+ }), Builtin.make({
125
+ name: "concerns",
126
+ arity: 2,
127
+ modes: ["fb"],
128
+ evaluate: ([factId, entity]) => {
129
+ if (entity === void 0) return [];
130
+ if (factId === void 0) return [...entities.facts(String(entity))].map((id) => [id, entity]);
131
+ return entities.concerns(String(factId)).includes(String(entity)) ? [[factId, entity]] : [];
132
+ }
133
+ }), Builtin.predicate("elapsed", 2, ([ref, duration]) => {
134
+ const start = reference(ref);
135
+ const length = parseDuration(duration);
136
+ return start !== void 0 && length !== void 0 && clock.now() - start >= length;
137
+ }, { volatile: true }), Builtin.predicate("every", 1, ([duration]) => {
138
+ const period = parseDuration(duration);
139
+ if (period === void 0 || period <= 0) return false;
140
+ const tick = (time) => Math.floor((time - clock.createdAt) / period);
141
+ return tick(clock.now()) > tick(clock.previous());
142
+ }, { volatile: true }), Builtin.predicate("due", 2, ([time, lead]) => {
143
+ const deadline = parseTime(time);
144
+ const length = parseDuration(lead);
145
+ return deadline !== void 0 && length !== void 0 && clock.now() >= deadline - length;
146
+ }, { volatile: true }), Builtin.make({
147
+ name: "weekday",
148
+ arity: 2,
149
+ modes: ["bf"],
150
+ evaluate: ([time, day]) => {
151
+ const parsed = time === void 0 ? void 0 : parseTime(time);
152
+ if (time === void 0 || parsed === void 0) return [];
153
+ const weekday = WEEKDAYS[new Date(parsed).getUTCDay()];
154
+ if (day === void 0) return [[time, weekday]];
155
+ return String(day).toLowerCase() === weekday ? [[time, day]] : [];
156
+ }
157
+ }), Builtin.make({
158
+ name: "hour",
159
+ arity: 2,
160
+ modes: ["bf"],
161
+ evaluate: ([time, hour]) => {
162
+ const parsed = time === void 0 ? void 0 : parseTime(time);
163
+ if (time === void 0 || parsed === void 0) return [];
164
+ const value = new Date(parsed).getUTCHours();
165
+ if (hour === void 0) return [[time, value]];
166
+ return Number(hour) === value ? [[time, hour]] : [];
167
+ }
168
+ }));
169
+ };
170
+ /** A context with empty indexes and a frozen clock, for checking rules without evaluating them. */
171
+ var emptyContext = () => ({
172
+ clock: {
173
+ now: () => 0,
174
+ previous: () => 0,
175
+ createdAt: 0,
176
+ saidAt: () => void 0
177
+ },
178
+ text: new KeywordIndex(),
179
+ entities: new MemoryEntityIndex()
180
+ });
181
+ //#endregion
182
+ export { KeywordIndex, MemoryEntityIndex, emptyContext, keywordMatch, make, parseDuration, Builtins_exports as t };
183
+
184
+ //# sourceMappingURL=Builtins.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Builtins.mjs","names":[],"sources":["../../src/Builtins.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Builtin from '@dxos/datalog/Builtin';\n\n/** Finds facts about a topic; a semantic index replaces the keyword one without touching rules. */\nexport interface TextIndex {\n add(factId: string, text: string): void;\n remove(factId: string): void;\n /** True if the fact is about `query`. */\n matches(factId: string, query: string): boolean;\n /** Every fact about `query`. */\n search(query: string): Iterable<string>;\n}\n\n/** The entities each fact concerns (entity resolution), for scoping possessive goals. */\nexport interface EntityIndex {\n add(factId: string, entities: ReadonlyArray<string>): void;\n remove(factId: string): void;\n concerns(factId: string): ReadonlyArray<string>;\n facts(entity: string): Iterable<string>;\n}\n\n/** What the time built-ins read; `previous` is the time of the evaluation before this one. */\nexport type Clock = {\n readonly now: () => number;\n readonly previous: () => number;\n /** When the goal was created; `elapsed(goal, …)` measures from it. */\n readonly createdAt: number;\n /** When a fact was said, for `elapsed(F, …)`. */\n readonly saidAt: (factId: string) => number | undefined;\n};\n\nexport type Context = {\n readonly clock: Clock;\n readonly text: TextIndex;\n readonly entities: EntityIndex;\n};\n\nconst STOP_WORDS = new Set([\n 'the',\n 'a',\n 'an',\n 'of',\n 'to',\n 'on',\n 'in',\n 'for',\n 'and',\n 'or',\n 'with',\n 'about',\n 'is',\n 'my',\n 'me',\n 'this',\n 'that',\n 'at',\n 'by',\n 'it',\n]);\n\nconst stem = (word: string): string => {\n let stemmed = word.toLowerCase();\n if (stemmed.length > 4 && stemmed.endsWith('ing')) {\n stemmed = stemmed.slice(0, -3);\n } else if (stemmed.length > 3 && (stemmed.endsWith('ed') || stemmed.endsWith('es'))) {\n stemmed = stemmed.slice(0, -2);\n } else if (stemmed.length > 2 && stemmed.endsWith('s')) {\n stemmed = stemmed.slice(0, -1);\n }\n if (stemmed.length > 3 && stemmed.at(-1) === stemmed.at(-2)) {\n stemmed = stemmed.slice(0, -1);\n }\n return stemmed;\n};\n\nconst words = (text: string): string[] =>\n text\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter(Boolean);\n\n/** True if every non-stop keyword of `query` (stemmed, prefix-tolerant) occurs in `text`. */\nexport const keywordMatch = (text: string, query: string): boolean => {\n const stems = new Set(words(text).map(stem));\n const keywords = words(query)\n .filter((word) => !STOP_WORDS.has(word))\n .map(stem);\n return (\n keywords.length > 0 &&\n keywords.every((keyword) =>\n [...stems].some(\n (candidate) =>\n candidate === keyword ||\n (keyword.length >= 4 && candidate.startsWith(keyword)) ||\n (candidate.length >= 4 && keyword.startsWith(candidate)),\n ),\n )\n );\n};\n\n/** Keyword stand-in for a semantic index. */\nexport class KeywordIndex implements TextIndex {\n readonly #texts = new Map<string, string>();\n\n add(factId: string, text: string): void {\n this.#texts.set(factId, text);\n }\n\n remove(factId: string): void {\n this.#texts.delete(factId);\n }\n\n matches(factId: string, query: string): boolean {\n return keywordMatch(this.#texts.get(factId) ?? '', query);\n }\n\n *search(query: string): Iterable<string> {\n for (const [factId, text] of this.#texts) {\n if (keywordMatch(text, query)) {\n yield factId;\n }\n }\n }\n}\n\n/** In-memory entity index. */\nexport class MemoryEntityIndex implements EntityIndex {\n readonly #byFact = new Map<string, ReadonlyArray<string>>();\n\n add(factId: string, entities: ReadonlyArray<string>): void {\n this.#byFact.set(factId, entities);\n }\n\n remove(factId: string): void {\n this.#byFact.delete(factId);\n }\n\n concerns(factId: string): ReadonlyArray<string> {\n return this.#byFact.get(factId) ?? [];\n }\n\n *facts(entity: string): Iterable<string> {\n for (const [factId, entities] of this.#byFact) {\n if (entities.includes(entity)) {\n yield factId;\n }\n }\n }\n}\n\nconst DURATION_UNITS: Record<string, number> = { s: 1e3, m: 6e4, h: 36e5, d: 864e5, w: 6048e5 };\n\n/** Parses `30s`, `5m`, `2h`, `2d`, `1w` (optionally ISO-prefixed `P`/`PT`) to milliseconds. */\nexport const parseDuration = (duration: string | number): number | undefined => {\n const match = /^P?T?(\\d+(?:\\.\\d+)?)\\s*([smhdw])$/i.exec(String(duration).trim());\n const unit = match ? DURATION_UNITS[match[2].toLowerCase()] : undefined;\n return match && unit !== undefined ? Number(match[1]) * unit : undefined;\n};\n\nconst WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];\n\nconst parseTime = (value: string | number): number | undefined => {\n const time = typeof value === 'number' ? value : Date.parse(value);\n return Number.isNaN(time) ? undefined : time;\n};\n\n/**\n * The goal built-ins: `about(F, Text)` and `concerns(F, Entity)` (both may bind `F`),\n * `elapsed(Ref, Duration)` (`Ref` is `goal`, a fact id or a time), `every(Duration)` (a period\n * boundary passed since the previous evaluation), `due(Time, Lead)`, `weekday(Time, Day)` and\n * `hour(Time, Hour)` (UTC).\n */\nexport const make = ({ clock, text, entities }: Context): Builtin.Registry => {\n const reference = (value: string | number): number | undefined =>\n value === 'goal' ? clock.createdAt : (clock.saidAt(String(value)) ?? parseTime(value));\n\n return Builtin.registry(\n Builtin.make({\n name: 'about',\n arity: 2,\n modes: ['fb'],\n evaluate: ([factId, query]) => {\n if (query === undefined) {\n return [];\n }\n if (factId === undefined) {\n return [...text.search(String(query))].map((id) => [id, query]);\n }\n return text.matches(String(factId), String(query)) ? [[factId, query]] : [];\n },\n }),\n Builtin.make({\n name: 'concerns',\n arity: 2,\n modes: ['fb'],\n evaluate: ([factId, entity]) => {\n if (entity === undefined) {\n return [];\n }\n if (factId === undefined) {\n return [...entities.facts(String(entity))].map((id) => [id, entity]);\n }\n return entities.concerns(String(factId)).includes(String(entity)) ? [[factId, entity]] : [];\n },\n }),\n Builtin.predicate(\n 'elapsed',\n 2,\n ([ref, duration]) => {\n const start = reference(ref);\n const length = parseDuration(duration);\n return start !== undefined && length !== undefined && clock.now() - start >= length;\n },\n { volatile: true },\n ),\n Builtin.predicate(\n 'every',\n 1,\n ([duration]) => {\n const period = parseDuration(duration);\n if (period === undefined || period <= 0) {\n return false;\n }\n const tick = (time: number) => Math.floor((time - clock.createdAt) / period);\n return tick(clock.now()) > tick(clock.previous());\n },\n { volatile: true },\n ),\n Builtin.predicate(\n 'due',\n 2,\n ([time, lead]) => {\n const deadline = parseTime(time);\n const length = parseDuration(lead);\n return deadline !== undefined && length !== undefined && clock.now() >= deadline - length;\n },\n { volatile: true },\n ),\n Builtin.make({\n name: 'weekday',\n arity: 2,\n modes: ['bf'],\n evaluate: ([time, day]) => {\n const parsed = time === undefined ? undefined : parseTime(time);\n if (time === undefined || parsed === undefined) {\n return [];\n }\n const weekday = WEEKDAYS[new Date(parsed).getUTCDay()];\n if (day === undefined) {\n return [[time, weekday]];\n }\n return String(day).toLowerCase() === weekday ? [[time, day]] : [];\n },\n }),\n Builtin.make({\n name: 'hour',\n arity: 2,\n modes: ['bf'],\n evaluate: ([time, hour]) => {\n const parsed = time === undefined ? undefined : parseTime(time);\n if (time === undefined || parsed === undefined) {\n return [];\n }\n const value = new Date(parsed).getUTCHours();\n if (hour === undefined) {\n return [[time, value]];\n }\n return Number(hour) === value ? [[time, hour]] : [];\n },\n }),\n );\n};\n\n/** A context with empty indexes and a frozen clock, for checking rules without evaluating them. */\nexport const emptyContext = (): Context => ({\n clock: { now: () => 0, previous: () => 0, createdAt: 0, saidAt: () => undefined },\n text: new KeywordIndex(),\n entities: new MemoryEntityIndex(),\n});\n"],"mappings":";;;;;;;;;;;AA0CA,IAAM,6BAAa,IAAI,IAAI;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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,CAAC,IAAI,CAAC;EACpD;CACF,CAAC,CACH;AACF;;AAGA,IAAa,sBAA+B;CAC1C,OAAO;EAAE,WAAW;EAAG,gBAAgB;EAAG,WAAW;EAAG,cAAc,KAAA;CAAU;CAChF,MAAM,IAAI,aAAa;CACvB,UAAU,IAAI,kBAAkB;AAClC"}
@@ -0,0 +1,305 @@
1
+ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
+ import { defaultVocabulary } from "./Compiler.mjs";
3
+ import * as Schema from "effect/Schema";
4
+ import { BaseError } from "@dxos/errors";
5
+ import { trim } from "@dxos/util";
6
+ //#region src/CompilePrompt.ts
7
+ var CompilePrompt_exports = /* @__PURE__ */ __exportAll({
8
+ Achievement: () => Achievement,
9
+ BUILTIN_DOCS: () => BUILTIN_DOCS,
10
+ Driver: () => Driver,
11
+ EXAMPLES: () => EXAMPLES,
12
+ FACT_RELATION_DOCS: () => FACT_RELATION_DOCS,
13
+ GOAL_RELATION_DOCS: () => GOAL_RELATION_DOCS,
14
+ HEAD_DOCS: () => HEAD_DOCS,
15
+ Kind: () => Kind,
16
+ Reply: () => Reply,
17
+ ReplyError: () => ReplyError,
18
+ SYSTEM_PROMPT: () => SYSTEM_PROMPT,
19
+ parseReply: () => parseReply,
20
+ systemPrompt: () => systemPrompt,
21
+ userMessage: () => userMessage
22
+ });
23
+ /** How a goal is satisfied; read from the goal text, never hardcoded in the runtime. */
24
+ var Kind = Schema.Literals([
25
+ "outcome",
26
+ "condition",
27
+ "constraint"
28
+ ]);
29
+ /** Runtime mechanisms a goal needs: an index subscription, an alarm, a hook before each action. */
30
+ var Driver = Schema.Literals([
31
+ "fact",
32
+ "time",
33
+ "action"
34
+ ]);
35
+ /** Whether `achieved(goal)` closes the goal on its own or only proposes closing it to judgment. */
36
+ var Achievement = Schema.Literals(["rule", "judgment"]);
37
+ /** A compilation as the model returned it, before `Compiler.compile` checks the rules. */
38
+ var Reply = Schema.Struct({
39
+ kind: Schema.optional(Kind),
40
+ drivers: Schema.Array(Driver),
41
+ achievement: Schema.optional(Achievement),
42
+ datalog: Schema.String,
43
+ notes: Schema.optional(Schema.String)
44
+ });
45
+ /** Thrown by `parseReply` when the model's reply does not follow the output format. */
46
+ var ReplyError = class extends BaseError.extend("ReplyError", "Reply does not follow the output format") {
47
+ code;
48
+ reason;
49
+ constructor(code, reason) {
50
+ super({
51
+ message: reason,
52
+ context: { code }
53
+ });
54
+ this.code = code;
55
+ this.reason = reason;
56
+ }
57
+ };
58
+ /** One line per fact relation; typed so a new relation cannot be added without describing it. */
59
+ var FACT_RELATION_DOCS = {
60
+ fact: "fact(F, S, P, O) subject, predicate, object (entities are lowercase handles: rich, dima; the goal itself is the constant goal)",
61
+ speaker: "speaker(F, X) who said it: a handle, or agent for the agent's own actions",
62
+ force: "force(F, X) assertive | directive | commissive | expressive",
63
+ polarity: "polarity(F, X) \"+\" (affirmed), \"-\" (negated or refused), \"?\" (open question or unknown)",
64
+ mood: "mood(F, X) declarative | interrogative | imperative",
65
+ factuality: "factuality(F, X) \"CT+\" (certain), \"PR+\" (probable), \"PS+\" (possible), \"Uu\" (unknown), \"CT-\" …",
66
+ addressee: "addressee(F, X) who it was said to",
67
+ quote: "quote(F, Text) the words as said",
68
+ source: "source(F, Src) the message or conversation, e.g. \"chat:general\", \"mailbox:rich\", \"session:s42\", \"goal\"",
69
+ saidAt: "saidAt(F, T) when it was said (ISO timestamp)",
70
+ surface: "surface(F, P) the predicate as extracted, before mapping to the canonical one",
71
+ supersedes: "supersedes(F, Older) F corrects the fact Older",
72
+ validFrom: "validFrom(F, T) when the statement starts to hold",
73
+ validTo: "validTo(F, T) when the statement stops holding",
74
+ confidence: "confidence(F, N) extractor confidence 0..1",
75
+ nature: "nature(F, X) epistemic | aleatory",
76
+ recordedAt: "recordedAt(F, T) when it was extracted",
77
+ pass: "pass(F, Id) the extraction pass that produced it"
78
+ };
79
+ /** One line per goal-state relation the runtime maintains. */
80
+ var GOAL_RELATION_DOCS = {
81
+ subgoal: "subgoal(goal, G) G is a sub-goal of this goal",
82
+ status: "status(G, S) current status of a sub-goal: active | paused | achieved | cancelled",
83
+ action: "action(A, Kind) an action the agent is ABOUT to take (constraints only)",
84
+ actionArg: "actionArg(A, Key, Value) an argument of that action"
85
+ };
86
+ /** One entry per goal built-in, keyed by its name in `Builtins.make`. */
87
+ var BUILTIN_DOCS = {
88
+ about: trim`
89
+ about(F, "text") fact F is about the text (its quote, subject, predicate and object). If F is unbound it
90
+ enumerates every matching fact (an index lookup), so it can start a rule body. Keep the text
91
+ short: the key noun phrase ("agent plugin", "release"), not a sentence.
92
+ `,
93
+ concerns: trim`
94
+ concerns(F, Entity) fact F concerns that entity (resolved subject or beneficiary, e.g. "your tax return" said to
95
+ rich concerns rich). If F is unbound it enumerates the facts concerning the entity.
96
+ `,
97
+ elapsed: "elapsed(Ref, Dur) at least Dur has passed since Ref: goal (its creation), a fact id, or a timestamp",
98
+ every: "every(Dur) true once per period of Dur, counted from the goal's creation: a cadence",
99
+ due: "due(Time, Lead) now is at or after Time minus Lead (due(\"2027-06-30T00:00:00Z\", 0d): the deadline has passed)",
100
+ weekday: "weekday(Time, D) D is monday..sunday (UTC); binds D if unbound",
101
+ hour: "hour(Time, H) H is the UTC hour 0..23; binds H if unbound"
102
+ };
103
+ /** One line per head the runtime reads. */
104
+ var HEAD_DOCS = {
105
+ wake: "wake(label) wake the goal for judgment; label is a constant naming the reason",
106
+ achieved: "achieved(goal) the outcome has been reached (outcome goals only)",
107
+ holds: "holds(goal) the maintained state currently holds (condition goals only)",
108
+ blocks: "blocks(A) the constraint forbids proposed action A (constraints only)"
109
+ };
110
+ /** Worked examples; tests compile each one so they stay valid in the dialect. */
111
+ var EXAMPLES = [
112
+ {
113
+ goal: "Tell me when Alice confirms the venue for the offsite",
114
+ owner: "rich",
115
+ kind: "outcome",
116
+ drivers: ["fact"],
117
+ achievement: "rule",
118
+ datalog: trim`
119
+ % anything Alice says about the venue may matter (judgment decides)
120
+ wake(venue_news) :- about(F, "venue"), speaker(F, alice), not achieved(goal).
121
+ % a confirmation is an affirmed, non-question statement about the venue
122
+ confirmed(F) :- about(F, "venue"), speaker(F, alice), polarity(F, "+"), not mood(F, interrogative).
123
+ % the outcome is that the owner was told after a confirmation
124
+ achieved(goal) :- confirmed(F), notified(N, goal, rich), saidAt(F, T1), saidAt(N, T2), T2 >= T1.
125
+ `,
126
+ notes: "Wakes on any Alice venue statement; judgment decides whether it is a confirmation worth telling."
127
+ },
128
+ {
129
+ goal: "Water the plants every 3 days until the end of June",
130
+ owner: "rich",
131
+ kind: "outcome",
132
+ drivers: ["time"],
133
+ achievement: "rule",
134
+ datalog: trim`
135
+ wake(water) :- every(3d), not due("2027-06-30T23:59:59Z", 0d).
136
+ achieved(goal) :- due("2027-06-30T23:59:59Z", 0d).
137
+ `,
138
+ notes: "Purely time-driven; the cadence is counted from the goal's creation."
139
+ },
140
+ {
141
+ goal: "Don't schedule anything before 9am",
142
+ owner: "rich",
143
+ kind: "constraint",
144
+ drivers: ["action"],
145
+ datalog: trim`
146
+ schedules(A) :- action(A, book_meeting).
147
+ schedules(A) :- action(A, update_meeting).
148
+ blocks(A) :- schedules(A), actionArg(A, start, T), hour(T, H), H < 9.
149
+ `,
150
+ notes: "Checked before actions only; facts never wake a constraint."
151
+ }
152
+ ];
153
+ var formatExample = ({ goal, owner, kind, drivers, achievement, datalog, notes }, index) => trim`
154
+ ## Example ${String.fromCharCode(65 + index)}
155
+ Goal: "${goal}" Owner: ${owner}
156
+ <kind>${kind}</kind>
157
+ <drivers>${drivers.join(", ")}</drivers>
158
+ ${achievement ? `<achievement>${achievement}</achievement>` : ""}
159
+ <datalog>
160
+ ${datalog}
161
+ </datalog>
162
+ <notes>${notes}</notes>
163
+ `.split("\n").filter((line) => line.length > 0).join("\n");
164
+ /** The compile prompt; built from the relations, built-ins and vocabulary so it cannot drift from the compiler. */
165
+ var systemPrompt = ({ vocabulary = defaultVocabulary() } = {}) => {
166
+ const lines = (docs) => Object.values(docs).map((doc) => `- ${doc.replaceAll("\n", "\n ")}`).join("\n");
167
+ const canonical = vocabulary.entries.map(({ predicate, synonyms = [] }) => synonyms.length > 0 ? `- ${predicate} (extracted as: ${synonyms.join(", ")})` : `- ${predicate}`).join("\n");
168
+ return trim`
169
+ You compile an agent's goals into rules that a cheap, deterministic runtime evaluates without a model.
170
+
171
+ A goal is a plain-text directive owned by an actor. The runtime only needs to know WHEN to wake the goal for model
172
+ judgment, WHEN its outcome is achieved (an outcome goal) or WHEN its state holds (a condition goal), and, for
173
+ constraints, WHICH proposed actions it blocks. Everything else (what to write, whether to act) is judgment and is NOT
174
+ your job. Prefer wake rules that are slightly too broad over ones that miss relevant facts: judgment filters noise, a
175
+ missed wake is lost forever. \`achieved\` must be precise: a false achievement closes the goal.
176
+
177
+ # Facts
178
+
179
+ The agent's knowledge is a set of fact tuples (one per extracted statement), each with an id F. Statements by people
180
+ and actions the agent itself takes are all facts. Predicates are open vocabulary chosen by an extractor; the
181
+ extractor maps the known surface forms below onto canonical predicates, keeping the original in surface(F, P). Do not
182
+ rely on any other exact predicate string: use about/2 for content.
183
+
184
+ # Datalog dialect
185
+
186
+ Syntax: \`head :- lit, lit, ... .\` Variables start uppercase or with \`_\` (\`_\` alone is anonymous). Constants are
187
+ lowercase identifiers (dima, commissive, goal) or "double-quoted strings". Durations are constants such as 30m, 12h,
188
+ 2d, 1w. \`%\` starts a comment.
189
+ Negation: \`not p(X)\` (stratified; every variable in a negated literal must be bound by a positive literal).
190
+ Comparisons: \`X < Y\`, \`X >= Y\`, \`X = Y\`, \`X != Y\` (numbers, ISO timestamps or strings; both sides bound).
191
+ Aggregates: \`N = count : { p(X) }\`, \`M = min T : { saidAt(F, T) }\` (count, min, max, sum).
192
+ You may define helper predicates (lowercase, any arity). No other syntax: no disjunction (\`;\`), no arithmetic, no
193
+ lists, no functions; write one rule per alternative instead.
194
+
195
+ Fact relations (F is a fact id):
196
+ ${lines(FACT_RELATION_DOCS)}
197
+
198
+ Canonical predicates. Each may be written as shorthand: \`helps_with(S, O)\` means \`fact(_, S, helps_with, O)\` and
199
+ \`helps_with(F, S, O)\` also binds the fact id. Use the canonical name, never a surface form, in fact/4 or shorthand:
200
+ ${canonical}
201
+
202
+ Goal-state relations (maintained by the runtime):
203
+ ${lines(GOAL_RELATION_DOCS)}
204
+
205
+ Built-ins (deterministic, evaluated by the runtime):
206
+ ${lines(BUILTIN_DOCS)}
207
+
208
+ Heads you produce (the runtime reads only these):
209
+ ${lines(HEAD_DOCS)}
210
+ You may reference achieved(goal) and holds(goal) in bodies (e.g. \`not achieved(goal)\`). Rules may not define the
211
+ fact or goal-state relations.
212
+
213
+ # Evaluation semantics
214
+
215
+ Rules are re-evaluated after every new fact and every clock tick. A wake rule FIRES when it gains a satisfying binding
216
+ of its body variables that it did not have at the previous evaluation. So:
217
+ - a fact-driven wake rule must bind the fact variable (F), so that each new matching fact fires it again;
218
+ - \`elapsed(goal, 3d)\` fires once when it first becomes true; \`every(1d)\` fires once per period;
219
+ - guard time-driven wakes with \`not achieved(goal)\` so a closed goal stops waking;
220
+ - the runtime itself wakes the goal when achieved(goal) first becomes true and whenever a sub-goal's status changes,
221
+ so you need no wake rule for either.
222
+
223
+ # Known vocabularies
224
+
225
+ - Agent actions are recorded in the goal's own feed as fact(F, goal, Verb, Obj) with speaker(F, agent) and
226
+ source(F, "goal"); the verbs are canonical predicates above (relayed, notified, awaiting, drafted, …).
227
+ - Mailbox: an arriving email is fact(F, Msg, received, inbox) with speaker = sender address and
228
+ source = "mailbox:<owner>"; when it leaves the inbox, fact(F, Msg, archived, inbox) or fact(F, Msg, deleted, inbox).
229
+ - Action kinds: book_meeting, update_meeting, cancel_meeting, send_email, send_message, archive_email.
230
+ Arguments: start, end, title, attendees (meetings); to, subject, sendAt (email and messages).
231
+ - A session goal's conversation has source(F, "<session id>"), given with the goal.
232
+
233
+ # Compilation guidance
234
+
235
+ - Match on CONTENT (about) and POLARITY. Do not require a particular speaker, force or mood for achievement unless the
236
+ goal itself names them ("get Dima to …" names Dima and a commitment). Extractor labels such as force are noisy, and
237
+ outcomes are often reported by third parties ("the accountant filed it", "Alice says it shipped").
238
+ - A goal about a person covers facts the person said AND facts whose subject is that person.
239
+ - Possessive goals ("my taxes", "my inbox") concern the owner: use concerns(F, <owner>) rather than a speaker.
240
+ - Session goals: scope wakes to the session's own source; facts from other sources do not concern them.
241
+ - Every variable in a negated literal, a comparison or the head must be bound by a positive literal in the same rule.
242
+
243
+ # Output format
244
+
245
+ Reply with exactly these sections and nothing else:
246
+ <kind>outcome | condition | constraint</kind>
247
+ <drivers>comma-separated subset of: fact, time, action</drivers>
248
+ <achievement>rule | judgment</achievement> (outcome goals only: rule when achieved(goal) is reliable on its own,
249
+ judgment when the model must confirm it before the goal closes)
250
+ <datalog>
251
+ ...rules...
252
+ </datalog>
253
+ <notes>one or two sentences on the judgment calls you made, or what the rules leave to judgment</notes>
254
+
255
+ # Worked examples
256
+
257
+ ${EXAMPLES.map(formatExample).join("\n\n")}
258
+ `;
259
+ };
260
+ /** The compile prompt over the default vocabulary. */
261
+ var SYSTEM_PROMPT = systemPrompt();
262
+ /** The user message for one goal. */
263
+ var userMessage = ({ goal, instructions, owner, now, session }) => [
264
+ `Goal: "${goal}"`,
265
+ `Owner: ${owner}`,
266
+ `Created: ${now}`,
267
+ session ? `Session goal; current session id: ${session}` : void 0,
268
+ instructions?.trim() ? `Instructions: ${instructions.trim()}` : void 0
269
+ ].filter((line) => line !== void 0).join("\n");
270
+ /**
271
+ * Extracts the rules and metadata from a model reply. Tolerates a code fence inside or instead of the `<datalog>`
272
+ * section; metadata sections are optional, but a present one must hold a valid value.
273
+ * @throws ReplyError if there are no rules or a metadata section is invalid.
274
+ */
275
+ var parseReply = (text) => {
276
+ const raw = section(text, "datalog") ?? fenced(text);
277
+ if (raw === void 0) throw new ReplyError("missing-datalog", "reply has no <datalog> section");
278
+ const datalog = fenced(raw) ?? raw;
279
+ if (datalog.trim().length === 0) throw new ReplyError("empty-datalog", "the <datalog> section is empty");
280
+ const kind = section(text, "kind")?.trim().toLowerCase();
281
+ if (kind !== void 0 && !isKind(kind)) throw new ReplyError("invalid-kind", `unknown kind "${kind}"`);
282
+ const drivers = (section(text, "drivers") ?? "").split(/[,\s]+/).map((driver) => driver.trim().toLowerCase()).filter((driver) => driver.length > 0);
283
+ const unknown = drivers.filter((driver) => !isDriver(driver));
284
+ if (unknown.length > 0) throw new ReplyError("invalid-drivers", `unknown drivers ${unknown.map((driver) => `"${driver}"`).join(", ")}`);
285
+ const achievementText = section(text, "achievement")?.trim().toLowerCase();
286
+ if (achievementText !== void 0 && !isAchievement(achievementText)) throw new ReplyError("invalid-achievement", `unknown achievement "${achievementText}"`);
287
+ const notes = section(text, "notes")?.trim();
288
+ return {
289
+ ...kind !== void 0 && isKind(kind) ? { kind } : {},
290
+ drivers: [...new Set(drivers.filter(isDriver))],
291
+ ...achievementText !== void 0 && isAchievement(achievementText) ? { achievement: achievementText } : {},
292
+ datalog: datalog.trim(),
293
+ ...notes ? { notes } : {}
294
+ };
295
+ };
296
+ var section = (text, tag) => new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, "i").exec(text)?.[1];
297
+ var FENCE = /```[a-z]*\s*\n([\s\S]*?)```/i;
298
+ var fenced = (text) => FENCE.exec(text)?.[1];
299
+ var isKind = (value) => Schema.is(Kind)(value);
300
+ var isDriver = (value) => Schema.is(Driver)(value);
301
+ var isAchievement = (value) => Schema.is(Achievement)(value);
302
+ //#endregion
303
+ export { Achievement, BUILTIN_DOCS, Driver, EXAMPLES, FACT_RELATION_DOCS, GOAL_RELATION_DOCS, HEAD_DOCS, Kind, Reply, ReplyError, SYSTEM_PROMPT, parseReply, systemPrompt, CompilePrompt_exports as t, userMessage };
304
+
305
+ //# sourceMappingURL=CompilePrompt.mjs.map