pico-engine 1.9.4 → 1.9.5

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 (84) hide show
  1. package/README.md +2 -0
  2. package/demos/bootstrap/README.md +12 -0
  3. package/demos/bootstrap/com.example.visitors.bootstrap.krl +97 -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 +85 -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 +81 -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 +95 -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/kblog/README.md +14 -0
  28. package/demos/kblog/com.example.kblog.bootstrap.krl +132 -0
  29. package/demos/kblog/com.example.kblog.config.krl +50 -0
  30. package/demos/kblog/com.example.kblog.data.krl +75 -0
  31. package/demos/kblog/com.example.kblog.krl +184 -0
  32. package/demos/kblog/com.example.kblog.posting.krl +109 -0
  33. package/demos/kblog/try-it.md +6 -0
  34. package/demos/layered_rulesets/README.md +13 -0
  35. package/demos/layered_rulesets/com.example.invitations.bootstrap.krl +84 -0
  36. package/demos/layered_rulesets/com.example.invitations.krl +164 -0
  37. package/demos/layered_rulesets/com.example.invitations.short_links.krl +45 -0
  38. package/demos/layered_rulesets/com.example.invitations.welcome.krl +39 -0
  39. package/demos/layered_rulesets/try-it.md +5 -0
  40. package/demos/moving_picos/README.md +15 -0
  41. package/demos/moving_picos/io.picolabs.club_gear_demo.krl +650 -0
  42. package/demos/moving_picos/io.picolabs.ride_coordinator_demo.krl +331 -0
  43. package/demos/score_tracker/README.md +11 -0
  44. package/demos/score_tracker/com.example.score_tracker.bootstrap.krl +104 -0
  45. package/demos/score_tracker/com.example.score_tracker.krl +162 -0
  46. package/demos/score_tracker/try-it.md +5 -0
  47. package/demos/secrets/README.md +12 -0
  48. package/demos/secrets/com.example.hook_service.krl +120 -0
  49. package/demos/secrets/com.example.notifier.bootstrap.krl +127 -0
  50. package/demos/secrets/com.example.notifier.krl +138 -0
  51. package/demos/secrets/try-it.md +5 -0
  52. package/demos/try-it-order.json +1 -0
  53. package/demos/two_picos/README.md +12 -0
  54. package/demos/two_picos/com.example.two_picos.answerer.krl +125 -0
  55. package/demos/two_picos/com.example.two_picos.asker.krl +124 -0
  56. package/demos/two_picos/com.example.two_picos.bootstrap.krl +131 -0
  57. package/demos/two_picos/try-it.md +5 -0
  58. package/demos/xmlui/README.md +17 -0
  59. package/demos/xmlui/com.example.contacts.krl +132 -0
  60. package/demos/xmlui/com.example.fav_color.krl +39 -0
  61. package/demos/xmlui/com.example.guestbook.krl +61 -0
  62. package/demos/xmlui/com.example.hello.krl +19 -0
  63. package/demos/xmlui/com.example.temperature_sensors_view.krl +105 -0
  64. package/demos/xmlui/com.example.thermostat.bootstrap.krl +92 -0
  65. package/demos/xmlui/com.example.thermostat.krl +124 -0
  66. package/demos/xmlui/temperature_sensors.krl +56 -0
  67. package/demos/xmlui/try-it.md +5 -0
  68. package/dist/bundledKrl.js +97 -12
  69. package/dist/cli.js +2 -0
  70. package/dist/engineConfig.js +19 -0
  71. package/dist/index.js +1 -0
  72. package/dist/server.js +14 -0
  73. package/krl/io.picolabs.xmlui.krl +3 -2
  74. package/mcp/docs/CLAUDE.md +3 -2
  75. package/mcp/docs/pico-engine.md +3 -0
  76. package/package.json +6 -3
  77. package/public/.DS_Store +0 -0
  78. package/public/pico-engine-ui.css +1 -1
  79. package/public/pico-engine-ui.js +23 -22
  80. package/src/bundledKrl.ts +118 -12
  81. package/src/cli.ts +2 -0
  82. package/src/engineConfig.ts +28 -0
  83. package/src/index.ts +8 -0
  84. package/src/server.ts +15 -0
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Hook service: stands in for an outside service that accepts webhook posts,
3
+ * such as a chat app. Its webhook URL carries a token, and that token is the
4
+ * secret: a post with the wrong token, or none, is refused.
5
+ *
6
+ * The token comes from the configuration this ruleset was installed with
7
+ * (meta:rulesetConfig), one of the two ways to get a secret into a ruleset.
8
+ * The other, an event, is how the notifier gets this URL.
9
+ */
10
+ ruleset com.example.hook_service {
11
+ meta {
12
+ name "Hook service"
13
+ description "Accepts webhook posts that carry its token and refuses the rest."
14
+ author "PICOLABS"
15
+
16
+ use module io.picolabs.wrangler alias wrangler
17
+ use module io.picolabs.xmlui alias ui
18
+
19
+ shares inbox, refused, inboxPage
20
+ }
21
+
22
+ global {
23
+ channel_tags = ["hook_service", "app"]
24
+ webhook_tags = ["hook_service", "webhook"]
25
+
26
+ token = function() {
27
+ meta:rulesetConfig{"token"}
28
+ }
29
+
30
+ /**
31
+ * Every message received with the right token, oldest first.
32
+ * @returns Array of { text, time }
33
+ */
34
+ inbox = function() {
35
+ ent:inbox.defaultsTo([])
36
+ }
37
+
38
+ /**
39
+ * How many posts were refused for a missing or wrong token.
40
+ * @returns Number
41
+ */
42
+ refused = function() {
43
+ ent:refused.defaultsTo(0)
44
+ }
45
+
46
+ /**
47
+ * The messages this service received.
48
+ * @view "Inbox"
49
+ */
50
+ inboxPage = function() {
51
+ inbox_url = ui:query_url("inbox", meta:rid, meta:eci)
52
+ refused_url = ui:query_url("refused", meta:rid, meta:eci)
53
+ <<
54
+ <Component name="InboxPage">
55
+ <DataSource id="messages" url="#{inbox_url}" headers="{appGlobals.auth}" pollIntervalInSeconds="2" />
56
+ <DataSource id="refused" url="#{refused_url}" headers="{appGlobals.auth}" pollIntervalInSeconds="2" />
57
+ <PicoTheme>
58
+ <Card title="Hook service inbox"
59
+ subtitle="{'Posts with the right token land here. Refused so far: ' + refused.value}" />
60
+ <Table data="{messages}">
61
+ <Column bindTo="text" header="Message" />
62
+ <Column bindTo="time" header="Received" />
63
+ </Table>
64
+ </PicoTheme>
65
+ </Component>
66
+ >>
67
+ }
68
+ }
69
+
70
+ /**
71
+ * A webhook post with the right token.
72
+ * @attr token String "must match this service's token"
73
+ * @attr text String "the message"
74
+ */
75
+ rule receive {
76
+ select when hook post where event:attr("token") == token()
77
+ pre {
78
+ text = event:attr("text") || ""
79
+ }
80
+ send_directive("received", {"text": text})
81
+ fired {
82
+ ent:inbox := inbox().append({"text": text, "time": time:now()})
83
+ }
84
+ }
85
+
86
+ rule refuse {
87
+ select when hook post where event:attr("token") != token()
88
+ send_directive("refused")
89
+ fired {
90
+ ent:refused := refused() + 1
91
+ }
92
+ }
93
+
94
+ rule installed {
95
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
96
+ every {
97
+ wrangler:createChannel(webhook_tags, {"allow": [{"domain": "hook", "name": "post"}], "deny": []}, {"allow": [], "deny": []})
98
+ ui:create_app_channel(channel_tags, [], ["inbox", "refused", "inboxPage"], meta:rid)
99
+ }
100
+ fired {
101
+ raise hook_service event "channels_created"
102
+ }
103
+ }
104
+
105
+ // Hand the webhook URL to the parent pico, the way a service shows you yours
106
+ // once. It travels in an event, so it is in the engine's logs from here on.
107
+ rule hand_out_webhook_url {
108
+ select when hook_service channels_created
109
+ pre {
110
+ channel = wrangler:channels(webhook_tags).head()
111
+ url = meta:host.replace(re#/$#, "") + "/sky/event/" + channel{"id"} + "/webhook/hook/post?token=" + token()
112
+ }
113
+ event:send({
114
+ "eci": wrangler:parent_eci(),
115
+ "domain": "hook_service",
116
+ "type": "webhook_url_issued",
117
+ "attrs": {"webhook_url": url}
118
+ })
119
+ }
120
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Try It! bootstrap for the Configuration and secrets demo. Install it on a new
3
+ * pico: it installs io.picolabs.xmlui and com.example.notifier here, and creates
4
+ * a Hook service child, installing com.example.hook_service there with a
5
+ * random token in its install configuration. The hook service hands back its
6
+ * webhook URL. The bootstrap sends one message before configuring the notifier
7
+ * (not sent), configures it with the URL, and sends another (delivered).
8
+ * tryIt() reports progress and links to both pages.
9
+ *
10
+ * This ruleset does not use io.picolabs.xmlui as a module, because it is the
11
+ * one that installs it.
12
+ */
13
+ ruleset com.example.notifier.bootstrap {
14
+ meta {
15
+ name "Configuration and secrets"
16
+ description "Shows getting secrets into a ruleset with install configuration or an event, keeping a rule idle with where until it is configured, keeping operator events off the app channel, and where secrets stay visible."
17
+ author "PICOLABS"
18
+
19
+ use module io.picolabs.wrangler alias wrangler
20
+
21
+ shares tryIt
22
+ }
23
+
24
+ global {
25
+ notifier_rid = "com.example.notifier"
26
+ hook_rid = "com.example.hook_service"
27
+ xmlui_rid = "io.picolabs.xmlui"
28
+
29
+ host = function() {
30
+ meta:host.defaultsTo("").replace(re#/$#, "")
31
+ }
32
+
33
+ inboxLink = function() {
34
+ channel = ent:hook_service
35
+ => wrangler:picoQuery(ent:hook_service, "io.picolabs.wrangler", "channels", {"tags": "hook_service,app"}).head()
36
+ | null
37
+ channel => {"label": "Hook service inbox", "url": host() + "/ui/" + channel{"id"} + "/" + hook_rid + "/"} | null
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(["notifier", "app"]).head()
46
+ ready = (ent:stage == "ready" && app) => true | false
47
+ links = ready => [
48
+ {"label": "Notifier", "url": host() + "/ui/" + app{"id"} + "/" + notifier_rid + "/"},
49
+ inboxLink()
50
+ ].filter(function(link) { link }) | []
51
+ status = {"ready": ready, "stage": ent:stage.defaultsTo("starting"), "links": links}
52
+ status
53
+ }
54
+ }
55
+
56
+ rule start {
57
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
58
+ pre {
59
+ has_xmlui = wrangler:installedRIDs() >< xmlui_rid
60
+ }
61
+ always {
62
+ ent:stage := "installing"
63
+ raise wrangler event "new_channel_request" attributes {
64
+ "tags": ["try_it"],
65
+ "eventPolicy": {"allow": [], "deny": []},
66
+ "queryPolicy": {"allow": [{"rid": meta:rid, "name": "tryIt"}], "deny": []}
67
+ }
68
+ raise wrangler event "install_ruleset_request" attributes
69
+ {"url": host() + "/krl/" + xmlui_rid + ".krl"}
70
+ if not has_xmlui
71
+ raise wrangler event "install_ruleset_request" attributes
72
+ {"absoluteURL": meta:rulesetURI, "rid": notifier_rid}
73
+ if has_xmlui
74
+ raise wrangler event "new_child_request" attributes
75
+ {"name": "Hook service", "secrets_demo": "hook_service", "backgroundColor": "#ffe0b2"}
76
+ }
77
+ }
78
+
79
+ rule install_notifier {
80
+ select when wrangler ruleset_installed where event:attr("rids") >< xmlui_rid
81
+ always {
82
+ raise wrangler event "install_ruleset_request" attributes
83
+ {"absoluteURL": meta:rulesetURI, "rid": notifier_rid}
84
+ }
85
+ }
86
+
87
+ // The hook service pico is set up: install its rulesets, with a new token in
88
+ // the install configuration.
89
+ rule set_up_hook_service {
90
+ select when wrangler child_initialized where event:attr("secrets_demo") == "hook_service"
91
+ pre {
92
+ child = event:attr("eci")
93
+ }
94
+ every {
95
+ event:send({
96
+ "eci": child,
97
+ "domain": "wrangler",
98
+ "type": "install_ruleset_request",
99
+ "attrs": {"url": host() + "/krl/" + xmlui_rid + ".krl"}
100
+ })
101
+ event:send({
102
+ "eci": child,
103
+ "domain": "wrangler",
104
+ "type": "install_ruleset_request",
105
+ "attrs": {"absoluteURL": meta:rulesetURI, "rid": hook_rid, "config": {"token": random:uuid()}}
106
+ })
107
+ }
108
+ always {
109
+ ent:hook_service := child
110
+ ent:stage := "setting up the hook service"
111
+ }
112
+ }
113
+
114
+ // The hook service handed out its webhook URL: show the notifier idle, then
115
+ // configure it, then send a message that is delivered.
116
+ rule configure_notifier {
117
+ select when hook_service webhook_url_issued
118
+ webhook_url re#(.+)#
119
+ setting(url)
120
+ always {
121
+ raise notifier event "message" attributes {"text": "Sent before the webhook was set"}
122
+ raise notifier_config event "new_webhook" attributes {"webhook_url": url}
123
+ raise notifier event "message" attributes {"text": "Hello from the notifier"}
124
+ ent:stage := "ready"
125
+ }
126
+ }
127
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Notifier: posts messages to a webhook. The webhook URL carries a secret, so
3
+ * it is not in this file. The pico's operator sends it in a
4
+ * notifier_config:new_webhook event, and until then the rule that posts is not
5
+ * selected (`where ent:webhook_url`). The ruleset can be installed on a working
6
+ * pico and does nothing until it is configured.
7
+ *
8
+ * The operator event is in its own domain. The app channel allows notifier
9
+ * events only, so the page can send messages but cannot change the webhook.
10
+ * Nothing this ruleset shares returns the URL itself.
11
+ */
12
+ ruleset com.example.notifier {
13
+ meta {
14
+ name "Notifier"
15
+ description "Posts messages to a webhook whose secret URL the operator sends in an event."
16
+ author "PICOLABS"
17
+
18
+ use module io.picolabs.xmlui alias ui
19
+
20
+ shares status, deliveries, notifierPage
21
+ }
22
+
23
+ global {
24
+ channel_tags = ["notifier", "app"]
25
+
26
+ masked = function(url) {
27
+ url => url.replace(re#token=.*$#, "token=(hidden)") | null
28
+ }
29
+
30
+ /**
31
+ * Whether the webhook is set, and where it points with its token hidden.
32
+ * @returns Map
33
+ */
34
+ status = function() {
35
+ result = {
36
+ "configured": ent:webhook_url => true | false,
37
+ "webhook": masked(ent:webhook_url),
38
+ "since": ent:configured_at,
39
+ "not_sent": ent:not_sent.defaultsTo(0)
40
+ }
41
+ result
42
+ }
43
+
44
+ /**
45
+ * Every post to the webhook and the HTTP status it got, oldest first.
46
+ * @returns Array of { text, status, time }
47
+ */
48
+ deliveries = function() {
49
+ ent:deliveries.defaultsTo([])
50
+ }
51
+
52
+ /**
53
+ * Send messages and see whether they were delivered.
54
+ * @view "Notifier"
55
+ */
56
+ notifierPage = function() {
57
+ status_url = ui:query_url("status", meta:rid, meta:eci)
58
+ deliveries_url = ui:query_url("deliveries", meta:rid, meta:eci)
59
+ message_url = ui:event_url("notifier", "message")
60
+ <<
61
+ <Component name="NotifierPage">
62
+ <DataSource id="status" url="#{status_url}" headers="{appGlobals.auth}" pollIntervalInSeconds="2" />
63
+ <DataSource id="deliveries" url="#{deliveries_url}" headers="{appGlobals.auth}" pollIntervalInSeconds="2" />
64
+ <APICall id="send" method="post" url="#{message_url}" headers="{appGlobals.auth}" body="{$param}"
65
+ onSuccess="status.refetch(); deliveries.refetch();" />
66
+ <PicoTheme>
67
+ <Card title="Notifier"
68
+ subtitle="{status.value.configured ? 'Posting to ' + status.value.webhook : 'Not configured: messages are not sent until the operator sets the webhook.'}" />
69
+ <Form saveLabel="Send" onSubmit="(data) => send.execute(data)">
70
+ <FormItem bindTo="text" label="Message" initialValue="The build finished" />
71
+ </Form>
72
+ <Text>{'Messages not sent because the webhook was not set: ' + status.value.not_sent}</Text>
73
+ <Table data="{deliveries}">
74
+ <Column bindTo="text" header="Message" />
75
+ <Column bindTo="status" header="HTTP status" />
76
+ <Column bindTo="time" header="Sent" />
77
+ </Table>
78
+ </PicoTheme>
79
+ </Component>
80
+ >>
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Set the webhook URL. It is a secret: send this event from the Testing tab
86
+ * or a script, not from a page.
87
+ * @attr webhook_url String "the webhook URL, with its token"
88
+ */
89
+ rule set_webhook {
90
+ select when notifier_config new_webhook
91
+ webhook_url re#^(https?://.+)$#
92
+ setting(url)
93
+ always {
94
+ ent:webhook_url := url
95
+ ent:configured_at := time:now()
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Forget the webhook URL. Messages stop being sent.
101
+ */
102
+ rule forget_webhook {
103
+ select when notifier_config webhook_forgotten
104
+ always {
105
+ ent:webhook_url := null
106
+ ent:configured_at := null
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Post a message to the webhook. Not selected until the webhook is set.
112
+ * @attr text String "the message"
113
+ * @example "build" { "text": "The build finished" }
114
+ */
115
+ rule notify {
116
+ select when notifier message where ent:webhook_url
117
+ pre {
118
+ text = event:attr("text") || "Hello from a pico"
119
+ }
120
+ http:post(ent:webhook_url, json = {"text": text}) setting(response)
121
+ fired {
122
+ ent:deliveries := deliveries().append({"text": text, "status": response{"status_code"}, "time": time:now()})
123
+ }
124
+ }
125
+
126
+ rule not_configured {
127
+ select when notifier message where not ent:webhook_url
128
+ send_directive("not sent", {"reason": "the webhook is not set"})
129
+ fired {
130
+ ent:not_sent := ent:not_sent.defaultsTo(0) + 1
131
+ }
132
+ }
133
+
134
+ rule create_app_channel {
135
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
136
+ ui:create_app_channel(channel_tags, ["notifier"], ["status", "deliveries", "notifierPage"], meta:rid)
137
+ }
138
+ }
@@ -0,0 +1,5 @@
1
+ - Open **Notifier**. It shows where it posts, with the token hidden. One message wasn't sent, because it came before the webhook was set. One was delivered.
2
+ - Open **Hook service inbox**: the delivered message. Send more from the Notifier page and watch them arrive.
3
+ - Find where the token is still visible. Open the Hook service pico (close this pico to see the tree). Its **Rulesets** tab shows the install configuration. Its **Logging** tab shows the token in the URL of every `hook:post`.
4
+ - Post to the webhook with a wrong token: copy the URL the Notifier shows, replace `(hidden)` with anything, and `curl -X POST` it. The inbox's **Refused** count goes up.
5
+ - Try to change the webhook from the Notifier page's channel: send `notifier_config/new_webhook` on it. The pico refuses it. Operator events are kept off the app channel.
@@ -0,0 +1 @@
1
+ ["echo", "score_tracker", "xmlui", "two_picos", "child_tasks", "guard_rules", "layered_rulesets", "collection", "secrets", "bootstrap", "kblog"]
@@ -0,0 +1,12 @@
1
+ # Two picos talking demo
2
+
3
+ Two picos, Alice and Bob, form a relationship. Bob asks Alice questions by querying her over it.
4
+
5
+ - Overview: [`docs/cookbook/two_picos/README.md`](../../docs/cookbook/two_picos/README.md) (on the docs site: https://docs.picolabs.io/#/cookbook/two_picos/)
6
+ - Instructions: [`docs/cookbook/two_picos/instructions.md`](../../docs/cookbook/two_picos/instructions.md)
7
+
8
+ | File | Shows |
9
+ |------|-------|
10
+ | `com.example.two_picos.answerer.krl` | Alice: shares `answer(question)`, accepts relationship requests from askers, and has a page to teach her facts |
11
+ | `com.example.two_picos.asker.krl` | Bob: asks for a relationship with Alice, asks her questions with `subscription:queryOnSub`, and keeps the conversation |
12
+ | `com.example.two_picos.bootstrap.krl` | Creates Alice and Bob as children of a new pico and introduces them; the **Try It!** tab runs it |
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Answerer (Alice): knows some facts and shares answer(question). Another pico
3
+ * reaches answer() through a relationship. This ruleset accepts relationship
4
+ * requests from an asker automatically.
5
+ */
6
+ ruleset com.example.two_picos.answerer {
7
+ meta {
8
+ name "Answerer"
9
+ description "Shares answers to questions over relationships, and accepts askers automatically."
10
+ author "PICOLABS"
11
+
12
+ use module io.picolabs.wrangler alias wrangler
13
+ use module io.picolabs.xmlui alias ui
14
+
15
+ shares answer, facts, factList, factsPage
16
+ }
17
+
18
+ global {
19
+ channel_tags = ["two_picos", "answerer"]
20
+ initial_facts = {
21
+ "name": "Alice",
22
+ "favorite color": "blue",
23
+ "cat": "Pixel",
24
+ "hometown": "Provo"
25
+ }
26
+
27
+ /**
28
+ * Everything this pico knows.
29
+ * @returns Map
30
+ */
31
+ facts = function() {
32
+ ent:facts.defaultsTo(initial_facts)
33
+ }
34
+
35
+ /**
36
+ * The facts as rows, sorted by topic.
37
+ * @returns Array of { topic, value }
38
+ */
39
+ factList = function() {
40
+ facts().keys().sort()
41
+ .map(function(topic) { {"topic": topic, "value": facts(){topic}} })
42
+ }
43
+
44
+ /**
45
+ * Answer a question by topic, such as "favorite color".
46
+ * @param question String "the topic to ask about"
47
+ * @returns String
48
+ */
49
+ answer = function(question) {
50
+ topic = question.defaultsTo("").lc()
51
+ known = facts(){topic}
52
+ known => "My " + topic + " is " + known + "." | "I don't know my " + topic + " yet."
53
+ }
54
+
55
+ /**
56
+ * What this pico knows, and a form to teach it more.
57
+ * @view "Facts"
58
+ */
59
+ factsPage = function() {
60
+ facts_url = ui:query_url("factList", meta:rid, meta:eci)
61
+ learn_url = ui:event_url("two_picos", "fact_learned")
62
+ <<
63
+ <Component name="FactsPage">
64
+ <DataSource id="known" url="#{facts_url}" headers="{appGlobals.auth}" />
65
+ <APICall id="learn" method="post" url="#{learn_url}" headers="{appGlobals.auth}" body="{$param}"
66
+ onSuccess="known.refetch()" />
67
+ <PicoTheme>
68
+ <Card title="What Alice knows"
69
+ subtitle="Bob reaches these through his relationship with Alice. Teach Alice something, then ask Bob to ask about it." />
70
+ <Table data="{known}">
71
+ <Column bindTo="topic" header="Topic" />
72
+ <Column bindTo="value" header="Answer" />
73
+ </Table>
74
+ <Form saveLabel="Teach Alice" onSubmit="(data) => learn.execute(data)">
75
+ <FormItem bindTo="topic" label="Topic" initialValue="favorite food" />
76
+ <FormItem bindTo="value" label="Answer" initialValue="pizza" />
77
+ </Form>
78
+ </PicoTheme>
79
+ </Component>
80
+ >>
81
+ }
82
+ }
83
+
84
+ // Accept a relationship request from an asker: in the request, this pico's
85
+ // role is answerer.
86
+ rule accept_asker {
87
+ select when wrangler inbound_pending_subscription_added
88
+ where event:attr("Rx_role") == "answerer"
89
+ always {
90
+ raise wrangler event "pending_subscription_approval" attributes event:attrs
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Learn a fact. Topics are lowercased.
96
+ * @attr topic String "what it is about"
97
+ * @attr value String "the answer"
98
+ * @example "food" { "topic": "favorite food", "value": "pizza" }
99
+ */
100
+ rule learn_fact {
101
+ select when two_picos fact_learned
102
+ topic re#(.+)#
103
+ value re#(.+)#
104
+ setting(topic, value)
105
+ always {
106
+ ent:facts{topic.lc()} := value
107
+ }
108
+ }
109
+
110
+ rule installed {
111
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
112
+ every {
113
+ ui:create_app_channel(channel_tags, ["two_picos"], ["answer", "facts", "factList", "factsPage"], meta:rid)
114
+ event:send({
115
+ "eci": wrangler:parent_eci(),
116
+ "domain": "two_picos",
117
+ "type": "child_ready",
118
+ "attrs": {"role": "answerer"}
119
+ })
120
+ }
121
+ always {
122
+ ent:facts := initial_facts
123
+ }
124
+ }
125
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Asker (Bob): when introduced to an answerer's well-known channel, asks for a
3
+ * relationship. Once the answerer accepts, it asks questions by calling the
4
+ * answerer's answer() over the relationship with subscription:queryOnSub, and
5
+ * keeps the conversation.
6
+ */
7
+ ruleset com.example.two_picos.asker {
8
+ meta {
9
+ name "Asker"
10
+ description "Asks another pico questions over a relationship and keeps the conversation."
11
+ author "PICOLABS"
12
+
13
+ use module io.picolabs.wrangler alias wrangler
14
+ use module io.picolabs.subscription alias subscription
15
+ use module io.picolabs.xmlui alias ui
16
+
17
+ shares conversation, conversationPage
18
+ }
19
+
20
+ global {
21
+ channel_tags = ["two_picos", "asker"]
22
+ answerer_rid = "com.example.two_picos.answerer"
23
+
24
+ /**
25
+ * Every question asked and the answer that came back, oldest first.
26
+ * @returns Array of { question, answer, time }
27
+ */
28
+ conversation = function() {
29
+ ent:conversation.defaultsTo([])
30
+ }
31
+
32
+ /**
33
+ * The conversation, and a form to ask another question.
34
+ * @view "Conversation"
35
+ */
36
+ conversationPage = function() {
37
+ conversation_url = ui:query_url("conversation", meta:rid, meta:eci)
38
+ ask_url = ui:event_url("two_picos", "ask")
39
+ <<
40
+ <Component name="ConversationPage">
41
+ <DataSource id="talk" url="#{conversation_url}" headers="{appGlobals.auth}" />
42
+ <APICall id="ask" method="post" url="#{ask_url}" headers="{appGlobals.auth}" body="{$param}"
43
+ onSuccess="talk.refetch()" />
44
+ <PicoTheme>
45
+ <Card title="Bob asks Alice"
46
+ subtitle="Each question is a query from Bob's pico to Alice's, over the relationship between them." />
47
+ <Table data="{talk}">
48
+ <Column bindTo="question" header="Bob asked" />
49
+ <Column bindTo="answer" header="Alice said" />
50
+ </Table>
51
+ <Form saveLabel="Ask Alice" onSubmit="(data) => ask.execute(data)">
52
+ <FormItem bindTo="question" label="Ask about" initialValue="cat" />
53
+ </Form>
54
+ </PicoTheme>
55
+ </Component>
56
+ >>
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Ask for a relationship with the answerer whose well-known channel this is.
62
+ * @attr wellKnown_Tx String "the answerer's wellKnown_Rx channel id"
63
+ */
64
+ rule introduce {
65
+ select when two_picos introduce
66
+ wellKnown_Tx re#(.+)#
67
+ setting(well_known)
68
+ always {
69
+ raise wrangler event "subscription" attributes {
70
+ "wellKnown_Tx": well_known,
71
+ "name": "Bob and Alice",
72
+ "Rx_role": "asker",
73
+ "Tx_role": "answerer"
74
+ }
75
+ }
76
+ }
77
+
78
+ // The answerer accepted: tell the parent, and ask a first question.
79
+ rule connected {
80
+ select when wrangler subscription_added
81
+ where event:attr("bus"){"Tx_role"} == "answerer"
82
+ event:send({
83
+ "eci": wrangler:parent_eci(),
84
+ "domain": "two_picos",
85
+ "type": "connected",
86
+ "attrs": {}
87
+ })
88
+ always {
89
+ raise two_picos event "ask" attributes {"question": "favorite color"}
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Ask the answerer about a topic and record the answer.
95
+ * @attr question String "the topic, such as favorite color"
96
+ * @example "cat" { "question": "cat" }
97
+ */
98
+ rule ask {
99
+ select when two_picos ask
100
+ question re#(.+)#
101
+ setting(question)
102
+ pre {
103
+ bus = subscription:established("Tx_role", "answerer").head()
104
+ reply = bus => subscription:queryOnSub(bus{"Id"}, answerer_rid, "answer", {"question": question})
105
+ | "(Bob has no relationship with an answerer yet.)"
106
+ }
107
+ always {
108
+ ent:conversation := conversation().append({"question": question, "answer": reply, "time": time:now()})
109
+ }
110
+ }
111
+
112
+ rule installed {
113
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
114
+ every {
115
+ ui:create_app_channel(channel_tags, ["two_picos"], ["conversation", "conversationPage"], meta:rid)
116
+ event:send({
117
+ "eci": wrangler:parent_eci(),
118
+ "domain": "two_picos",
119
+ "type": "child_ready",
120
+ "attrs": {"role": "asker"}
121
+ })
122
+ }
123
+ }
124
+ }