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
package/README.md CHANGED
@@ -13,7 +13,7 @@ pico-engine
13
13
 
14
14
  Open `http://localhost:3000` — a root pico and UI channel are created on first run. Operator settings (port, data dir, policy ceiling) live in **`~/.config/pico-engine/config.json`**; copy [`config.example.json`](https://github.com/Picolab/pico-engine/blob/master/packages/pico-engine/config.example.json). See the [engine guide](https://docs.picolabs.io/#/pico-engine).
15
15
 
16
- **AI coding assistants:** `pico-engine mcp --stdio` runs an MCP server against the same engine (status, picos, channels, events, queries, KRL validation). Machine-readable docs: [`llms.txt`](https://docs.picolabs.io/llms.txt) and [`llms-full.txt`](https://docs.picolabs.io/llms-full.txt). Repo conventions for agents: [`CLAUDE.md`](https://github.com/Picolab/pico-engine/blob/master/CLAUDE.md).
16
+ **AI coding assistants:** `pico-engine mcp --stdio` runs an MCP server against the same engine (status, picos, channels, events, queries, KRL validation, and the Try It! demos: `list_try_it_demos`, `run_try_it_demo`, `try_it_status`). It also serves the cookbook and Developing with Picos docs as `pico://docs/...` resources. Machine-readable docs: [`llms.txt`](https://docs.picolabs.io/llms.txt) and [`llms-full.txt`](https://docs.picolabs.io/llms-full.txt). Repo conventions for agents: [`CLAUDE.md`](https://github.com/Picolab/pico-engine/blob/master/CLAUDE.md).
17
17
 
18
18
  ## Getting Started
19
19
 
@@ -132,9 +132,11 @@ The server is configured via some environment variables.
132
132
  - `PICO_ENGINE_HOME` - Where the database and other files should be stored. By default it's `~/.pico-engine/`
133
133
  - `PICO_ENGINE_BASE_URL` - The public url prefix to reach this engine. By default it's `"http://localhost:3000"`
134
134
  - `PICO_ENGINE_ALLOW_SELF_SIGNUP` - Set to `"true"` or `"1"` to allow open registration after bootstrap (default: off; bootstrap and invite still work)
135
- - `PICO_ENGINE_ALLOW_LOCALHOST_C` - Set to `"0"` to require passkey session on `/c/*` even from localhost (default: allow localhost without session for in-engine HTTP loops). Full registry: repo `MEMORY.md` § Engine environment variables.
135
+ - `PICO_ENGINE_ALLOW_LOCALHOST_C` - `"1"` or `"true"` lets a direct loopback connection call `/c/*` without a passkey (default: off). Proxy headers are never treated as local. The dev MCP sends `X-Pico-Internal` from `$PICO_ENGINE_HOME/internal-token`. Full registry: repo `MEMORY.md` § Engine environment variables.
136
136
  - `PICO_ENGINE_LOG_FILE` - Log file path. Set to `stdout`, `-`, or `0` for **stdout only** (recommended on Fargate + EFS; use CloudWatch for retention). Default: `$PICO_ENGINE_HOME/pico-engine.log`.
137
137
  - `PICO_ENGINE_LOG_MIRROR` - When stdout-only: **`true`/`1`** (default) mirrors structured JSON to **`$PICO_ENGINE_HOME/pico-engine.log`** so **`ctx:logs`** and the Developer UI **Logging** tab work; set **`false`/`0`** to skip the mirror file (e.g. avoid EFS log churn). **Config:** `logMirror` in `config.json` (see `config.example.json`).
138
+ - `PICO_ENGINE_SHOW_TRYIT_MENU` - Where the Developer UI shows the **Try It!** tab: `off`, `root_only` (default), or `all` (config: `show_tryit_menu`).
139
+ - `PICO_ENGINE_DEMOS_DIR` - A directory to serve as `demos/` instead of the copy shipped with the engine, such as the `demos/` folder of a pico-engine checkout you're editing.
138
140
 
139
141
  The `PORT` is the only value used in setting up the engine’s [nodejs http server](https://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback). We only specify the `port` so it listens listens to all traffic on that port, it will not filter by host.
140
142
 
@@ -230,7 +232,7 @@ The developer UI uses **passkeys** (WebAuthn). On first visit you register a pas
230
232
 
231
233
  When self-signup is disabled, **Settings → Invite someone** can include an optional **bootstrap ruleset URL** (`file://` or `https://`). The engine validates the URL when the invite is created; when the invitee registers, that ruleset is installed on their new root after the base OS rulesets (e.g. a Manifold bootstrap KRL). The invite **label** pre-fills the invitee's mesh name (editable before registering). WebAuthn `user.name` is set to the mesh name so password managers (e.g. 1Password) show it alongside the site hostname.
232
234
 
233
- - **`/c/*`** — internal/UI API; requires a passkey session cookie (localhost bypass is on by default for in-engine KRL HTTP loops; set `PICO_ENGINE_ALLOW_LOCALHOST_C=0` to disable).
235
+ - **`/c/*`** — internal/UI API. Requires a passkey session cookie, or the dev MCP's `X-Pico-Internal` token (`$PICO_ENGINE_HOME/internal-token`, rewritten each startup). A direct loopback bypass exists only when `PICO_ENGINE_ALLOW_LOCALHOST_C=1`.
234
236
  - **`/auth/*`** — registration, login, session management.
235
237
 
236
238
  ## OAuth
@@ -244,6 +246,10 @@ Two grant types can coexist in the same mesh:
244
246
  | **Client Credentials** | Inbound webhooks (Stripe, GitHub, …) | Channel **ECI** | Single channel only |
245
247
  | **Authorization Code + PKCE** | Apps like Home Assistant | `app_…` | Whole mesh (root + descendants) |
246
248
 
249
+ An MCP client discovers this server without a pre-registered app. `GET /.well-known/oauth-authorization-server` describes the authorization server. `GET /.well-known/oauth-protected-resource/mcp/{eci}` describes that channel's MCP URL. `/mcp/{eci}` answers a missing bearer token with `401` and `WWW-Authenticate: Bearer resource_metadata="…"`.
250
+
251
+ A client can use an https URL as its `client_id`. The engine fetches that URL as a Client ID Metadata Document. The document's `client_id` must equal the URL, and its `redirect_uris` must include the request's `redirect_uri`. The approval screen shows the client's name, logo, page, and host, plus the mesh and the scopes requested. These clients are public: S256 PKCE and no client secret. Pre-registered apps still work.
252
+
247
253
  ### Mesh lock
248
254
 
249
255
  Install the optional ruleset **`io.picolabs.oauth`** on the **root pico** to require a Bearer token on most **`/sky/*`** requests for that mesh. Without it, open channels work as before (channel policy only); channels tagged **`oauth-webhook`** always require Bearer.
@@ -320,7 +326,7 @@ Content-Type: application/json
320
326
  }
321
327
  ```
322
328
 
323
- For manual testing with plain PKCE, use `code_challenge_method=plain` and set `code_challenge` and `code_verifier` to the same string.
329
+ PKCE is S256 only: `code_challenge` is the base64url SHA-256 of `code_verifier`. Send the same `resource` on the authorize request and the token request (`{base}/sky` for Sky, `{base}/mcp/{eci}` for that channel's MCP URL, or `{base}/mcp/mesh/{eci}` for the whole-mesh endpoint). A token is accepted only at the resource it names. Tokens issued with no `resource` still work on `/sky/*`. `mesh:read` is required for queries and `mesh:act` for events.
324
330
 
325
331
  **Refresh:**
326
332
 
@@ -335,6 +341,8 @@ Content-Type: application/json
335
341
  }
336
342
  ```
337
343
 
344
+ Each refresh returns a new access token and a new refresh token. The previous refresh token no longer works. Sending it again revokes the replacement as well. A public client (no secret, including a Client ID Metadata Document) gets an access token that lasts one hour. A confidential app's access token lasts 24 hours. The refresh token lasts 90 days, and a successful refresh starts that clock again. Send the same `resource` the grant was issued with.
345
+
338
346
  **Use the access token** on any channel ECI in the mesh:
339
347
 
340
348
  ```http
@@ -392,7 +400,7 @@ Every pico has a portable **did:webvh** identity. **DID-based relationships** (L
392
400
 
393
401
  Full guide: [Layer 2 relationships](https://docs.picolabs.io/#/guides/layer2-subscriptions) · Release notes: [1.6](https://docs.picolabs.io/#/release/1.6) · [CHANGELOG.md](https://github.com/Picolab/pico-engine/blob/master/CHANGELOG.md) (1.6.4 mesh-oauth-exempt + KRL directory UI; 1.6.3 fixes)
394
402
 
395
- **Dependency:** pico-engine 1.6 requires **pico-framework `^0.8.1`** (npm). When developing engine + framework together, use `npm run link-framework` from the repo root.
403
+ **Dependency:** `pico-framework` is `packages/pico-framework` in this repo and is versioned with the engine. `krl-stdlib`, `pico-engine-core`, and `pico-engine` depend on it.
396
404
 
397
405
  ### Layer 2 tests
398
406
 
@@ -0,0 +1,12 @@
1
+ # Bootstrap and channels demo
2
+
3
+ A bootstrap ruleset installs a small app in dependency order and configures it, and the app creates its own channel on install, with a policy built from its schema.
4
+
5
+ - Overview: [`docs/cookbook/bootstrap/README.md`](../../docs/cookbook/bootstrap/README.md) (on the docs site: https://docs.picolabs.io/#/cookbook/bootstrap/)
6
+ - Instructions: [`docs/cookbook/bootstrap/instructions.md`](../../docs/cookbook/bootstrap/instructions.md)
7
+
8
+ | File | Shows |
9
+ |------|-------|
10
+ | `com.example.visitors.bootstrap.krl` | The bootstrap: installs each ruleset when the one it needs is installed, and gives the app its install configuration |
11
+ | `com.example.visitors.format.krl` | A module the app uses, so it is installed first |
12
+ | `com.example.visitors.krl` | The app: reads its configuration, and creates or updates its channel on install. Its page shows the pico's rulesets and channels |
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Try It! bootstrap for the Bootstrap and channels demo. Install it on a new
3
+ * pico. It installs io.picolabs.xmlui, then com.example.visitors.format, then
4
+ * com.example.visitors with a greeting in its install configuration. Each step
5
+ * waits for the ruleset_installed event of the one before, because each needs
6
+ * the one before. The visitor log creates its own channel when it is
7
+ * installed. tryIt() reports progress and links to the visitor log.
8
+ *
9
+ * This ruleset does not use io.picolabs.xmlui as a module, because it is the
10
+ * one that installs it.
11
+ */
12
+ ruleset com.example.visitors.bootstrap {
13
+ meta {
14
+ name "Bootstrap and channels"
15
+ description "Shows a bootstrap ruleset installing an app in dependency order and configuring it, and an app ruleset that creates its own channel on install, with a policy built from its schema, updated in place instead of duplicated."
16
+ author "PICOLABS"
17
+
18
+ use module io.picolabs.wrangler alias wrangler
19
+
20
+ shares tryIt
21
+ }
22
+
23
+ global {
24
+ xmlui_rid = "io.picolabs.xmlui"
25
+ format_rid = "com.example.visitors.format"
26
+ app_rid = "com.example.visitors"
27
+
28
+ host = function() {
29
+ meta:host.defaultsTo("").replace(re#/$#, "")
30
+ }
31
+
32
+ /**
33
+ * Progress of this demo's setup, and the links to open when it is ready.
34
+ * @returns Map
35
+ */
36
+ tryIt = function() {
37
+ app = wrangler:channels(["visitors", "app"]).head()
38
+ ready = (ent:stage == "ready" && app) => true | false
39
+ status = {
40
+ "ready": ready,
41
+ "stage": ent:stage.defaultsTo("starting"),
42
+ "links": ready => [
43
+ {"label": "Visitor log", "url": host() + "/ui/" + app{"id"} + "/" + app_rid + "/"}
44
+ ] | []
45
+ }
46
+ status
47
+ }
48
+ }
49
+
50
+ // Step 1: a channel for tryIt(), and the views runtime (unless it's here).
51
+ rule start {
52
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
53
+ pre {
54
+ has_xmlui = wrangler:installedRIDs() >< xmlui_rid
55
+ }
56
+ if not has_xmlui then noop()
57
+ fired {
58
+ ent:stage := "installing " + xmlui_rid
59
+ raise wrangler event "install_ruleset_request" attributes
60
+ {"url": host() + "/krl/" + xmlui_rid + ".krl"}
61
+ }
62
+ else {
63
+ raise bootstrap event "xmlui_ready"
64
+ }
65
+ finally {
66
+ raise wrangler event "new_channel_request" attributes {
67
+ "tags": ["try_it"],
68
+ "eventPolicy": {"allow": [], "deny": []},
69
+ "queryPolicy": {"allow": [{"rid": meta:rid, "name": "tryIt"}], "deny": []}
70
+ }
71
+ }
72
+ }
73
+
74
+ // Step 2: the module the app uses.
75
+ rule install_format {
76
+ select when wrangler ruleset_installed where event:attr("rids") >< xmlui_rid
77
+ or bootstrap xmlui_ready
78
+ always {
79
+ ent:stage := "installing " + format_rid
80
+ raise wrangler event "install_ruleset_request" attributes
81
+ {"absoluteURL": meta:rulesetURI, "rid": format_rid}
82
+ }
83
+ }
84
+
85
+ // Step 3: the app, configured. Its own install rule creates its channel.
86
+ rule install_app {
87
+ select when wrangler ruleset_installed where event:attr("rids") >< format_rid
88
+ always {
89
+ ent:stage := "installing " + app_rid
90
+ raise wrangler event "install_ruleset_request" attributes
91
+ {"absoluteURL": meta:rulesetURI, "rid": app_rid, "config": {"greeting": "Welcome"}}
92
+ }
93
+ }
94
+
95
+ rule app_installed {
96
+ select when wrangler ruleset_installed where event:attr("rids") >< app_rid
97
+ always {
98
+ ent:stage := "ready"
99
+ }
100
+ }
101
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Visitor log formatting: a module the visitor log uses, so it has to be
3
+ * installed first.
4
+ */
5
+ ruleset com.example.visitors.format {
6
+ meta {
7
+ name "Visitor log formatting"
8
+ description "Formats greetings for the visitor log."
9
+ author "PICOLABS"
10
+
11
+ provides greeting
12
+ }
13
+
14
+ global {
15
+ /**
16
+ * A greeting for a visitor.
17
+ * @param word String "the greeting word, such as Welcome"
18
+ * @param name String "the visitor's name"
19
+ * @returns String
20
+ */
21
+ greeting = function(word, name) {
22
+ word + ", " + name + "!"
23
+ }
24
+ }
25
+ }
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Visitor log: signs visitors in and greets them. Its greeting word comes from
3
+ * the configuration it was installed with, and it uses
4
+ * com.example.visitors.format as a module.
5
+ *
6
+ * On install it creates its own channel, with a policy built from this
7
+ * ruleset's schema: every event its documented rules select (except
8
+ * wrangler's) and every function it shares and documents. The schema is the
9
+ * ruleset's documented API, so undocumented rules stay off the channel. If the channel already exists, the same rule updates it
10
+ * in place, so the channel id, and every link that uses it, stays the same.
11
+ * Flushing doesn't run install rules again, so the page has a button that does.
12
+ */
13
+ ruleset com.example.visitors {
14
+ meta {
15
+ name "Visitor log"
16
+ description "Signs visitors in and greets them; creates its own channel on install."
17
+ author "PICOLABS"
18
+
19
+ use module com.example.visitors.format alias format
20
+ use module io.picolabs.wrangler alias wrangler
21
+ use module io.picolabs.xmlui alias ui
22
+
23
+ shares visitors, setup, visitorsPage
24
+ }
25
+
26
+ global {
27
+ channel_tags = ["visitors", "app"]
28
+ xmlui_rid = "io.picolabs.xmlui"
29
+
30
+ greetingWord = function() {
31
+ meta:rulesetConfig{"greeting"} || "Hello"
32
+ }
33
+
34
+ schema = function(rid) {
35
+ wrangler:rulesetSchema(rid).defaultsTo({})
36
+ }
37
+
38
+ unique = function(list) {
39
+ list.reduce(function(acc, item) { acc >< item => acc | acc.append([item]) }, [])
40
+ }
41
+
42
+ // Every event a documented rule selects, except wrangler's. The schema has
43
+ // only rules and functions with doc comments.
44
+ eventPolicy = function() {
45
+ allow = schema(meta:rid){"operations"}.defaultsTo([])
46
+ .map(function(op) { op{"entry"}.defaultsTo([]) })
47
+ .reduce(function(a, b) { a.append(b) }, [])
48
+ .filter(function(e) { e{"domain"} && e{"domain"} != "wrangler" })
49
+ .map(function(e) { {"domain": e{"domain"}, "name": e{"name"} || "*"} })
50
+ policy = {"allow": unique(allow), "deny": []}
51
+ policy
52
+ }
53
+
54
+ // Every function this ruleset shares, and what the page shell needs.
55
+ queryPolicy = function() {
56
+ mine = schema(meta:rid){"queries"}.defaultsTo([])
57
+ .map(function(q) { {"rid": meta:rid, "name": q{"name"}} })
58
+ shell = schema(xmlui_rid){"queries"}.defaultsTo([])
59
+ .filter(function(q) { not q{"component"}.isnull() })
60
+ .map(function(q) { {"rid": xmlui_rid, "name": q{"name"}} })
61
+ .append([{"rid": xmlui_rid, "name": "file"}])
62
+ policy = {"allow": mine.append(shell), "deny": []}
63
+ policy
64
+ }
65
+
66
+ /**
67
+ * Everyone signed in, oldest first.
68
+ * @returns Array of { name, message, time }
69
+ */
70
+ visitors = function() {
71
+ ent:visitors.defaultsTo([])
72
+ }
73
+
74
+ /**
75
+ * How this pico was set up: its rulesets, this ruleset's install
76
+ * configuration, and the channels tagged visitors, app.
77
+ * @returns Map
78
+ */
79
+ setup = function() {
80
+ channels = wrangler:channels(channel_tags).map(function(c) {
81
+ {
82
+ "id": c{"id"},
83
+ "events": c{["eventPolicy", "allow"]}.defaultsTo([])
84
+ .map(function(r) { r{"domain"} + ":" + r{"name"} }).join(", "),
85
+ "queries": c{["queryPolicy", "allow"]}.defaultsTo([]).length(),
86
+ "this_page": c{"id"} == meta:eci => "yes" | ""
87
+ }
88
+ })
89
+ result = {
90
+ "rulesets": wrangler:installedRIDs().map(function(rid) { {"rid": rid} }),
91
+ "config": meta:rulesetConfig.encode(),
92
+ "channels": channels
93
+ }
94
+ result
95
+ }
96
+
97
+ /**
98
+ * Sign in, and see how the bootstrap set this pico up.
99
+ * @view "Visitor log"
100
+ */
101
+ visitorsPage = function() {
102
+ setup_url = ui:query_url("setup", meta:rid, meta:eci)
103
+ visitors_url = ui:query_url("visitors", meta:rid, meta:eci)
104
+ arrived_url = ui:event_url("visitor", "arrived")
105
+ check_url = ui:event_url("visitor_channel", "check_requested")
106
+ duplicate_url = ui:event_url("visitor_channel", "duplicate_requested")
107
+ cleanup_url = ui:event_url("visitor_channel", "cleanup_requested")
108
+ <<
109
+ <Component name="VisitorsPage" var.said="">
110
+ <DataSource id="setup" url="#{setup_url}" headers="{appGlobals.auth}" pollIntervalInSeconds="2" />
111
+ <DataSource id="visitors" url="#{visitors_url}" headers="{appGlobals.auth}" />
112
+ <APICall id="arrive" method="post" url="#{arrived_url}" headers="{appGlobals.auth}" body="{$param}"
113
+ onSuccess="(result) => { said = result.directives.length ? result.directives[0].options.message : ''; visitors.refetch(); }" />
114
+ <APICall id="check" method="post" url="#{check_url}" headers="{appGlobals.auth}"
115
+ onSuccess="(result) => { said = result.directives.map((d) => d.name).join(', '); setup.refetch(); }" />
116
+ <APICall id="duplicate" method="post" url="#{duplicate_url}" headers="{appGlobals.auth}"
117
+ onSuccess="(result) => { said = result.directives.map((d) => d.name).join(', '); setup.refetch(); }" />
118
+ <APICall id="cleanup" method="post" url="#{cleanup_url}" headers="{appGlobals.auth}"
119
+ onSuccess="(result) => { said = result.directives.map((d) => d.name).join(', ') || 'nothing to clean up'; setup.refetch(); }" />
120
+ <PicoTheme>
121
+ <Card title="Visitor log"
122
+ subtitle="A bootstrap ruleset installed this app: a formatting module first, then this ruleset with a greeting in its install configuration. On install, this ruleset made the channel this page uses." />
123
+ <Form saveLabel="Sign in" onSubmit="(data) => arrive.execute(data)">
124
+ <FormItem bindTo="name" label="Your name" initialValue="Ada" />
125
+ </Form>
126
+ <Card title="The pico said" subtitle="{said || '(nothing yet)'}" />
127
+ <Table data="{visitors}">
128
+ <Column bindTo="name" header="Visitor" />
129
+ <Column bindTo="message" header="Greeted with" />
130
+ </Table>
131
+
132
+ <Card title="How the bootstrap set up this pico"
133
+ subtitle="{'This ruleset was installed with the configuration ' + setup.value.config}" />
134
+ <Table data="{setup.value.rulesets}">
135
+ <Column bindTo="rid" header="Installed rulesets, in order" />
136
+ </Table>
137
+
138
+ <Card title="This app's channel"
139
+ subtitle="Its policy was built from this ruleset's schema when the ruleset was installed. Try the buttons and watch the table." />
140
+ <Table data="{setup.value.channels}">
141
+ <Column bindTo="id" header="Channel" />
142
+ <Column bindTo="events" header="Events it allows" />
143
+ <Column bindTo="queries" header="Queries" />
144
+ <Column bindTo="this_page" header="This page" />
145
+ </Table>
146
+ <HStack wrapContent="true">
147
+ <Button label="Run the channel rule again" onClick="check.execute({})" />
148
+ <Button label="Make a duplicate, the naive way" variant="outlined" onClick="duplicate.execute({})" />
149
+ <Button label="Clean up duplicates" variant="outlined" onClick="cleanup.execute({})" />
150
+ </HStack>
151
+ </PicoTheme>
152
+ </Component>
153
+ >>
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Sign a visitor in and greet them.
159
+ * @attr name String "the visitor's name"
160
+ * @example "Ada" { "name": "Ada" }
161
+ */
162
+ rule greet_visitor {
163
+ select when visitor arrived
164
+ name re#(\S.*)#
165
+ setting(name)
166
+ pre {
167
+ message = format:greeting(greetingWord(), name)
168
+ }
169
+ send_directive("greeting", {"message": message})
170
+ fired {
171
+ ent:visitors := visitors().append({"name": name, "message": message, "time": time:now()})
172
+ raise visitor event "greeted" attributes {"name": name}
173
+ }
174
+ }
175
+
176
+ /**
177
+ * On install, or when asked: update this app's channel if it exists, so its
178
+ * id stays the same. Otherwise raise visitor_setup:channel_missing.
179
+ */
180
+ rule set_up_channel {
181
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
182
+ or visitor_channel check_requested
183
+ pre {
184
+ existing = wrangler:channels(channel_tags).head()
185
+ }
186
+ if existing then every {
187
+ wrangler:updateChannel(existing{"id"}, channel_tags, eventPolicy(), queryPolicy())
188
+ send_directive("set_up_channel", {"result": "updated", "id": existing{"id"}})
189
+ }
190
+ notfired {
191
+ raise visitor_setup event "channel_missing"
192
+ }
193
+ }
194
+
195
+ // No doc comment, so it isn't in the schema, and the channel doesn't allow
196
+ // its event: only set_up_channel raises it.
197
+ rule create_channel {
198
+ select when visitor_setup channel_missing
199
+ every {
200
+ wrangler:createChannel(channel_tags, eventPolicy(), queryPolicy())
201
+ send_directive("create_channel")
202
+ }
203
+ }
204
+
205
+ /**
206
+ * The naive way: create a channel every time, whether or not one exists.
207
+ */
208
+ rule make_duplicate {
209
+ select when visitor_channel duplicate_requested
210
+ every {
211
+ wrangler:createChannel(channel_tags, eventPolicy(), queryPolicy())
212
+ send_directive("make_duplicate")
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Delete every channel tagged visitors, app except the one this request came
218
+ * in on, which is the one the page is using.
219
+ */
220
+ rule clean_up_channels {
221
+ select when visitor_channel cleanup_requested
222
+ foreach wrangler:channels(channel_tags).filter(function(c) { c{"id"} != meta:eci }) setting(channel)
223
+ every {
224
+ wrangler:deleteChannel(channel{"id"})
225
+ send_directive("clean_up_channels", {"deleted": channel{"id"}})
226
+ }
227
+ }
228
+ }
@@ -0,0 +1,5 @@
1
+ - Open **Visitor log** and sign in. The greeting word, "Welcome", came from the configuration the bootstrap installed the app with.
2
+ - Under **How the bootstrap set up this pico**, the installed rulesets are in install order: the bootstrap, then `io.picolabs.xmlui`, then `com.example.visitors.format` (a module), then `com.example.visitors`, which uses it. Open the child pico's **Logging** tab to follow the chain of `wrangler:ruleset_installed` events that drove each step.
3
+ - Under **This app's channel**, the policy lists the events of the app's documented rules. It doesn't list `wrangler:ruleset_installed`, which its install rule selects, or the event only `set_up_channel` raises.
4
+ - Click **Run the channel rule again**: the same channel is updated, and its id doesn't change. Click **Make a duplicate, the naive way** twice: three channels with the same tags. Click **Clean up duplicates**: only the channel this page uses is left.
5
+ - Add a documented rule to `com.example.visitors.krl` that selects `visitor waved`, and click **Flush**. Sending `visitor/waved` on the page's channel is refused: flushing doesn't run install rules again. Click **Run the channel rule again** and send it again. Now it works.
@@ -0,0 +1,12 @@
1
+ # Child pico tasks demo
2
+
3
+ A pico that never waits: each task runs in a new child pico, which reports back to its parent and then deletes itself.
4
+
5
+ - Overview: [`docs/cookbook/child_tasks/README.md`](../../docs/cookbook/child_tasks/README.md) (on the docs site: https://docs.picolabs.io/#/cookbook/child_tasks/)
6
+ - Instructions: [`docs/cookbook/child_tasks/instructions.md`](../../docs/cookbook/child_tasks/instructions.md)
7
+
8
+ | File | Shows |
9
+ |------|-------|
10
+ | `com.example.task_runner.krl` | The parent: creates a child per task, hands it the task, records the result, and notes when the child is gone. Has the Tasks page |
11
+ | `com.example.task_worker.krl` | The child: counts primes up to `n`, sends `task:done` to its parent, and asks to be deleted |
12
+ | `com.example.task_runner.bootstrap.krl` | Sets up the demo on a new pico and starts three tasks; the **Try It!** tab runs it |
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Try It! bootstrap for the child tasks demo. Install it on a new pico: it
3
+ * installs io.picolabs.xmlui and com.example.task_runner, then starts three
4
+ * tasks of different sizes. tryIt() reports progress and links to the Tasks
5
+ * page.
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.task_runner.bootstrap {
11
+ meta {
12
+ name "Child pico tasks"
13
+ description "Shows the child pico lifecycle: creating a child with extra attributes, installing a ruleset on it, reporting to the parent, and deleting itself, so the parent never waits."
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.task_runner"
23
+ xmlui_rid = "io.picolabs.xmlui"
24
+ seed_tasks = ["1000", "10000", "30000"]
25
+
26
+ host = function() {
27
+ meta:host.defaultsTo("").replace(re#/$#, "")
28
+ }
29
+
30
+ /**
31
+ * Progress of this demo's setup, and the links to open when it is ready.
32
+ * @returns Map
33
+ */
34
+ tryIt = function() {
35
+ app = wrangler:channels(["task_runner", "app"]).head()
36
+ ready = (ent:stage == "ready" && app) => true | false
37
+ status = {
38
+ "ready": ready,
39
+ "stage": ent:stage.defaultsTo("starting"),
40
+ "links": ready => [
41
+ {"label": "Tasks", "url": host() + "/ui/" + app{"id"} + "/" + app_rid + "/"}
42
+ ] | []
43
+ }
44
+ status
45
+ }
46
+ }
47
+
48
+ rule start {
49
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
50
+ pre {
51
+ has_xmlui = wrangler:installedRIDs() >< xmlui_rid
52
+ }
53
+ if not has_xmlui then noop()
54
+ fired {
55
+ raise wrangler event "install_ruleset_request" attributes
56
+ {"url": host() + "/krl/" + xmlui_rid + ".krl"}
57
+ }
58
+ else {
59
+ raise wrangler event "install_ruleset_request" attributes
60
+ {"absoluteURL": meta:rulesetURI, "rid": app_rid}
61
+ }
62
+ finally {
63
+ ent:stage := "installing"
64
+ raise wrangler event "new_channel_request" attributes {
65
+ "tags": ["try_it"],
66
+ "eventPolicy": {"allow": [], "deny": []},
67
+ "queryPolicy": {"allow": [{"rid": meta:rid, "name": "tryIt"}], "deny": []}
68
+ }
69
+ }
70
+ }
71
+
72
+ rule install_app {
73
+ select when wrangler ruleset_installed where event:attr("rids") >< xmlui_rid
74
+ always {
75
+ raise wrangler event "install_ruleset_request" attributes
76
+ {"absoluteURL": meta:rulesetURI, "rid": app_rid}
77
+ }
78
+ }
79
+
80
+ rule start_tasks {
81
+ select when wrangler ruleset_installed where event:attr("rids") >< app_rid
82
+ foreach seed_tasks setting(n)
83
+ always {
84
+ raise task event "start" attributes {"n": n}
85
+ ent:stage := "ready" on final
86
+ }
87
+ }
88
+ }