pico-engine 1.9.4 → 1.10.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 (186) hide show
  1. package/README.md +13 -5
  2. package/demos/bootstrap/README.md +12 -0
  3. package/demos/bootstrap/com.example.visitors.bootstrap.krl +101 -0
  4. package/demos/bootstrap/com.example.visitors.format.krl +25 -0
  5. package/demos/bootstrap/com.example.visitors.krl +228 -0
  6. package/demos/bootstrap/try-it.md +5 -0
  7. package/demos/child_tasks/README.md +12 -0
  8. package/demos/child_tasks/com.example.task_runner.bootstrap.krl +88 -0
  9. package/demos/child_tasks/com.example.task_runner.krl +139 -0
  10. package/demos/child_tasks/com.example.task_worker.krl +45 -0
  11. package/demos/child_tasks/try-it.md +5 -0
  12. package/demos/collection/README.md +13 -0
  13. package/demos/collection/com.example.collection.bootstrap.krl +148 -0
  14. package/demos/collection/com.example.collection.krl +95 -0
  15. package/demos/collection/com.example.collection.report.krl +93 -0
  16. package/demos/collection/com.example.collection.room.krl +101 -0
  17. package/demos/collection/try-it.md +6 -0
  18. package/demos/echo/README.md +11 -0
  19. package/demos/echo/com.example.echo.bootstrap.krl +84 -0
  20. package/demos/echo/com.example.echo.krl +73 -0
  21. package/demos/echo/try-it.md +5 -0
  22. package/demos/guard_rules/README.md +12 -0
  23. package/demos/guard_rules/com.example.archive.bootstrap.krl +98 -0
  24. package/demos/guard_rules/com.example.archive.krl +213 -0
  25. package/demos/guard_rules/com.example.archive_store.krl +36 -0
  26. package/demos/guard_rules/try-it.md +5 -0
  27. package/demos/json_query/README.md +11 -0
  28. package/demos/json_query/com.example.json_query.bootstrap.krl +84 -0
  29. package/demos/json_query/com.example.json_query.krl +162 -0
  30. package/demos/json_query/try-it.md +5 -0
  31. package/demos/kblog/README.md +14 -0
  32. package/demos/kblog/com.example.kblog.bootstrap.krl +135 -0
  33. package/demos/kblog/com.example.kblog.config.krl +50 -0
  34. package/demos/kblog/com.example.kblog.data.krl +75 -0
  35. package/demos/kblog/com.example.kblog.krl +184 -0
  36. package/demos/kblog/com.example.kblog.posting.krl +109 -0
  37. package/demos/kblog/try-it.md +6 -0
  38. package/demos/layered_rulesets/README.md +13 -0
  39. package/demos/layered_rulesets/com.example.invitations.bootstrap.krl +87 -0
  40. package/demos/layered_rulesets/com.example.invitations.krl +164 -0
  41. package/demos/layered_rulesets/com.example.invitations.short_links.krl +45 -0
  42. package/demos/layered_rulesets/com.example.invitations.welcome.krl +39 -0
  43. package/demos/layered_rulesets/try-it.md +5 -0
  44. package/demos/moving_picos/README.md +15 -0
  45. package/demos/moving_picos/io.picolabs.club_gear_demo.krl +650 -0
  46. package/demos/moving_picos/io.picolabs.ride_coordinator_demo.krl +331 -0
  47. package/demos/score_tracker/README.md +11 -0
  48. package/demos/score_tracker/com.example.score_tracker.bootstrap.krl +107 -0
  49. package/demos/score_tracker/com.example.score_tracker.krl +162 -0
  50. package/demos/score_tracker/try-it.md +5 -0
  51. package/demos/secrets/README.md +12 -0
  52. package/demos/secrets/com.example.hook_service.krl +120 -0
  53. package/demos/secrets/com.example.notifier.bootstrap.krl +130 -0
  54. package/demos/secrets/com.example.notifier.krl +138 -0
  55. package/demos/secrets/try-it.md +5 -0
  56. package/demos/try-it-order.json +1 -0
  57. package/demos/two_picos/README.md +12 -0
  58. package/demos/two_picos/com.example.two_picos.answerer.krl +125 -0
  59. package/demos/two_picos/com.example.two_picos.asker.krl +124 -0
  60. package/demos/two_picos/com.example.two_picos.bootstrap.krl +134 -0
  61. package/demos/two_picos/try-it.md +5 -0
  62. package/demos/xmlui/README.md +17 -0
  63. package/demos/xmlui/com.example.contacts.krl +132 -0
  64. package/demos/xmlui/com.example.fav_color.krl +39 -0
  65. package/demos/xmlui/com.example.guestbook.krl +61 -0
  66. package/demos/xmlui/com.example.hello.krl +19 -0
  67. package/demos/xmlui/com.example.temperature_sensors_view.krl +105 -0
  68. package/demos/xmlui/com.example.thermostat.bootstrap.krl +95 -0
  69. package/demos/xmlui/com.example.thermostat.krl +124 -0
  70. package/demos/xmlui/temperature_sensors.krl +56 -0
  71. package/demos/xmlui/try-it.md +5 -0
  72. package/dist/bundledKrl.js +97 -12
  73. package/dist/cli.js +7 -1
  74. package/dist/engineConfig.js +20 -1
  75. package/dist/identity/portableMove.js +5 -1
  76. package/dist/index.js +45 -12
  77. package/dist/internalAccess.js +110 -0
  78. package/dist/oauth/OAuthService.js +172 -10
  79. package/dist/oauth/acg.js +194 -24
  80. package/dist/oauth/cimd.js +381 -0
  81. package/dist/oauth/discovery.js +175 -0
  82. package/dist/runMcp.js +1 -1
  83. package/dist/server.js +210 -47
  84. package/dist/subtreeWrangler.js +8 -5
  85. package/dist/uiChannelPolicies.js +2 -0
  86. package/krl/io.picolabs.pds.krl +109 -21
  87. package/krl/io.picolabs.pico-engine-ui.krl +13 -7
  88. package/krl/io.picolabs.wrangler.krl +21 -9
  89. package/krl/io.picolabs.xmlui.krl +3 -2
  90. package/mcp/devResources.js +52 -0
  91. package/mcp/devTools.js +40 -9
  92. package/mcp/docs/CLAUDE.md +6 -4
  93. package/mcp/docs/cookbook/README.md +23 -0
  94. package/mcp/docs/cookbook/bootstrap/README.md +23 -0
  95. package/mcp/docs/cookbook/bootstrap/instructions.md +75 -0
  96. package/mcp/docs/cookbook/child_tasks/README.md +20 -0
  97. package/mcp/docs/cookbook/child_tasks/instructions.md +60 -0
  98. package/mcp/docs/cookbook/collection/README.md +21 -0
  99. package/mcp/docs/cookbook/collection/instructions.md +93 -0
  100. package/mcp/docs/cookbook/echo/README.md +19 -0
  101. package/mcp/docs/cookbook/echo/instructions.md +59 -0
  102. package/mcp/docs/cookbook/guard_rules/README.md +22 -0
  103. package/mcp/docs/cookbook/guard_rules/instructions.md +73 -0
  104. package/mcp/docs/cookbook/json_query/README.md +26 -0
  105. package/mcp/docs/cookbook/json_query/instructions.md +64 -0
  106. package/mcp/docs/cookbook/kblog/README.md +60 -0
  107. package/mcp/docs/cookbook/kblog/instructions.md +102 -0
  108. package/mcp/docs/cookbook/layered_rulesets/README.md +24 -0
  109. package/mcp/docs/cookbook/layered_rulesets/instructions.md +87 -0
  110. package/mcp/docs/cookbook/moving_picos/README.md +44 -0
  111. package/mcp/docs/cookbook/moving_picos/instructions.md +150 -0
  112. package/mcp/docs/cookbook/score_tracker/README.md +19 -0
  113. package/mcp/docs/cookbook/score_tracker/instructions.md +73 -0
  114. package/mcp/docs/cookbook/secrets/README.md +25 -0
  115. package/mcp/docs/cookbook/secrets/instructions.md +98 -0
  116. package/mcp/docs/cookbook/two_picos/README.md +20 -0
  117. package/mcp/docs/cookbook/two_picos/instructions.md +88 -0
  118. package/mcp/docs/cookbook/xmlui/README.md +23 -0
  119. package/mcp/docs/cookbook/xmlui/instructions.md +84 -0
  120. package/mcp/docs/developing/README.md +28 -0
  121. package/mcp/docs/developing/accepting-relationship-requests.md +65 -0
  122. package/mcp/docs/developing/arrays-and-maps.md +77 -0
  123. package/mcp/docs/developing/converting-time-formats.md +28 -0
  124. package/mcp/docs/developing/cookies-and-redirects.md +81 -0
  125. package/mcp/docs/developing/decoding-form-data.md +67 -0
  126. package/mcp/docs/developing/engine-log-files.md +34 -0
  127. package/mcp/docs/developing/event-loop.md +77 -0
  128. package/mcp/docs/developing/events-from-email.md +80 -0
  129. package/mcp/docs/developing/initializing-entity-variables.md +83 -0
  130. package/mcp/docs/developing/mcp-ai-tools.md +98 -0
  131. package/mcp/docs/developing/misconceptions.md +467 -0
  132. package/mcp/docs/developing/names-and-scope.md +44 -0
  133. package/mcp/docs/developing/postman.md +159 -0
  134. package/mcp/docs/developing/querying-another-pico.md +47 -0
  135. package/mcp/docs/developing/singleton-picos.md +36 -0
  136. package/mcp/docs/developing/tabular-data.md +67 -0
  137. package/mcp/docs/developing/tips.md +251 -0
  138. package/mcp/docs/developing/webhook-signatures.md +56 -0
  139. package/mcp/docs/developing/workflow.md +106 -0
  140. package/mcp/docs/exp/README.md +46 -0
  141. package/mcp/docs/exp/event.md +110 -0
  142. package/mcp/docs/exp/query.md +94 -0
  143. package/mcp/docs/lessons/README.md +59 -0
  144. package/mcp/docs/lessons/events-and-queries.md +247 -0
  145. package/mcp/docs/lessons/gossip.md +28 -0
  146. package/mcp/docs/lessons/modules-and-apis.md +270 -0
  147. package/mcp/docs/lessons/pico-based-systems.md +470 -0
  148. package/mcp/docs/lessons/pico-state.md +267 -0
  149. package/mcp/docs/lessons/pico-views.md +290 -0
  150. package/mcp/docs/lessons/quickstart.md +157 -0
  151. package/mcp/docs/lessons/relationships.md +530 -0
  152. package/mcp/docs/lessons/scatter-gather.md +362 -0
  153. package/mcp/docs/pico-engine.md +10 -5
  154. package/mcp/docs/pico-overview.md +3 -3
  155. package/mcp/docs/wrangler/README.md +47 -0
  156. package/mcp/docs/wrangler/channels.md +235 -0
  157. package/mcp/docs/wrangler/oauth.md +56 -0
  158. package/mcp/docs/wrangler/pds.md +423 -0
  159. package/mcp/docs/wrangler/portable-subtree.md +44 -0
  160. package/mcp/docs/wrangler/relationships.md +297 -0
  161. package/mcp/docs/wrangler/wrangler.md +253 -0
  162. package/mcp/docs/wrangler/xmlui.md +60 -0
  163. package/mcp/engineClient.js +57 -5
  164. package/mcp/mcpScopes.js +118 -0
  165. package/mcp/meshHttp.js +151 -45
  166. package/mcp/runStdio.js +2 -0
  167. package/mcp/subtreeTools.js +184 -0
  168. package/mcp/tryItTools.js +202 -0
  169. package/package.json +18 -9
  170. package/public/.DS_Store +0 -0
  171. package/public/pico-engine-ui.css +1 -1
  172. package/public/pico-engine-ui.js +26 -25
  173. package/src/bundledKrl.ts +118 -12
  174. package/src/cli.ts +8 -2
  175. package/src/engineConfig.ts +33 -2
  176. package/src/identity/portableMove.ts +6 -1
  177. package/src/index.ts +469 -422
  178. package/src/internalAccess.ts +127 -0
  179. package/src/oauth/OAuthService.ts +243 -11
  180. package/src/oauth/acg.ts +289 -25
  181. package/src/oauth/cimd.ts +508 -0
  182. package/src/oauth/discovery.ts +233 -0
  183. package/src/runMcp.ts +3 -1
  184. package/src/server.ts +266 -51
  185. package/src/subtreeWrangler.ts +17 -5
  186. package/src/uiChannelPolicies.ts +2 -0
