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,280 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.installEngineRuntimeSettings = installEngineRuntimeSettings;
4
+ exports.getEngineRuntimeSettings = getEngineRuntimeSettings;
5
+ exports.defaultEngineSettings = defaultEngineSettings;
6
+ exports.defaultEngineConfigFilePath = defaultEngineConfigFilePath;
7
+ exports.resolveEngineConfigFilePath = resolveEngineConfigFilePath;
8
+ exports.applyConfigCliArgs = applyConfigCliArgs;
9
+ exports.loadConfigFileSettings = loadConfigFileSettings;
10
+ exports.settingsFromEnv = settingsFromEnv;
11
+ exports.resolveEngineSettings = resolveEngineSettings;
12
+ const fs = require("fs");
13
+ const os = require("os");
14
+ const path = require("path");
15
+ const policyConfigFromJson_1 = require("./policyConfigFromJson");
16
+ const homeDir = require("home-dir");
17
+ let runtimeSettings = null;
18
+ function installEngineRuntimeSettings(settings) {
19
+ runtimeSettings = settings;
20
+ }
21
+ function getEngineRuntimeSettings() {
22
+ if (!runtimeSettings) {
23
+ runtimeSettings = defaultEngineSettings();
24
+ }
25
+ return runtimeSettings;
26
+ }
27
+ function defaultEngineSettings() {
28
+ return {
29
+ home: homeDir(".pico-engine"),
30
+ port: 3000,
31
+ baseUrl: "http://localhost:3000",
32
+ allowSelfSignup: false,
33
+ allowLocalhostChannelBypass: true,
34
+ wildcardSkyRequireBearer: false,
35
+ logToStdout: false,
36
+ };
37
+ }
38
+ function defaultEngineConfigFilePath() {
39
+ const xdg = process.env.XDG_CONFIG_HOME &&
40
+ process.env.XDG_CONFIG_HOME.trim().length > 0
41
+ ? process.env.XDG_CONFIG_HOME
42
+ : path.join(os.homedir(), ".config");
43
+ return path.join(xdg, "pico-engine", "config.json");
44
+ }
45
+ function resolveEngineConfigFilePath() {
46
+ const explicit = process.env.PICO_ENGINE_CONFIG;
47
+ if (typeof explicit === "string" && explicit.trim().length > 0) {
48
+ return path.resolve(expandHome(explicit.trim()));
49
+ }
50
+ return defaultEngineConfigFilePath();
51
+ }
52
+ /**
53
+ * Parse `--config` / `-c` from argv and set `PICO_ENGINE_CONFIG` before settings resolve.
54
+ * Use one config file per engine process (host or container).
55
+ */
56
+ function applyConfigCliArgs(argv) {
57
+ const out = [];
58
+ for (let i = 0; i < argv.length; i++) {
59
+ const arg = argv[i];
60
+ if (arg === "--config" || arg === "-c") {
61
+ const val = argv[++i];
62
+ if (typeof val !== "string" || val.length === 0) {
63
+ throw new Error(`${arg} requires a config file path`);
64
+ }
65
+ process.env.PICO_ENGINE_CONFIG = path.resolve(expandHome(val));
66
+ continue;
67
+ }
68
+ if (arg.startsWith("--config=")) {
69
+ const val = arg.slice("--config=".length);
70
+ if (val.length === 0) {
71
+ throw new Error("--config= requires a config file path");
72
+ }
73
+ process.env.PICO_ENGINE_CONFIG = path.resolve(expandHome(val));
74
+ continue;
75
+ }
76
+ out.push(arg);
77
+ }
78
+ return out;
79
+ }
80
+ function expandHome(p) {
81
+ if (p.startsWith("~/")) {
82
+ return path.join(os.homedir(), p.slice(2));
83
+ }
84
+ return p;
85
+ }
86
+ function parseConfigFile(raw) {
87
+ let data;
88
+ try {
89
+ data = JSON.parse(raw);
90
+ }
91
+ catch (err) {
92
+ throw new Error(`Invalid engine config JSON (${resolveEngineConfigFilePath()}): ${err}`);
93
+ }
94
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
95
+ throw new Error("Engine config must be a JSON object");
96
+ }
97
+ const o = data;
98
+ const out = {};
99
+ if (typeof o.home === "string" && o.home.length > 0) {
100
+ out.home = expandHome(o.home);
101
+ }
102
+ if (typeof o.port === "number" && o.port >= 0) {
103
+ out.port = o.port;
104
+ }
105
+ if (typeof o.baseUrl === "string" && o.baseUrl.length > 0) {
106
+ out.baseUrl = o.baseUrl;
107
+ }
108
+ const webauthn = o.webauthn && typeof o.webauthn === "object" && !Array.isArray(o.webauthn)
109
+ ? o.webauthn
110
+ : null;
111
+ if (webauthn) {
112
+ if (typeof webauthn.rpId === "string")
113
+ out.rpID = webauthn.rpId;
114
+ if (typeof webauthn.rpName === "string")
115
+ out.rpName = webauthn.rpName;
116
+ if (typeof webauthn.origin === "string")
117
+ out.origin = webauthn.origin;
118
+ }
119
+ if (typeof o.rpID === "string")
120
+ out.rpID = o.rpID;
121
+ if (typeof o.rpName === "string")
122
+ out.rpName = o.rpName;
123
+ if (typeof o.origin === "string")
124
+ out.origin = o.origin;
125
+ if (typeof o.allowSelfSignup === "boolean") {
126
+ out.allowSelfSignup = o.allowSelfSignup;
127
+ }
128
+ if (typeof o.allowLocalhostChannelBypass === "boolean") {
129
+ out.allowLocalhostChannelBypass = o.allowLocalhostChannelBypass;
130
+ }
131
+ if (typeof o.wildcardSkyRequireBearer === "boolean") {
132
+ out.wildcardSkyRequireBearer = o.wildcardSkyRequireBearer;
133
+ }
134
+ if (typeof o.logToStdout === "boolean") {
135
+ out.logToStdout = o.logToStdout;
136
+ }
137
+ if (typeof o.logFile === "string" && o.logFile.length > 0) {
138
+ if (o.logFile === "stdout" || o.logFile === "-") {
139
+ out.logToStdout = true;
140
+ }
141
+ else {
142
+ out.logFile = path.resolve(expandHome(o.logFile));
143
+ }
144
+ }
145
+ const rootCeiling = (0, policyConfigFromJson_1.parsePolicyCeilingFromJson)(o.defaultRootPolicyCeiling, "defaultRootPolicyCeiling");
146
+ if (rootCeiling) {
147
+ out.defaultRootPolicyCeiling = rootCeiling;
148
+ }
149
+ const globalEventDeny = (0, policyConfigFromJson_1.parseGlobalEventDenyFromJson)(o.globalEventDeny);
150
+ if (globalEventDeny) {
151
+ out.globalEventDeny = globalEventDeny;
152
+ }
153
+ const globalQueryDeny = (0, policyConfigFromJson_1.parseGlobalQueryDenyFromJson)(o.globalQueryDeny);
154
+ if (globalQueryDeny) {
155
+ out.globalQueryDeny = globalQueryDeny;
156
+ }
157
+ return out;
158
+ }
159
+ function loadConfigFileSettings() {
160
+ if (process.env.NODE_ENV === "test" && !process.env.PICO_ENGINE_CONFIG) {
161
+ return {};
162
+ }
163
+ const filePath = resolveEngineConfigFilePath();
164
+ if (!fs.existsSync(filePath)) {
165
+ return {};
166
+ }
167
+ const raw = fs.readFileSync(filePath, "utf8");
168
+ return parseConfigFile(raw);
169
+ }
170
+ function parseBoolEnv(val) {
171
+ if (val === undefined)
172
+ return undefined;
173
+ if (val === "true" || val === "1")
174
+ return true;
175
+ if (val === "false" || val === "0")
176
+ return false;
177
+ return undefined;
178
+ }
179
+ function settingsFromEnv() {
180
+ const out = {};
181
+ if (process.env.PORT) {
182
+ const port = parseInt(process.env.PORT, 10);
183
+ if (port >= 0)
184
+ out.port = port;
185
+ }
186
+ if (typeof process.env.PICO_ENGINE_HOME === "string" &&
187
+ process.env.PICO_ENGINE_HOME.length > 0) {
188
+ out.home = expandHome(process.env.PICO_ENGINE_HOME);
189
+ }
190
+ if (typeof process.env.PICO_ENGINE_BASE_URL === "string" &&
191
+ process.env.PICO_ENGINE_BASE_URL.length > 0) {
192
+ out.baseUrl = process.env.PICO_ENGINE_BASE_URL;
193
+ }
194
+ if (typeof process.env.PICO_ENGINE_RP_ID === "string" &&
195
+ process.env.PICO_ENGINE_RP_ID.length > 0) {
196
+ out.rpID = process.env.PICO_ENGINE_RP_ID;
197
+ }
198
+ if (typeof process.env.PICO_ENGINE_ORIGIN === "string" &&
199
+ process.env.PICO_ENGINE_ORIGIN.length > 0) {
200
+ out.origin = process.env.PICO_ENGINE_ORIGIN;
201
+ }
202
+ const signup = parseBoolEnv(process.env.PICO_ENGINE_ALLOW_SELF_SIGNUP);
203
+ if (signup !== undefined)
204
+ out.allowSelfSignup = signup;
205
+ const localhostC = parseBoolEnv(process.env.PICO_ENGINE_ALLOW_LOCALHOST_C);
206
+ if (localhostC !== undefined) {
207
+ out.allowLocalhostChannelBypass = localhostC;
208
+ }
209
+ else if (process.env.PICO_ENGINE_ALLOW_LOCALHOST_C === "0") {
210
+ out.allowLocalhostChannelBypass = false;
211
+ }
212
+ const wildcard = parseBoolEnv(process.env.PICO_ENGINE_WILDCARD_SKY_REQUIRE_BEARER);
213
+ if (wildcard !== undefined)
214
+ out.wildcardSkyRequireBearer = wildcard;
215
+ const logFile = process.env.PICO_ENGINE_LOG_FILE;
216
+ if (logFile === "0" || logFile === "-" || logFile === "stdout" || logFile === "") {
217
+ out.logToStdout = true;
218
+ }
219
+ else if (typeof logFile === "string" && logFile.length > 0) {
220
+ out.logFile = path.resolve(expandHome(logFile));
221
+ }
222
+ return out;
223
+ }
224
+ function mergeSettings(base, ...layers) {
225
+ const merged = Object.assign({}, base);
226
+ for (const layer of layers) {
227
+ Object.assign(merged, layer);
228
+ }
229
+ return merged;
230
+ }
231
+ /**
232
+ * Resolve settings: defaults ← environment ← config file ← programmatic (tests, API).
233
+ * `PORT` and `PICO_ENGINE_HOME` (and other env keys) apply when the file omits them;
234
+ * values in the config file win when both are set.
235
+ */
236
+ function resolveEngineSettings(programmatic = {}) {
237
+ var _a;
238
+ const fromProgrammatic = {};
239
+ if (programmatic.home)
240
+ fromProgrammatic.home = programmatic.home;
241
+ if (programmatic.port != null)
242
+ fromProgrammatic.port = programmatic.port;
243
+ const baseUrl = (_a = programmatic.baseUrl) !== null && _a !== void 0 ? _a : programmatic.base_url;
244
+ if (baseUrl)
245
+ fromProgrammatic.baseUrl = baseUrl;
246
+ if (programmatic.rpID)
247
+ fromProgrammatic.rpID = programmatic.rpID;
248
+ if (programmatic.rpName)
249
+ fromProgrammatic.rpName = programmatic.rpName;
250
+ if (programmatic.origin)
251
+ fromProgrammatic.origin = programmatic.origin;
252
+ if (programmatic.allowSelfSignup !== undefined) {
253
+ fromProgrammatic.allowSelfSignup = programmatic.allowSelfSignup;
254
+ }
255
+ if (programmatic.allowLocalhostChannelBypass !== undefined) {
256
+ fromProgrammatic.allowLocalhostChannelBypass =
257
+ programmatic.allowLocalhostChannelBypass;
258
+ }
259
+ if (programmatic.wildcardSkyRequireBearer !== undefined) {
260
+ fromProgrammatic.wildcardSkyRequireBearer =
261
+ programmatic.wildcardSkyRequireBearer;
262
+ }
263
+ if (programmatic.logToStdout !== undefined) {
264
+ fromProgrammatic.logToStdout = programmatic.logToStdout;
265
+ }
266
+ if (programmatic.logFile !== undefined) {
267
+ fromProgrammatic.logFile = programmatic.logFile;
268
+ }
269
+ if (programmatic.defaultRootPolicyCeiling !== undefined) {
270
+ fromProgrammatic.defaultRootPolicyCeiling =
271
+ programmatic.defaultRootPolicyCeiling;
272
+ }
273
+ if (programmatic.globalEventDeny !== undefined) {
274
+ fromProgrammatic.globalEventDeny = programmatic.globalEventDeny;
275
+ }
276
+ if (programmatic.globalQueryDeny !== undefined) {
277
+ fromProgrammatic.globalQueryDeny = programmatic.globalQueryDeny;
278
+ }
279
+ return mergeSettings(defaultEngineSettings(), settingsFromEnv(), loadConfigFileSettings(), fromProgrammatic);
280
+ }
@@ -9,16 +9,79 @@ const veramoDidComm_1 = require("./veramoDidComm");
9
9
  const establishSubscription_1 = require("./establishSubscription");
