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
@@ -0,0 +1,363 @@
1
+ import * as fs from "fs";
2
+ import * as os from "os";
3
+ import * as path from "path";
4
+ import type {
5
+ EventPolicyRule,
6
+ PolicyCeiling,
7
+ QueryPolicyRule,
8
+ } from "pico-framework";
9
+ import {
10
+ parseGlobalEventDenyFromJson,
11
+ parseGlobalQueryDenyFromJson,
12
+ parsePolicyCeilingFromJson,
13
+ } from "./policyConfigFromJson";
14
+
15
+ const homeDir = require("home-dir") as (sub?: string) => string;
16
+
17
+ /**
18
+ * Operator settings (file + env). Ephemeral state stays under {@link home} (DB, cache, logs).
19
+ * Config file default: ~/.config/pico-engine/config.json (override with PICO_ENGINE_CONFIG).
20
+ */
21
+ export interface EngineSettings {
22
+ home: string;
23
+ port: number;
24
+ baseUrl: string;
25
+ rpID?: string;
26
+ rpName?: string;
27
+ origin?: string;
28
+ allowSelfSignup: boolean;
29
+ /** When true, localhost may call /c/* without passkey (dev MCP, ctx HTTP loops). */
30
+ allowLocalhostChannelBypass: boolean;
31
+ wildcardSkyRequireBearer: boolean;
32
+ logToStdout: boolean;
33
+ /** Absolute log file path; ignored when logToStdout is true. */
34
+ logFile?: string;
35
+ /**
36
+ * When `logToStdout` is true: also write structured JSON lines to
37
+ * `$PICO_ENGINE_HOME/pico-engine.log` so `ctx:logs` / Developer UI Logging work.
38
+ * Set false on EFS/Fargate to avoid mirror file churn (`PICO_ENGINE_LOG_MIRROR=0`).
39
+ */
40
+ logMirror: boolean;
41
+ /** Max channel policy for root picos when none stored on the pico (1.8). */
42
+ defaultRootPolicyCeiling?: PolicyCeiling;
43
+ /** Deny rules applied on every ECI before per-channel policy (1.8). */
44
+ globalEventDeny?: EventPolicyRule[];
45
+ globalQueryDeny?: QueryPolicyRule[];
46
+ }
47
+
48
+ export interface EngineSettingsOverrides {
49
+ home?: string;
50
+ port?: number;
51
+ baseUrl?: string;
52
+ base_url?: string;
53
+ rpID?: string;
54
+ rpName?: string;
55
+ origin?: string;
56
+ allowSelfSignup?: boolean;
57
+ allowLocalhostChannelBypass?: boolean;
58
+ wildcardSkyRequireBearer?: boolean;
59
+ logToStdout?: boolean;
60
+ logFile?: string;
61
+ logMirror?: boolean;
62
+ defaultRootPolicyCeiling?: PolicyCeiling;
63
+ globalEventDeny?: EventPolicyRule[];
64
+ globalQueryDeny?: QueryPolicyRule[];
65
+ }
66
+
67
+ let runtimeSettings: EngineSettings | null = null;
68
+
69
+ export function installEngineRuntimeSettings(settings: EngineSettings): void {
70
+ runtimeSettings = settings;
71
+ }
72
+
73
+ export function getEngineRuntimeSettings(): EngineSettings {
74
+ if (!runtimeSettings) {
75
+ runtimeSettings = defaultEngineSettings();
76
+ }
77
+ return runtimeSettings;
78
+ }
79
+
80
+ export function defaultEngineSettings(): EngineSettings {
81
+ return {
82
+ home: homeDir(".pico-engine") as string,
83
+ port: 3000,
84
+ baseUrl: "http://localhost:3000",
85
+ allowSelfSignup: false,
86
+ allowLocalhostChannelBypass: true,
87
+ wildcardSkyRequireBearer: false,
88
+ logToStdout: false,
89
+ logMirror: true,
90
+ };
91
+ }
92
+
93
+ export function defaultEngineConfigFilePath(): string {
94
+ const xdg =
95
+ process.env.XDG_CONFIG_HOME &&
96
+ process.env.XDG_CONFIG_HOME.trim().length > 0
97
+ ? process.env.XDG_CONFIG_HOME
98
+ : path.join(os.homedir(), ".config");
99
+ return path.join(xdg, "pico-engine", "config.json");
100
+ }
101
+
102
+ export function resolveEngineConfigFilePath(): string {
103
+ const explicit = process.env.PICO_ENGINE_CONFIG;
104
+ if (typeof explicit === "string" && explicit.trim().length > 0) {
105
+ return path.resolve(expandHome(explicit.trim()));
106
+ }
107
+ return defaultEngineConfigFilePath();
108
+ }
109
+
110
+ /**
111
+ * Parse `--config` / `-c` from argv and set `PICO_ENGINE_CONFIG` before settings resolve.
112
+ * Use one config file per engine process (host or container).
113
+ */
114
+ export function applyConfigCliArgs(argv: string[]): string[] {
115
+ const out: string[] = [];
116
+ for (let i = 0; i < argv.length; i++) {
117
+ const arg = argv[i];
118
+ if (arg === "--config" || arg === "-c") {
119
+ const val = argv[++i];
120
+ if (typeof val !== "string" || val.length === 0) {
121
+ throw new Error(`${arg} requires a config file path`);
122
+ }
123
+ process.env.PICO_ENGINE_CONFIG = path.resolve(expandHome(val));
124
+ continue;
125
+ }
126
+ if (arg.startsWith("--config=")) {
127
+ const val = arg.slice("--config=".length);
128
+ if (val.length === 0) {
129
+ throw new Error("--config= requires a config file path");
130
+ }
131
+ process.env.PICO_ENGINE_CONFIG = path.resolve(expandHome(val));
132
+ continue;
133
+ }
134
+ out.push(arg);
135
+ }
136
+ return out;
137
+ }
138
+
139
+ function expandHome(p: string): string {
140
+ if (p.startsWith("~/")) {
141
+ return path.join(os.homedir(), p.slice(2));
142
+ }
143
+ return p;
144
+ }
145
+
146
+ function parseConfigFile(raw: string): Partial<EngineSettings> {
147
+ let data: unknown;
148
+ try {
149
+ data = JSON.parse(raw);
150
+ } catch (err) {
151
+ throw new Error(
152
+ `Invalid engine config JSON (${resolveEngineConfigFilePath()}): ${err}`,
153
+ );
154
+ }
155
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
156
+ throw new Error("Engine config must be a JSON object");
157
+ }
158
+ const o = data as Record<string, unknown>;
159
+ const out: Partial<EngineSettings> = {};
160
+
161
+ if (typeof o.home === "string" && o.home.length > 0) {
162
+ out.home = expandHome(o.home);
163
+ }
164
+ if (typeof o.port === "number" && o.port >= 0) {
165
+ out.port = o.port;
166
+ }
167
+ if (typeof o.baseUrl === "string" && o.baseUrl.length > 0) {
168
+ out.baseUrl = o.baseUrl;
169
+ }
170
+ const webauthn =
171
+ o.webauthn && typeof o.webauthn === "object" && !Array.isArray(o.webauthn)
172
+ ? (o.webauthn as Record<string, unknown>)
173
+ : null;
174
+ if (webauthn) {
175
+ if (typeof webauthn.rpId === "string") out.rpID = webauthn.rpId;
176
+ if (typeof webauthn.rpName === "string") out.rpName = webauthn.rpName;
177
+ if (typeof webauthn.origin === "string") out.origin = webauthn.origin;
178
+ }
179
+ if (typeof o.rpID === "string") out.rpID = o.rpID;
180
+ if (typeof o.rpName === "string") out.rpName = o.rpName;
181
+ if (typeof o.origin === "string") out.origin = o.origin;
182
+ if (typeof o.allowSelfSignup === "boolean") {
183
+ out.allowSelfSignup = o.allowSelfSignup;
184
+ }
185
+ if (typeof o.allowLocalhostChannelBypass === "boolean") {
186
+ out.allowLocalhostChannelBypass = o.allowLocalhostChannelBypass;
187
+ }
188
+ if (typeof o.wildcardSkyRequireBearer === "boolean") {
189
+ out.wildcardSkyRequireBearer = o.wildcardSkyRequireBearer;
190
+ }
191
+ if (typeof o.logToStdout === "boolean") {
192
+ out.logToStdout = o.logToStdout;
193
+ }
194
+ if (typeof o.logMirror === "boolean") {
195
+ out.logMirror = o.logMirror;
196
+ }
197
+ if (typeof o.logFile === "string" && o.logFile.length > 0) {
198
+ if (o.logFile === "stdout" || o.logFile === "-") {
199
+ out.logToStdout = true;
200
+ } else {
201
+ out.logFile = path.resolve(expandHome(o.logFile));
202
+ }
203
+ }
204
+ const rootCeiling = parsePolicyCeilingFromJson(
205
+ o.defaultRootPolicyCeiling,
206
+ "defaultRootPolicyCeiling",
207
+ );
208
+ if (rootCeiling) {
209
+ out.defaultRootPolicyCeiling = rootCeiling;
210
+ }
211
+ const globalEventDeny = parseGlobalEventDenyFromJson(o.globalEventDeny);
212
+ if (globalEventDeny) {
213
+ out.globalEventDeny = globalEventDeny;
214
+ }
215
+ const globalQueryDeny = parseGlobalQueryDenyFromJson(o.globalQueryDeny);
216
+ if (globalQueryDeny) {
217
+ out.globalQueryDeny = globalQueryDeny;
218
+ }
219
+
220
+ return out;
221
+ }
222
+
223
+ export function loadConfigFileSettings(): Partial<EngineSettings> {
224
+ if (process.env.NODE_ENV === "test" && !process.env.PICO_ENGINE_CONFIG) {
225
+ return {};
226
+ }
227
+ const filePath = resolveEngineConfigFilePath();
228
+ if (!fs.existsSync(filePath)) {
229
+ return {};
230
+ }
231
+ const raw = fs.readFileSync(filePath, "utf8");
232
+ return parseConfigFile(raw);
233
+ }
234
+
235
+ function parseBoolEnv(val: string | undefined): boolean | undefined {
236
+ if (val === undefined) return undefined;
237
+ if (val === "true" || val === "1") return true;
238
+ if (val === "false" || val === "0") return false;
239
+ return undefined;
240
+ }
241
+
242
+ export function settingsFromEnv(): Partial<EngineSettings> {
243
+ const out: Partial<EngineSettings> = {};
244
+
245
+ if (process.env.PORT) {
246
+ const port = parseInt(process.env.PORT, 10);
247
+ if (port >= 0) out.port = port;
248
+ }
249
+ if (
250
+ typeof process.env.PICO_ENGINE_HOME === "string" &&
251
+ process.env.PICO_ENGINE_HOME.length > 0
252
+ ) {
253
+ out.home = expandHome(process.env.PICO_ENGINE_HOME);
254
+ }
255
+ if (
256
+ typeof process.env.PICO_ENGINE_BASE_URL === "string" &&
257
+ process.env.PICO_ENGINE_BASE_URL.length > 0
258
+ ) {
259
+ out.baseUrl = process.env.PICO_ENGINE_BASE_URL;
260
+ }
261
+ if (
262
+ typeof process.env.PICO_ENGINE_RP_ID === "string" &&
263
+ process.env.PICO_ENGINE_RP_ID.length > 0
264
+ ) {
265
+ out.rpID = process.env.PICO_ENGINE_RP_ID;
266
+ }
267
+ if (
268
+ typeof process.env.PICO_ENGINE_ORIGIN === "string" &&
269
+ process.env.PICO_ENGINE_ORIGIN.length > 0
270
+ ) {
271
+ out.origin = process.env.PICO_ENGINE_ORIGIN;
272
+ }
273
+ const signup = parseBoolEnv(process.env.PICO_ENGINE_ALLOW_SELF_SIGNUP);
274
+ if (signup !== undefined) out.allowSelfSignup = signup;
275
+ const localhostC = parseBoolEnv(process.env.PICO_ENGINE_ALLOW_LOCALHOST_C);
276
+ if (localhostC !== undefined) {
277
+ out.allowLocalhostChannelBypass = localhostC;
278
+ } else if (process.env.PICO_ENGINE_ALLOW_LOCALHOST_C === "0") {
279
+ out.allowLocalhostChannelBypass = false;
280
+ }
281
+ const wildcard = parseBoolEnv(
282
+ process.env.PICO_ENGINE_WILDCARD_SKY_REQUIRE_BEARER,
283
+ );
284
+ if (wildcard !== undefined) out.wildcardSkyRequireBearer = wildcard;
285
+ const logFile = process.env.PICO_ENGINE_LOG_FILE;
286
+ if (logFile === "0" || logFile === "-" || logFile === "stdout" || logFile === "") {
287
+ out.logToStdout = true;
288
+ } else if (typeof logFile === "string" && logFile.length > 0) {
289
+ out.logFile = path.resolve(expandHome(logFile));
290
+ }
291
+ const logMirror = parseBoolEnv(process.env.PICO_ENGINE_LOG_MIRROR);
292
+ if (logMirror !== undefined) {
293
+ out.logMirror = logMirror;
294
+ }
295
+
296
+ return out;
297
+ }
298
+
299
+ function mergeSettings(
300
+ base: EngineSettings,
301
+ ...layers: Partial<EngineSettings>[]
302
+ ): EngineSettings {
303
+ const merged = { ...base };
304
+ for (const layer of layers) {
305
+ Object.assign(merged, layer);
306
+ }
307
+ return merged;
308
+ }
309
+
310
+ /**
311
+ * Resolve settings: defaults ← environment ← config file ← programmatic (tests, API).
312
+ * `PORT` and `PICO_ENGINE_HOME` (and other env keys) apply when the file omits them;
313
+ * values in the config file win when both are set.
314
+ */
315
+ export function resolveEngineSettings(
316
+ programmatic: EngineSettingsOverrides = {},
317
+ ): EngineSettings {
318
+ const fromProgrammatic: Partial<EngineSettings> = {};
319
+ if (programmatic.home) fromProgrammatic.home = programmatic.home;
320
+ if (programmatic.port != null) fromProgrammatic.port = programmatic.port;
321
+ const baseUrl = programmatic.baseUrl ?? programmatic.base_url;
322
+ if (baseUrl) fromProgrammatic.baseUrl = baseUrl;
323
+ if (programmatic.rpID) fromProgrammatic.rpID = programmatic.rpID;
324
+ if (programmatic.rpName) fromProgrammatic.rpName = programmatic.rpName;
325
+ if (programmatic.origin) fromProgrammatic.origin = programmatic.origin;
326
+ if (programmatic.allowSelfSignup !== undefined) {
327
+ fromProgrammatic.allowSelfSignup = programmatic.allowSelfSignup;
328
+ }
329
+ if (programmatic.allowLocalhostChannelBypass !== undefined) {
330
+ fromProgrammatic.allowLocalhostChannelBypass =
331
+ programmatic.allowLocalhostChannelBypass;
332
+ }
333
+ if (programmatic.wildcardSkyRequireBearer !== undefined) {
334
+ fromProgrammatic.wildcardSkyRequireBearer =
335
+ programmatic.wildcardSkyRequireBearer;
336
+ }
337
+ if (programmatic.logToStdout !== undefined) {
338
+ fromProgrammatic.logToStdout = programmatic.logToStdout;
339
+ }
340
+ if (programmatic.logFile !== undefined) {
341
+ fromProgrammatic.logFile = programmatic.logFile;
342
+ }
343
+ if (programmatic.logMirror !== undefined) {
344
+ fromProgrammatic.logMirror = programmatic.logMirror;
345
+ }
346
+ if (programmatic.defaultRootPolicyCeiling !== undefined) {
347
+ fromProgrammatic.defaultRootPolicyCeiling =
348
+ programmatic.defaultRootPolicyCeiling;
349
+ }
350
+ if (programmatic.globalEventDeny !== undefined) {
351
+ fromProgrammatic.globalEventDeny = programmatic.globalEventDeny;
352
+ }
353
+ if (programmatic.globalQueryDeny !== undefined) {
354
+ fromProgrammatic.globalQueryDeny = programmatic.globalQueryDeny;
355
+ }
356
+
357
+ return mergeSettings(
358
+ defaultEngineSettings(),
359
+ settingsFromEnv(),
360
+ loadConfigFileSettings(),
361
+ fromProgrammatic,
362
+ );
363
+ }
@@ -1,6 +1,6 @@
1
1
  import * as cuid from "cuid";