@@ -0,0 +1,331 @@
1
+ ruleset io.picolabs.ride_coordinator_demo {
2
+ meta {
3
+ name "Ride coordinator demo"
4
+ description <<
5
+ Portable-move demo setup for the Ride Coordinator mesh (install on the mesh root).
6
+
7
+ Install via flush — host dev:
8
+ file:///…/pico-engine/demos/io.picolabs.ride_coordinator_demo.krl
9
+ Docker (docker-compose.cross-engine.yml):
10
+ file:///var/pico-demos/moving_picos/io.picolabs.ride_coordinator_demo.krl
11
+
12
+ On install, creates a tagged demo channel (see demoState().demoEci). Raise setup,
13
+ sync, and cleanup on that channel — root default channels are too restrictive.
14
+
15
+ Setup — creates Ride Participants and opens a Layer 2 subscription to the bike
16
+ (bikeDid required; bikeName optional for Relationships tab label). Setup stops at
17
+ stage "connecting" — do not query
18
+ the bike during setup (cross-engine deadlock with sky_intro).
19
+
20
+ If the coordinator↔bike Layer 2 relationship already exists before export, it
21
+ should survive import (identity snapshot + SKY rotate + local peer reconcile) —
22
+ you only need setup/approve when forming a **new** relationship after import.
23
+
24
+ Manifold thing picos do not auto-accept **new** inbound relationships. When
25
+ setup is required, on the imported bike (thingQueryEci from import_portable_thing_done):
26
+ 1. Query io.picolabs.subscription:inbound() for pending "Ride Participants:…".
27
+ 2. raise wrangler event "pending_subscription_approval" attributes { "Id": "<Id>" }.
28
+
29
+ After approving the pending sub on the bike, raise ride_coordinator_demo event "sync"
30
+ on the demo channel (not listed in Testing — internal checkpoint; use Events or schedule).
31
+
32
+ Query ride_coordinator_demo:demoState() when ready is true (stage "done").
33
+ After cleanup, demoState() returns only stage "idle" and demoEci.
34
+ raise ride_coordinator_demo event "cleanup" to reset (discovers orphaned
35
+ Ride Participants children by name).
36
+ >>
37
+ author "PICOLABS"
38
+
39
+ use module io.picolabs.wrangler alias wrangler
40
+
41
+ shares demoState
42
+ }
43
+
44
+ global {
45
+ __testing = {
46
+ "queries": [
47
+ {"name": "demoState"}
48
+ ],
49
+ "events": [
50
+ {
51
+ "domain": "ride_coordinator_demo",
52
+ "name": "setup",
53
+ "attrs": ["bikeDid", "bikeName"]
54
+ },
55
+ {"domain": "ride_coordinator_demo", "name": "cleanup"}
56
+ ]
57
+ }
58
+
59
+ DEMO_CHANNEL_TAG = "ride_coordinator_demo"
60
+ PARTICIPANTS_NAME = "Ride Participants"
61
+
62
+ coordinatorLinkName = function(bikeName) {
63
+ label = bikeName.defaultsTo("bike")
64
+ PARTICIPANTS_NAME + ":" + label
65
+ }
66
+
67
+ demoEventPolicy = {
68
+ "allow": [
69
+ {"domain": "ride_coordinator_demo", "name": "*"},
70
+ {"domain": "wrangler", "name": "new_child_created"},
71
+ {"domain": "wrangler", "name": "new_child_request"},
72
+ {"domain": "wrangler", "name": "child_deletion_request"},
73
+ {"domain": "wrangler", "name": "child_deleted"}
74
+ ],
75
+ "deny": []
76
+ }
77
+
78
+ demoQueryPolicy = {
79
+ "allow": [{"rid": "*", "name": "*"}],
80
+ "deny": []
81
+ }
82
+
83
+ subscriptionEstablished = function() {
84
+ wrangler:picoQuery(
85
+ ent:participants_eci,
86
+ "io.picolabs.subscription",
87
+ "established",
88
+ {}
89
+ )
90
+ .filter(function(row) {
91
+ row{"Rx_role"} == "bike"
92
+ && row{"Tx_role"} == "ride_coordinator"
93
+ && row{"layer2"} == true
94
+ })
95
+ .length() > 0
96
+ }
97
+
98
+ participantsChildEci = function() {
99
+ wrangler:children()
100
+ .filter(function(child) { child{"name"} == PARTICIPANTS_NAME })
101
+ .head()
102
+ {"eci"}
103
+ }
104
+
105
+ participantsTargetEci = function() {
106
+ participantsChildEci()
107
+ .defaultsTo(ent:participants_eci)
108
+ .defaultsTo(ent:cleanup_participants_eci)
109
+ }
110
+
111
+ demoState = function() {
112
+ stage = ent:stage.defaultsTo("idle")
113
+ stage == "idle" =>
114
+ { "stage": "idle", "demoEci": ent:demo_eci } |
115
+ {
116
+ "ready": ent:ready == true,
117
+ "stage": stage,
118
+ "runId": ent:run_id,
119
+ "demoEci": ent:demo_eci,
120
+ "participantsEci": ent:participants_eci,
121
+ "participantsUiEci": ent:participants_ui_eci,
122
+ "bikeDid": ent:bike_did,
123
+ "bikeName": ent:bike_name,
124
+ "cleanupParticipantsEci": ent:cleanup_participants_eci,
125
+ "subscriptionName": coordinatorLinkName(ent:bike_name)
126
+ }
127
+ }
128
+ }
129
+
130
+ rule ensure_demo_channel {
131
+ select when wrangler ruleset_installed or engine started
132
+ where event:attr("rids").isnull() || event:attr("rids") >< meta:rid
133
+ pre {
134
+ demo_eci = wrangler:channels(DEMO_CHANNEL_TAG).head(){"id"}
135
+ }
136
+ if demo_eci.isnull() then every {
137
+ ctx:newChannel(
138
+ [DEMO_CHANNEL_TAG],
139
+ demoEventPolicy,
140
+ demoQueryPolicy
141
+ ) setting(new_channel)
142
+ }
143
+ fired {
144
+ ent:demo_eci := new_channel{"id"}
145
+ } else {
146
+ ent:demo_eci := demo_eci
147
+ }
148
+ }
149
+
150
+ rule setup_clear {
151
+ select when ride_coordinator_demo setup
152
+ where ent:stage.isnull() || ent:stage == "idle"
153
+ schedule:clear()
154
+ }
155
+
156
+ rule setup {
157
+ select when ride_coordinator_demo setup
158
+ where ent:stage.isnull() || ent:stage == "idle"
159
+ pre {
160
+ bike_did = event:attr("bikeDid")
161
+ bike_name = event:attr("bikeName")
162
+ }
163
+ fired {
164
+ ent:run_id := ent:run_id.defaultsTo(0) + 1
165
+ ent:demoHost := true
166
+ ent:ready := false
167
+ ent:stage := "creating"
168
+ ent:bike_did := bike_did
169
+ ent:bike_name := bike_name
170
+ ent:participants_eci := null
171
+ ent:participants_ui_eci := null
172
+ raise wrangler event "new_child_request" attributes {
173
+ "name": PARTICIPANTS_NAME,
174
+ "backgroundColor": "#C9A0DC"
175
+ }
176
+ }
177
+ }
178
+
179
+ rule on_participants_created {
180
+ select when wrangler new_child_created
181
+ where ent:demoHost == true
182
+ && ent:stage == "creating"
183
+ && event:attr("name") == PARTICIPANTS_NAME
184
+ pre {
185
+ logLine = {
186
+ "participantsEci": event:attr("eci"),
187
+ "bikeDid": ent:bike_did
188
+ }.encode().klog("ride_coordinator_demo participants_created")
189
+ }
190
+ fired {
191
+ ent:participants_eci := event:attr("eci")
192
+ ent:participants_ui_eci := event:attr("uiEci")
193
+ raise ride_coordinator_demo event "proceed_subscribe"
194
+ }
195
+ }
196
+
197
+ rule proceed_subscribe {
198
+ select when ride_coordinator_demo proceed_subscribe
199
+ where ent:demoHost == true
200
+ && ent:participants_eci
201
+ && ent:bike_did
202
+ pre {
203
+ logLine = {
204
+ "bikeDid": ent:bike_did,
205
+ "participantsEci": ent:participants_eci
206
+ }.encode().klog("ride_coordinator_demo proceed_subscribe")
207
+ }
208
+ if ent:bike_did then every {
209
+ event:send({
210
+ "eci": ent:participants_eci,
211
+ "domain": "wrangler",
212
+ "type": "subscription",
213
+ "attrs": {
214
+ "layer2": true,
215
+ "target_did": ent:bike_did,
216
+ "name": coordinatorLinkName(ent:bike_name),
217
+ "Tx_role": "ride_coordinator",
218
+ "Rx_role": "bike",
219
+ "channel_type": "Tx_Rx"
220
+ }
221
+ })
222
+ }
223
+ fired {
224
+ ent:stage := "connecting"
225
+ }
226
+ }
227
+
228
+ rule finish_subscription {
229
+ select when ride_coordinator_demo sync
230
+ where ent:demoHost == true
231
+ && ent:participants_eci
232
+ pre {
233
+ logLine = {
234
+ "established": subscriptionEstablished(),
235
+ "stage": ent:stage
236
+ }.encode().klog("ride_coordinator_demo finish_subscription")
237
+ }
238
+ fired {
239
+ ent:ready := subscriptionEstablished()
240
+ ent:stage := ent:ready == true => "done" | "connecting"
241
+ raise ride_coordinator_demo event "ready" attributes demoState()
242
+ if ent:ready == true
243
+ }
244
+ }
245
+
246
+ rule cleanup_clear {
247
+ select when ride_coordinator_demo cleanup
248
+ schedule:clear()
249
+ }
250
+
251
+ rule cleanup {
252
+ select when ride_coordinator_demo cleanup
253
+ fired {
254
+ raise ride_coordinator_demo event "cleanup_go"
255
+ }
256
+ }
257
+
258
+ rule cleanup_go {
259
+ select when ride_coordinator_demo cleanup_go
260
+ pre {
261
+ target_eci = participantsTargetEci()
262
+ logLine = {
263
+ "targetEci": target_eci,
264
+ "discoveredEci": participantsChildEci(),
265
+ "stage": ent:stage
266
+ }.encode().klog("ride_coordinator_demo cleanup start")
267
+ }
268
+ if target_eci then every {
269
+ event:send({
270
+ "eci": target_eci,
271
+ "domain": "wrangler",
272
+ "type": "cancel_subscriptions",
273
+ "attrs": {}
274
+ })
275
+ }
276
+ fired {
277
+ ent:stage := "cleaning"
278
+ ent:demoHost := null
279
+ ent:ready := null
280
+ ent:participants_eci := null
281
+ ent:participants_ui_eci := null
282
+ ent:bike_did := null
283
+ ent:bike_name := null
284
+ ent:cleanup_participants_eci := target_eci
285
+ raise wrangler event "child_deletion_request" attributes {
286
+ "eci": target_eci
287
+ }
288
+ }
289
+ }
290
+
291
+ rule cleanup_go_none {
292
+ select when ride_coordinator_demo cleanup_go
293
+ pre {
294
+ target_eci = participantsTargetEci()
295
+ }
296
+ if target_eci.isnull() then every {
297
+ noop()
298
+ }
299
+ fired {
300
+ raise ride_coordinator_demo event "cleanup_finish"
301
+ }
302
+ }
303
+
304
+ rule on_participants_deleted {
305
+ select when wrangler child_deleted
306
+ where ent:stage == "cleaning"
307
+ && ent:cleanup_participants_eci
308
+ && event:attr("eci") == ent:cleanup_participants_eci
309
+ pre {
310
+ logLine = event:attrs.encode().klog("ride_coordinator_demo participants_deleted")
311
+ }
312
+ fired {
313
+ raise ride_coordinator_demo event "cleanup_finish"
314
+ }
315
+ }
316
+
317
+ rule cleanup_finish {
318
+ select when ride_coordinator_demo cleanup_finish
319
+ fired {
320
+ ent:stage := "idle"
321
+ ent:demoHost := null
322
+ ent:ready := null
323
+ ent:run_id := null
324
+ ent:participants_eci := null
325
+ ent:participants_ui_eci := null
326
+ ent:bike_did := null
327
+ ent:bike_name := null
328
+ ent:cleanup_participants_eci := null
329
+ }
330
+ }
331
+ }
@@ -0,0 +1,11 @@
1
+ # Score tracker demo
2
+
3
+ One pico per contest. Contestants register, send points, and see a leaderboard. The app channel's policy lets them play without being able to change the pico.
4
+
5
+ - Overview: [`docs/cookbook/score_tracker/README.md`](../../docs/cookbook/score_tracker/README.md) (on the docs site: https://docs.picolabs.io/#/cookbook/score_tracker/)
6
+ - Instructions: [`docs/cookbook/score_tracker/instructions.md`](../../docs/cookbook/score_tracker/instructions.md)
7
+
8
+ | File | Shows |
9
+ |------|-------|
10
+ | `com.example.score_tracker.krl` | Registration and points rules, the `currentRanks` query, a leaderboard page, and a narrow app channel |
11
+ | `com.example.score_tracker.bootstrap.krl` | Sets up the demo on a new pico with three contestants; the **Try It!** tab runs it |
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Try It! bootstrap for the Score tracker demo. Install it on a new pico: it
3
+ * installs io.picolabs.xmlui and com.example.score_tracker, then registers
4
+ * three contestants and gives them points. tryIt() reports progress and links
5
+ * to the leaderboard.
6
+ *
7
+ * This ruleset does not use io.picolabs.xmlui as a module, because it is the
8
+ * one that installs it.
9
+ */
10
+ ruleset com.example.score_tracker.bootstrap {
11
+ meta {
12
+ name "Score tracker"
13
+ description "Shows entity variables keyed by id, returning new ids in directives, a sorted query, and a narrow app channel whose policy lets contestants play but not change the pico."
14
+ author "PICOLABS"
15
+
16
+ use module io.picolabs.wrangler alias wrangler
17
+
18
+ shares tryIt
19
+ }
20
+
21
+ global {
22
+ app_rid = "com.example.score_tracker"
23
+ xmlui_rid = "io.picolabs.xmlui"
24
+ contestants = [
25
+ {"pid": "ada", "first": "Ada", "last": "Lovelace"},
26
+ {"pid": "grace", "first": "Grace", "last": "Hopper"},
27
+ {"pid": "alan", "first": "Alan", "last": "Turing"}
28
+ ]
29
+ seed_points = [
30
+ {"pid": "grace", "points": "40", "descr": "Found the first bug"},
31
+ {"pid": "ada", "points": "30", "descr": "Wrote the first program"},
32
+ {"pid": "alan", "points": "25", "descr": "Broke a code"},
33
+ {"pid": "ada", "points": "15", "descr": "Explained the engine"}
34
+ ]
35
+
36
+ host = function() {
37
+ meta:host.defaultsTo("").replace(re#/$#, "")
38
+ }
39
+
40
+ /**
41
+ * Progress of this demo's setup, and the links to open when it is ready.
42
+ * @returns Map
43
+ */
44
+ tryIt = function() {
45
+ app = wrangler:channels(["score_tracker", "app"]).head()
46
+ ready = (ent:stage == "ready" && app) => true | false
47
+ status = {
48
+ "ready": ready,
49
+ "stage": ent:stage.defaultsTo("starting"),
50
+ "links": ready => [
51
+ {"label": "Leaderboard", "url": host() + "/ui/" + app{"id"} + "/" + app_rid + "/"}
52
+ ] | []
53
+ }
54
+ status
55
+ }
56
+ }
57
+
58
+ rule start {
59
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
60
+ pre {
61
+ has_xmlui = wrangler:installedRIDs() >< xmlui_rid
62
+ }
63
+ if not has_xmlui then noop()
64
+ fired {
65
+ raise wrangler event "install_ruleset_request" attributes
66
+ {"url": host() + "/krl/" + xmlui_rid + ".krl"}
67
+ }
68
+ else {
69
+ raise wrangler event "install_ruleset_request" attributes
70
+ {"absoluteURL": meta:rulesetURI, "rid": app_rid}
71
+ }
72
+ finally {
73
+ ent:stage := "installing"
74
+ raise wrangler event "new_channel_request" attributes {
75
+ "tags": ["try_it"],
76
+ "eventPolicy": {"allow": [], "deny": []},
77
+ "queryPolicy": {"allow": [{"rid": meta:rid, "name": "tryIt"}], "deny": []}
78
+ }
79
+ }
80
+ }
81
+
82
+ rule install_app {
83
+ select when wrangler ruleset_installed where event:attr("rids") >< xmlui_rid
84
+ always {
85
+ raise wrangler event "install_ruleset_request" attributes
86
+ {"absoluteURL": meta:rulesetURI, "rid": app_rid}
87
+ }
88
+ }
89
+
90
+ rule register_contestants {
91
+ select when wrangler ruleset_installed where event:attr("rids") >< app_rid
92
+ foreach contestants setting(c)
93
+ always {
94
+ raise score event "new_participant" attributes c
95
+ raise try_it event "contestants_registered" on final
96
+ }
97
+ }
98
+
99
+ rule add_points {
100
+ select when try_it contestants_registered
101
+ foreach seed_points setting(entry)
102
+ always {
103
+ raise score event "new_points" attributes entry
104
+ ent:stage := "ready" on final
105
+ }
106
+ }
107
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Score tracker: one pico per contest. People register with a first and last
3
+ * name and get a participant id, then send points with a description. The
4
+ * leaderboard ranks everyone by total.
5
+ *
6
+ * The app channel allows only score events and this ruleset's queries, so a
7
+ * contestant holding that channel can register and add points but cannot, for
8
+ * example, create child picos or install rulesets.
9
+ */
10
+ ruleset com.example.score_tracker {
11
+ meta {
12
+ name "Score tracker"
13
+ description "Keeps contestants' points and ranks them on a leaderboard."
14
+ author "PICOLABS"
15
+
16
+ use module io.picolabs.xmlui alias ui
17
+
18
+ shares currentRanks, participant, leaderboard
19
+ }
20
+
21
+ global {
22
+ channel_tags = ["score_tracker", "app"]
23
+
24
+ totalOf = function(p) {
25
+ p{"points"}.defaultsTo([])
26
+ .map(function(entry) { entry{"points"} })
27
+ .reduce(function(a, b) { a + b }, 0)
28
+ }
29
+
30
+ findByName = function(first, last) {
31
+ ent:participants.defaultsTo({}).values()
32
+ .filter(function(p) { p{"first"} == first && p{"last"} == last })
33
+ .head()
34
+ }
35
+
36
+ /**
37
+ * Everyone, highest total first, with a rank.
38
+ * @returns Array of { rank, pid, name, total, entries }
39
+ */
40
+ currentRanks = function() {
41
+ ent:participants.defaultsTo({}).values()
42
+ .map(function(p) {
43
+ {
44
+ "pid": p{"pid"},
45
+ "name": p{"first"} + " " + p{"last"},
46
+ "total": totalOf(p),
47
+ "entries": p{"points"}.defaultsTo([]).length()
48
+ }
49
+ })
50
+ .sort(function(a, b) { b{"total"} <=> a{"total"} })
51
+ .map(function(row, i) { row.put("rank", i + 1) })
52
+ }
53
+
54
+ /**
55
+ * One participant, with every entry.
56
+ * @param pid String "participant id"
57
+ * @returns Map
58
+ */
59
+ participant = function(pid) {
60
+ ent:participants{pid}
61
+ }
62
+
63
+ /**
64
+ * The leaderboard, with forms to register and to add points.
65
+ * @view "Leaderboard"
66
+ */
67
+ leaderboard = function() {
68
+ ranks_url = ui:query_url("currentRanks", meta:rid, meta:eci)
69
+ register_url = ui:event_url("score", "new_participant")
70
+ points_url = ui:event_url("score", "new_points")
71
+ <<
72
+ <Component name="Leaderboard"
73
+ var.pid="{sessionStorage.getItem('scoreTrackerPid')}"
74
+ var.me="{sessionStorage.getItem('scoreTrackerName')}">
75
+ <DataSource id="ranks" url="#{ranks_url}" headers="{appGlobals.auth}" />
76
+ <APICall id="register" method="post" url="#{register_url}" headers="{appGlobals.auth}" body="{$param}"
77
+ onSuccess="(result) => { pid = result.directives[0].options.pid; me = result.directives[0].options.name; sessionStorage.setItem('scoreTrackerPid', pid); sessionStorage.setItem('scoreTrackerName', me); ranks.refetch(); }" />
78
+ <APICall id="addPoints" method="post" url="#{points_url}" headers="{appGlobals.auth}" body="{$param}"
79
+ onSuccess="ranks.refetch()" />
80
+ <PicoTheme>
81
+ <Card title="Leaderboard" subtitle="{pid ? 'You are ' + me + '.' : 'Register to add points.'}" />
82
+ <Table data="{ranks}">
83
+ <Column bindTo="rank" header="Rank" />
84
+ <Column bindTo="name" header="Name" />
85
+ <Column bindTo="total" header="Points" />
86
+ <Column bindTo="entries" header="Entries" />
87
+ </Table>
88
+ <Form when="{!pid}" saveLabel="Register"
89
+ onSubmit="(data) => register.execute({first: data.firstName, last: data.lastName})">
90
+ <FormItem bindTo="firstName" label="First name" required="true" />
91
+ <FormItem bindTo="lastName" label="Last name" required="true" />
92
+ </Form>
93
+ <Form when="{pid}" saveLabel="Add points"
94
+ onSubmit="(data) => addPoints.execute({pid: pid, points: data.points, descr: data.descr})">
95
+ <FormItem bindTo="points" label="Points" type="integer" initialValue="10" />
96
+ <FormItem bindTo="descr" label="For" initialValue="Answered a question" />
97
+ </Form>
98
+ </PicoTheme>
99
+ </Component>
100
+ >>
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Register a contestant. Someone already registered under the same name
106
+ * gets their existing id back. The directive carries the id and name.
107
+ * @attr first String "first name"
108
+ * @attr last String "last name"
109
+ * @attr pid String optional "use this id instead of a generated one (seeding, tests)"
110
+ * @example "Ada" { "first": "Ada", "last": "Lovelace" }
111
+ */
112
+ rule new_participant {
113
+ select when score new_participant
114
+ first re#(.+)#
115
+ last re#(.+)#
116
+ setting(first, last)
117
+ pre {
118
+ existing = findByName(first, last)
119
+ pid = existing => existing{"pid"} | event:attr("pid") || random:uuid()
120
+ }
121
+ send_directive("registered", {
122
+ "pid": pid,
123
+ "name": first + " " + last,
124
+ "new": existing => false | true
125
+ })
126
+ always {
127
+ ent:participants{pid} := {"pid": pid, "first": first, "last": last, "points": []}
128
+ if not existing
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Add points for a registered contestant.
134
+ * @attr pid String "participant id from new_participant"
135
+ * @attr points Number "points to add (may be negative)"
136
+ * @attr descr String optional "what the points are for"
137
+ * @example "ten points" { "pid": "<pid>", "points": "10", "descr": "Answered a question" }
138
+ */
139
+ rule new_points {
140
+ select when score new_points
141
+ pid re#(.+)#
142
+ points re#^(-?\d+)$#
143
+ setting(pid, points)
144
+ pre {
145
+ p = ent:participants{pid}
146
+ descr = event:attr("descr") || "points"
147
+ }
148
+ if p then send_directive("points_added", {"pid": pid, "points": points.as("Number")})
149
+ fired {
150
+ ent:participants{[pid, "points"]} := p{"points"}.defaultsTo([])
151
+ .append({"points": points.as("Number"), "descr": descr, "time": time:now()})
152
+ }
153
+ else {
154
+ error warn <<score new_points: no participant #{pid}>>
155
+ }
156
+ }
157
+
158
+ rule create_app_channel {
159
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
160
+ ui:create_app_channel(channel_tags, ["score"], ["currentRanks", "participant", "leaderboard"], meta:rid)
161
+ }
162
+ }
@@ -0,0 +1,5 @@
1
+ - Open **Leaderboard**: Ada Lovelace, Grace Hopper, and Alan Turing, ranked by points.
2
+ - Register yourself, add points a few times, and watch your rank change. Open the page in a second browser window to play as someone else.
3
+ - In another window, register a name that's already on the board. You get that contestant's id back, not a second entry. Look at `new_participant` in the code to see why.
4
+ - Open the child pico's **Channels** tab. The `score_tracker, app` channel allows only `score` events and the leaderboard's queries. Anyone with that channel can play, but can't change the pico.
5
+ - Try it: send `wrangler/new_child_request` on that channel with `curl`. The pico refuses it.
@@ -0,0 +1,12 @@
1
+ # Configuration and secrets demo
2
+
3
+ How to get a secret into a ruleset without putting it in the code, how to keep a ruleset idle until it has one, and where secrets stay visible.
4
+
5
+ - Overview: [`docs/cookbook/secrets/README.md`](../../docs/cookbook/secrets/README.md) (on the docs site: https://docs.picolabs.io/#/cookbook/secrets/)
6
+ - Instructions: [`docs/cookbook/secrets/instructions.md`](../../docs/cookbook/secrets/instructions.md)
7
+
8
+ | File | Shows |
9
+ |------|-------|
10
+ | `com.example.notifier.krl` | Gets its webhook URL in an event, posts only once it has one (`where ent:webhook_url`), and never shares the URL. Has the Notifier page |
11
+ | `com.example.hook_service.krl` | Stands in for an outside webhook service; gets its token from install configuration (`meta:rulesetConfig`) and refuses posts without it. Has the Inbox page |
12
+ | `com.example.notifier.bootstrap.krl` | Sets up both, sends one message before configuring the notifier and one after; the **Try It!** tab runs it |