pico-engine 1.6.4 → 1.9.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 (108) hide show
  1. package/README.md +16 -9
  2. package/dist/RulesetRegistryLoaderFs.js +60 -6
  3. package/dist/auth/cookies.js +32 -0
  4. package/dist/auth/index.js +6 -1
  5. package/dist/channelIdentityPolicy.js +22 -0
  6. package/dist/cli.js +106 -69
  7. package/dist/engineConfig.js +291 -0
  8. package/dist/identity/IdentityService.js +90 -0
  9. package/dist/identity/crossPico.js +24 -8
  10. package/dist/identity/didoModule.js +80 -18
  11. package/dist/identity/establishSubscription.js +2 -2
  12. package/dist/identity/identityPortable.js +92 -0
  13. package/dist/identity/index.js +10 -1
  14. package/dist/identity/localPeerReconcile.js +65 -0
  15. package/dist/identity/peerDid4.js +175 -0
  16. package/dist/identity/peerDid4Create.js +90 -0
  17. package/dist/identity/portableExportPrepare.js +196 -0
  18. package/dist/identity/portableMove.js +87 -0
  19. package/dist/identity/skyIntro.js +6 -3
  20. package/dist/identity/skyProtocol.js +26 -1
  21. package/dist/identity/skyRotation.js +121 -0
  22. package/dist/identity/store.js +5 -1
  23. package/dist/identity/subscriptionEntSync.js +72 -0
  24. package/dist/identity/veramoDidComm.js +41 -2
  25. package/dist/identity/webvh.js +4 -2
  26. package/dist/identity/webvhRelocation.js +115 -0
  27. package/dist/index.js +84 -27
  28. package/dist/logging.js +156 -16
  29. package/dist/oauth/OAuthService.js +6 -2
  30. package/dist/policyConfigFromJson.js +112 -0
  31. package/dist/runMcp.js +27 -0
  32. package/dist/server.js +261 -24
  33. package/dist/stageKrl.js +26 -0
  34. package/dist/subtreeWrangler.js +180 -0
  35. package/dist/uiChannelPolicies.js +15 -0
  36. package/dist/xmluiRuntime.js +68 -0
  37. package/krl/io.picolabs.oauth.krl +41 -2
  38. package/krl/io.picolabs.pds.krl +131 -10
  39. package/krl/io.picolabs.pico-engine-ui.krl +217 -94
  40. package/krl/io.picolabs.portable_subtree.krl +97 -0
  41. package/krl/io.picolabs.subscription.krl +180 -72
  42. package/krl/io.picolabs.wrangler.krl +313 -57
  43. package/krl/io.picolabs.xmlui.krl +295 -0
  44. package/mcp/devResources.js +118 -0
  45. package/mcp/devTools.js +351 -0
  46. package/mcp/engineClient.js +133 -0
  47. package/mcp/meshHttp.js +137 -0
  48. package/mcp/meshTools.js +189 -0
  49. package/mcp/runStdio.js +34 -0
  50. package/mcp/schemaToZod.js +56 -0
  51. package/package.json +24 -9
  52. package/public/.DS_Store +0 -0
  53. package/public/docs/_sidebar.md +3 -1
  54. package/public/docs/llms-full.txt +630 -0
  55. package/public/docs/llms.txt +38 -0
  56. package/public/docs/openapi.yaml +78 -0
  57. package/public/docs/pico-engine.md +239 -4
  58. package/public/docs/pico-overview.md +117 -0
  59. package/public/docs/pico-views-xmlui.md +5 -0
  60. package/public/docs/pico-views.md +140 -0
  61. package/public/docs/pico.md +3 -1
  62. package/public/docs/rulesets/README.md +26 -0
  63. package/public/docs/rulesets/io.picolabs.oauth.md +71 -0
  64. package/public/docs/rulesets/io.picolabs.pds.md +327 -0
  65. package/public/docs/rulesets/io.picolabs.pico-engine-ui.md +65 -0
  66. package/public/docs/rulesets/io.picolabs.portable_subtree.md +94 -0
  67. package/public/docs/rulesets/io.picolabs.subscription.md +398 -0
  68. package/public/docs/rulesets/io.picolabs.wrangler.md +471 -0
  69. package/public/pico-engine-ui.css +1 -1
  70. package/public/pico-engine-ui.js +27 -23
  71. package/public/xmlui/0.12.7.js +419 -0
  72. package/public/xmlui/pico-view-boot.js +153 -0
  73. package/src/RulesetRegistryLoaderFs.ts +66 -7
  74. package/src/auth/cookies.ts +34 -0
  75. package/src/auth/index.ts +7 -0
  76. package/src/channelIdentityPolicy.ts +29 -0
  77. package/src/cli.ts +70 -37
  78. package/src/engineConfig.ts +363 -0
  79. package/src/identity/IdentityService.ts +189 -1
  80. package/src/identity/crossPico.ts +57 -8
  81. package/src/identity/didoModule.ts +140 -23
  82. package/src/identity/establishSubscription.ts +2 -2
  83. package/src/identity/identityPortable.ts +153 -0
  84. package/src/identity/index.ts +14 -0
  85. package/src/identity/localPeerReconcile.ts +97 -0
  86. package/src/identity/peerDid4.ts +197 -0
  87. package/src/identity/peerDid4Create.ts +121 -0
  88. package/src/identity/portableExportPrepare.ts +302 -0
  89. package/src/identity/portableMove.ts +193 -0
  90. package/src/identity/skyIntro.ts +11 -11
  91. package/src/identity/skyProtocol.ts +46 -0
  92. package/src/identity/skyRotation.ts +211 -0
  93. package/src/identity/store.ts +5 -1
  94. package/src/identity/subscriptionEntSync.ts +97 -0
  95. package/src/identity/veramoDidComm.ts +52 -2
  96. package/src/identity/webvh.ts +4 -4
  97. package/src/identity/webvhRelocation.ts +167 -0
  98. package/src/index.ts +123 -31
  99. package/src/logging.ts +173 -18
  100. package/src/oauth/OAuthService.ts +11 -3
  101. package/src/policyConfigFromJson.ts +131 -0
  102. package/src/runMcp.ts +30 -0
  103. package/src/server.ts +328 -27
  104. package/src/stageKrl.ts +26 -0
  105. package/src/subtreeWrangler.ts +278 -0
  106. package/src/uiChannelPolicies.ts +15 -0
  107. package/src/xmluiRuntime.ts +66 -0
  108. package/krl/io.picolabs.did-o.krl +0 -349
