pico-engine 1.9.5 → 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 (126) hide show
  1. package/README.md +11 -5
  2. package/demos/bootstrap/com.example.visitors.bootstrap.krl +9 -5
  3. package/demos/child_tasks/com.example.task_runner.bootstrap.krl +10 -7
  4. package/demos/echo/com.example.echo.bootstrap.krl +10 -7
  5. package/demos/guard_rules/com.example.archive.bootstrap.krl +10 -7
  6. package/demos/json_query/README.md +11 -0
  7. package/demos/json_query/com.example.json_query.bootstrap.krl +84 -0
  8. package/demos/json_query/com.example.json_query.krl +162 -0
  9. package/demos/json_query/try-it.md +5 -0
  10. package/demos/kblog/com.example.kblog.bootstrap.krl +10 -7
  11. package/demos/layered_rulesets/com.example.invitations.bootstrap.krl +10 -7
  12. package/demos/score_tracker/com.example.score_tracker.bootstrap.krl +10 -7
  13. package/demos/secrets/com.example.notifier.bootstrap.krl +10 -7
  14. package/demos/try-it-order.json +1 -1
  15. package/demos/two_picos/com.example.two_picos.bootstrap.krl +5 -2
  16. package/demos/xmlui/com.example.thermostat.bootstrap.krl +10 -7
  17. package/dist/cli.js +5 -1
  18. package/dist/engineConfig.js +1 -1
  19. package/dist/identity/portableMove.js +5 -1
  20. package/dist/index.js +44 -12
  21. package/dist/internalAccess.js +110 -0
  22. package/dist/oauth/OAuthService.js +172 -10
  23. package/dist/oauth/acg.js +194 -24
  24. package/dist/oauth/cimd.js +381 -0
  25. package/dist/oauth/discovery.js +175 -0
  26. package/dist/runMcp.js +1 -1
  27. package/dist/server.js +197 -48
  28. package/dist/subtreeWrangler.js +8 -5
  29. package/dist/uiChannelPolicies.js +2 -0
  30. package/krl/io.picolabs.pds.krl +109 -21
  31. package/krl/io.picolabs.pico-engine-ui.krl +13 -7
  32. package/krl/io.picolabs.wrangler.krl +21 -9
  33. package/mcp/devResources.js +52 -0
  34. package/mcp/devTools.js +40 -9
  35. package/mcp/docs/CLAUDE.md +3 -2
  36. package/mcp/docs/cookbook/README.md +23 -0
  37. package/mcp/docs/cookbook/bootstrap/README.md +23 -0
  38. package/mcp/docs/cookbook/bootstrap/instructions.md +75 -0
  39. package/mcp/docs/cookbook/child_tasks/README.md +20 -0
  40. package/mcp/docs/cookbook/child_tasks/instructions.md +60 -0
  41. package/mcp/docs/cookbook/collection/README.md +21 -0
  42. package/mcp/docs/cookbook/collection/instructions.md +93 -0
  43. package/mcp/docs/cookbook/echo/README.md +19 -0
  44. package/mcp/docs/cookbook/echo/instructions.md +59 -0
  45. package/mcp/docs/cookbook/guard_rules/README.md +22 -0
  46. package/mcp/docs/cookbook/guard_rules/instructions.md +73 -0
  47. package/mcp/docs/cookbook/json_query/README.md +26 -0
  48. package/mcp/docs/cookbook/json_query/instructions.md +64 -0
  49. package/mcp/docs/cookbook/kblog/README.md +60 -0
  50. package/mcp/docs/cookbook/kblog/instructions.md +102 -0
  51. package/mcp/docs/cookbook/layered_rulesets/README.md +24 -0
  52. package/mcp/docs/cookbook/layered_rulesets/instructions.md +87 -0
  53. package/mcp/docs/cookbook/moving_picos/README.md +44 -0
  54. package/mcp/docs/cookbook/moving_picos/instructions.md +150 -0
  55. package/mcp/docs/cookbook/score_tracker/README.md +19 -0
  56. package/mcp/docs/cookbook/score_tracker/instructions.md +73 -0
  57. package/mcp/docs/cookbook/secrets/README.md +25 -0
  58. package/mcp/docs/cookbook/secrets/instructions.md +98 -0
  59. package/mcp/docs/cookbook/two_picos/README.md +20 -0
  60. package/mcp/docs/cookbook/two_picos/instructions.md +88 -0
  61. package/mcp/docs/cookbook/xmlui/README.md +23 -0
  62. package/mcp/docs/cookbook/xmlui/instructions.md +84 -0
  63. package/mcp/docs/developing/README.md +28 -0
  64. package/mcp/docs/developing/accepting-relationship-requests.md +65 -0
  65. package/mcp/docs/developing/arrays-and-maps.md +77 -0
  66. package/mcp/docs/developing/converting-time-formats.md +28 -0
  67. package/mcp/docs/developing/cookies-and-redirects.md +81 -0
  68. package/mcp/docs/developing/decoding-form-data.md +67 -0
  69. package/mcp/docs/developing/engine-log-files.md +34 -0
  70. package/mcp/docs/developing/event-loop.md +77 -0
  71. package/mcp/docs/developing/events-from-email.md +80 -0
  72. package/mcp/docs/developing/initializing-entity-variables.md +83 -0
  73. package/mcp/docs/developing/mcp-ai-tools.md +98 -0
  74. package/mcp/docs/developing/misconceptions.md +467 -0
  75. package/mcp/docs/developing/names-and-scope.md +44 -0
  76. package/mcp/docs/developing/postman.md +159 -0
  77. package/mcp/docs/developing/querying-another-pico.md +47 -0
  78. package/mcp/docs/developing/singleton-picos.md +36 -0
  79. package/mcp/docs/developing/tabular-data.md +67 -0
  80. package/mcp/docs/developing/tips.md +251 -0
  81. package/mcp/docs/developing/webhook-signatures.md +56 -0
  82. package/mcp/docs/developing/workflow.md +106 -0
  83. package/mcp/docs/exp/README.md +46 -0
  84. package/mcp/docs/exp/event.md +110 -0
  85. package/mcp/docs/exp/query.md +94 -0
  86. package/mcp/docs/lessons/README.md +59 -0
  87. package/mcp/docs/lessons/events-and-queries.md +247 -0
  88. package/mcp/docs/lessons/gossip.md +28 -0
  89. package/mcp/docs/lessons/modules-and-apis.md +270 -0
  90. package/mcp/docs/lessons/pico-based-systems.md +470 -0
  91. package/mcp/docs/lessons/pico-state.md +267 -0
  92. package/mcp/docs/lessons/pico-views.md +290 -0
  93. package/mcp/docs/lessons/quickstart.md +157 -0
  94. package/mcp/docs/lessons/relationships.md +530 -0
  95. package/mcp/docs/lessons/scatter-gather.md +362 -0
  96. package/mcp/docs/pico-engine.md +7 -5
  97. package/mcp/docs/pico-overview.md +3 -3
  98. package/mcp/docs/wrangler/README.md +47 -0
  99. package/mcp/docs/wrangler/channels.md +235 -0
  100. package/mcp/docs/wrangler/oauth.md +56 -0
  101. package/mcp/docs/wrangler/pds.md +423 -0
  102. package/mcp/docs/wrangler/portable-subtree.md +44 -0
  103. package/mcp/docs/wrangler/relationships.md +297 -0
  104. package/mcp/docs/wrangler/wrangler.md +253 -0
  105. package/mcp/docs/wrangler/xmlui.md +60 -0
  106. package/mcp/engineClient.js +57 -5
  107. package/mcp/mcpScopes.js +118 -0
  108. package/mcp/meshHttp.js +151 -45
  109. package/mcp/runStdio.js +2 -0
  110. package/mcp/subtreeTools.js +184 -0
  111. package/mcp/tryItTools.js +202 -0
  112. package/package.json +14 -8
  113. package/public/pico-engine-ui.js +26 -26
  114. package/src/cli.ts +6 -2
  115. package/src/engineConfig.ts +5 -2
  116. package/src/identity/portableMove.ts +6 -1
  117. package/src/index.ts +469 -430
  118. package/src/internalAccess.ts +127 -0
  119. package/src/oauth/OAuthService.ts +243 -11
  120. package/src/oauth/acg.ts +289 -25
  121. package/src/oauth/cimd.ts +508 -0
  122. package/src/oauth/discovery.ts +233 -0
  123. package/src/runMcp.ts +3 -1
  124. package/src/server.ts +252 -52
  125. package/src/subtreeWrangler.ts +17 -5
  126. package/src/uiChannelPolicies.ts +2 -0