2
2
  import fetch from "cross-fetch";
3
- import { PicoFramework } from "pico-framework";
3
+ import { Pico, PicoFramework } from "pico-framework";
4
4
  import { IdentityStore } from "./store";
5
5
  import { DidCommRoutes, PeerSubscriptionRecord } from "./types";
6
6
  import { IdentityError } from "./errors";
@@ -41,9 +41,32 @@ import {
41
41
  SKY_INTRO_RESPONSE,
42
42
  SKY_EVENT,
43
43
  SKY_QUERY,
44
+ SKY_ROTATE,
44
45
  parseSkyEventBody,
45
46
  parseSkyQueryBody,
46
47
  } from "./skyProtocol";
48
+ import {
49
+ handleSkyRotateAtIngress,
50
+ notifyPeersOfWebvhRotation,
51
+ } from "./skyRotation";
52
+ import {
53
+ relocateWebvhDid,
54
+ type RelocateWebvhOptions,
55
+ type RelocateWebvhResult,
56
+ } from "./webvhRelocation";
57
+ import { createSubtreePortableHooks } from "./identityPortable";
58
+ import {
59
+ exportPortableSubtree as exportPortableSubtreeImpl,
60
+ finalizePortableImport as finalizePortableImportImpl,
61
+ importPortableSubtree as importPortableSubtreeImpl,
62
+ type PortableMoveImportResult,
63
+ } from "./portableMove";
64
+ import {
65
+ summarizeSubtreeExportBlob,
66
+ type SubtreeImportResult,
67
+ } from "pico-engine-core";
68
+ import type { RulesetRegistry } from "pico-engine-core";
69
+ import type { SubtreePortableHooks } from "pico-engine-core";
47
70
  import {
48
71
  sendSkyIntro,
49
72
  sendSkyIntroResponse,
@@ -72,6 +95,7 @@ export interface DidCommPlainMessage {
72
95
  to?: string[];
73
96
  thid?: string;
74
97
  pthid?: string;
98
+ from_prior?: string;
75
99
  created_time: number;
76
100
  expires_time?: number;
77
101
  }
@@ -80,21 +104,135 @@ export interface IdentityServiceDeps {
80
104
  store: IdentityStore;
81
105
  getBaseUrl: () => string;
82
106
  pf: PicoFramework;
107
+ rsRegistry: RulesetRegistry;
108
+ resolveBundledRulesetUrl?: (url: string) => string;
109
+ reloadImportedSchedules?: (picoIds: string[]) => Promise<void>;
110
+ firePicoImported?: (
111
+ result: import("pico-engine-core").SubtreeImportResult
112
+ ) => Promise<void>;
83
113
  }
84
114
 
85
115
  /**
86
116
  * Engine identity primitive — store-backed DID state and DIDComm capabilities.
87
117
  * Crypto (pack/unpack) is delegated to Veramo when installed (Epic 2+).
88
118
  */
119
+ function isSelfOrDescendant(
120
+ pf: PicoFramework,
121
+ ancestorPicoId: string,
122
+ descendantPicoId: string
123
+ ): boolean {
124
+ if (ancestorPicoId === descendantPicoId) {
125
+ return true;
126
+ }
127
+ let current: Pico | undefined = pf.getPico(descendantPicoId);
128
+ while (current) {
129
+ if (current.id === ancestorPicoId) {
130
+ return true;
131
+ }
132
+ current = current.parent ? pf.getPico(current.parent) : undefined;
133
+ }
134
+ return false;
135
+ }
136
+
89
137
  export class IdentityService {
90
138
  private store: IdentityStore;
91
139
  private getBaseUrl: () => string;
92
140
  private pf: PicoFramework;
141
+ private rsRegistry: RulesetRegistry;
142
+ private resolveBundledRulesetUrl?: (url: string) => string;
143
+ private reloadImportedSchedules?: (picoIds: string[]) => Promise<void>;
144
+ private firePicoImported?: (
145
+ result: import("pico-engine-core").SubtreeImportResult
146
+ ) => Promise<void>;
93
147
 
94
148
  constructor(deps: IdentityServiceDeps) {
95
149
  this.store = deps.store;
96
150
  this.getBaseUrl = deps.getBaseUrl;
97
151
  this.pf = deps.pf;
152
+ this.rsRegistry = deps.rsRegistry;
153
+ this.resolveBundledRulesetUrl = deps.resolveBundledRulesetUrl;
154
+ this.reloadImportedSchedules = deps.reloadImportedSchedules;
155
+ this.firePicoImported = deps.firePicoImported;
156
+ }
157
+
158
+ /** Hooks wired into ctx:exportSubtree / importSubtree for identity snapshots. */
159
+ subtreePortableHooks(): SubtreePortableHooks {
160
+ return createSubtreePortableHooks(this.store, this.pf);
161
+ }
162
+
163
+ private portableMoveDeps() {
164
+ return {
165
+ store: this.store,
166
+ pf: this.pf,
167
+ rsRegistry: this.rsRegistry,
168
+ identity: this,
169
+ getBaseUrl: this.getBaseUrl,
170
+ resolveBundledRulesetUrl: this.resolveBundledRulesetUrl,
171
+ reloadImportedSchedules: this.reloadImportedSchedules,
172
+ firePicoImported: this.firePicoImported,
173
+ };
174
+ }
175
+
176
+ /**
177
+ * Export subtree + per-pico identity. Caller must be the subtree root or an ancestor.
178
+ */
179
+ async exportPortableSubtree(
180
+ fromPicoId: string,
181
+ subtreeRootPicoId: string,
182
+ secret: string,
183
+ options?: { recurse?: boolean; skipRelationshipUpgrade?: boolean }
184
+ ): Promise<string> {
185
+ if (!isSelfOrDescendant(this.pf, fromPicoId, subtreeRootPicoId)) {
186
+ throw new IdentityError(
187
+ `Pico ${fromPicoId} cannot export subtree rooted at ${subtreeRootPicoId}`,
188
+ 403
189
+ );
190
+ }
191
+ return exportPortableSubtreeImpl(
192
+ this.portableMoveDeps(),
193
+ subtreeRootPicoId,
194
+ secret,
195
+ options
196
+ );
197
+ }
198
+
199
+ /** Decrypt a portable subtree export blob and return a debug summary (no pico access). */
200
+ summarizePortableSubtreeExport(blob: string, secret: string) {
201
+ return summarizeSubtreeExportBlob(blob, secret);
202
+ }
203
+
204
+ /** Import portable subtree under parent; relocate webvh and notify peer subscriptions. */
205
+ async importPortableSubtree(
206
+ parentPicoId: string,
207
+ blob: string,
208
+ secret: string,
209
+ relocateOptions?: RelocateWebvhOptions,
210
+ importOptions?: import("pico-engine-core").SubtreeImportOptions
211
+ ): Promise<PortableMoveImportResult> {
212
+ const parent = this.pf.getPico(parentPicoId);
213
+ if (!parent) {
214
+ throw new IdentityError(`Parent pico not found: ${parentPicoId}`, 404);
215
+ }
216
+ return importPortableSubtreeImpl(
217
+ this.portableMoveDeps(),
218
+ parent,
219
+ blob,
220
+ secret,
221
+ relocateOptions,
222
+ importOptions
223
+ );
224
+ }
225
+
226
+ /** Relocate webvh and notify peers after ctx/importIntoExistingChild hydration. */
227
+ async finalizePortableImport(
228
+ importResult: SubtreeImportResult,
229
+ relocateOptions?: RelocateWebvhOptions
230
+ ): Promise<PortableMoveImportResult["relocation"]> {
231
+ return finalizePortableImportImpl(
232
+ this.portableMoveDeps(),
233
+ importResult,
234
+ relocateOptions
235
+ );
98
236
  }
99
237
 
100
238
  async ensureWebvhDid(
@@ -276,6 +414,52 @@ export class IdentityService {
276
414
  return (await this.store.getRoutes(picoId)) || {};
277
415
  }
278
416
 
417
+ /**
418
+ * Append a did:webvh log entry after move (SCID unchanged, host/path/endpoint may change).
419
+ */
420
+ async relocateWebvhAfterMove(
421
+ picoId: string,
422
+ options: RelocateWebvhOptions = {}
423
+ ): Promise<RelocateWebvhResult> {
424
+ return relocateWebvhDid(
425
+ this.store,
426
+ this.pf,
427
+ () => this.getBaseUrl(),
428
+ picoId,
429
+ options
430
+ );
431
+ }
432
+
433
+ /** Notify established peer subscriptions of a did:webvh relocation. */
434
+ async notifyPeersOfWebvhRotation(
435
+ picoId: string,
436
+ relocation: RelocateWebvhResult
437
+ ): Promise<number> {
438
+ return notifyPeersOfWebvhRotation(this.rotationDeps(), picoId, relocation);
439
+ }
440
+
441
+ /** Relocate did:webvh and notify all peer subscriptions (Phase D move). */
442
+ async completePortableMove(
443
+ picoId: string,
444
+ options: RelocateWebvhOptions = {}
445
+ ): Promise<RelocateWebvhResult & { peersNotified: number }> {
446
+ const relocation = await this.relocateWebvhAfterMove(picoId, options);
447
+ const peersNotified = await this.notifyPeersOfWebvhRotation(
448
+ picoId,
449
+ relocation
450
+ );
451
+ return { ...relocation, peersNotified };
452
+ }
453
+
454
+ private rotationDeps() {
455
+ return {
456
+ store: this.store,
457
+ pf: this.pf,
458
+ getBaseUrl: this.getBaseUrl,
459
+ identity: this,
460
+ };
461
+ }
462
+
279
463
  generateMessage(options: DidCommMessageOptions): DidCommPlainMessage {
280
464
  const message: DidCommPlainMessage = {
281
465
  id: cuid(),
@@ -432,6 +616,10 @@ export class IdentityService {
432
616
  );
433
617
  }
434
618
 
619
+ if (message.type === SKY_ROTATE) {
620
+ return handleSkyRotateAtIngress(this.rotationDeps(), picoId, message);
621
+ }
622
+
435
623
  // Channel policy (Epic 7): authenticated sender peer DID → subscription record →
436
624
  // internal Rx channel. Door verify proves crypto + subscription relationship;
437
625
  // pf.eventWait / pf.query enforce assertEventPolicy / assertQueryPolicy on rxEci.