package/dist/server.js CHANGED
@@ -8,16 +8,20 @@ const helmet_1 = require("helmet");
8
8
  const _ = require("lodash");
9
9
  const path = require("path");
10
10
  const bundledKrl_1 = require("./bundledKrl");
11
+ const pico_engine_core_1 = require("pico-engine-core");
11
12
  const auth_1 = require("./auth");
12
13
  const oauth_1 = require("./oauth");
13
14
  const provisionRoot_1 = require("./provisionRoot");
15
+ const pico_engine_core_2 = require("pico-engine-core");
16
+ const xmluiRuntime_1 = require("./xmluiRuntime");
14
17
  const webvhRoutes_1 = require("./identity/webvhRoutes");
15
18
  const didcommIngressRoutes_1 = require("./identity/didcommIngressRoutes");
19
+ const engineConfig_1 = require("./engineConfig");
20
+ const logging_1 = require("./logging");
21
+ const stageKrl_1 = require("./stageKrl");
16
22
  const engineVersion = require("../package.json").version;
17
- const SESSION_COOKIE = "pico-session";
18
- const CEREMONY_COOKIE = "pico-ceremony";
19
23
  function localhostChannelBypassEnabled() {
20
- return process.env.PICO_ENGINE_ALLOW_LOCALHOST_C !== "0";
24
+ return (0, engineConfig_1.getEngineRuntimeSettings)().allowLocalhostChannelBypass;
21
25
  }
