pico-engine 1.9.4 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/README.md +13 -5
  2. package/demos/bootstrap/README.md +12 -0
  3. package/demos/bootstrap/com.example.visitors.bootstrap.krl +101 -0
  4. package/demos/bootstrap/com.example.visitors.format.krl +25 -0
  5. package/demos/bootstrap/com.example.visitors.krl +228 -0
  6. package/demos/bootstrap/try-it.md +5 -0
  7. package/demos/child_tasks/README.md +12 -0
  8. package/demos/child_tasks/com.example.task_runner.bootstrap.krl +88 -0
  9. package/demos/child_tasks/com.example.task_runner.krl +139 -0
  10. package/demos/child_tasks/com.example.task_worker.krl +45 -0
  11. package/demos/child_tasks/try-it.md +5 -0
  12. package/demos/collection/README.md +13 -0
  13. package/demos/collection/com.example.collection.bootstrap.krl +148 -0
  14. package/demos/collection/com.example.collection.krl +95 -0
  15. package/demos/collection/com.example.collection.report.krl +93 -0
  16. package/demos/collection/com.example.collection.room.krl +101 -0
  17. package/demos/collection/try-it.md +6 -0
  18. package/demos/echo/README.md +11 -0
  19. package/demos/echo/com.example.echo.bootstrap.krl +84 -0
  20. package/demos/echo/com.example.echo.krl +73 -0
  21. package/demos/echo/try-it.md +5 -0
  22. package/demos/guard_rules/README.md +12 -0
  23. package/demos/guard_rules/com.example.archive.bootstrap.krl +98 -0
  24. package/demos/guard_rules/com.example.archive.krl +213 -0
  25. package/demos/guard_rules/com.example.archive_store.krl +36 -0
  26. package/demos/guard_rules/try-it.md +5 -0
  27. package/demos/json_query/README.md +11 -0
  28. package/demos/json_query/com.example.json_query.bootstrap.krl +84 -0
  29. package/demos/json_query/com.example.json_query.krl +162 -0
  30. package/demos/json_query/try-it.md +5 -0
  31. package/demos/kblog/README.md +14 -0
  32. package/demos/kblog/com.example.kblog.bootstrap.krl +135 -0
  33. package/demos/kblog/com.example.kblog.config.krl +50 -0
  34. package/demos/kblog/com.example.kblog.data.krl +75 -0
  35. package/demos/kblog/com.example.kblog.krl +184 -0
  36. package/demos/kblog/com.example.kblog.posting.krl +109 -0
  37. package/demos/kblog/try-it.md +6 -0
  38. package/demos/layered_rulesets/README.md +13 -0
  39. package/demos/layered_rulesets/com.example.invitations.bootstrap.krl +87 -0
  40. package/demos/layered_rulesets/com.example.invitations.krl +164 -0
  41. package/demos/layered_rulesets/com.example.invitations.short_links.krl +45 -0
  42. package/demos/layered_rulesets/com.example.invitations.welcome.krl +39 -0
  43. package/demos/layered_rulesets/try-it.md +5 -0
  44. package/demos/moving_picos/README.md +15 -0
  45. package/demos/moving_picos/io.picolabs.club_gear_demo.krl +650 -0
  46. package/demos/moving_picos/io.picolabs.ride_coordinator_demo.krl +331 -0
  47. package/demos/score_tracker/README.md +11 -0
  48. package/demos/score_tracker/com.example.score_tracker.bootstrap.krl +107 -0
  49. package/demos/score_tracker/com.example.score_tracker.krl +162 -0
  50. package/demos/score_tracker/try-it.md +5 -0
  51. package/demos/secrets/README.md +12 -0
  52. package/demos/secrets/com.example.hook_service.krl +120 -0
  53. package/demos/secrets/com.example.notifier.bootstrap.krl +130 -0
  54. package/demos/secrets/com.example.notifier.krl +138 -0
  55. package/demos/secrets/try-it.md +5 -0
  56. package/demos/try-it-order.json +1 -0
  57. package/demos/two_picos/README.md +12 -0
  58. package/demos/two_picos/com.example.two_picos.answerer.krl +125 -0
  59. package/demos/two_picos/com.example.two_picos.asker.krl +124 -0
  60. package/demos/two_picos/com.example.two_picos.bootstrap.krl +134 -0
  61. package/demos/two_picos/try-it.md +5 -0
  62. package/demos/xmlui/README.md +17 -0
  63. package/demos/xmlui/com.example.contacts.krl +132 -0
  64. package/demos/xmlui/com.example.fav_color.krl +39 -0
  65. package/demos/xmlui/com.example.guestbook.krl +61 -0
  66. package/demos/xmlui/com.example.hello.krl +19 -0
  67. package/demos/xmlui/com.example.temperature_sensors_view.krl +105 -0
  68. package/demos/xmlui/com.example.thermostat.bootstrap.krl +95 -0
  69. package/demos/xmlui/com.example.thermostat.krl +124 -0
  70. package/demos/xmlui/temperature_sensors.krl +56 -0
  71. package/demos/xmlui/try-it.md +5 -0
  72. package/dist/bundledKrl.js +97 -12
  73. package/dist/cli.js +7 -1
  74. package/dist/engineConfig.js +20 -1
  75. package/dist/identity/portableMove.js +5 -1
  76. package/dist/index.js +45 -12
  77. package/dist/internalAccess.js +110 -0
  78. package/dist/oauth/OAuthService.js +172 -10
  79. package/dist/oauth/acg.js +194 -24
  80. package/dist/oauth/cimd.js +381 -0
  81. package/dist/oauth/discovery.js +175 -0
  82. package/dist/runMcp.js +1 -1
  83. package/dist/server.js +210 -47
  84. package/dist/subtreeWrangler.js +8 -5
  85. package/dist/uiChannelPolicies.js +2 -0
  86. package/krl/io.picolabs.pds.krl +109 -21
  87. package/krl/io.picolabs.pico-engine-ui.krl +13 -7
  88. package/krl/io.picolabs.wrangler.krl +21 -9
  89. package/krl/io.picolabs.xmlui.krl +3 -2
  90. package/mcp/devResources.js +52 -0
  91. package/mcp/devTools.js +40 -9
  92. package/mcp/docs/CLAUDE.md +6 -4
  93. package/mcp/docs/cookbook/README.md +23 -0
  94. package/mcp/docs/cookbook/bootstrap/README.md +23 -0
  95. package/mcp/docs/cookbook/bootstrap/instructions.md +75 -0
  96. package/mcp/docs/cookbook/child_tasks/README.md +20 -0
  97. package/mcp/docs/cookbook/child_tasks/instructions.md +60 -0
  98. package/mcp/docs/cookbook/collection/README.md +21 -0
  99. package/mcp/docs/cookbook/collection/instructions.md +93 -0
  100. package/mcp/docs/cookbook/echo/README.md +19 -0
  101. package/mcp/docs/cookbook/echo/instructions.md +59 -0
  102. package/mcp/docs/cookbook/guard_rules/README.md +22 -0
  103. package/mcp/docs/cookbook/guard_rules/instructions.md +73 -0
  104. package/mcp/docs/cookbook/json_query/README.md +26 -0
  105. package/mcp/docs/cookbook/json_query/instructions.md +64 -0
  106. package/mcp/docs/cookbook/kblog/README.md +60 -0
  107. package/mcp/docs/cookbook/kblog/instructions.md +102 -0
  108. package/mcp/docs/cookbook/layered_rulesets/README.md +24 -0
  109. package/mcp/docs/cookbook/layered_rulesets/instructions.md +87 -0
  110. package/mcp/docs/cookbook/moving_picos/README.md +44 -0
  111. package/mcp/docs/cookbook/moving_picos/instructions.md +150 -0
  112. package/mcp/docs/cookbook/score_tracker/README.md +19 -0
  113. package/mcp/docs/cookbook/score_tracker/instructions.md +73 -0
  114. package/mcp/docs/cookbook/secrets/README.md +25 -0
  115. package/mcp/docs/cookbook/secrets/instructions.md +98 -0
  116. package/mcp/docs/cookbook/two_picos/README.md +20 -0
  117. package/mcp/docs/cookbook/two_picos/instructions.md +88 -0
  118. package/mcp/docs/cookbook/xmlui/README.md +23 -0
  119. package/mcp/docs/cookbook/xmlui/instructions.md +84 -0
  120. package/mcp/docs/developing/README.md +28 -0
  121. package/mcp/docs/developing/accepting-relationship-requests.md +65 -0
  122. package/mcp/docs/developing/arrays-and-maps.md +77 -0
  123. package/mcp/docs/developing/converting-time-formats.md +28 -0
  124. package/mcp/docs/developing/cookies-and-redirects.md +81 -0
  125. package/mcp/docs/developing/decoding-form-data.md +67 -0
  126. package/mcp/docs/developing/engine-log-files.md +34 -0
  127. package/mcp/docs/developing/event-loop.md +77 -0
  128. package/mcp/docs/developing/events-from-email.md +80 -0
  129. package/mcp/docs/developing/initializing-entity-variables.md +83 -0
  130. package/mcp/docs/developing/mcp-ai-tools.md +98 -0
  131. package/mcp/docs/developing/misconceptions.md +467 -0
  132. package/mcp/docs/developing/names-and-scope.md +44 -0
  133. package/mcp/docs/developing/postman.md +159 -0
  134. package/mcp/docs/developing/querying-another-pico.md +47 -0
  135. package/mcp/docs/developing/singleton-picos.md +36 -0
  136. package/mcp/docs/developing/tabular-data.md +67 -0
  137. package/mcp/docs/developing/tips.md +251 -0
  138. package/mcp/docs/developing/webhook-signatures.md +56 -0
  139. package/mcp/docs/developing/workflow.md +106 -0
  140. package/mcp/docs/exp/README.md +46 -0
  141. package/mcp/docs/exp/event.md +110 -0
  142. package/mcp/docs/exp/query.md +94 -0
  143. package/mcp/docs/lessons/README.md +59 -0
  144. package/mcp/docs/lessons/events-and-queries.md +247 -0
  145. package/mcp/docs/lessons/gossip.md +28 -0
  146. package/mcp/docs/lessons/modules-and-apis.md +270 -0
  147. package/mcp/docs/lessons/pico-based-systems.md +470 -0
  148. package/mcp/docs/lessons/pico-state.md +267 -0
  149. package/mcp/docs/lessons/pico-views.md +290 -0
  150. package/mcp/docs/lessons/quickstart.md +157 -0
  151. package/mcp/docs/lessons/relationships.md +530 -0
  152. package/mcp/docs/lessons/scatter-gather.md +362 -0
  153. package/mcp/docs/pico-engine.md +10 -5
  154. package/mcp/docs/pico-overview.md +3 -3
  155. package/mcp/docs/wrangler/README.md +47 -0
  156. package/mcp/docs/wrangler/channels.md +235 -0
  157. package/mcp/docs/wrangler/oauth.md +56 -0
  158. package/mcp/docs/wrangler/pds.md +423 -0
  159. package/mcp/docs/wrangler/portable-subtree.md +44 -0
  160. package/mcp/docs/wrangler/relationships.md +297 -0
  161. package/mcp/docs/wrangler/wrangler.md +253 -0
  162. package/mcp/docs/wrangler/xmlui.md +60 -0
  163. package/mcp/engineClient.js +57 -5
  164. package/mcp/mcpScopes.js +118 -0
  165. package/mcp/meshHttp.js +151 -45
  166. package/mcp/runStdio.js +2 -0
  167. package/mcp/subtreeTools.js +184 -0
  168. package/mcp/tryItTools.js +202 -0
  169. package/package.json +18 -9
  170. package/public/.DS_Store +0 -0
  171. package/public/pico-engine-ui.css +1 -1
  172. package/public/pico-engine-ui.js +26 -25
  173. package/src/bundledKrl.ts +118 -12
  174. package/src/cli.ts +8 -2
  175. package/src/engineConfig.ts +33 -2
  176. package/src/identity/portableMove.ts +6 -1
  177. package/src/index.ts +469 -422
  178. package/src/internalAccess.ts +127 -0
  179. package/src/oauth/OAuthService.ts +243 -11
  180. package/src/oauth/acg.ts +289 -25
  181. package/src/oauth/cimd.ts +508 -0
  182. package/src/oauth/discovery.ts +233 -0
  183. package/src/runMcp.ts +3 -1
  184. package/src/server.ts +266 -51
  185. package/src/subtreeWrangler.ts +17 -5
  186. package/src/uiChannelPolicies.ts +2 -0