@@ -0,0 +1,110 @@
1
+ # Event API (Sky)
2
+
3
+ Raise an event on a pico over HTTP. The channel in the URL identifies the pico; its event policy has to allow the domain and type. Rules that select on that event run, and their directives come back in the response.
4
+
5
+ Sky is the current [Event Exchange Protocol](/exp/) version; the path prefix is `/sky/event/…`.
6
+
7
+ ## URL
8
+
9
+ ```
10
+ /sky/event/<eci>/<eid>/<domain>/<type>
11
+ ```
12
+
13
+ | Part | Meaning |
14
+ |------|---------|
15
+ | `<eci>` | A channel on the pico. Make channels on the **Channels** tab, or have a ruleset create one when it is installed (see [Bootstrap and channels](/cookbook/bootstrap/)). |
16
+ | `<eid>` | An event id of your choosing, for your own tracing. Anything URL-safe works; `none` is common. When it isn't `none`, the engine also puts it in the event attributes as `__eid`. |
17
+ | `<domain>` | The event's domain (namespace). |
18
+ | `<type>` | The event's type (also called its name). |
19
+
20
+ The scheme is `http` or `https`. GET or POST both work; **POST is preferred**.
21
+
22
+ ```
23
+ /sky/event/<eci>/none/echo/message
24
+ ```
25
+
26
+ ## Attributes
27
+
28
+ Attributes further define the event. Send them:
29
+
30
+ - in the **query string** (GET or POST), or
31
+ - in a **POST body**, as `application/x-www-form-urlencoded` or `application/json`
32
+
33
+ When the same name appears in both, the body wins. A JSON body is an object of names to values:
34
+
35
+ ```json
36
+ {
37
+ "temperature": 67,
38
+ "node_id": "2392029d003a:1"
39
+ }
40
+ ```
41
+
42
+ ```sh
43
+ curl "http://localhost:3000/sky/event/<eci>/none/echo/message?input=hello"
44
+
45
+ curl -X POST "http://localhost:3000/sky/event/<eci>/none/echo/message" \
46
+ -H 'content-type: application/json' -d '{"input": "hello"}'
47
+ ```
48
+
49
+ Every event raised over HTTP also gets an attribute `_headers` with the request's HTTP headers, minus `Authorization`, `Proxy-Authorization`, `Cookie`, and `X-Pico-Internal`. Read one application cookie with `http:cookie(name)`. See [Cookies and redirects](/developing/cookies-and-redirects).
50
+
51
+ The parsed body is the event's attributes. The exact bytes are available as `event:raw_body()` only when the channel has `rawBody: true`, which is how a webhook signature is checked. See [Webhook signatures](/developing/webhook-signatures).
52
+
53
+ ## Response
54
+
55
+ The engine answers with JSON:
56
+
57
+ ```json
58
+ {
59
+ "eid": "…",
60
+ "directives": [
61
+ {
62
+ "type": "directive",
63
+ "name": "say",
64
+ "options": { "something": "hello" },
65
+ "meta": { "rid": "com.example.echo", "rule_name": "echo", "txnId": "…" }
66
+ }
67
+ ],
68
+ "ruleOutcomes": [
69
+ { "rid": "com.example.echo", "rule": "echo", "status": "fired" }
70
+ ],
71
+ "events": [
72
+ { "domain": "…", "name": "…", "attrs": { } }
73
+ ]
74
+ }
75
+ ```
76
+
77
+ | Field | Meaning |
78
+ |-------|---------|
79
+ | `eid` | The transaction id the engine assigned this event |
80
+ | `directives` | Directives from rules that ran (`send_directive`, and the special `_cookie` / `_redirect` names) |
81
+ | `ruleOutcomes` | Which rules fired, did not fire, or were not selected (when the engine records them) |
82
+ | `events` | Events raised during the same transaction (not the ingress event). Omitted when there were none |
83
+
84
+ A channel that doesn't allow the event answers with HTTP 200 and `{"error":"Error: Not allowed by channel policy"}`. On a mesh with [OAuth](/wrangler/oauth) turned on, a missing or bad bearer token is refused before the channel policy runs.
85
+
86
+ ### Special directives
87
+
88
+ Two directive names change the HTTP response itself, instead of only appearing in the JSON:
89
+
90
+ | Directive | Effect |
91
+ |-----------|--------|
92
+ | `_cookie` | Adds a `Set-Cookie` header from `options.cookie` |
93
+ | `_redirect` | Answers with HTTP 302 and `Location: options.url` |
94
+
95
+ Details and examples: [Cookies and redirects](/developing/cookies-and-redirects).
96
+
97
+ ## From KRL
98
+
99
+ To raise an event on another pico (or this one), use `event:send` with an ECI, or `wrangler:picoQuery` / relationships for higher-level patterns. See the [event library](/krl/libraries/event) and [Wrangler](/wrangler/).
100
+
101
+ ## See also
102
+
103
+ - [Event Exchange Protocol](/exp/) — overview
104
+ - [Query API](/exp/query) — call a shared function
105
+ - [Echo](/cookbook/echo/) — a demo that raises events and shows directives
106
+ - [OpenAPI](/openapi.yaml) — machine-readable routes
107
+
108
+ ---
109
+
110
+ <small>Ported from the [Pico Labs wiki](https://picolabs.atlassian.net/wiki/spaces/docs/pages/1189909/Sky+Event+API) (last edited there 2022-02-24), and updated for this engine.</small>
@@ -0,0 +1,94 @@
1
+ # Query API (Sky)
2
+
3
+ Call a shared function on a pico over HTTP and get its return value. The channel in the URL identifies the pico; its query policy has to allow that ruleset and function. Which functions exist is up to the ruleset: the query API is a meta-API that every ruleset extends by listing names in `shares`.
4
+
5
+ Use it together with the [Event API](/exp/event): events change a pico's state; queries read it. Sky is the current [Event Exchange Protocol](/exp/) version; the path prefix is `/sky/query/…`.
6
+
7
+ ## URL
8
+
9
+ ```
10
+ /sky/query/<eci>/<rid>/<function>?<arguments>
11
+ ```
12
+
13
+ | Part | Meaning |
14
+ |------|---------|
15
+ | `<eci>` | A channel on the pico |
16
+ | `<rid>` | The ruleset id that shares the function. If that ruleset isn't installed on the pico, the response is a JSON object with an `error` field |
17
+ | `<function>` | The name of a function listed in that ruleset's `shares` |
18
+ | arguments | The function's parameters, by name. Order does not matter |
19
+
20
+ The scheme is `http` or `https`. GET or POST both work. Arguments go in the query string, or in a POST body as form-encoded or JSON (same rules as [event attributes](/exp/event): the body wins when a name appears in both).
21
+
22
+ ```sh
23
+ curl "http://localhost:3000/sky/query/<eci>/com.example.echo/hello?name=Ada"
24
+
25
+ curl -X POST "http://localhost:3000/sky/query/<eci>/com.example.json_query/runQuery" \
26
+ -H 'content-type: application/json' -d '{"path": "$.vehicles[*].name"}'
27
+ ```
28
+
29
+ `/sky/cloud/...` is a legacy alias for the same handler. Prefer `/sky/query/`.
30
+
31
+ Every query also gets an argument `_headers` with the request's HTTP headers, minus `Authorization`, `Proxy-Authorization`, `Cookie`, and `X-Pico-Internal`. Read one application cookie with `http:cookie(name)`.
32
+
33
+ ## Response
34
+
35
+ The body is the function's return value, as JSON (`Content-Type: application/json`). A channel that doesn't allow the query answers with HTTP 200 and `{"error":"Error: Not allowed by channel policy"}`. On a mesh with [OAuth](/wrangler/oauth) turned on, a missing or bad bearer token is refused first.
36
+
37
+ ### Text and HTML
38
+
39
+ Add `.txt` or `.html` to the function name and the engine returns the string the function produced, with that content type:
40
+
41
+ ```krl
42
+ page = function() {
43
+ <<<h1>Hello from a pico</h1>
44
+ >>
45
+ }
46
+ ```
47
+
48
+ `/sky/query/<eci>/<rid>/page.html` shows a heading in a browser. `/sky/query/<eci>/<rid>/page.txt` shows the markup as text. For whole interactive pages, use a [pico view](/pico-views) instead.
49
+
50
+ ## Preparing a ruleset
51
+
52
+ List the functions you want callable in `shares`. Only functions can be shared; wrap a constant in a parameterless function if you need to return a fixed value:
53
+
54
+ ```krl
55
+ ruleset com.example.thermostat {
56
+ meta {
57
+ name "Thermostat"
58
+ shares mode, temperature
59
+ }
60
+ global {
61
+ mode = function() {
62
+ ent:mode.defaultsTo("off")
63
+ }
64
+ temperature = function(room) {
65
+ ent:rooms{room}{"temp"}
66
+ }
67
+ }
68
+ }
69
+ ```
70
+
71
+ Then:
72
+
73
+ ```
74
+ GET /sky/query/<eci>/com.example.thermostat/temperature?room=bedroom
75
+ ```
76
+
77
+ Parameter names in the URL (or JSON body) must match the function's parameter names. Good parameter names make a clearer HTTP API.
78
+
79
+ The channel's query policy must allow that rid and name. App channels created with `ui:create_app_channel` allow the shared functions you pass them; see [Pico views](/pico-views) and [Bootstrap and channels](/cookbook/bootstrap/).
80
+
81
+ ## From KRL
82
+
83
+ To query another pico from a ruleset, use `wrangler:picoQuery` (works over family channels and relationships). Prefer that over building an `http:get` to `/sky/query/` yourself. See [Querying another pico](/developing/querying-another-pico) and [Wrangler](/wrangler/).
84
+
85
+ ## See also
86
+
87
+ - [Event Exchange Protocol](/exp/) — overview
88
+ - [Event API](/exp/event) — raise an event
89
+ - [Querying JSON](/cookbook/json_query/) — a demo that calls a shared function from a page
90
+ - [OpenAPI](/openapi.yaml) — machine-readable routes
91
+
92
+ ---
93
+
94
+ <small>Ported from the [Pico Labs wiki](https://picolabs.atlassian.net/wiki/spaces/docs/pages/1186084/Sky+Query+API) (last edited there 2025-07-11), and updated for this engine.</small>
@@ -0,0 +1,59 @@
1
+ # Pico Programming Lessons
2
+
3
+ Short, hands-on lessons that take you from a fresh install to systems of cooperating picos. Each one builds on the last: you write KRL, install it in a running engine, and watch what the pico does.
4
+
5
+ ## Before you begin
6
+
7
+ Start with the [Quickstart](/lessons/quickstart). It installs the engine, registers your passkey, and gets a first ruleset running. You need [Node.js](https://nodejs.org/) 20 or later.
8
+
9
+ ## The lessons
10
+
11
+ Do them in order. Each one assumes what the earlier ones taught.
12
+
13
+ | # | Lesson | You learn |
14
+ |---|--------|-----------|
15
+ | 1 | [Quickstart](/lessons/quickstart) | Install and run the engine, meet your root pico, install and flush `hello_world` |
16
+ | 2 | [Events and Queries](/lessons/events-and-queries) | Channels and policies, sending events and queries over HTTP, the Testing and Logging tabs, `klog` |
17
+ | 3 | [Pico State](/lessons/pico-state) | Entity variables, `defaultsTo` and `\|\|`, maps with path assignment, `clear` |
18
+ | 4 | [Modules and External APIs](/lessons/modules-and-apis) | `use module`, `provides`, `configure using`, calling web APIs, secrets in install configuration |
19
+ | 5 | [Pico views](/lessons/pico-views) | Giving a pico a web page of its own |
20
+ | 6 | [Pico-Based Systems](/lessons/pico-based-systems) | Children, and systems made of many picos |
21
+ | 7 | [Relationships](/lessons/relationships) | Picos that stay connected over time, and how they talk (called subscriptions in older material) |
22
+ | 8 | [Scatter-Gather](/lessons/scatter-gather) | Asking many picos at once and combining their answers |
23
+ | 9 | [Gossip Lab](/lessons/gossip) | Optional pointer to the BYU CS 462 gossip lab (video only here) |
24
+
25
+ Complete lessons 1 through 7 in order. **Scatter-Gather** is an optional advanced pattern lesson. The **Gossip Lab** page is only a pointer to the course video; the assignment itself isn't in these docs.
26
+
27
+ > **A note on names.** These lessons say **relationships**. Older lessons, blog posts, and the KRL module that implements them, `io.picolabs.subscription`, say *subscriptions*. They're the same thing; the module name stays for compatibility. See [Relationships](/wrangler/relationships).
28
+
29
+ ## How the lessons work
30
+
31
+ - **Run everything.** Each lesson has code to install and things to try. Use the developer UI at `http://localhost:3000` or `curl`.
32
+ - **The Testing tab builds forms from the ruleset's schema**, which comes from `/** … */` doc comments on rules and functions. You'll see `@attr`, `@param`, and `@example` in the lessons' KRL.
33
+ - **Use wrangler.** Picos create children and channels through [wrangler](/wrangler/) events and functions, not by reaching into the engine.
34
+ - **Check your KRL.** `krl-check`, in the `krl-compiler` package, finds errors before you install. See [Tips](/developing/tips).
35
+
36
+ ## Runnable examples beside the lessons
37
+
38
+ The [Cookbook](/cookbook/) has demos you can run in a new child pico with one click, from the **Try It!** tab on your root pico. They're a good parallel to the lessons:
39
+
40
+ | After | Try |
41
+ |-------|-----|
42
+ | [Quickstart](/lessons/quickstart) and [Events and Queries](/lessons/events-and-queries) | [Echo](/cookbook/echo/): a rule answers an event with a directive, from a page or from `curl` |
43
+ | [Pico State](/lessons/pico-state) | [Score tracker](/cookbook/score_tracker/): a contest pico with a leaderboard kept in entity variables |
44
+ | [Modules and External APIs](/lessons/modules-and-apis) | [Configuration and secrets](/cookbook/secrets/), and [Bootstrap and channels](/cookbook/bootstrap/) |
45
+ | [Pico views](/lessons/pico-views) | [Pico view demos](/cookbook/xmlui/) |
46
+ | [Pico-Based Systems](/lessons/pico-based-systems) | [Child pico tasks](/cookbook/child_tasks/) |
47
+ | [Relationships](/lessons/relationships) | [Two picos talking](/cookbook/two_picos/) and [Collection](/cookbook/collection/) |
48
+
49
+ ## Reference while you work
50
+
51
+ - [Persistent Compute Objects](/pico-overview): what picos are and why
52
+ - [Pico Engine](/pico-engine): installing, configuring, and operating the engine
53
+ - [KRL manual](/krl/)
54
+ - [Event Exchange Protocol](/exp/): the HTTP event and query APIs
55
+ - [Developing with Picos](/developing/)
56
+
57
+ ---
58
+
59
+ <small>Ported from the [Pico Labs wiki](https://picolabs.atlassian.net/wiki/spaces/docs/pages/1185969/Pico+Programming+Lessons) (last edited there 2023-10-10), and updated for this engine.</small>
@@ -0,0 +1,247 @@
1
+ # Events and Queries
2
+
3
+ Picos do two things for the world outside them: they react to **events**, and they answer **queries**. This lesson makes both real. You'll give a pico its own channel, send it events and queries with a browser, `curl`, and the Testing tab, and watch what happens in the Logging tab.
4
+
5
+ ## Objectives
6
+
7
+ When you finish you will be able to:
8
+
9
+ - explain the difference between an event and a query, and why picos separate them
10
+ - create a channel with tags and a policy
11
+ - send an event and a query to a pico over HTTP
12
+ - add `klog` to a rule and read the output in the Logging tab
13
+ - tell why a request was refused
14
+
15
+ **Before you begin**, finish the [Quickstart](/lessons/quickstart). You need a running engine and a pico with `io.picolabs.hello_world` installed.
16
+
17
+ ## Motivation: events change things, queries read them
18
+
19
+ Most web APIs are request-response: you call a function and it returns a value, and who knows what else happened. Picos split that in two:
20
+
21
+ | | Event | Query |
22
+ |--|-------|-------|
23
+ | Means | "Something happened. React if you care." | "Tell me something." |
24
+ | Changes the pico's state? | May | Never |
25
+ | Answered by | Zero, one, or many **rules**, each selecting events by domain and type | One **function** the ruleset lists in `shares` |
26
+ | Returns | **Directives** from the rules that ran | The function's return value |
27
+
28
+ The sender of an event doesn't name a function to run. It reports what happened, and the rules installed on the pico decide whether to react, and how. That lets you add behavior to a pico by installing another ruleset, without changing the sender. A query is a plain read: because it can't change state, it's safe to repeat and to cache. The engine enforces the split: functions can't write persistent state, only rules can.
29
+
30
+ Both kinds of traffic arrive on a **channel**. For the full model, see the [Event Exchange Protocol](/exp/) and the overview in [Persistent Compute Objects](/pico-overview).
31
+
32
+ ## Channels
33
+
34
+ A channel is a communication path to one pico, identified by its **ECI** (event channel identifier), a unique string. Anyone who has the ECI and can reach the engine can use the channel, so an ECI works like a key. Each channel has:
35
+
36
+ - **tags**, a short list of words so you can find the channel later without remembering the ECI
37
+ - an **event policy** and a **query policy**, which list the events and queries the channel will accept. Anything not allowed is refused. This is how a pico limits what each party can do.
38
+
39
+ Your pico already has channels the engine made for it. The developer UI uses one, and the Testing tab sends on it. You'll make a new one for outside callers. The [Managing channels](/wrangler/channels) page has the whole story.
40
+
41
+ ### Create a channel for hello_world
42
+
43
+ <img src="/lessons/_media/19791904-root-pico-channels.png" alt="The Channels tab before creating a new channel" width="50%">
44
+
45
+ 1. Open your pico and click its **Channels** tab.
46
+ 2. In the **New Channel** form, leave **Channel id (ECI)** blank to let the engine pick one. (You can choose your own, at least 12 characters of letters, digits, hyphen or underscore, but it can't be changed later.)
47
+ 3. Set **Tags** to `hello, lesson`.
48
+ 4. Set **Event Policy** to:
49
+
50
+ ```json
51
+ {
52
+ "allow": [{"domain": "echo", "name": "hello"}],
53
+ "deny": []
54
+ }
55
+ ```
56
+
57
+ 5. Set **Query Policy** to:
58
+
59
+ ```json
60
+ {
61
+ "allow": [{"rid": "io.picolabs.hello_world", "name": "hello"}],
62
+ "deny": []
63
+ }
64
+ ```
65
+
66
+ 6. Click **Add**. The new channel appears in the list, with its ECI. Copy it.
67
+
68
+ <img src="/lessons/_media/19791904-root-pico-channels2.png" alt="The New Channel form with tags, an event policy, and a query policy filled in" width="50%">
69
+
70
+ <img src="/lessons/_media/19791904-root-pico-channels3.png" alt="The Channels tab listing the new channel, tagged hello_world, with its event and query policy" width="50%">
71
+
72
+ The policy says this channel accepts one event, `echo:hello`, and one query, the `hello` function of `io.picolabs.hello_world`. Use `"*"` to match anything, for instance `{"domain": "echo", "name": "*"}` allows every `echo` event. A rule in `deny` always wins over `allow`.
73
+
74
+ From here on, `<eci>` means the ECI you copied and `http://localhost:3000` is your engine's address.
75
+
76
+ ## Send an event
77
+
78
+ The Event API URL is:
79
+
80
+ ```
81
+ /sky/event/<eci>/<eid>/<domain>/<type>
82
+ ```
83
+
84
+ `<eid>` is an event id you choose, for your own tracing. `none` is common. Attributes go in the query string, or in a POST body as form data or JSON. [Event API](/exp/event) has the details.
85
+
86
+ From a terminal:
87
+
88
+ ```sh
89
+ curl -X POST "http://localhost:3000/sky/event/<eci>/none/echo/hello?name=Ada"
90
+ ```
91
+
92
+ or with a JSON body:
93
+
94
+ ```sh
95
+ curl -X POST "http://localhost:3000/sky/event/<eci>/none/echo/hello" \
96
+ -H 'content-type: application/json' -d '{"name": "Ada"}'
97
+ ```
98
+
99
+ You get JSON back:
100
+
101
+ ```json
102
+ {
103
+ "eid": "…",
104
+ "directives": [
105
+ {
106
+ "type": "directive",
107
+ "name": "say",
108
+ "options": {"something": "Hello ADA"},
109
+ "meta": {"rid": "io.picolabs.hello_world", "rule_name": "hello_world", "txnId": "…"}
110
+ }
111
+ ],
112
+ "ruleOutcomes": [
113
+ {"rid": "io.picolabs.hello_world", "rule": "hello_world", "status": "fired"}
114
+ ]
115
+ }
116
+ ```
117
+
118
+ Those are the **directives** from every rule the event ran. The sender asked nothing of a function: the rule `hello_world` selected the event and answered with `say`.
119
+
120
+ <img src="/lessons/_media/19791904-echo-hello.png" alt="The directives returned by an echo:hello event, shown in a browser" width="50%">
121
+
122
+ GET works too, so you can paste the URL in a browser, but **POST is preferred** for events because an event can change state.
123
+
124
+ Now try the things that should fail:
125
+
126
+ - Send `echo:goodbye`. The channel's policy doesn't allow it, so you get `{"error":"Error: Not allowed by channel policy"}`. The rule never saw the event.
127
+ - Send `echo:hello` with no `name`. The rule runs with its default, and says `Hello WORLD`.
128
+
129
+ ## Send a query
130
+
131
+ The Query API URL is:
132
+
133
+ ```
134
+ /sky/query/<eci>/<rid>/<function>?<arguments>
135
+ ```
136
+
137
+ `<rid>` is the ruleset id, and `<function>` has to be listed in that ruleset's `shares`. Arguments are the function's parameters by name:
138
+
139
+ ```sh
140
+ curl "http://localhost:3000/sky/query/<eci>/io.picolabs.hello_world/hello?name=Ada"
141
+ ```
142
+
143
+ The answer is the return value: `"Hello Ada"`. Leave off `name` and the function's default gives `"Hello world"`. Query details are in [Query API](/exp/query).
144
+
145
+ <img src="/lessons/_media/19791904-root-pico-testing3.png" alt="The Testing tab running the hello query with a name argument" width="50%">
146
+
147
+ > **Note:** Older docs and rulesets show `/sky/cloud/…`. It's a legacy alias for the same handler. Use `/sky/query/…`.
148
+
149
+ ## Use the Testing tab
150
+
151
+ <img src="/lessons/_media/19791904-root-pico-testing.png" alt="The Testing tab overview with ECI and Ruleset menus" width="50%">
152
+
153
+ You can send the same events and queries without typing URLs. Open the pico's **Testing** tab:
154
+
155
+ 1. Pick the **ECI** to send on. The menu lists the pico's channels with their tags, and the tab remembers your choice. It starts on the pico's own `self` channel (its ECI is the pico's id), which allows everything. Pick the channel you just made to see its policy at work.
156
+ 2. Pick the **Ruleset**, `io.picolabs.hello_world`.
157
+ 3. The tab builds a form for each event the ruleset's rules select and each query it shares. The forms come from the ruleset's **schema**, which the compiler generates from the code and from the `/** … */` doc comments on rules and functions: the `@attr` and `@param` tags name the inputs, and `@example` supplies presets. Fill in `name`, then send.
158
+
159
+ The result shows below the forms, and the tab keeps a history of what you sent so you can send it again.
160
+
161
+ <img src="/lessons/_media/19791904-root-pico-testing2.png" alt="The Testing tab with the hello_world ruleset selected, a name typed in the echo:hello form, and the directive in the Results panel" width="50%">
162
+
163
+ <img src="/lessons/_media/19791904-root-pico-testing4.png" alt="The Testing tab echo:hello event form with the name field" width="50%">
164
+
165
+ > **Note:** Older rulesets list their events and queries in a global `__testing` map. That's legacy: the engine still understands it for older rulesets, but new rulesets should use doc comments. Rules and functions with no doc comment still appear, with attributes the engine can find in the code, but you won't get descriptions or examples.
166
+
167
+ ## Debug with klog and the Logging tab
168
+
169
+ `klog` is KRL's print statement. It's a function that returns the value it was applied to, so you can slip it into the middle of an expression:
170
+
171
+ ```krl
172
+ my_name = event:attr("name")
173
+ .defaultsTo("world")
174
+ .lc()
175
+ .klog("Here's the name I saw: ")
176
+ .uc()
177
+ ```
178
+
179
+ Change the rule in your `hello_world.krl` to look like this, and flush the ruleset (see the Quickstart). The full rule:
180
+
181
+ ```krl
182
+ rule hello_world {
183
+ select when echo hello
184
+ pre {
185
+ my_name = event:attr("name")
186
+ .defaultsTo("world")
187
+ .lc()
188
+ .klog("Here's the name I saw: ")
189
+ .uc()
190
+ }
191
+ send_directive("say", {"something": "Hello " + my_name})
192
+ }
193
+ ```
194
+
195
+ Send `echo:hello` with `name` set to `Ada`. Then open the **Logging** tab. It lists what the pico did, newest first, one transaction for each event or query that arrived. Select the `echo:hello` transaction. The panel shows:
196
+
197
+ - the channel it arrived on, and the policy decision
198
+ - the attributes the event carried
199
+ - which rules were selected and which fired
200
+ - your `klog` line, `Here's the name I saw: ada`
201
+ - the directives that went back
202
+ - any events the rules raised
203
+
204
+ <img src="/lessons/_media/19791904-root-pico-logging.png" alt="The Logging tab listing the transactions for an event and a query, with klog output" width="50%">
205
+
206
+ The **Filters** button narrows the list: by ruleset, by `domain:type`, errors only, or transactions that logged `klog`. The tab follows new transactions as they arrive. You'll use it constantly: if a rule didn't run, this is where you find out why. Rules that didn't select an event are shown with their `select` text, so you can see what they were waiting for.
207
+
208
+ `klog` also works inside a rule's postlude, and KRL has explicit [log statements](/krl/rulesets/rules/postlude/explicit-logging) with levels.
209
+
210
+ ## Exercises
211
+
212
+ ### Beginner
213
+
214
+ 1. Create a new channel (any tags you like, same event and query policy as before). Send an event on it. Do you get the same result? Why or why not?
215
+ 2. Delete that channel. Resend the event using the deleted ECI. What happens? Why?
216
+ 3. Send the event `ecco/hello` (note the spelling) to your pico. What do you observe? Why?
217
+ 4. Add a rule that selects `echo/monkey` and answers `"Hello Monkey"` unless an attribute `name` is given, in which case it answers `"Hello "` plus that name. Hint: `.defaultsTo()`. Use `.klog()` on the value you use.
218
+ 5. Repeat the previous exercise with the ternary conditional (`=>` / `|`) instead of `.defaultsTo()`.
219
+ 6. Create a second channel whose query policy allows only `hello` and whose event policy allows nothing (`{"allow": [], "deny": []}`). Show that the query works and the event is refused. Where in the Logging tab do you see the refusal?
220
+
221
+ ### Intermediate
222
+
223
+ These presume [Pico State](/lessons/pico-state) and [Modules and External APIs](/lessons/modules-and-apis). Come back after those lessons.
224
+
225
+ 1. Write and install a ruleset `track_trips` with a rule `process_trips` that selects `car:new_trip` with attribute `mileage` and answers a directive `trip` with option `trip_length` set to that mileage.
226
+ 2. Create a pico that represents a car and install `track_trips` on it. Test with and without `mileage`.
227
+ 3. Tighten the select so the rule only runs when `mileage` is a positive number (hint: the `as` operator).
228
+ 4. Have `process_trips` raise `explicit:trip_processed` with the same attributes (`event:attrs`).
229
+ 5. Add `find_long_trips` on `explicit:trip_processed`: if `mileage` is greater than a global `long_trip`, raise `explicit:found_long_trip`.
230
+ 6. Add `trip_fuel_usage` on `explicit:trip_processed` that uses a vehicle-info function from your Modules lesson and the mileage to estimate gallons used, and returns that in a directive.
231
+ 7. Use the Logging tab to convince yourself the cascade runs.
232
+
233
+ ## What you learned
234
+
235
+ - Events report that something happened. Rules select them by domain and type, and answer with directives.
236
+ - Queries read state with no side effects, by calling a function listed in `shares`.
237
+ - Channels carry both, and a channel's policy decides what it accepts. Tags help you find channels.
238
+ - URLs: `/sky/event/<eci>/<eid>/<domain>/<type>` and `/sky/query/<eci>/<rid>/<function>`.
239
+ - The Testing tab builds forms from the schema; the Logging tab and `klog` show what happened.
240
+
241
+ ## Next
242
+
243
+ [Pico State](/lessons/pico-state) adds memory: a pico that remembers the names it's been told. For a runnable relative of this lesson, see the [Echo demo](/cookbook/echo/), and for more on how apps make channels for themselves, [Bootstrap and channels](/cookbook/bootstrap/).
244
+
245
+ ---
246
+
247
+ <small>Ported from the [Pico Labs wiki](https://picolabs.atlassian.net/wiki/spaces/docs/pages/19791904/Events+and+Queries+Lesson) (last edited there 2021-02-02), and updated for this engine.</small>
@@ -0,0 +1,28 @@
1
+ # Gossip Lab
2
+
3
+ The Gossip Lab is an optional, advanced exercise. It was the ninth lab (Lab 9) in BYU CS 462, the course that uses picos to teach reactive, event-based programming. The Pico Programming Lessons list it last, and it isn't part of the main sequence.
4
+
5
+ ## What's here, and what isn't
6
+
7
+ The original wiki page is almost empty. It holds one thing: a video recorded for the Lab 9 assignment. You can watch it on YouTube: [Gossip Lab video](https://www.youtube.com/watch?v=WrBf9kg-_ZY).
8
+
9
+ This engine's documentation doesn't reproduce the assignment. The wiki page doesn't contain it (students got the assignment through the course), and rather than guess at the protocol, this page stops here. If you're taking the course, use the assignment text from your instructor.
10
+
11
+ ## Preparing for it
12
+
13
+ Whatever the details of the assignment, a gossip-style system of picos uses things these lessons teach. If you want to be ready, work through:
14
+
15
+ - [Pico-Based Systems](/lessons/pico-based-systems): create a set of picos and keep track of them
16
+ - [Relationships](/lessons/relationships): link picos that aren't parent and child, and send events over the link
17
+ - [Scatter-Gather](/lessons/scatter-gather): send events to many picos without waiting, correlate the answers, and deal with lost events
18
+ - [Pico State](/lessons/pico-state): keep and update persistent state
19
+
20
+ In the cookbook, [Two picos talking](/cookbook/two_picos/) and [Collection](/cookbook/collection/) are small runnable examples of picos with relationships. Picos communicate only by events and queries, so any distributed protocol on picos is built from those, plus a channel policy for what each peer may do.
21
+
22
+ ## Back to the lessons
23
+
24
+ The main sequence starts at the [Quickstart](/lessons/quickstart).
25
+
26
+ ---
27
+
28
+ <small>Ported from the [Pico Labs wiki](https://picolabs.atlassian.net/wiki/spaces/docs/pages/727384069) (Gossip Lab, last edited there 2019-03-29). The wiki page holds only a video.</small>