22
26
  function mergeGetPost(req) {
23
27
  // give preference to post body params
@@ -63,6 +67,11 @@ function isLocalhostRequest(req) {
63
67
  function server(core, uiECI, auth, oauth, identity) {
64
68
  const pf = core.picoFramework;
65
69
  const app = express();
70
+ function cookies() {
71
+ return auth
72
+ ? (0, auth_1.authCookieNames)(auth.rp().origin)
73
+ : (0, auth_1.authCookieNames)("http://localhost:3000");
74
+ }
66
75
  app.use(function (req, res, next) {
67
76
  // /auth routes need a specific credentialed CORS origin (below), not "*".
68
77
  if (req.path.indexOf("/auth") === 0) {
@@ -99,6 +108,10 @@ function server(core, uiECI, auth, oauth, identity) {
99
108
  if (req.path === "/oauth/authorize" || req.path === "/oauth/approve") {
100
109
  return (0, helmet_1.default)({ contentSecurityPolicy: false })(req, res, next);
101
110
  }
111
+ // XMLUI view shells use small inline scripts (__PUBLIC_PATH, startApp).
112
+ if (req.path === "/ui" || req.path.startsWith("/ui/")) {
113
+ return (0, helmet_1.default)({ contentSecurityPolicy: false })(req, res, next);
114
+ }
102
115
  return defaultHelmet(req, res, next);
103
116
  });
104
117
  app.use(express.static(path.resolve(__dirname, "..", "public")));
@@ -122,7 +135,7 @@ function server(core, uiECI, auth, oauth, identity) {
122
135
  (0, didcommIngressRoutes_1.registerDidcommIngressRoutes)(app, identity);
123
136
  }
124
137
  if (auth) {
125
- registerAuthRoutes(app, auth);
138
+ registerAuthRoutes(app, auth, cookies);
126
139
  }
127
140
  function isEciInRootTree(rootPicoId, eci) {
128
141
  try {
@@ -147,7 +160,7 @@ function server(core, uiECI, auth, oauth, identity) {
147
160
  next();
148
161
  return;
149
162
  }
150
- const token = parseCookies(req)[SESSION_COOKIE] || "";
163
+ const token = parseCookies(req)[cookies().session] || "";
151
164
  auth
152
165
  .getSession(token)
153
166
  .then((session) => {
@@ -212,8 +225,25 @@ function server(core, uiECI, auth, oauth, identity) {
212
225
  .catch(next);
213
226
  }
214
227
  if (oauth) {
215
- registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookies);
228
+ registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookies, cookies);
216
229
  }
230
+ app.get("/api/ui-sky-context", function (req, res, next) {
231
+ const eci = typeof req.query.eci === "string" ? req.query.eci.trim() : "";
232
+ if (!eci) {
233
+ res.status(400).json({ error: "eci query parameter required" });
234
+ return;
235
+ }
236
+ if (!oauth) {
237
+ res.json({ bearerRequired: false });
238
+ return;
239
+ }
240
+ oauth
241
+ .skyRequiresBearer(eci)
242
+ .then((bearerRequired) => {
243
+ res.json({ bearerRequired });
244
+ })
245
+ .catch(next);
246
+ });
217
247
  app.get("/api/oauth/mesh-enabled", requireAuthSession, function (_req, res) {
218
248
  const roots = pf.rootPicos();
219
249
  const meshOAuthEnabled = roots.length > 0 &&
@@ -272,6 +302,23 @@ function server(core, uiECI, auth, oauth, identity) {
272
302
  next(err);
273
303
  }
274
304
  });
305
+ app.post("/api/stage-krl", function (req, res, next) {
306
+ var _a, _b;
307
+ try {
308
+ const content = (_a = req.body) === null || _a === void 0 ? void 0 : _a.content;
309
+ const filename = typeof ((_b = req.body) === null || _b === void 0 ? void 0 : _b.filename) === "string" ? req.body.filename : "staged.krl";
310
+ if (typeof content !== "string" || content.length > 2000000) {
311
+ res.status(400).json({ error: "content required (max 2MB)" });
312
+ return;
313
+ }
314
+ const url = (0, stageKrl_1.stageKrlContent)(content, filename);
315
+ res.json({ url });
316
+ }
317
+ catch (err) {
318
+ const message = err instanceof Error ? err.message : String(err);
319
+ res.status(400).json({ error: message });
320
+ }
321
+ });
275
322
  app.get(/^\/krl\/(.+\.krl)$/, function (req, res, next) {
276
323
  const suffix = req.params[0];
277
324
  if (typeof suffix !== "string" || !suffix.endsWith(".krl")) {
@@ -303,7 +350,7 @@ function server(core, uiECI, auth, oauth, identity) {
303
350
  res.json(base);
304
351
  return;
305
352
  }
306
- const token = parseCookies(req)[SESSION_COOKIE] || "";
353
+ const token = parseCookies(req)[cookies().session] || "";
307
354
  auth
308
355
  .needsAuthMigration()
309
356
  .then((needsAuthMigration) => {
@@ -319,6 +366,91 @@ function server(core, uiECI, auth, oauth, identity) {
319
366
  })
320
367
  .catch(next);
321
368
  });
369
+ /**
370
+ * Pushes each finished transaction for this pico. Owner session only,
371
+ * same gate as the rest of the developer UI.
372
+ */
373
+ app.get("/api/picos/:eci/logs/live", requireAuthSession, function (req, res) {
374
+ let picoId;
375
+ try {
376
+ picoId = pf.getPico(req.params.eci).id;
377
+ }
378
+ catch (_e) {
379
+ res.status(404).json({ error: "Unknown pico" });
380
+ return;
381
+ }
382
+ res.writeHead(200, {
383
+ "Content-Type": "text/event-stream",
384
+ "Cache-Control": "no-cache, no-transform",
385
+ Connection: "keep-alive",
386
+ "X-Accel-Buffering": "no",
387
+ });
388
+ res.write(": ok\n\n");
389
+ let closed = false;
390
+ const unsubscribe = (0, logging_1.subscribePicoLogRing)((id, txnId) => {
391
+ if (closed || id !== picoId)
392
+ return;
393
+ const entries = (0, logging_1.picoLogEntries)(picoId).filter((entry) => entry.txnId === txnId);
394
+ const [txn] = (0, pico_engine_core_1.assembleLogTransactions)(entries);
395
+ if (!txn)
396
+ return;
397
+ try {
398
+ res.write(`data: ${JSON.stringify(txn)}\n\n`);
399
+ }
400
+ catch (_err) {
401
+ closed = true;
402
+ unsubscribe();
403
+ }
404
+ });
405
+ const beat = setInterval(() => {
406
+ if (closed)
407
+ return;
408
+ res.write(": ping\n\n");
409
+ }, 25000);
410
+ req.on("close", () => {
411
+ closed = true;
412
+ clearInterval(beat);
413
+ unsubscribe();
414
+ });
415
+ });
416
+ /** Localhost-only context for dev MCP (stdio) and other local tooling. */
417
+ app.get("/api/dev/local", function (req, res) {
418
+ var _a;
419
+ if (!localhostChannelBypassEnabled() || !isLocalhostRequest(req)) {
420
+ res.status(403).json({ error: "localhost only" });
421
+ return;
422
+ }
423
+ const roots = pf.rootPicos();
424
+ const rootPico = roots[0];
425
+ const rootUiEci = rootPico ? (0, provisionRoot_1.uiECIForRoot)(pf, rootPico.id) : null;
426
+ let baseUrl = core.base_url;
427
+ if (!baseUrl) {
428
+ baseUrl = `${req.protocol}://${req.get("host") || "localhost"}`;
429
+ }
430
+ const settings = (0, engineConfig_1.getEngineRuntimeSettings)();
431
+ const primaryLogFile = (0, logging_1.resolveEngineLogFilePath)(settings.home);
432
+ const picoLogsReadPath = (0, logging_1.resolvePicoLogsReadPath)(settings.home);
433
+ const mirrorDisabled = settings.logToStdout && settings.logMirror === false;
434
+ res.json({
435
+ version: engineVersion,
436
+ hasRoots: roots.length > 0,
437
+ rootUiEci,
438
+ baseUrl: baseUrl.replace(/\/$/, ""),
439
+ logging: {
440
+ home: settings.home,
441
+ logToStdout: settings.logToStdout,
442
+ logMirror: settings.logMirror,
443
+ logFileSetting: (_a = settings.logFile) !== null && _a !== void 0 ? _a : null,
444
+ primaryLogFile,
445
+ /** File `getPicoLogs` reads (mirrors under stdout-only unless PICO_ENGINE_LOG_MIRROR=0). */
446
+ picoLogsReadPath,
447
+ picoLogsForDeveloperUi: true,
448
+ logMirrorDisabled: mirrorDisabled,
449
+ logRing: true,
450
+ hint: "Logging tab reads the in-memory ring (last N transactions per pico, PICO_ENGINE_LOG_RING, default 200). A restart clears it. The log file remains the operator record.",
451
+ },
452
+ });
453
+ });
322
454
  app.all("/api/flush", requireAuthSession, function (req, res, next) {
323
455
  const attrs = mergeGetPost(req);
324
456
  const url = attrs["url"];
@@ -472,9 +604,109 @@ function server(core, uiECI, auth, oauth, identity) {
472
604
  })
473
605
  .catch(next);
474
606
  });
607
+ const XMLUI_FILE_RID = "io.picolabs.xmlui";
608
+ function respondXmluiQueryFailure(err, res, next) {
609
+ if (!(0, pico_engine_core_1.isRoutineQueryError)(err)) {
610
+ return false;
611
+ }
612
+ const message = err + "";
613
+ if (!res.headersSent) {
614
+ if (/channel policy/i.test(message)) {
615
+ res.status(403).type("text/plain").end(message);
616
+ }
617
+ else {
618
+ res.status(404).type("text/plain").end("Not found");
619
+ }
620
+ }
621
+ return true;
622
+ }
623
+ async function serveXmluiFile(req, res, next, eci, appRid, filePath) {
624
+ const rel = (filePath || "index.html").replace(/^\/+/, "") || "index.html";
625
+ try {
626
+ if ((0, xmluiRuntime_1.isXmluiCodeBehindPath)(rel)) {
627
+ res
628
+ .status(200)
629
+ .setHeader("Content-Type", (0, xmluiRuntime_1.contentTypeForUiPath)(rel))
630
+ .end(xmluiRuntime_1.XMLUI_EMPTY_CODE_BEHIND);
631
+ return;
632
+ }
633
+ let data;
634
+ const componentName = appRid ? (0, xmluiRuntime_1.parseComponentXmluiPath)(rel) : null;
635
+ if (componentName) {
636
+ const { pico } = pf.lookupChannel(eci);
637
+ const channelSchema = (0, pico_engine_core_2.channelSchemaForEci)(pico, core.rsRegistry, (channelEci) => pf.lookupChannel(channelEci), eci);
638
+ const viewFn = (0, xmluiRuntime_1.viewQueryNameForComponent)(channelSchema.queries, appRid, componentName);
639
+ if (!viewFn) {
640
+ res.status(404).type("text/plain").end("Not found");
641
+ return;
642
+ }
643
+ data = await core.query({
644
+ eci,
645
+ rid: appRid,
646
+ name: viewFn,
647
+ args: {},
648
+ });
649
+ }
650
+ else {
651
+ data = await core.query({
652
+ eci,
653
+ rid: XMLUI_FILE_RID,
654
+ name: "file",
655
+ args: { rid: appRid, path: rel },
656
+ });
657
+ }
658
+ if (data == null && appRid && (0, xmluiRuntime_1.isXmluiSpaClientRoute)(rel)) {
659
+ data = await core.query({
660
+ eci,
661
+ rid: XMLUI_FILE_RID,
662
+ name: "file",
663
+ args: { rid: appRid, path: "index.html" },
664
+ });
665
+ }
666
+ if (data == null) {
667
+ res.status(404).type("text/plain").end("Not found");
668
+ return;
669
+ }
670
+ if (typeof data === "object" &&
671
+ data !== null &&
672
+ "error" in data) {
673
+ const message = String(data.error);
674
+ res.status(404).type("text/plain").end(message);
675
+ return;
676
+ }
677
+ const servedPath = rel === "index.html" || !(0, xmluiRuntime_1.isXmluiSpaClientRoute)(rel) ? rel : "index.html";
678
+ const contentType = (0, xmluiRuntime_1.contentTypeForUiPath)(servedPath);
679
+ res.setHeader("Content-Type", contentType);
680
+ if (contentType.startsWith("application/json") && typeof data === "object") {
681
+ res.json(data);
682
+ return;
683
+ }
684
+ res.end(typeof data === "string" ? data : JSON.stringify(data));
685
+ }
686
+ catch (err) {
687
+ if (respondXmluiQueryFailure(err, res, next)) {
688
+ return;
689
+ }
690
+ next(err);
691
+ }
692
+ }
693
+ app.get("/ui/:eci", function (req, res, next) {
694
+ void serveXmluiFile(req, res, next, req.params.eci, "", "index.html");
695
+ });
696
+ app.get("/ui/:eci/:rid", function (req, res, next) {
697
+ void serveXmluiFile(req, res, next, req.params.eci, req.params.rid, "index.html");
698
+ });
699
+ app.get("/ui/:eci/:rid/*", function (req, res, next) {
700
+ const rest = req.params[0] || "index.html";
701
+ void serveXmluiFile(req, res, next, req.params.eci, req.params.rid, rest);
702
+ });
475
703
  app.all("/sky/query/:eci/:rid/:function", requireSkyBearerIfOAuth, handleSkyQuery);
476
704
  // Legacy alias; prefer /sky/query/ per Sky Query API docs.
477
705
  app.all("/sky/cloud/:eci/:rid/:function", requireSkyBearerIfOAuth, handleSkyQuery);
706
+ // Mesh MCP (Streamable HTTP, OAuth bearer scoped to :eci)
707
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
708
+ const { registerMeshMcpRoutes } = require("../mcp/meshHttp.js");
709
+ registerMeshMcpRoutes(app, core, oauth);
478
710
  app.use(function (err, req, res, next) {
479
711
  var _a, _b, _c;
480
712
  if (err instanceof auth_1.AuthError) {
@@ -486,7 +718,12 @@ function server(core, uiECI, auth, oauth, identity) {
486
718
  return;
487
719
  }
488
720
  let message = err + "";
489
- console.error(err);
721
+ const policyNoise = process.env.NODE_ENV === "test" &&
722
+ ((0, pico_engine_core_1.isRoutineQueryError)(err) ||
723
+ /not allowed by channel policy/i.test(message));
724
+ if (!policyNoise) {
725
+ console.error(err);
726
+ }
490
727
  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) {
491
728
  message +=
492
729
  " [at line " +
@@ -510,9 +747,9 @@ function server(core, uiECI, auth, oauth, identity) {
510
747
  });
511
748
  return app;
512
749
  }
513
- function registerAuthRoutes(app, auth) {
750
+ function registerAuthRoutes(app, auth, cookies) {
514
751
  function setSessionCookie(res, token, expiry) {
515
- res.cookie(SESSION_COOKIE, token, {
752
+ res.cookie(cookies().session, token, {
516
753
  httpOnly: true,
517
754
  sameSite: "lax",
518
755
  secure: auth.isSecure(),
@@ -521,7 +758,7 @@ function registerAuthRoutes(app, auth) {
521
758
  });
522
759
  }
523
760
  function setCeremonyCookie(res, ceremonyId) {
524
- res.cookie(CEREMONY_COOKIE, ceremonyId, {
761
+ res.cookie(cookies().ceremony, ceremonyId, {
525
762
  httpOnly: true,
526
763
  sameSite: "lax",
527
764
  secure: auth.isSecure(),
@@ -530,7 +767,7 @@ function registerAuthRoutes(app, auth) {
530
767
  });
531
768
  }
532
769
  function clearCeremonyCookie(res) {
533
- res.clearCookie(CEREMONY_COOKIE, { path: "/" });
770
+ res.clearCookie(cookies().ceremony, { path: "/" });
534
771
  }
535
772
  // WebAuthn requires a specific, credentialed origin — never "*".
536
773
  app.use("/auth", function (req, res, next) {
@@ -546,7 +783,7 @@ function registerAuthRoutes(app, auth) {
546
783
  next();
547
784
  });
548
785
  function requireSession(req, res, next) {
549
- const token = parseCookies(req)[SESSION_COOKIE] || "";
786
+ const token = parseCookies(req)[cookies().session] || "";
550
787
  auth
551
788
  .getSession(token)
552
789
  .then((session) => {
@@ -572,7 +809,7 @@ function registerAuthRoutes(app, auth) {
572
809
  .catch(next);
573
810
  });
574
811
  app.post("/auth/register/verify", function (req, res, next) {
575
- const ceremonyId = parseCookies(req)[CEREMONY_COOKIE] || "";
812
+ const ceremonyId = parseCookies(req)[cookies().ceremony] || "";
576
813
  auth
577
814
  .registerNewAccountVerify({ ceremonyId, response: req.body })
578
815
  .then(({ account, session, uiECI }) => {
@@ -597,7 +834,7 @@ function registerAuthRoutes(app, auth) {
597
834
  .catch(next);
598
835
  });
599
836
  app.post("/auth/claim/verify", function (req, res, next) {
600
- const ceremonyId = parseCookies(req)[CEREMONY_COOKIE] || "";
837
+ const ceremonyId = parseCookies(req)[cookies().ceremony] || "";
601
838
  auth
602
839
  .claimPrimaryRootVerify({ ceremonyId, response: req.body })
603
840
  .then(({ account, session, uiECI }) => {
@@ -622,7 +859,7 @@ function registerAuthRoutes(app, auth) {
622
859
  .catch(next);
623
860
  });
624
861
  app.post("/auth/login/verify", function (req, res, next) {
625
- const ceremonyId = parseCookies(req)[CEREMONY_COOKIE] || "";
862
+ const ceremonyId = parseCookies(req)[cookies().ceremony] || "";
626
863
  auth
627
864
  .loginVerify({ ceremonyId, response: req.body })
628
865
  .then(({ account, session }) => {
@@ -637,17 +874,17 @@ function registerAuthRoutes(app, auth) {
637
874
  .catch(next);
638
875
  });
639
876
  app.post("/auth/logout", function (req, res, next) {
640
- const token = parseCookies(req)[SESSION_COOKIE] || "";
877
+ const token = parseCookies(req)[cookies().session] || "";
641
878
  auth
642
879
  .deleteSession(token)
643
880
  .then(() => {
644
- res.clearCookie(SESSION_COOKIE, { path: "/" });
881
+ res.clearCookie(cookies().session, { path: "/" });
645
882
  res.json({ ok: true });
646
883
  })
647
884
  .catch(next);
648
885
  });
649
886
  app.get("/auth/session", function (req, res, next) {
650
- const token = parseCookies(req)[SESSION_COOKIE] || "";
887
+ const token = parseCookies(req)[cookies().session] || "";
651
888
  auth
652
889
  .whoami(token)
653
890
  .then((who) => res.json(who))
@@ -665,7 +902,7 @@ function registerAuthRoutes(app, auth) {
665
902
  });
666
903
  app.post("/auth/credentials/verify", requireSession, function (req, res, next) {
667
904
  const session = req.picoSession;
668
- const ceremonyId = parseCookies(req)[CEREMONY_COOKIE] || "";
905
+ const ceremonyId = parseCookies(req)[cookies().ceremony] || "";
669
906
  auth
670
907
  .addCredentialVerify({
671
908
  ceremonyId,
@@ -704,13 +941,13 @@ function registerAuthRoutes(app, auth) {
704
941
  .catch(next);
705
942
  });
706
943
  }
707
- function registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookiesFn) {
944
+ function registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookiesFn, cookies) {
708
945
  function requireOAuthSession(req, res, next) {
709
946
  if (!auth) {
710
947
  res.status(503).json({ error: "Authentication is not configured" });
711
948
  return;
712
949
  }
713
- const token = parseCookiesFn(req)[SESSION_COOKIE] || "";
950
+ const token = parseCookiesFn(req)[cookies().session] || "";
714
951
  auth
715
952
  .getSession(token)
716
953
  .then((session) => {
@@ -754,7 +991,7 @@ function registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookiesF
754
991
  res.status(503).send("Authentication is not configured");
755
992
  return;
756
993
  }
757
- const token = parseCookiesFn(req)[SESSION_COOKIE] || "";
994
+ const token = parseCookiesFn(req)[cookies().session] || "";
758
995
  const session = await auth.getSession(token);
759
996
  if (!session) {
760
997
  const returnPath = req.originalUrl || "/oauth/authorize";
@@ -774,7 +1011,7 @@ function registerOAuthRoutes(app, oauth, auth, requireAuthSession, parseCookiesF
774
1011
  res.status(503).send("Authentication is not configured");
775
1012
  return;
776
1013
  }
777
- const token = parseCookiesFn(req)[SESSION_COOKIE] || "";
1014
+ const token = parseCookiesFn(req)[cookies().session] || "";
778
1015
  auth
779
1016
  .getSession(token)
780
1017
  .then((session) => {
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stageKrlContent = stageKrlContent;
4
+ const fs = require("fs");
5
+ const path = require("path");
6
+ const os = require("os");
7
+ const toFileUrl_1 = require("./utils/toFileUrl");
8
+ const STAGE_DIR = path.join(os.tmpdir(), "pico-engine-staged-krl");
9
+ /** Write KRL source to a temp file and return a file:// URL the registry can load. */
10
+ function stageKrlContent(content, filename) {
11
+ if (typeof content !== "string" || !/^ruleset\s+/m.test(content)) {
12
+ throw new Error("File must contain a KRL ruleset (starting with ruleset …)");
13
+ }
14
+ let base = path.basename(filename || "staged.krl");
15
+ if (!base.toLowerCase().endsWith(".krl")) {
16
+ base = base + ".krl";
17
+ }
18
+ base = base.replace(/[^\w.-]+/g, "_");
19
+ if (base === ".krl" || base === "") {
20
+ base = "staged.krl";
21
+ }
22
+ fs.mkdirSync(STAGE_DIR, { recursive: true });
23
+ const dest = path.join(STAGE_DIR, `${Date.now()}-${base}`);
24
+ fs.writeFileSync(dest, content, { encoding: "utf8", flag: "wx" });
25
+ return (0, toFileUrl_1.toFileUrl)(dest);
26
+ }
@@ -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
+ }