@@ -0,0 +1,124 @@
1
+ ruleset com.example.thermostat {
2
+ meta {
3
+ name "Thermostat"
4
+ use module io.picolabs.xmlui alias ui
5
+ shares readings, threshold, dashboard, settings, readingHistory
6
+ }
7
+ global {
8
+ /**
9
+ * Recent readings, newest first (updates after thermostat new_reading).
10
+ * @returns Array
11
+ * @example "history" {}
12
+ */
13
+ readings = function() {
14
+ ent:readings.defaultsTo([]).reverse()
15
+ }
16
+
17
+ /**
18
+ * Alert threshold in degrees F
19
+ * @returns Number
20
+ * @example "default" {}
21
+ */
22
+ threshold = function() {
23
+ ent:threshold.defaultsTo(80)
24
+ }
25
+
26
+ /**
27
+ * Readings as a table. Props: rows (Array of { time, temperature }).
28
+ * @component
29
+ */
30
+ readingHistory = function() {
31
+ <<
32
+ <Component name="ReadingHistory">
33
+ <Table data="{$props.rows}">
34
+ <Column bindTo="time" header="Time" />
35
+ <Column bindTo="temperature" header="Temperature (F)" />
36
+ </Table>
37
+ </Component>
38
+ >>
39
+ }
40
+
41
+ /**
42
+ * Current temperature and history. Display picks the theme, using the
43
+ * shared PicoSettings, PicoThemeField, and PicoTheme components.
44
+ * @view "Dashboard"
45
+ */
46
+ dashboard = function() {
47
+ <<
48
+ <Component name="Dashboard">
49
+ #{ui:query("readings", "readings", {"rid": meta:rid})}
50
+ #{ui:query("threshold", "threshold", {"rid": meta:rid})}
51
+ <PicoSettings id="display" title="Display">
52
+ <PicoThemeField />
53
+ </PicoSettings>
54
+ <PicoTheme>
55
+ <HStack horizontalAlignment="end">
56
+ <Button label="Display" onClick="display.open()" />
57
+ </HStack>
58
+ <Card title="Now: {readings.value[0].temperature} F"
59
+ subtitle="Alert above {threshold.value} F" />
60
+ <ReadingHistory rows="{readings}" />
61
+ </PicoTheme>
62
+ </Component>
63
+ >>
64
+ }
65
+
66
+ /**
67
+ * Change the alert threshold
68
+ * @view "Settings"
69
+ */
70
+ settings = function() {
71
+ <<
72
+ <Component name="Settings">
73
+ #{ui:query("threshold", "threshold", {"rid": meta:rid})}
74
+ #{ui:event("setThreshold", "thermostat", "threshold_set",
75
+ {"rid": meta:rid, "refresh": ["threshold"], "confirm": "Change the alert threshold?"})}
76
+ <Form data="{{ threshold: threshold.value }}"
77
+ onSubmit="(toSave) => setThreshold.execute(toSave)">
78
+ <FormItem bindTo="threshold" label="Alert above (F)" type="integer" />
79
+ </Form>
80
+ </Component>
81
+ >>
82
+ }
83
+
84
+ viewer_tags = ["thermostat", "viewer"]
85
+ admin_tags = ["thermostat", "admin"]
86
+ }
87
+
88
+ /**
89
+ * Record a temperature reading (shown on the Dashboard view).
90
+ * @attr temperature Number Degrees Fahrenheit
91
+ * @example "room temperature" { "temperature": "72" }
92
+ * @example "warm alert" { "temperature": "85" }
93
+ */
94
+ rule record_reading {
95
+ select when thermostat new_reading
96
+ temperature re#(.+)# setting(temperature)
97
+ fired {
98
+ ent:readings := ent:readings.defaultsTo([])
99
+ .append({"temperature": temperature.as("Number"), "time": time:now()})
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Set the alert threshold (same as the Settings view form).
105
+ * @attr threshold Number Degrees Fahrenheit
106
+ * @example "alert at 80 F" { "threshold": "80" }
107
+ * @example "alert at 75 F" { "threshold": "75" }
108
+ */
109
+ rule set_threshold {
110
+ select when thermostat threshold_set
111
+ threshold re#^(\d+)$# setting(threshold)
112
+ fired {
113
+ ent:threshold := threshold.as("Number")
114
+ }
115
+ }
116
+
117
+ rule create_app_channels {
118
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
119
+ every {
120
+ ui:create_app_channel(viewer_tags, [], ["readings", "threshold", "dashboard"], meta:rid)
121
+ ui:create_app_channel(admin_tags, ["thermostat"], null, meta:rid)
122
+ }
123
+ }
124
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Demo data ruleset: `latestReadings` returns a fixed array (no `picoQuery`).
3
+ * Install on the **data** pico. The view demo (`com.example.temperature_sensors_view`)
4
+ * queries this ruleset over a relationship/subscription Tx (`wrangler:picoQuery`).
5
+ *
6
+ * Shape per row: `name`, `lastTemperature`, `readingAt`, `timestamp`.
7
+ */
8
+ ruleset com.example.temperature_sensors {
9
+ meta {
10
+ name "Temperature sensors (static demo)"
11
+ description "Static sample readings for XMLUI demos"
12
+ provides latestReadings
13
+ shares latestReadings
14
+ }
15
+
16
+ global {
17
+ /**
18
+ * Fixed sample readings (replace with real data or `ent:` when you are ready).
19
+ * @returns Array
20
+ */
21
+ latestReadings = function() {
22
+ [
23
+ {
24
+ "name": "Sensors:Beehive",
25
+ "lastTemperature": 51.47,
26
+ "readingAt": "2026-11-06 19:11:14 Coordinated Universal Time",
27
+ "timestamp": 1793992274126
28
+ },
29
+ {
30
+ "name": "Sensors:Cabin Crawl Space",
31
+ "lastTemperature": 55.4,
32
+ "readingAt": "2026-11-06 19:01:48 Coordinated Universal Time",
33
+ "timestamp": 1793991708383
34
+ },
35
+ {
36
+ "name": "Sensors:Cabin North Side",
37
+ "lastTemperature": 38.46,
38
+ "readingAt": "2026-11-06 18:59:45 Coordinated Universal Time",
39
+ "timestamp": 1793991585382
40
+ },
41
+ {
42
+ "name": "Sensors:Pump House",
43
+ "lastTemperature": 51.15,
44
+ "readingAt": "2026-11-06 19:01:24 Coordinated Universal Time",
45
+ "timestamp": 1793991684238
46
+ },
47
+ {
48
+ "name": "Sensors:Triple Temp",
49
+ "lastTemperature": 51.08,
50
+ "readingAt": "2026-11-06 19:11:54 Coordinated Universal Time",
51
+ "timestamp": 1793992314892
52
+ }
53
+ ]
54
+ }
55
+ }
56
+ }
@@ -0,0 +1,5 @@
1
+ - Open both dashboard links. On the viewer channel the navigation has only Dashboard. On the admin channel it also has Settings.
2
+ - On **Settings**, change the alert threshold, then go back to the Dashboard.
3
+ - Click **Display** on the Dashboard. The theme picker is built from the shared `PicoSettings` and `PicoThemeField` components. The readings table is the ruleset's own `ReadingHistory` component.
4
+ - Open the child pico's **Channels** tab and compare the query policies of `thermostat, viewer` and `thermostat, admin`. That policy is the whole difference between the two views.
5
+ - On the **Testing** tab, raise `thermostat` `new_reading` with a `temperature`, and reload the dashboard.
@@ -7,7 +7,9 @@ exports.engineKrlHttpPath = engineKrlHttpPath;
7
7
  exports.engineKrlFileUrl = engineKrlFileUrl;
8
8
  exports.listEngineKrlSources = listEngineKrlSources;
9
9
  exports.engineKrlRelativeFromUrl = engineKrlRelativeFromUrl;
10
+ exports.demosDir = demosDir;
10
11
  exports.resolveEngineKrlFile = resolveEngineKrlFile;
12
+ exports.listTryItDemos = listTryItDemos;
11
13
  exports.resolveBundledKrlUrl = resolveBundledKrlUrl;
12
14
  const fs = require("fs");
13
15
  const path = require("path");
@@ -126,27 +128,110 @@ function engineKrlRelativeFromUrl(url) {
126
128
  }
127
129
  if (parsed.protocol === "http:" || parsed.protocol === "https:") {
128
130
  const match = parsed.pathname.match(/^\/krl\/(.+\.krl)$/);
129
- if (match) {
130
- const relativePath = match[1].split("/").join(path.sep);
131
- const candidate = path.join(bundledKrlDir(), relativePath);
132
- if (fs.existsSync(candidate)) {
133
- return match[1];
134
- }
131
+ if (match && resolveEngineKrlFile(match[1])) {
132
+ return match[1];
135
133
  }
136
134
  }
137
135
  return null;
138
136
  }
139
- function resolveEngineKrlFile(relativePath) {
140
- const normalized = relativePath.split("/").join(path.sep);
141
- const candidate = path.resolve(bundledKrlDir(), normalized);
142
- const root = bundledKrlDir();
137
+ /**
138
+ * The demos/ directory: PICO_ENGINE_DEMOS_DIR when set (a copy someone edits
139
+ * and keeps across upgrades), else inside the package when installed from npm
140
+ * (copied at pack time), else the repository root in a checkout.
141
+ */
142
+ function demosDir() {
143
+ const override = process.env.PICO_ENGINE_DEMOS_DIR;
144
+ const candidates = [
145
+ ...(override && override.trim() ? [path.resolve(override.trim())] : []),
146
+ path.resolve(__dirname, "..", "demos"),
147
+ path.resolve(__dirname, "..", "..", "..", "demos"),
148
+ ];
149
+ for (const dir of candidates) {
150
+ if (fs.existsSync(dir) && fs.statSync(dir).isDirectory())
151
+ return dir;
152
+ }
153
+ return null;
154
+ }
155
+ function fileWithin(root, relativePath) {
156
+ const candidate = path.resolve(root, relativePath.split("/").join(path.sep));
143
157
  if (candidate.startsWith(root + path.sep) &&
144
- fs.existsSync(candidate) &&
145
- candidate.endsWith(".krl")) {
158
+ candidate.endsWith(".krl") &&
159
+ fs.existsSync(candidate)) {
146
160
  return candidate;
147
161
  }
148
162
  return null;
149
163
  }
164
+ /** `relativePath` is under krl/, or under demos/ when it starts with `demos/`. */
165
+ function resolveEngineKrlFile(relativePath) {
166
+ if (relativePath.startsWith("demos/")) {
167
+ const root = demosDir();
168
+ return root ? fileWithin(root, relativePath.slice("demos/".length)) : null;
169
+ }
170
+ return fileWithin(bundledKrlDir(), relativePath);
171
+ }
172
+ function readNotes(root, folder) {
173
+ try {
174
+ return fs.readFileSync(path.join(root, folder, "try-it.md"), "utf8");
175
+ }
176
+ catch (_a) {
177
+ return undefined;
178
+ }
179
+ }
180
+ /** Folder names from demos/try-it-order.json (a JSON array), or none if it is missing or invalid. */
181
+ function tryItOrder(root) {
182
+ try {
183
+ const order = JSON.parse(fs.readFileSync(path.join(root, "try-it-order.json"), "utf8"));
184
+ return Array.isArray(order) ? order.filter((f) => typeof f === "string") : [];
185
+ }
186
+ catch (_a) {
187
+ return [];
188
+ }
189
+ }
190
+ /**
191
+ * Every demos/<folder>/<rid>.bootstrap.krl, for the developer UI's "Try It!" tab.
192
+ * Folders named in demos/try-it-order.json come first, in that order; the rest follow by path.
193
+ */
194
+ function listTryItDemos(baseUrl) {
195
+ const root = demosDir();
196
+ if (!root)
197
+ return [];
198
+ const files = [];
199
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
200
+ if (!entry.isDirectory() || entry.name.startsWith("."))
201
+ continue;
202
+ walkKrlFiles(path.join(root, entry.name), root, files);
203
+ }
204
+ const base = baseUrl.replace(/\/$/, "");
205
+ const fileInfo = (rel) => ({
206
+ rid: readKrlMeta(path.join(root, rel)).rid,
207
+ file: path.basename(rel),
208
+ url: `${base}/krl/demos/${rel}`,
209
+ path: path.join(root, rel),
210
+ });
211
+ const order = tryItOrder(root);
212
+ const rank = (rel) => {
213
+ const i = order.indexOf(rel.split("/")[0]);
214
+ return i < 0 ? order.length : i;
215
+ };
216
+ return files
217
+ .filter((rel) => rel.endsWith(".bootstrap.krl"))
218
+ .sort((a, b) => rank(a) - rank(b) || (a < b ? -1 : a > b ? 1 : 0))
219
+ .map((rel) => {
220
+ const meta = readKrlMeta(path.join(root, rel));
221
+ const folder = rel.split("/")[0];
222
+ return {
223
+ rid: meta.rid,
224
+ name: meta.name,
225
+ description: meta.description,
226
+ folder,
227
+ url: `${base}/krl/demos/${rel}`,
228
+ path: path.join(root, rel),
229
+ docs: `https://docs.picolabs.io/#/cookbook/${folder}/`,
230
+ notes: readNotes(root, folder),
231
+ files: files.filter((f) => f.split("/")[0] === folder).sort().map(fileInfo),
232
+ };
233
+ });
234
+ }
150
235
  function resolveBundledKrlUrl(url) {
151
236
  const relativePath = engineKrlRelativeFromUrl(url);
152
237
  if (!relativePath) {
package/dist/cli.js CHANGED
@@ -70,11 +70,13 @@ Environment (optional; Docker/CI when not set in config file):
70
70
  PICO_ENGINE_BASE_URL - Public URL (WebAuthn, did:webvh)
71
71
  PICO_ENGINE_RP_ID / PICO_ENGINE_ORIGIN - WebAuthn (or use webauthn block in config file)
72
72
  PICO_ENGINE_ALLOW_SELF_SIGNUP - "true"/"1" or "false"/"0"
73
- PICO_ENGINE_ALLOW_LOCALHOST_C - "0" disables localhost /c/* bypass (see config allowLocalhostChannelBypass)
73
+ PICO_ENGINE_ALLOW_LOCALHOST_C - "1"/"true" allows direct loopback /c/* without a passkey (default off; config allowLocalhostChannelBypass). Dev MCP uses $PICO_ENGINE_HOME/internal-token
74
74
  PICO_ENGINE_WILDCARD_SKY_REQUIRE_BEARER - "1" enables wildcard /sky/* bearer requirement
75
75
  PICO_ENGINE_LOG_FILE - Log path, or stdout/- / 0 for console-only
76
76
  PICO_ENGINE_LOG_MIRROR - "true"/"1" or "false"/"0" (mirror JSON lines to \$PICO_ENGINE_HOME/pico-engine.log when stdout-only; default on)
77
77
  PICO_ENGINE_LOG_RING - how many recent transactions per pico the Logging tab keeps in memory (default 200; cleared on restart)
78
+ PICO_ENGINE_SHOW_TRYIT_MENU - off, root_only (default), or all: where the Developer UI shows the Try It! tab (config: show_tryit_menu)
79
+ PICO_ENGINE_DEMOS_DIR - directory to serve as demos/ (/krl/demos/) instead of the shipped copy
78
80
  `);
79
81
  process.exit(0);
80
82
  }
@@ -113,6 +115,10 @@ Environment (optional; Docker/CI when not set in config file):
113
115
  installGracefulShutdown(engine);
114
116
  })
115
117
  .catch((err) => {
118
+ if (err && err.code === "EADDRINUSE") {
119
+ console.error(`Port ${err.port} is already in use.`);
120
+ process.exit(1);
121
+ }
116
122
  console.error("Failed to start engine.");
117
123
  console.error(err);
118
124
  process.exit(1);
@@ -14,6 +14,15 @@ const os = require("os");
14
14
  const path = require("path");
15
15
  const policyConfigFromJson_1 = require("./policyConfigFromJson");
16
16
  const homeDir = require("home-dir");
17
+ const SHOW_TRY_IT_MENU_VALUES = ["off", "root_only", "all"];
18
+ function parseShowTryItMenu(val, source) {
19
+ if (val === undefined)
20
+ return undefined;
21
+ if (typeof val === "string" && SHOW_TRY_IT_MENU_VALUES.includes(val)) {
22
+ return val;
23
+ }
24
+ throw new Error(`${source} must be one of ${SHOW_TRY_IT_MENU_VALUES.join(", ")} (got ${JSON.stringify(val)})`);
25
+ }
17
26
  let runtimeSettings = null;
18
27
  function installEngineRuntimeSettings(settings) {
19
28
  runtimeSettings = settings;
@@ -30,10 +39,11 @@ function defaultEngineSettings() {
30
39
  port: 3000,
31
40
  baseUrl: "http://localhost:3000",
32
41
  allowSelfSignup: false,
33
- allowLocalhostChannelBypass: true,
42
+ allowLocalhostChannelBypass: false,
34
43
  wildcardSkyRequireBearer: false,
35
44
  logToStdout: false,
36
45
  logMirror: true,
46
+ showTryItMenu: "root_only",
37
47
  };
38
48
  }
39
49
  function defaultEngineConfigFilePath() {
@@ -146,6 +156,9 @@ function parseConfigFile(raw) {
146
156
  out.logFile = path.resolve(expandHome(o.logFile));
147
157
  }
148
158
  }
159
+ const showTryItMenu = parseShowTryItMenu(o.show_tryit_menu, "show_tryit_menu");
160
+ if (showTryItMenu)
161
+ out.showTryItMenu = showTryItMenu;
149
162
  const rootCeiling = (0, policyConfigFromJson_1.parsePolicyCeilingFromJson)(o.defaultRootPolicyCeiling, "defaultRootPolicyCeiling");
150
163
  if (rootCeiling) {
151
164
  out.defaultRootPolicyCeiling = rootCeiling;
@@ -227,6 +240,9 @@ function settingsFromEnv() {
227
240
  if (logMirror !== undefined) {
228
241
  out.logMirror = logMirror;
229
242
  }
243
+ const showTryItMenu = parseShowTryItMenu(process.env.PICO_ENGINE_SHOW_TRYIT_MENU || undefined, "PICO_ENGINE_SHOW_TRYIT_MENU");
244
+ if (showTryItMenu)
245
+ out.showTryItMenu = showTryItMenu;
230
246
  return out;
231
247
  }
232
248
  function mergeSettings(base, ...layers) {
@@ -277,6 +293,9 @@ function resolveEngineSettings(programmatic = {}) {
277
293
  if (programmatic.logMirror !== undefined) {
278
294
  fromProgrammatic.logMirror = programmatic.logMirror;
279
295
  }
296
+ if (programmatic.showTryItMenu !== undefined) {
297
+ fromProgrammatic.showTryItMenu = programmatic.showTryItMenu;
298
+ }
280
299
  if (programmatic.defaultRootPolicyCeiling !== undefined) {
281
300
  fromProgrammatic.defaultRootPolicyCeiling =
282
301
  programmatic.defaultRootPolicyCeiling;
@@ -75,7 +75,11 @@ async function importPortableSubtree(deps, parent, blob, secret, relocateOptions
75
75
  ? { channelEci: importOptions.parentChannelEci }
76
76
  : undefined;
77
77
  const bootstrapName = resolveImportBootstrapName(blob, secret, importOptions === null || importOptions === void 0 ? void 0 : importOptions.bootstrapDisplayName);
78
- const { familyEci } = await (0, subtreeWrangler_1.createImportChildViaWrangler)(deps.pf, parent, bootstrapName, deps.rsRegistry, createOpts);
78
+ const { familyEci } = await (0, subtreeWrangler_1.createImportChildViaWrangler)(deps.pf, parent, bootstrapName, deps.rsRegistry, createOpts, async (picoId, ctx) => {
79
+ if (deps.getBaseUrl()) {
80
+ await deps.identity.ensureWebvhDid(picoId, { isRoot: ctx.isRoot });
81
+ }
82
+ });
79
83
  const importResult = await (0, pico_engine_core_1.importIntoExistingChild)(services, deps.pf, parent, familyEci, blob, secret, Object.assign(Object.assign({}, importOptions), { async afterImport(result, payload) {
80
84
  if (importOptions === null || importOptions === void 0 ? void 0 : importOptions.afterImport) {
81
85
  await importOptions.afterImport(result, payload);
package/dist/index.js CHANGED
@@ -15,6 +15,7 @@ const provisionRoot_1 = require("./provisionRoot");
15
15
  const RulesetRegistryLoaderFs_1 = require("./RulesetRegistryLoaderFs");
16
16
  const bundledKrl_1 = require("./bundledKrl");
17
17
  const subtreeWrangler_1 = require("./subtreeWrangler");
18
+ const internalAccess_1 = require("./internalAccess");
18
19
  const server_1 = require("./server");
19
20
  const engineConfig_1 = require("./engineConfig");
20
21
  const charwise = require("charwise");
@@ -45,6 +46,8 @@ async function startEngine(configuration = {}) {
45
46
  rpName: configuration.rpName,
46
47
  origin: configuration.origin,
47
48
  allowSelfSignup: configuration.allowSelfSignup,
49
+ allowLocalhostChannelBypass: configuration.allowLocalhostChannelBypass,
50
+ showTryItMenu: configuration.showTryItMenu,
48
51
  defaultRootPolicyCeiling: configuration.defaultRootPolicyCeiling,
49
52
  globalEventDeny: configuration.globalEventDeny,
50
53
  globalQueryDeny: configuration.globalQueryDeny,
@@ -84,7 +87,7 @@ async function startEngine(configuration = {}) {
84
87
  });
85
88
  const pf = core.picoFramework;
86
89
  core.resolveBundledRulesetUrl = bundledKrl_1.resolveBundledKrlUrl;
87
- core.subtreeImportServices = (0, subtreeWrangler_1.wranglerSubtreeImportServices)(core.rsRegistry);
90
+ core.subtreeImportServices = (0, subtreeWrangler_1.wranglerSubtreeImportServices)(core.rsRegistry, (picoId, ctx) => onPicoCreated(picoId, ctx));
88
91
  const identity = new identity_1.IdentityStore({ db: pf.db });
89
92
  let identityService;
90
93
  const onPicoCreated = async (picoId, ctx) => {
@@ -187,25 +190,55 @@ async function startEngine(configuration = {}) {
187
190
  const oauth = new oauth_1.OAuthService({
188
191
  db: pf.db,
189
192
  pf,
193
+ getBaseUrl: () => core.base_url,
190
194
  });
191
195
  core.modules["oauth"] = (0, oauth_1.initOAuthModule)(oauth);
192
- const app = (0, server_1.server)(core, uiECI, auth, oauth, identityService);
196
+ await (0, pico_engine_core_1.warmPdsSecretLog)(core);
197
+ const internalToken = (0, internalAccess_1.writeInternalToken)(home);
198
+ const app = (0, server_1.server)(core, uiECI, auth, oauth, identityService, internalToken);
193
199
  if ((!port || !_.isInteger(port) || port < 1) && port !== 0) {
194
200
  port = process.env.NODE_ENV === "test" ? 0 : 3000;
195
201
  }
196
202
  let httpServer;
197
- await new Promise((resolve) => {
198
- httpServer = app.listen(port, () => {
199
- if (httpServer) {
200
- const addr = httpServer.address();
201
- if (addr && typeof addr !== "string" && _.isInteger(addr.port)) {
202
- // Get the actual port i.e. if they set port to 0 nodejs will assign you an available port
203
- port = addr.port;
203
+ let listening = false;
204
+ try {
205
+ await new Promise((resolve, reject) => {
206
+ httpServer = app.listen(port, () => {
207
+ listening = true;
208
+ if (httpServer) {
209
+ const addr = httpServer.address();
210
+ if (addr && typeof addr !== "string" && _.isInteger(addr.port)) {
211
+ // Get the actual port i.e. if they set port to 0 nodejs will assign you an available port
212
+ port = addr.port;
213
+ }
204
214
  }
205
- }
206
- resolve(undefined);
215
+ resolve(undefined);
216
+ });
217
+ // listen failures are an 'error' event. With no listener, Node throws.
218
+ httpServer.on("error", (err) => {
219
+ if (!listening) {
220
+ reject(err);
221
+ return;
222
+ }
223
+ log.error("HTTP server error", { error: err });
224
+ });
207
225
  });
208
- });
226
+ }
227
+ catch (err) {
228
+ const coded = err;
229
+ if (coded.code === "EADDRINUSE") {
230
+ log.error(`Port ${port} is already in use`);
231
+ }
232
+ else {
233
+ log.error("HTTP server failed to listen", { error: err, port });
234
+ }
235
+ if (httpServer) {
236
+ await new Promise((resolve) => httpServer.close(() => resolve()));
237
+ }
238
+ await rulesetLoaderHandle.close().catch(() => undefined);
239
+ await db.close().catch(() => undefined);
240
+ throw err;
241
+ }
209
242
  if (typeof base_url !== "string") {
210
243
  base_url = `http://localhost:${port}`;
211
244
  }
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.INTERNAL_TOKEN_HEADER = exports.INTERNAL_TOKEN_FILENAME = void 0;
4
+ exports.internalTokenPath = internalTokenPath;
5
+ exports.writeInternalToken = writeInternalToken;
6
+ exports.readInternalToken = readInternalToken;
7
+ exports.timingSafeEqualString = timingSafeEqualString;
8
+ exports.internalTokenAccepted = internalTokenAccepted;
9
+ exports.requestCarriesProxyClientHeaders = requestCarriesProxyClientHeaders;
10
+ exports.isDirectLoopbackRequest = isDirectLoopbackRequest;
11
+ exports.headersForKrl = headersForKrl;
12
+ const crypto = require("crypto");
13
+ const fs = require("fs");
14
+ const path = require("path");
15
+ /** File name under `PICO_ENGINE_HOME`. The dev MCP client reads the same file. */
16
+ exports.INTERNAL_TOKEN_FILENAME = "internal-token";
17
+ /** HTTP header the dev MCP sends. Express stores it lower-case. */
18
+ exports.INTERNAL_TOKEN_HEADER = "x-pico-internal";
19
+ /**
20
+ * Request headers that must not reach KRL. `x-pico-internal` is the engine's
21
+ * own dev credential; the others are caller credentials (1.10 §5 H1).
22
+ */
23
+ const CREDENTIAL_HEADERS = new Set([
24
+ "authorization",
25
+ "proxy-authorization",
26
+ "cookie",
27
+ "x-pico-internal",
28
+ ]);
29
+ const PROXY_CLIENT_HEADERS = ["x-forwarded-for", "x-real-ip", "forwarded"];
30
+ function internalTokenPath(home) {
31
+ return path.join(home, exports.INTERNAL_TOKEN_FILENAME);
32
+ }
33
+ /** New secret on every startup. Mode 0600 even when umask would loosen the write. */
34
+ function writeInternalToken(home) {
35
+ const token = crypto.randomBytes(32).toString("base64url");
36
+ const file = internalTokenPath(home);
37
+ fs.writeFileSync(file, `${token}\n`, { encoding: "utf8", mode: 0o600 });
38
+ fs.chmodSync(file, 0o600);
39
+ return token;
40
+ }
41
+ function readInternalToken(home) {
42
+ try {
43
+ const token = fs.readFileSync(internalTokenPath(home), "utf8").trim();
44
+ return token.length > 0 ? token : null;
45
+ }
46
+ catch (_err) {
47
+ return null;
48
+ }
49
+ }
50
+ function timingSafeEqualString(actual, expected) {
51
+ const a = Buffer.from(actual);
52
+ const b = Buffer.from(expected);
53
+ if (a.length !== b.length) {
54
+ return false;
55
+ }
56
+ return crypto.timingSafeEqual(a, b);
57
+ }
58
+ function internalTokenAccepted(presented, expected) {
59
+ if (!expected || typeof presented !== "string") {
60
+ return false;
61
+ }
62
+ const token = presented.trim();
63
+ if (!token) {
64
+ return false;
65
+ }
66
+ return timingSafeEqualString(token, expected);
67
+ }
68
+ function headerIsPresent(headers, name) {
69
+ const value = headers[name];
70
+ if (typeof value === "string") {
71
+ return true;
72
+ }
73
+ return Array.isArray(value) && value.length > 0;
74
+ }
75
+ /** A proxy sat in front of this request. Its socket address is the proxy, not the client. */
76
+ function requestCarriesProxyClientHeaders(headers) {
77
+ return PROXY_CLIENT_HEADERS.some((name) => headerIsPresent(headers, name));
78
+ }
79
+ function isLoopbackAddress(addr) {
80
+ if (!addr) {
81
+ return false;
82
+ }
83
+ const normalized = addr.replace(/^::ffff:/, "");
84
+ return normalized === "127.0.0.1" || normalized === "::1";
85
+ }
86
+ /**
87
+ * Direct TCP from this machine. The `Host` header is not consulted: clients set it.
88
+ * `X-Forwarded-For`, `X-Real-IP`, and `Forwarded` mean the peer is a proxy.
89
+ */
90
+ function isDirectLoopbackRequest(req) {
91
+ var _a;
92
+ if (requestCarriesProxyClientHeaders(req.headers)) {
93
+ return false;
94
+ }
95
+ if (isLoopbackAddress(req.ip)) {
96
+ return true;
97
+ }
98
+ return isLoopbackAddress((_a = req.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress);
99
+ }
100
+ /** Copy of the request headers with credential headers removed. */
101
+ function headersForKrl(headers) {
102
+ const out = {};
103
+ for (const [key, value] of Object.entries(headers)) {
104
+ if (value === undefined || CREDENTIAL_HEADERS.has(key.toLowerCase())) {
105
+ continue;
106
+ }
107
+ out[key] = value;
108
+ }
109
+ return out;
110
+ }