10
10
  const crossPico_1 = require("./crossPico");
11
11
  const skyProtocol_1 = require("./skyProtocol");
12
+ const skyRotation_1 = require("./skyRotation");
13
+ const webvhRelocation_1 = require("./webvhRelocation");
14
+ const identityPortable_1 = require("./identityPortable");
15
+ const portableMove_1 = require("./portableMove");
16
+ const pico_engine_core_1 = require("pico-engine-core");
12
17
  const skyIntro_1 = require("./skyIntro");
13
18
  /**
14
19
  * Engine identity primitive — store-backed DID state and DIDComm capabilities.
15
20
  * Crypto (pack/unpack) is delegated to Veramo when installed (Epic 2+).
16
21
  */
22
+ function isSelfOrDescendant(pf, ancestorPicoId, descendantPicoId) {
23
+ if (ancestorPicoId === descendantPicoId) {
24
+ return true;
25
+ }
26
+ let current = pf.getPico(descendantPicoId);
27
+ while (current) {
28
+ if (current.id === ancestorPicoId) {
29
+ return true;
30
+ }
31
+ current = current.parent ? pf.getPico(current.parent) : undefined;
32
+ }
33
+ return false;
34
+ }
17
35
  class IdentityService {
18
36
  constructor(deps) {
19
37
  this.store = deps.store;
20
38
  this.getBaseUrl = deps.getBaseUrl;
21
39
  this.pf = deps.pf;
40
+ this.rsRegistry = deps.rsRegistry;
41
+ this.resolveBundledRulesetUrl = deps.resolveBundledRulesetUrl;
42
+ this.reloadImportedSchedules = deps.reloadImportedSchedules;
43
+ this.firePicoImported = deps.firePicoImported;
44
+ }
45
+ /** Hooks wired into ctx:exportSubtree / importSubtree for identity snapshots. */
46
+ subtreePortableHooks() {
47
+ return (0, identityPortable_1.createSubtreePortableHooks)(this.store, this.pf);
48
+ }
49
+ portableMoveDeps() {
50
+ return {
51
+ store: this.store,
52
+ pf: this.pf,
53
+ rsRegistry: this.rsRegistry,
54
+ identity: this,
55
+ getBaseUrl: this.getBaseUrl,
56
+ resolveBundledRulesetUrl: this.resolveBundledRulesetUrl,
57
+ reloadImportedSchedules: this.reloadImportedSchedules,
58
+ firePicoImported: this.firePicoImported,
59
+ };
60
+ }
61
+ /**
62
+ * Export subtree + per-pico identity. Caller must be the subtree root or an ancestor.
63
+ */
64
+ async exportPortableSubtree(fromPicoId, subtreeRootPicoId, secret, options) {
65
+ if (!isSelfOrDescendant(this.pf, fromPicoId, subtreeRootPicoId)) {
66
+ throw new errors_1.IdentityError(`Pico ${fromPicoId} cannot export subtree rooted at ${subtreeRootPicoId}`, 403);
67
+ }
68
+ return (0, portableMove_1.exportPortableSubtree)(this.portableMoveDeps(), subtreeRootPicoId, secret, options);
69
+ }
70
+ /** Decrypt a portable subtree export blob and return a debug summary (no pico access). */
71
+ summarizePortableSubtreeExport(blob, secret) {
72
+ return (0, pico_engine_core_1.summarizeSubtreeExportBlob)(blob, secret);
73
+ }
74
+ /** Import portable subtree under parent; relocate webvh and notify peer subscriptions. */
75
+ async importPortableSubtree(parentPicoId, blob, secret, relocateOptions, importOptions) {
76
+ const parent = this.pf.getPico(parentPicoId);
77
+ if (!parent) {
78
+ throw new errors_1.IdentityError(`Parent pico not found: ${parentPicoId}`, 404);
79
+ }
80
+ return (0, portableMove_1.importPortableSubtree)(this.portableMoveDeps(), parent, blob, secret, relocateOptions, importOptions);
81
+ }
82
+ /** Relocate webvh and notify peers after ctx/importIntoExistingChild hydration. */
83
+ async finalizePortableImport(importResult, relocateOptions) {
84
+ return (0, portableMove_1.finalizePortableImport)(this.portableMoveDeps(), importResult, relocateOptions);
22
85
  }
23
86
  async ensureWebvhDid(picoId, options = {}) {
24
87
  return (0, webvh_1.ensureWebvhDid)(this.store, this.pf, () => this.getBaseUrl(), picoId, options);
@@ -133,6 +196,30 @@ class IdentityService {
133
196
  async getRoutes(picoId) {
134
197
  return (await this.store.getRoutes(picoId)) || {};
135
198
  }
199
+ /**
200
+ * Append a did:webvh log entry after move (SCID unchanged, host/path/endpoint may change).
201
+ */
202
+ async relocateWebvhAfterMove(picoId, options = {}) {
203
+ return (0, webvhRelocation_1.relocateWebvhDid)(this.store, this.pf, () => this.getBaseUrl(), picoId, options);
204
+ }
205
+ /** Notify established peer subscriptions of a did:webvh relocation. */
206
+ async notifyPeersOfWebvhRotation(picoId, relocation) {
207
+ return (0, skyRotation_1.notifyPeersOfWebvhRotation)(this.rotationDeps(), picoId, relocation);
208
+ }
209
+ /** Relocate did:webvh and notify all peer subscriptions (Phase D move). */
210
+ async completePortableMove(picoId, options = {}) {
211
+ const relocation = await this.relocateWebvhAfterMove(picoId, options);
212
+ const peersNotified = await this.notifyPeersOfWebvhRotation(picoId, relocation);
213
+ return Object.assign(Object.assign({}, relocation), { peersNotified });
214
+ }
215
+ rotationDeps() {
216
+ return {
217
+ store: this.store,
218
+ pf: this.pf,
219
+ getBaseUrl: this.getBaseUrl,
220
+ identity: this,
221
+ };
222
+ }
136
223
  generateMessage(options) {
137
224
  const message = {
138
225
  id: cuid(),
@@ -219,6 +306,9 @@ class IdentityService {
219
306
  if (message.type === skyProtocol_1.SKY_INTRO_RESPONSE) {
220
307
  return (0, skyIntro_1.handleSkyIntroResponseAtIngress)(this.skyIntroDeps(), picoId, message);
221
308
  }
309
+ if (message.type === skyProtocol_1.SKY_ROTATE) {
310
+ return (0, skyRotation_1.handleSkyRotateAtIngress)(this.rotationDeps(), picoId, message);
311
+ }
222
312
  // Channel policy (Epic 7): authenticated sender peer DID → subscription record →
223
313
  // internal Rx channel. Door verify proves crypto + subscription relationship;
224
314
  // pf.eventWait / pf.query enforce assertEventPolicy / assertQueryPolicy on rxEci.
@@ -13,7 +13,7 @@ const skyProtocol_1 = require("./skyProtocol");
13
13
  const veramoDidComm_1 = require("./veramoDidComm");
14
14
  const errors_1 = require("./errors");
15
15
  function remotePeerDid(sub) {
16
- const did = sub.remotePeerDid || sub.remoteDid;
16
+ const did = sub.remotePeerDid || sub.remoteDid || sub.remoteWebvhDid;
17
17
  if (!did) {
18
18
  throw new errors_1.IdentityError("Subscription missing remote peer DID", 400);
19
19
  }
@@ -23,7 +23,20 @@ function remoteTxHost(sub, fallback) {
23
23
  const host = sub.remoteTxHost || fallback;
24
24
  return host.replace(/\/$/, "");
25
25
  }
26
- async function usesLocalDispatch(store, pf, fromPicoId, toPicoId, sub) {
26
+ function normalizeBaseUrl(url) {
27
+ return url.replace(/\/$/, "");
28
+ }
29
+ /** Peer lives on another engine when identity store says so (post-move rotate). */
30
+ function peerOnRemoteEngine(sub, localBaseUrl) {
31
+ if (!sub.remoteTxHost) {
32
+ return false;
33
+ }
34
+ return normalizeBaseUrl(sub.remoteTxHost) !== normalizeBaseUrl(localBaseUrl);
35
+ }
36
+ async function usesLocalDispatch(store, pf, fromPicoId, toPicoId, sub, localBaseUrl) {
37
+ if (peerOnRemoteEngine(sub, localBaseUrl)) {
38
+ return false;
39
+ }
27
40
  const fromMesh = await store.getMeshRootId(fromPicoId);
28
41
  const toMesh = await store.getMeshRootId(toPicoId);
29
42
  if (!fromMesh || !toMesh || fromMesh !== toMesh) {
@@ -34,19 +47,20 @@ async function usesLocalDispatch(store, pf, fromPicoId, toPicoId, sub) {
34
47
  }
35
48
  return pf.loadedPicos().some((p) => p.id === toPicoId);
36
49
  }
37
- async function resolveRecipientPicoId(store, pf, fromPicoId, subscriptionId) {
50
+ async function resolveRecipientPicoId(store, pf, fromPicoId, subscriptionId, localBaseUrl) {
38
51
  const sub = await store.getPeerSubscription(fromPicoId, subscriptionId);
39
52
  if (!sub) {
40
53
  return undefined;
41
54
  }
55
+ const remoteEngine = peerOnRemoteEngine(sub, localBaseUrl);
42
56
  const remotePeer = sub.remotePeerDid || sub.remoteDid;
43
- if (remotePeer) {
57
+ if (remotePeer && !remoteEngine) {
44
58
  const byPeer = await store.findPicoIdByLocalPeerDid(remotePeer);
45
59
  if (byPeer && pf.loadedPicos().some((p) => p.id === byPeer)) {
46
60
  return byPeer;
47
61
  }
48
62
  }
49
- if (sub.remoteWebvhDid) {
63
+ if (sub.remoteWebvhDid && !remoteEngine) {
50
64
  const byWebvh = await store.findPicoIdByWebvhDid(sub.remoteWebvhDid);
51
65
  if (byWebvh && pf.loadedPicos().some((p) => p.id === byWebvh)) {
52
66
  return byWebvh;
@@ -61,46 +75,108 @@ async function crossPicoEvent(deps, fromPicoId, toPicoId, subscriptionId, event)
61
75
  }
62
76
  const callerDid = await deps.store.getWebvhDid(fromPicoId);
63
77
  const attrs = Object.assign(Object.assign({}, (event.attrs || {})), { callerDid: callerDid || undefined });
78
+ const localBase = deps.getBaseUrl();
64
79
  const to = toPicoId ||
65
- (await resolveRecipientPicoId(deps.store, deps.pf, fromPicoId, subscriptionId));
80
+ (await resolveRecipientPicoId(deps.store, deps.pf, fromPicoId, subscriptionId, localBase));
66
81
  if (to &&
67
- (await usesLocalDispatch(deps.store, deps.pf, fromPicoId, to, sub))) {
68
- const recipientSub = await findRecipientSub(deps.store, to, subscriptionId);
69
- return deps.pf.eventWait({
70
- eci: recipientSub.rxEci,
71
- domain: event.domain,
72
- name: event.name,
73
- data: { attrs },
74
- time: 0,
75
- }, fromPicoId);
82
+ (await usesLocalDispatch(deps.store, deps.pf, fromPicoId, to, sub, localBase))) {
83
+ const rxEci = await resolveRecipientRxEci(deps, to, subscriptionId);
84
+ if (rxEci) {
85
+ return deps.pf.eventWait({
86
+ eci: rxEci,
87
+ domain: event.domain,
88
+ name: event.name,
89
+ data: { attrs },
90
+ time: 0,
91
+ }, fromPicoId);
92
+ }
76
93
  }
77
- return sendSkyEvent(deps, fromPicoId, sub, event, attrs);
94
+ try {
95
+ return await sendSkyEvent(deps, fromPicoId, sub, event, attrs);
96
+ }
97
+ catch (err) {
98
+ if (isRemovalNotification(event.name)) {
99
+ return { eid: "none", responses: [] };
100
+ }
101
+ throw err;
102
+ }
103
+ }
104
+ function isRemovalNotification(name) {
105
+ return (name === "inbound_removal" ||
106
+ name === "outbound_removal" ||
107
+ name === "established_removal");
78
108
  }
79
109
  async function crossPicoQuery(deps, fromPicoId, toPicoId, subscriptionId, query) {
80
110
  const sub = await deps.store.getPeerSubscription(fromPicoId, subscriptionId);
81
111
  if (!sub || !sub.rxEci) {
82
112
  throw new errors_1.IdentityError(`Unknown subscription ${subscriptionId}`, 404);
83
113
  }
114
+ const localBase = deps.getBaseUrl();
84
115
  const to = toPicoId ||
85
- (await resolveRecipientPicoId(deps.store, deps.pf, fromPicoId, subscriptionId));
116
+ (await resolveRecipientPicoId(deps.store, deps.pf, fromPicoId, subscriptionId, localBase));
86
117
  if (to &&
87
- (await usesLocalDispatch(deps.store, deps.pf, fromPicoId, to, sub))) {
88
- const recipientSub = await findRecipientSub(deps.store, to, subscriptionId);
89
- return deps.pf.query({
90
- eci: recipientSub.rxEci,
91
- rid: query.rid,
92
- name: query.name,
93
- args: query.args || {},
94
- }, fromPicoId);
118
+ (await usesLocalDispatch(deps.store, deps.pf, fromPicoId, to, sub, localBase))) {
119
+ const rxEci = await resolveRecipientRxEci(deps, to, subscriptionId);
120
+ if (rxEci) {
121
+ return deps.pf.query({
122
+ eci: rxEci,
123
+ rid: query.rid,
124
+ name: query.name,
125
+ args: query.args || {},
126
+ }, fromPicoId);
127
+ }
95
128
  }
96
129
  return sendSkyQuery(deps, fromPicoId, sub, query);
97
130
  }
98
- async function findRecipientSub(store, toPicoId, subscriptionId) {
99
- const recipientSub = await store.getPeerSubscription(toPicoId, subscriptionId);
100
- if (!(recipientSub === null || recipientSub === void 0 ? void 0 : recipientSub.rxEci)) {
101
- throw new errors_1.IdentityError(`Recipient subscription ${subscriptionId} missing rxEci`, 404);
131
+ function deliveryEci(pf, picoId, preferred) {
132
+ if (preferred) {
133
+ return preferred;
134
+ }
135
+ const pico = pf.loadedPicos().find((p) => p.id === picoId);
136
+ if (!pico) {
137
+ throw new errors_1.IdentityError(`Pico ${picoId} not loaded`, 404);
138
+ }
139
+ for (const ch of Object.values(pico.channels)) {
140
+ const ro = ch.toReadOnly();
141
+ if (ro.tags.includes("wellKnown_Rx")) {
142
+ return ro.id;
143
+ }
144
+ }
145
+ for (const ch of Object.values(pico.channels)) {
146
+ const ro = ch.toReadOnly();
147
+ if (ro.tags.includes("allow-all")) {
148
+ return ro.id;
149
+ }
102
150
  }
103
- return recipientSub;
151
+ const first = Object.keys(pico.channels)[0];
152
+ if (!first) {
153
+ throw new errors_1.IdentityError("Pico has no channel for cross-pico delivery", 404);
154
+ }
155
+ return first;
156
+ }
157
+ /** Resolve Rx ECI on the recipient for local dispatch (identity store, then inbound bus). */
158
+ async function resolveRecipientRxEci(deps, toPicoId, subscriptionId) {
159
+ const recipientSub = await deps.store.getPeerSubscription(toPicoId, subscriptionId);
160
+ if (recipientSub === null || recipientSub === void 0 ? void 0 : recipientSub.rxEci) {
161
+ return recipientSub.rxEci;
162
+ }
163
+ try {
164
+ const queryEci = deliveryEci(deps.pf, toPicoId, recipientSub === null || recipientSub === void 0 ? void 0 : recipientSub.rxEci);
165
+ const inbound = (await deps.pf.query({
166
+ eci: queryEci,
167
+ rid: "io.picolabs.subscription",
168
+ name: "inbound",
169
+ args: {},
170
+ }, toPicoId));
171
+ const bus = inbound.find((b) => b.Id === subscriptionId);
172
+ if (typeof (bus === null || bus === void 0 ? void 0 : bus.Rx) === "string" && bus.Rx.length > 0) {
173
+ return bus.Rx;
174
+ }
175
+ }
176
+ catch (_a) {
177
+ // fall through to DIDComm or no-op
178
+ }
179
+ return undefined;
104
180
  }
105
181
  async function sendSkyEvent(deps, fromPicoId, sub, event, attrs) {
106
182
  const message = deps.identity.generateMessage({