pico-engine 1.6.2 → 1.8.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 (107) hide show
  1. package/README.md +117 -14
  2. package/dist/RulesetRegistryLoaderFs.js +24 -8
  3. package/dist/auth/cookies.js +32 -0
  4. package/dist/auth/index.js +6 -1
  5. package/dist/bundledKrl.js +129 -11
  6. package/dist/channelIdentityPolicy.js +22 -0
  7. package/dist/cli.js +105 -46
  8. package/dist/engineConfig.js +280 -0
  9. package/dist/identity/IdentityService.js +90 -0
  10. package/dist/identity/crossPico.js +106 -30
  11. package/dist/identity/didoModule.js +80 -18
  12. package/dist/identity/establishSubscription.js +2 -2
  13. package/dist/identity/identityPortable.js +92 -0
  14. package/dist/identity/index.js +10 -1
  15. package/dist/identity/localPeerReconcile.js +65 -0
  16. package/dist/identity/peerDid4.js +175 -0
  17. package/dist/identity/peerDid4Create.js +90 -0
  18. package/dist/identity/portableExportPrepare.js +196 -0
  19. package/dist/identity/portableMove.js +87 -0
  20. package/dist/identity/skyIntro.js +10 -4
  21. package/dist/identity/skyProtocol.js +26 -1
  22. package/dist/identity/skyRotation.js +121 -0
  23. package/dist/identity/store.js +5 -1
  24. package/dist/identity/subscriptionEntSync.js +72 -0
  25. package/dist/identity/veramoDidComm.js +41 -2
  26. package/dist/identity/webvh.js +4 -2
  27. package/dist/identity/webvhRelocation.js +115 -0
  28. package/dist/index.js +127 -34
  29. package/dist/levelDb.js +102 -0
  30. package/dist/logging.js +47 -8
  31. package/dist/oauth/OAuthService.js +12 -5
  32. package/dist/oauth/channelEligibility.js +7 -1
  33. package/dist/oauth/index.js +3 -1
  34. package/dist/policyConfigFromJson.js +112 -0
  35. package/dist/runMcp.js +27 -0
  36. package/dist/server.js +95 -24
  37. package/dist/subtreeWrangler.js +180 -0
  38. package/dist/uiChannelPolicies.js +16 -0
  39. package/krl/io.picolabs.oauth.krl +51 -5
  40. package/krl/io.picolabs.pds.krl +131 -10
  41. package/krl/io.picolabs.pico-engine-ui.krl +219 -22
  42. package/krl/io.picolabs.portable_subtree.krl +97 -0
  43. package/krl/io.picolabs.subscription.krl +226 -72
  44. package/krl/io.picolabs.wrangler.krl +300 -58
  45. package/mcp/devResources.js +118 -0
  46. package/mcp/devTools.js +351 -0
  47. package/mcp/engineClient.js +133 -0
  48. package/mcp/meshHttp.js +137 -0
  49. package/mcp/meshTools.js +189 -0
  50. package/mcp/runStdio.js +34 -0
  51. package/mcp/schemaToZod.js +56 -0
  52. package/package.json +22 -8
  53. package/public/docs/_sidebar.md +2 -1
  54. package/public/docs/llms-full.txt +479 -0
  55. package/public/docs/llms.txt +37 -0
  56. package/public/docs/openapi.yaml +78 -0
  57. package/public/docs/pico-engine.md +235 -4
  58. package/public/docs/pico-overview.md +117 -0
  59. package/public/docs/pico.md +3 -1
  60. package/public/docs/rulesets/README.md +25 -0
  61. package/public/docs/rulesets/io.picolabs.oauth.md +71 -0
  62. package/public/docs/rulesets/io.picolabs.pds.md +327 -0
  63. package/public/docs/rulesets/io.picolabs.pico-engine-ui.md +65 -0
  64. package/public/docs/rulesets/io.picolabs.portable_subtree.md +94 -0
  65. package/public/docs/rulesets/io.picolabs.subscription.md +398 -0
  66. package/public/docs/rulesets/io.picolabs.wrangler.md +471 -0
  67. package/public/pico-engine-ui.css +1 -1
  68. package/public/pico-engine-ui.js +28 -26
  69. package/src/RulesetRegistryLoaderFs.ts +43 -11
  70. package/src/auth/cookies.ts +34 -0
  71. package/src/auth/index.ts +7 -0
  72. package/src/bundledKrl.ts +150 -12
  73. package/src/channelIdentityPolicy.ts +29 -0
  74. package/src/cli.ts +98 -40
  75. package/src/engineConfig.ts +345 -0
  76. package/src/identity/IdentityService.ts +189 -1
  77. package/src/identity/crossPico.ts +161 -41
  78. package/src/identity/didoModule.ts +140 -23
  79. package/src/identity/establishSubscription.ts +2 -2
  80. package/src/identity/identityPortable.ts +153 -0
  81. package/src/identity/index.ts +14 -0
  82. package/src/identity/localPeerReconcile.ts +97 -0
  83. package/src/identity/peerDid4.ts +197 -0
  84. package/src/identity/peerDid4Create.ts +121 -0
  85. package/src/identity/portableExportPrepare.ts +302 -0
  86. package/src/identity/portableMove.ts +193 -0
  87. package/src/identity/skyIntro.ts +16 -12
  88. package/src/identity/skyProtocol.ts +46 -0
  89. package/src/identity/skyRotation.ts +211 -0
  90. package/src/identity/store.ts +5 -1
  91. package/src/identity/subscriptionEntSync.ts +97 -0
  92. package/src/identity/veramoDidComm.ts +52 -2
  93. package/src/identity/webvh.ts +4 -4
  94. package/src/identity/webvhRelocation.ts +167 -0
  95. package/src/index.ts +179 -39
  96. package/src/levelDb.ts +122 -0
  97. package/src/logging.ts +63 -11
  98. package/src/oauth/OAuthService.ts +20 -6
  99. package/src/oauth/channelEligibility.ts +9 -0
  100. package/src/oauth/index.ts +7 -1
  101. package/src/policyConfigFromJson.ts +131 -0
  102. package/src/runMcp.ts +30 -0
  103. package/src/server.ts +133 -27
  104. package/src/subtreeWrangler.ts +278 -0
  105. package/src/uiChannelPolicies.ts +16 -0
  106. package/krl/io.picolabs.did-o.krl +0 -349
  107. package/krl/test/didtestdid.krl +0 -78
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parsePolicyCeilingFromJson = parsePolicyCeilingFromJson;
4
+ exports.parseGlobalEventDenyFromJson = parseGlobalEventDenyFromJson;
5
+ exports.parseGlobalQueryDenyFromJson = parseGlobalQueryDenyFromJson;
6
+ function isRecord(v) {
7
+ return v != null && typeof v === "object" && !Array.isArray(v);
8
+ }
9
+ function cleanEventPolicyFromJson(orig) {
10
+ if (!isRecord(orig) ||
11
+ !Array.isArray(orig.allow) ||
12
+ !Array.isArray(orig.deny)) {
13
+ throw new TypeError("eventPolicy expects { allow: EventPolicyRule[], deny: EventPolicyRule[] }");
14
+ }
15
+ const allow = [];
16
+ for (const item of orig.allow) {
17
+ if (!isRecord(item) || typeof item.domain !== "string" || typeof item.name !== "string") {
18
+ throw new TypeError("eventPolicy allow entries need domain and name strings");
19
+ }
20
+ allow.push({ domain: item.domain.trim(), name: item.name.trim() });
21
+ }
22
+ const deny = [];
23
+ for (const item of orig.deny) {
24
+ if (!isRecord(item) || typeof item.domain !== "string" || typeof item.name !== "string") {
25
+ throw new TypeError("eventPolicy deny entries need domain and name strings");
26
+ }
27
+ deny.push({ domain: item.domain.trim(), name: item.name.trim() });
28
+ }
29
+ return { allow, deny };
30
+ }
31
+ function cleanQueryPolicyFromJson(orig) {
32
+ if (!isRecord(orig) ||
33
+ !Array.isArray(orig.allow) ||
34
+ !Array.isArray(orig.deny)) {
35
+ throw new TypeError("queryPolicy expects { allow: QueryPolicyRule[], deny: QueryPolicyRule[] }");
36
+ }
37
+ const allow = [];
38
+ for (const item of orig.allow) {
39
+ if (!isRecord(item) || typeof item.rid !== "string" || typeof item.name !== "string") {
40
+ throw new TypeError("queryPolicy allow entries need rid and name strings");
41
+ }
42
+ allow.push({ rid: item.rid.trim(), name: item.name.trim() });
43
+ }
44
+ const deny = [];
45
+ for (const item of orig.deny) {
46
+ if (!isRecord(item) || typeof item.rid !== "string" || typeof item.name !== "string") {
47
+ throw new TypeError("queryPolicy deny entries need rid and name strings");
48
+ }
49
+ deny.push({ rid: item.rid.trim(), name: item.name.trim() });
50
+ }
51
+ return { allow, deny };
52
+ }
53
+ function parseEventRule(v) {
54
+ if (!isRecord(v))
55
+ return null;
56
+ if (typeof v.domain !== "string" || typeof v.name !== "string")
57
+ return null;
58
+ return { domain: v.domain, name: v.name };
59
+ }
60
+ function parseQueryRule(v) {
61
+ if (!isRecord(v))
62
+ return null;
63
+ if (typeof v.rid !== "string" || typeof v.name !== "string")
64
+ return null;
65
+ return { rid: v.rid, name: v.name };
66
+ }
67
+ function parsePolicyCeilingFromJson(val, fieldName) {
68
+ if (val === undefined || val === null) {
69
+ return undefined;
70
+ }
71
+ if (!isRecord(val) || !val.eventPolicy || !val.queryPolicy) {
72
+ throw new Error(`${fieldName} must be { eventPolicy: { allow, deny }, queryPolicy: { allow, deny } }`);
73
+ }
74
+ return {
75
+ eventPolicy: cleanEventPolicyFromJson(val.eventPolicy),
76
+ queryPolicy: cleanQueryPolicyFromJson(val.queryPolicy),
77
+ };
78
+ }
79
+ function parseGlobalEventDenyFromJson(val) {
80
+ if (val === undefined || val === null) {
81
+ return undefined;
82
+ }
83
+ if (!Array.isArray(val)) {
84
+ throw new Error("globalEventDeny must be an array of { domain, name } rules");
85
+ }
86
+ const rules = [];
87
+ for (const item of val) {
88
+ const rule = parseEventRule(item);
89
+ if (!rule) {
90
+ throw new Error("globalEventDeny: each entry needs domain and name strings");
91
+ }
92
+ rules.push(rule);
93
+ }
94
+ return rules;
95
+ }
96
+ function parseGlobalQueryDenyFromJson(val) {
97
+ if (val === undefined || val === null) {
98
+ return undefined;
99
+ }
100
+ if (!Array.isArray(val)) {
101
+ throw new Error("globalQueryDeny must be an array of { rid, name } rules");
102
+ }
103
+ const rules = [];
104
+ for (const item of val) {
105
+ const rule = parseQueryRule(item);
106
+ if (!rule) {
107
+ throw new Error("globalQueryDeny: each entry needs rid and name strings");
108
+ }
109
+ rules.push(rule);
110
+ }
111
+ return rules;
112
+ }
package/dist/runMcp.js ADDED
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runMcpCli = runMcpCli;
4
+ const engineConfig_1 = require("./engineConfig");
5
+ /** Dev MCP stdio entry (pico-engine mcp --stdio). */
6
+ async function runMcpCli(argv) {
7
+ const settings = (0, engineConfig_1.resolveEngineSettings)({});
8
+ (0, engineConfig_1.installEngineRuntimeSettings)(settings);
9
+ if (!process.env.PICO_ENGINE_BASE_URL) {
10
+ process.env.PICO_ENGINE_BASE_URL = settings.baseUrl;
11
+ }
12
+ if (!process.env.PICO_ENGINE_HOME) {
13
+ process.env.PICO_ENGINE_HOME = settings.home;
14
+ }
15
+ const args = argv.slice(1);
16
+ const stdio = args.includes("--stdio") || args.length === 0;
17
+ if (!stdio) {
18
+ console.error("Usage: pico-engine mcp --stdio");
19
+ console.error("");
20
+ console.error("Connects to a running local engine (PICO_ENGINE_BASE_URL).");
21
+ console.error("Requires localhost /c access or PICO_ENGINE_UI_ECI.");
22
+ process.exit(1);
23
+ }
24
+ // JS (not tsc): avoids pulling MCP SDK types into the main compile.
25
+ const { runDevMcpStdio } = require("../mcp/runStdio.js");
26
+ await runDevMcpStdio();
27
+ }
package/dist/server.js CHANGED
@@ -3,19 +3,20 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.server = server;
4
4
  const bodyParser = require("body-parser");
5
5
  const express = require("express");
6
+ const fs = require("fs");
6
7
  const helmet_1 = require("helmet");
7
8
  const _ = require("lodash");
8
9
  const path = require("path");
10
+ const bundledKrl_1 = require("./bundledKrl");
9
11
  const auth_1 = require("./auth");
10
12
  const oauth_1 = require("./oauth");
11
13
  const provisionRoot_1 = require("./provisionRoot");
12
14
  const webvhRoutes_1 = require("./identity/webvhRoutes");
13
15
  const didcommIngressRoutes_1 = require("./identity/didcommIngressRoutes");
16
+ const engineConfig_1 = require("./engineConfig");
14
17
  const engineVersion = require("../package.json").version;
15
- const SESSION_COOKIE = "pico-session";
16
- const CEREMONY_COOKIE = "pico-ceremony";
17
18
  function localhostChannelBypassEnabled() {
18
- return process.env.PICO_ENGINE_ALLOW_LOCALHOST_C !== "0";
19
+ return (0, engineConfig_1.getEngineRuntimeSettings)().allowLocalhostChannelBypass;
19
20
  }
20
21
  function mergeGetPost(req) {
21
22
  // give preference to post body params
@@ -61,6 +62,11 @@ function isLocalhostRequest(req) {
61
62
  function server(core, uiECI, auth, oauth, identity) {
62
63
  const pf = core.picoFramework;
63
64
  const app = express();
65
+ function cookies() {
66
+ return auth
67
+ ? (0, auth_1.authCookieNames)(auth.rp().origin)
68
+ : (0, auth_1.authCookieNames)("http://localhost:3000");
69
+ }
64
70
  app.use(function (req, res, next) {
65
71
  // /auth routes need a specific credentialed CORS origin (below), not "*".
66
72
  if (req.path.indexOf("/auth") === 0) {
@@ -120,7 +126,7 @@ function server(core, uiECI, auth, oauth, identity) {
120
126
  (0, didcommIngressRoutes_1.registerDidcommIngressRoutes)(app, identity);
121
127
  }
122
128
  if (auth) {
123
- registerAuthRoutes(app, auth);
129
+ registerAuthRoutes(app, auth, cookies);
124
130
  }
125
131
  function isEciInRootTree(rootPicoId, eci) {
126
132
  try {
@@ -145,7 +151,7 @@ function server(core, uiECI, auth, oauth, identity) {
145
151
  next();
146
152
  return;
147
153
  }
148
- const token = parseCookies(req)[SESSION_COOKIE] || "";
154
+ const token = parseCookies(req)[cookies().session] || "";
149
155
  auth
150
156
  .getSession(token)
151
157
  .then((session) => {
@@ -210,8 +216,14 @@ function server(core, uiECI, auth, oauth, identity) {
210
216
  .catch(next);
211
217
  }
212
218
  if (oauth) {
213
- registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookies);
219
+ registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookies, cookies);
214
220
  }
221
+ app.get("/api/oauth/mesh-enabled", requireAuthSession, function (_req, res) {
222
+ const roots = pf.rootPicos();
223
+ const meshOAuthEnabled = roots.length > 0 &&
224
+ roots.some((root) => (0, oauth_1.rootHasOAuthMeshRuleset)(pf, root.id));
225
+ res.json({ meshOAuthEnabled });
226
+ });
215
227
  app.get("/api/mesh-context", function (req, res, next) {
216
228
  if (!oauth) {
217
229
  res.status(503).json({ error: "OAuth not enabled" });
@@ -252,6 +264,37 @@ function server(core, uiECI, auth, oauth, identity) {
252
264
  })
253
265
  .catch(next);
254
266
  });
267
+ app.get("/api/krl-sources", function (req, res, next) {
268
+ try {
269
+ let baseUrl = core.base_url;
270
+ if (!baseUrl) {
271
+ baseUrl = `${req.protocol}://${req.get("host") || "localhost"}`;
272
+ }
273
+ res.json({ sources: (0, bundledKrl_1.listEngineKrlSources)(baseUrl.replace(/\/$/, "")) });
274
+ }
275
+ catch (err) {
276
+ next(err);
277
+ }
278
+ });
279
+ app.get(/^\/krl\/(.+\.krl)$/, function (req, res, next) {
280
+ const suffix = req.params[0];
281
+ if (typeof suffix !== "string" || !suffix.endsWith(".krl")) {
282
+ res.status(404).end();
283
+ return;
284
+ }
285
+ const filePath = (0, bundledKrl_1.resolveEngineKrlFile)(suffix);
286
+ if (!filePath) {
287
+ res.status(404).end();
288
+ return;
289
+ }
290
+ fs.readFile(filePath, { encoding: "utf8" }, function (err, data) {
291
+ if (err) {
292
+ next(err);
293
+ return;
294
+ }
295
+ res.type("text/plain").send(data);
296
+ });
297
+ });
255
298
  app.get("/api/ui-context", function (req, res, next) {
256
299
  const hasRoots = pf.rootPicos().length > 0;
257
300
  const base = {
@@ -264,7 +307,7 @@ function server(core, uiECI, auth, oauth, identity) {
264
307
  res.json(base);
265
308
  return;
266
309
  }
267
- const token = parseCookies(req)[SESSION_COOKIE] || "";
310
+ const token = parseCookies(req)[cookies().session] || "";
268
311
  auth
269
312
  .needsAuthMigration()
270
313
  .then((needsAuthMigration) => {
@@ -280,6 +323,26 @@ function server(core, uiECI, auth, oauth, identity) {
280
323
  })
281
324
  .catch(next);
282
325
  });
326
+ /** Localhost-only context for dev MCP (stdio) and other local tooling. */
327
+ app.get("/api/dev/local", function (req, res) {
328
+ if (!localhostChannelBypassEnabled() || !isLocalhostRequest(req)) {
329
+ res.status(403).json({ error: "localhost only" });
330
+ return;
331
+ }
332
+ const roots = pf.rootPicos();
333
+ const rootPico = roots[0];
334
+ const rootUiEci = rootPico ? (0, provisionRoot_1.uiECIForRoot)(pf, rootPico.id) : null;
335
+ let baseUrl = core.base_url;
336
+ if (!baseUrl) {
337
+ baseUrl = `${req.protocol}://${req.get("host") || "localhost"}`;
338
+ }
339
+ res.json({
340
+ version: engineVersion,
341
+ hasRoots: roots.length > 0,
342
+ rootUiEci,
343
+ baseUrl: baseUrl.replace(/\/$/, ""),
344
+ });
345
+ });
283
346
  app.all("/api/flush", requireAuthSession, function (req, res, next) {
284
347
  const attrs = mergeGetPost(req);
285
348
  const url = attrs["url"];
@@ -436,6 +499,10 @@ function server(core, uiECI, auth, oauth, identity) {
436
499
  app.all("/sky/query/:eci/:rid/:function", requireSkyBearerIfOAuth, handleSkyQuery);
437
500
  // Legacy alias; prefer /sky/query/ per Sky Query API docs.
438
501
  app.all("/sky/cloud/:eci/:rid/:function", requireSkyBearerIfOAuth, handleSkyQuery);
502
+ // Mesh MCP (Streamable HTTP, OAuth bearer scoped to :eci)
503
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
504
+ const { registerMeshMcpRoutes } = require("../mcp/meshHttp.js");
505
+ registerMeshMcpRoutes(app, core, oauth);
439
506
  app.use(function (err, req, res, next) {
440
507
  var _a, _b, _c;
441
508
  if (err instanceof auth_1.AuthError) {
@@ -447,7 +514,11 @@ function server(core, uiECI, auth, oauth, identity) {
447
514
  return;
448
515
  }
449
516
  let message = err + "";
450
- console.error(err);
517
+ const policyNoise = process.env.NODE_ENV === "test" &&
518
+ /not allowed by channel policy/i.test(message);
519
+ if (!policyNoise) {
520
+ console.error(err);
521
+ }
451
522
  if ((_b = (_a = err === null || err === void 0 ? void 0 : err.krl_compiler) === null || _a === void 0 ? void 0 : _a.loc) === null || _b === void 0 ? void 0 : _b.start) {
452
523
  message +=
453
524
  " [at line " +
@@ -471,9 +542,9 @@ function server(core, uiECI, auth, oauth, identity) {
471
542
  });
472
543
  return app;
473
544
  }
474
- function registerAuthRoutes(app, auth) {
545
+ function registerAuthRoutes(app, auth, cookies) {
475
546
  function setSessionCookie(res, token, expiry) {
476
- res.cookie(SESSION_COOKIE, token, {
547
+ res.cookie(cookies().session, token, {
477
548
  httpOnly: true,
478
549
  sameSite: "lax",
479
550
  secure: auth.isSecure(),
@@ -482,7 +553,7 @@ function registerAuthRoutes(app, auth) {
482
553
  });
483
554
  }
484
555
  function setCeremonyCookie(res, ceremonyId) {
485
- res.cookie(CEREMONY_COOKIE, ceremonyId, {
556
+ res.cookie(cookies().ceremony, ceremonyId, {
486
557
  httpOnly: true,
487
558
  sameSite: "lax",
488
559
  secure: auth.isSecure(),
@@ -491,7 +562,7 @@ function registerAuthRoutes(app, auth) {
491
562
  });
492
563
  }
493
564
  function clearCeremonyCookie(res) {
494
- res.clearCookie(CEREMONY_COOKIE, { path: "/" });
565
+ res.clearCookie(cookies().ceremony, { path: "/" });
495
566
  }
496
567
  // WebAuthn requires a specific, credentialed origin — never "*".
497
568
  app.use("/auth", function (req, res, next) {
@@ -507,7 +578,7 @@ function registerAuthRoutes(app, auth) {
507
578
  next();
508
579
  });
509
580
  function requireSession(req, res, next) {
510
- const token = parseCookies(req)[SESSION_COOKIE] || "";
581
+ const token = parseCookies(req)[cookies().session] || "";
511
582
  auth
512
583
  .getSession(token)
513
584
  .then((session) => {
@@ -533,7 +604,7 @@ function registerAuthRoutes(app, auth) {
533
604
  .catch(next);
534
605
  });
535
606
  app.post("/auth/register/verify", function (req, res, next) {
536
- const ceremonyId = parseCookies(req)[CEREMONY_COOKIE] || "";
607
+ const ceremonyId = parseCookies(req)[cookies().ceremony] || "";
537
608
  auth
538
609
  .registerNewAccountVerify({ ceremonyId, response: req.body })
539
610
  .then(({ account, session, uiECI }) => {
@@ -558,7 +629,7 @@ function registerAuthRoutes(app, auth) {
558
629
  .catch(next);
559
630
  });
560
631
  app.post("/auth/claim/verify", function (req, res, next) {
561
- const ceremonyId = parseCookies(req)[CEREMONY_COOKIE] || "";
632
+ const ceremonyId = parseCookies(req)[cookies().ceremony] || "";
562
633
  auth
563
634
  .claimPrimaryRootVerify({ ceremonyId, response: req.body })
564
635
  .then(({ account, session, uiECI }) => {
@@ -583,7 +654,7 @@ function registerAuthRoutes(app, auth) {
583
654
  .catch(next);
584
655
  });
585
656
  app.post("/auth/login/verify", function (req, res, next) {
586
- const ceremonyId = parseCookies(req)[CEREMONY_COOKIE] || "";
657
+ const ceremonyId = parseCookies(req)[cookies().ceremony] || "";
587
658
  auth
588
659
  .loginVerify({ ceremonyId, response: req.body })
589
660
  .then(({ account, session }) => {
@@ -598,17 +669,17 @@ function registerAuthRoutes(app, auth) {
598
669
  .catch(next);
599
670
  });
600
671
  app.post("/auth/logout", function (req, res, next) {
601
- const token = parseCookies(req)[SESSION_COOKIE] || "";
672
+ const token = parseCookies(req)[cookies().session] || "";
602
673
  auth
603
674
  .deleteSession(token)
604
675
  .then(() => {
605
- res.clearCookie(SESSION_COOKIE, { path: "/" });
676
+ res.clearCookie(cookies().session, { path: "/" });
606
677
  res.json({ ok: true });
607
678
  })
608
679
  .catch(next);
609
680
  });
610
681
  app.get("/auth/session", function (req, res, next) {
611
- const token = parseCookies(req)[SESSION_COOKIE] || "";
682
+ const token = parseCookies(req)[cookies().session] || "";
612
683
  auth
613
684
  .whoami(token)
614
685
  .then((who) => res.json(who))
@@ -626,7 +697,7 @@ function registerAuthRoutes(app, auth) {
626
697
  });
627
698
  app.post("/auth/credentials/verify", requireSession, function (req, res, next) {
628
699
  const session = req.picoSession;
629
- const ceremonyId = parseCookies(req)[CEREMONY_COOKIE] || "";
700
+ const ceremonyId = parseCookies(req)[cookies().ceremony] || "";
630
701
  auth
631
702
  .addCredentialVerify({
632
703
  ceremonyId,
@@ -665,13 +736,13 @@ function registerAuthRoutes(app, auth) {
665
736
  .catch(next);
666
737
  });
667
738
  }
668
- function registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookiesFn) {
739
+ function registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookiesFn, cookies) {
669
740
  function requireOAuthSession(req, res, next) {
670
741
  if (!auth) {
671
742
  res.status(503).json({ error: "Authentication is not configured" });
672
743
  return;
673
744
  }
674
- const token = parseCookiesFn(req)[SESSION_COOKIE] || "";
745
+ const token = parseCookiesFn(req)[cookies().session] || "";
675
746
  auth
676
747
  .getSession(token)
677
748
  .then((session) => {
@@ -715,7 +786,7 @@ function registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookiesF
715
786
  res.status(503).send("Authentication is not configured");
716
787
  return;
717
788
  }
718
- const token = parseCookiesFn(req)[SESSION_COOKIE] || "";
789
+ const token = parseCookiesFn(req)[cookies().session] || "";
719
790
  const session = await auth.getSession(token);
720
791
  if (!session) {
721
792
  const returnPath = req.originalUrl || "/oauth/authorize";
@@ -735,7 +806,7 @@ function registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookiesF
735
806
  res.status(503).send("Authentication is not configured");
736
807
  return;
737
808
  }
738
- const token = parseCookiesFn(req)[SESSION_COOKIE] || "";
809
+ const token = parseCookiesFn(req)[cookies().session] || "";
739
810
  auth
740
811
  .getSession(token)
741
812
  .then((session) => {
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ /**
3
+ * Subtree import child creation via wrangler (engine layer — above ctx).
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createImportChildViaWrangler = createImportChildViaWrangler;
7
+ exports.wranglerSubtreeImportServices = wranglerSubtreeImportServices;
8
+ const pico_framework_1 = require("pico-framework");
9
+ const WRANGLER_RID = "io.picolabs.wrangler";
10
+ const ENGINE_UI_RID = "io.picolabs.pico-engine-ui";
11
+ const SUBSCRIPTION_RID = "io.picolabs.subscription";
12
+ const PDS_RID = "io.picolabs.pds";
13
+ function isUiChannel(c) {
14
+ return [...c.tags].sort().join(",") === "engine,ui";
15
+ }
16
+ function nonFamilyChannels(pico) {
17
+ return pico.toReadOnly().channels.filter((c) => !c.familyChannelPicoID);
18
+ }
19
+ function channelAllowsEvent(c, event) {
20
+ return (0, pico_framework_1.allowsEventPolicy)(c.eventPolicy, event);
21
+ }
22
+ /** Pick a channel that may deliver a specific wrangler bootstrap event. */
23
+ function pickEventEci(pico, event) {
24
+ const channels = nonFamilyChannels(pico);
25
+ if (channels.length === 0) {
26
+ throw new Error(`Pico ${pico.id} has no non-family channels for wrangler events`);
27
+ }
28
+ const permitted = channels.filter((c) => channelAllowsEvent(c, event));
29
+ if (permitted.length > 0) {
30
+ const ui = permitted.find((c) => isUiChannel(c));
31
+ return (ui !== null && ui !== void 0 ? ui : permitted[0]).id;
32
+ }
33
+ throw new Error(`Pico ${pico.id} has no channel that allows ${event.domain}:${event.name}`);
34
+ }
35
+ /**
36
+ * Prefer caller's channel when it allows the event; otherwise pick one that does.
37
+ * HTTP/UI import passes the UI ECI — skip it when policy blocks wrangler bootstrap.
38
+ */
39
+ function resolveWranglerChannelEci(pico, event, preferred) {
40
+ if (preferred) {
41
+ const ch = nonFamilyChannels(pico).find((c) => c.id === preferred);
42
+ if (ch && channelAllowsEvent(ch, event)) {
43
+ return preferred;
44
+ }
45
+ }
46
+ return pickEventEci(pico, event);
47
+ }
48
+ async function rulesetFromParent(parent, rid, rsRegistry) {
49
+ var _a;
50
+ const config = (_a = parent.rulesets[rid]) === null || _a === void 0 ? void 0 : _a.config;
51
+ if (!(config === null || config === void 0 ? void 0 : config.url)) {
52
+ throw new Error(`Parent pico ${parent.id} does not have ${rid} installed (required for wrangler import bootstrap)`);
53
+ }
54
+ const loaded = await rsRegistry.load(config.url);
55
+ return { rs: loaded.ruleset, config };
56
+ }
57
+ /** Same bootstrap as wrangler bootstrapNewChild, without blocking the parent's event queue. */
58
+ async function bootstrapImportChildSync(pf, parent, name, rsRegistry, options) {
59
+ const ui = await rulesetFromParent(parent, ENGINE_UI_RID, rsRegistry);
60
+ const wrangler = await rulesetFromParent(parent, WRANGLER_RID, rsRegistry);
61
+ const familyEci = await parent.newPico({
62
+ rulesets: [ui, wrangler],
63
+ });
64
+ const child = pf.getPico(familyEci);
65
+ if (!child) {
66
+ throw new Error(`Failed to resolve child for family ECI ${familyEci}`);
67
+ }
68
+ const parentUi = parent.toReadOnly().channels.find((c) => [...c.tags].sort().join(",") === "engine,ui");
69
+ await pf.eventWait({
70
+ eci: familyEci,
71
+ domain: "wrangler",
72
+ name: "pico_created",
73
+ data: { attrs: { name: name || "imported" } },
74
+ time: Date.now(),
75
+ }, parent.id);
76
+ await waitForWranglerBootstrapRulesets(pf, parent.id, familyEci, child);
77
+ const uiEci = await pf.eventQuery({
78
+ eci: familyEci,
79
+ domain: "engine_ui",
80
+ name: "setup",
81
+ data: { attrs: {} },
82
+ time: Date.now(),
83
+ }, {
84
+ eci: familyEci,
85
+ rid: ENGINE_UI_RID,
86
+ name: "uiECI",
87
+ args: {},
88
+ }, parent.id);
89
+ await pf.event({
90
+ eci: uiEci,
91
+ domain: "engine_ui",
92
+ name: "box",
93
+ data: {
94
+ attrs: {
95
+ name: name || "imported",
96
+ parentUiEci: parentUi === null || parentUi === void 0 ? void 0 : parentUi.id,
97
+ },
98
+ },
99
+ time: Date.now(),
100
+ });
101
+ const newChildCreated = {
102
+ domain: "wrangler",
103
+ name: "new_child_created",
104
+ };
105
+ const parentEci = resolveWranglerChannelEci(parent, newChildCreated, options === null || options === void 0 ? void 0 : options.channelEci);
106
+ await pf.event({
107
+ eci: parentEci,
108
+ domain: newChildCreated.domain,
109
+ name: newChildCreated.name,
110
+ data: {
111
+ attrs: {
112
+ name: name || "imported",
113
+ eci: familyEci,
114
+ uiEci,
115
+ },
116
+ },
117
+ time: Date.now(),
118
+ });
119
+ return { familyEci, child };
120
+ }
121
+ function parentIsHandlingEvent(parent) {
122
+ var _a;
123
+ return ((_a = parent.getCurrentTxn()) === null || _a === void 0 ? void 0 : _a.kind) === "event";
124
+ }
125
+ /** Wait for pico_created's queued install_ruleset_request (pds + subscription). */
126
+ async function waitForWranglerBootstrapRulesets(pf, parentPicoId, familyEci, child, timeoutMs = 20000) {
127
+ const need = [SUBSCRIPTION_RID, PDS_RID];
128
+ const deadline = Date.now() + timeoutMs;
129
+ while (Date.now() < deadline) {
130
+ if (need.every((rid) => child.rulesets[rid])) {
131
+ return;
132
+ }
133
+ await pf
134
+ .query({
135
+ eci: familyEci,
136
+ rid: WRANGLER_RID,
137
+ name: "id",
138
+ args: {},
139
+ }, parentPicoId)
140
+ .catch(() => undefined);
141
+ await new Promise((resolve) => setTimeout(resolve, 15));
142
+ }
143
+ const missing = need.filter((rid) => !child.rulesets[rid]);
144
+ throw new Error(`Import child wrangler bootstrap missing rulesets: ${missing.join(", ")}`);
145
+ }
146
+ /** Create an import child through wrangler (sync bootstrap when parent queue is busy). */
147
+ async function createImportChildViaWrangler(pf, parent, name, rsRegistry, options) {
148
+ if (parentIsHandlingEvent(parent)) {
149
+ return bootstrapImportChildSync(pf, parent, name, rsRegistry, options);
150
+ }
151
+ const newChildRequest = {
152
+ domain: "wrangler",
153
+ name: "new_child_request",
154
+ };
155
+ const parentEci = resolveWranglerChannelEci(parent, newChildRequest, options === null || options === void 0 ? void 0 : options.channelEci);
156
+ const childCountBefore = parent.toReadOnly().children.length;
157
+ await pf.eventWait({
158
+ eci: parentEci,
159
+ domain: newChildRequest.domain,
160
+ name: newChildRequest.name,
161
+ data: { attrs: { name: name || "imported" } },
162
+ time: Date.now(),
163
+ });
164
+ const children = parent.toReadOnly().children;
165
+ if (children.length <= childCountBefore) {
166
+ throw new Error("wrangler new_child_request did not create a child (is io.picolabs.wrangler installed on the parent?)");
167
+ }
168
+ const familyEci = children[children.length - 1];
169
+ const child = pf.getPico(familyEci);
170
+ if (!child) {
171
+ throw new Error(`Failed to resolve child for family ECI ${familyEci}`);
172
+ }
173
+ return { familyEci, child };
174
+ }
175
+ /** Wrangler-backed child creation wired into ctx subtree import. */
176
+ function wranglerSubtreeImportServices(rsRegistry) {
177
+ return {
178
+ createImportChild: (pf, parent, name, opts) => createImportChildViaWrangler(pf, parent, name, rsRegistry, opts),
179
+ };
180
+ }
@@ -15,7 +15,12 @@ exports.UI_CHANNEL_EVENT_POLICY = {
15
15
  { domain: "engine_ui", name: "del_channel" },
16
16
  { domain: "engine_ui", name: "update_channel" },
17
17
  { domain: "engine_ui", name: "testing_eci" },
18
+ { domain: "engine_ui", name: "testing_history_record" },
19
+ { domain: "engine_ui", name: "testing_history_clear" },
20
+ { domain: "engine_ui", name: "testing_saved_upsert" },
21
+ { domain: "engine_ui", name: "testing_saved_delete" },
18
22
  { domain: "engine", name: "started" },
23
+ { domain: "engine", name: "ruleset_set_changed" },
19
24
  { domain: "wrangler", name: "subscription" },
20
25
  { domain: "wrangler", name: "relationship" },
21
26
  { domain: "wrangler", name: "pending_subscription_approval" },
@@ -28,6 +33,12 @@ exports.UI_CHANNEL_EVENT_POLICY = {
28
33
  { domain: "wrangler", name: "relationship_cancellation" },
29
34
  { domain: "wrangler", name: "set_public_intro" },
30
35
  { domain: "wrangler", name: "send_event_on_subs" },
36
+ { domain: "wrangler", name: "send_event_on_relationships" },
37
+ { domain: "wrangler", name: "child_deleted" },
38
+ { domain: "wrangler", name: "new_child_request" },
39
+ { domain: "wrangler", name: "new_child_created" },
40
+ { domain: "wrangler", name: "install_ruleset_request" },
41
+ { domain: "wrangler", name: "new_channel_request" },
31
42
  ],
32
43
  deny: [],
33
44
  };
@@ -35,11 +46,16 @@ exports.UI_CHANNEL_EVENT_POLICY = {
35
46
  exports.UI_CHANNEL_QUERY_POLICY = {
36
47
  allow: [
37
48
  { rid: "*", name: "__testing" },
49
+ { rid: "*", name: "__consoleEval" },
50
+ { rid: "io.picolabs.wrangler", name: "rulesetSchema" },
51
+ { rid: "io.picolabs.wrangler", name: "picoSchema" },
38
52
  { rid: "io.picolabs.pico-engine-ui", name: "uiECI" },
39
53
  { rid: "io.picolabs.pico-engine-ui", name: "box" },
40
54
  { rid: "io.picolabs.pico-engine-ui", name: "pico" },
41
55
  { rid: "io.picolabs.pico-engine-ui", name: "logs" },
42
56
  { rid: "io.picolabs.pico-engine-ui", name: "testingECI" },
57
+ { rid: "io.picolabs.pico-engine-ui", name: "testingHistory" },
58
+ { rid: "io.picolabs.pico-engine-ui", name: "testingSaved" },
43
59
  { rid: "io.picolabs.pico-engine-ui", name: "name" },
44
60
  { rid: "io.picolabs.subscription", name: "established" },
45
61
  { rid: "io.picolabs.subscription", name: "inbound" },