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,193 @@
1
+ /**
2
+ * End-to-end portable move: export subtree + identity, import, relocate, notify peers.
3
+ */
4
+
5
+ import { Pico, PicoFramework } from "pico-framework";
6
+ import {
7
+ exportSubtree,
8
+ importIntoExistingChild,
9
+ subtreeRootBootstrapName,
10
+ type SubtreeImportOptions,
11
+ type SubtreeImportResult,
12
+ } from "pico-engine-core";
13
+ import { createImportChildViaWrangler } from "../subtreeWrangler";
14
+ import { wranglerSubtreeImportServices } from "../subtreeWrangler";
15
+ import type { RulesetRegistry } from "pico-engine-core";
16
+ import { IdentityStore } from "./store";
17
+ import type { IdentityService } from "./IdentityService";
18
+ import type {
19
+ RelocateWebvhOptions,
20
+ RelocateWebvhResult,
21
+ } from "./webvhRelocation";
22
+ import { refreshLocalPeersOfMovedRoot } from "./localPeerReconcile";
23
+ import { prepareSubtreeRelationshipsForPortableExport } from "./portableExportPrepare";
24
+ import { syncLayer2EstablishedFromIdentity } from "./subscriptionEntSync";
25
+
26
+ export interface PortableMoveDeps {
27
+ store: IdentityStore;
28
+ pf: PicoFramework;
29
+ rsRegistry: RulesetRegistry;
30
+ identity: IdentityService;
31
+ getBaseUrl: () => string;
32
+ resolveBundledRulesetUrl?: (url: string) => string;
33
+ reloadImportedSchedules?(picoIds: string[]): Promise<void>;
34
+ firePicoImported?(result: SubtreeImportResult): Promise<void>;
35
+ }
36
+
37
+ export interface PortableMoveExportResult {
38
+ blob: string;
39
+ }
40
+
41
+ export type PortableImportRelocation =
42
+ | (RelocateWebvhResult & { peersNotified: number })
43
+ | { skipped: true; peersNotified: 0 };
44
+
45
+ export interface PortableMoveImportResult extends SubtreeImportResult {
46
+ relocation: PortableImportRelocation;
47
+ }
48
+
49
+ function resolveImportBootstrapName(
50
+ blob: string,
51
+ secret: string,
52
+ displayNameOverride?: string
53
+ ): string {
54
+ const override = displayNameOverride?.trim();
55
+ if (override) {
56
+ return override;
57
+ }
58
+ try {
59
+ const fromBlob = subtreeRootBootstrapName(blob, secret);
60
+ if (fromBlob !== "imported") {
61
+ return fromBlob;
62
+ }
63
+ } catch {
64
+ // invalid blob handled later in importIntoExistingChild
65
+ }
66
+ return "imported";
67
+ }
68
+
69
+ function subtreeServices(deps: PortableMoveDeps) {
70
+ return {
71
+ db: deps.pf.db,
72
+ rsRegistry: deps.rsRegistry,
73
+ portableHooks: deps.identity.subtreePortableHooks(),
74
+ resolveBundledRulesetUrl: deps.resolveBundledRulesetUrl,
75
+ ...wranglerSubtreeImportServices(deps.rsRegistry),
76
+ };
77
+ }
78
+
79
+ /** Export a subtree including identity snapshots for each pico. */
80
+ export async function exportPortableSubtree(
81
+ deps: PortableMoveDeps,
82
+ picoId: string,
83
+ secret: string,
84
+ options?: { recurse?: boolean; skipRelationshipUpgrade?: boolean }
85
+ ): Promise<string> {
86
+ if (options?.skipRelationshipUpgrade !== true) {
87
+ await prepareSubtreeRelationshipsForPortableExport(deps, picoId);
88
+ }
89
+ return exportSubtree(
90
+ subtreeServices(deps),
91
+ deps.pf,
92
+ picoId,
93
+ secret,
94
+ options
95
+ );
96
+ }
97
+
98
+ /** Relocate webvh + ingress for every imported pico; notify peers from the moved root. */
99
+ export async function finalizePortableImport(
100
+ deps: PortableMoveDeps,
101
+ importResult: SubtreeImportResult,
102
+ relocateOptions: RelocateWebvhOptions = { renewIngress: true }
103
+ ): Promise<PortableMoveImportResult["relocation"]> {
104
+ const importedPicoIds = Object.values(importResult.picoIdMap);
105
+ for (const picoId of importedPicoIds) {
106
+ if (picoId === importResult.newRootPicoId) {
107
+ continue;
108
+ }
109
+ if (await deps.store.getWebvhDid(picoId)) {
110
+ await deps.identity.relocateWebvhAfterMove(picoId, relocateOptions);
111
+ }
112
+ }
113
+ const rootDid = await deps.store.getWebvhDid(importResult.newRootPicoId);
114
+ if (!rootDid) {
115
+ return { skipped: true, peersNotified: 0 };
116
+ }
117
+ const relocation = await deps.identity.completePortableMove(
118
+ importResult.newRootPicoId,
119
+ relocateOptions
120
+ );
121
+ await refreshLocalPeersOfMovedRoot(
122
+ deps.pf,
123
+ importResult,
124
+ relocation,
125
+ deps.getBaseUrl()
126
+ );
127
+ return relocation;
128
+ }
129
+
130
+ async function afterPortableHydrate(
131
+ deps: PortableMoveDeps,
132
+ result: SubtreeImportResult
133
+ ): Promise<void> {
134
+ if (deps.reloadImportedSchedules) {
135
+ await deps.reloadImportedSchedules(Object.values(result.picoIdMap));
136
+ }
137
+ for (const picoId of Object.values(result.picoIdMap)) {
138
+ await syncLayer2EstablishedFromIdentity(deps.store, deps.pf, picoId);
139
+ }
140
+ if (deps.firePicoImported) {
141
+ await deps.firePicoImported(result);
142
+ }
143
+ }
144
+
145
+ /** Import a portable subtree under parent and finalize relocation + peer notification. */
146
+ export async function importPortableSubtree(
147
+ deps: PortableMoveDeps,
148
+ parent: Pico,
149
+ blob: string,
150
+ secret: string,
151
+ relocateOptions?: RelocateWebvhOptions,
152
+ importOptions?: SubtreeImportOptions
153
+ ): Promise<PortableMoveImportResult> {
154
+ const services = subtreeServices(deps);
155
+ const createOpts = importOptions?.parentChannelEci
156
+ ? { channelEci: importOptions.parentChannelEci }
157
+ : undefined;
158
+ const bootstrapName = resolveImportBootstrapName(
159
+ blob,
160
+ secret,
161
+ importOptions?.bootstrapDisplayName
162
+ );
163
+ const { familyEci } = await createImportChildViaWrangler(
164
+ deps.pf,
165
+ parent,
166
+ bootstrapName,
167
+ deps.rsRegistry,
168
+ createOpts
169
+ );
170
+ const importResult = await importIntoExistingChild(
171
+ services,
172
+ deps.pf,
173
+ parent,
174
+ familyEci,
175
+ blob,
176
+ secret,
177
+ {
178
+ ...importOptions,
179
+ async afterImport(result, payload) {
180
+ if (importOptions?.afterImport) {
181
+ await importOptions.afterImport(result, payload);
182
+ }
183
+ await afterPortableHydrate(deps, result);
184
+ },
185
+ }
186
+ );
187
+ const relocation = await finalizePortableImport(
188
+ deps,
189
+ importResult,
190
+ relocateOptions
191
+ );
192
+ return { ...importResult, relocation };
193
+ }
@@ -101,6 +101,11 @@ export async function sendSkyIntro(
101
101
  picoId: string,
102
102
  input: SkyIntroSendInput
103
103
  ): Promise<{ messageId: string; peerDid: string }> {
104
+ const senderWebvh = await deps.store.getWebvhDid(picoId);
105
+ if (senderWebvh && input.targetDid === senderWebvh) {
106
+ throw new IdentityError("Cannot form a relationship with self", 400);
107
+ }
108
+
104
109
  const established = await establishSubscriptionIdentity(
105
110
  deps.store,
106
111
  deps.pf,
@@ -126,7 +131,6 @@ export async function sendSkyIntro(
126
131
  subscription_id: input.subscriptionId,
127
132
  };
128
133
 
129
- const senderWebvh = await deps.store.getWebvhDid(picoId);
130
134
  if (senderWebvh) {
131
135
  body.sender_webvh = senderWebvh;
132
136
  try {
@@ -306,16 +310,16 @@ export async function handleSkyIntroResponseAtIngress(
306
310
  Id: subscriptionId,
307
311
  });
308
312
 
309
- await deps.pf.eventWait(
310
- {
311
- eci,
312
- domain: "wrangler",
313
- name: "sky_intro_response",
314
- data: { attrs },
315
- time: 0,
316
- },
317
- undefined
318
- );
313
+ // Queue without waiting: the Tx pico may still be inside the outbound
314
+ // subscription transaction that triggered sendSkyIntro (same-engine local
315
+ // dispatch or cross-engine HTTP). eventWait here deadlocks that queue.
316
+ await deps.pf.event({
317
+ eci,
318
+ domain: "wrangler",
319
+ name: "sky_intro_response",
320
+ data: { attrs },
321
+ time: 0,
322
+ });
319
323
 
320
- return { status: "intro_response_delivered", subscriptionId };
324
+ return { status: "intro_response_queued", subscriptionId };
321
325
  }
@@ -7,6 +7,7 @@ export const SKY_INTRO_RESPONSE = `${SKY_NS}/intro-response`;
7
7
  export const SKY_EVENT = `${SKY_NS}/event`;
8
8
  export const SKY_QUERY = `${SKY_NS}/query`;
9
9
  export const SKY_QUERY_RESPONSE = `${SKY_NS}/query-response`;
10
+ export const SKY_ROTATE = `${SKY_NS}/rotate`;
10
11
 
11
12
  export interface SkyEventBody {
12
13
  sky_version: string;
@@ -45,6 +46,14 @@ export interface SkyIntroBody {
45
46
  subscription_id?: string;
46
47
  }
47
48
 
49
+ export interface SkyRotateBody {
50
+ sky_version: string;
51
+ prior_webvh_did: string;
52
+ new_webvh_did: string;
53
+ new_tx_host?: string;
54
+ new_didcomm_endpoint?: string;
55
+ }
56
+
48
57
  export interface SkyIntroResponseBody {
49
58
  sky_version: string;
50
59
  status: "accepted" | "rejected";
@@ -149,6 +158,43 @@ export function skyIntroResponseToWranglerAttrs(
149
158
  };
150
159
  }
151
160
 
161
+ export function parseSkyRotateBody(body: unknown): SkyRotateBody {
162
+ if (!body || typeof body !== "object") {
163
+ throw new Error("Invalid SKY rotate body");
164
+ }
165
+ const b = body as Record<string, unknown>;
166
+ if (
167
+ typeof b.prior_webvh_did !== "string" ||
168
+ typeof b.new_webvh_did !== "string"
169
+ ) {
170
+ throw new Error("SKY rotate body missing prior_webvh_did or new_webvh_did");
171
+ }
172
+ return {
173
+ sky_version: String(b.sky_version || "1.0"),
174
+ prior_webvh_did: b.prior_webvh_did,
175
+ new_webvh_did: b.new_webvh_did,
176
+ new_tx_host:
177
+ typeof b.new_tx_host === "string" ? b.new_tx_host : undefined,
178
+ new_didcomm_endpoint:
179
+ typeof b.new_didcomm_endpoint === "string"
180
+ ? b.new_didcomm_endpoint
181
+ : undefined,
182
+ };
183
+ }
184
+
185
+ export function skyRotateToWranglerAttrs(
186
+ rotate: SkyRotateBody,
187
+ extras: Record<string, unknown> = {}
188
+ ): Record<string, unknown> {
189
+ return {
190
+ prior_webvh_did: rotate.prior_webvh_did,
191
+ new_webvh_did: rotate.new_webvh_did,
192
+ new_tx_host: rotate.new_tx_host,
193
+ new_didcomm_endpoint: rotate.new_didcomm_endpoint,
194
+ ...extras,
195
+ };
196
+ }
197
+
152
198
  export function parseSkyEventBody(body: unknown): SkyEventBody {
153
199
  if (!body || typeof body !== "object") {
154
200
  throw new Error("Invalid SKY event body");
@@ -0,0 +1,211 @@
1
+ /**
2
+ * DIDComm SKY rotation notices for portable did:webvh move (Phase D).
3
+ */
4
+
5
+ import fetch from "cross-fetch";
6
+ import { Pico, PicoFramework } from "pico-framework";
7
+ import { IdentityStore } from "./store";
8
+ import type { DidCommPlainMessage, IdentityService } from "./IdentityService";
9
+ import { IdentityError } from "./errors";
10
+ import { linkRemotePeer } from "./establishSubscription";
11
+ import { extractDidcommEndpoint } from "./crossPico";
12
+ import {
13
+ SKY_ROTATE,
14
+ parseSkyRotateBody,
15
+ skyRotateToWranglerAttrs,
16
+ type SkyRotateBody,
17
+ } from "./skyProtocol";
18
+ import { packDidCommMessage } from "./veramoDidComm";
19
+ import type { RelocateWebvhResult } from "./webvhRelocation";
20
+ import type { PendingRotation } from "./types";
21
+
22
+ export interface SkyRotationDeps {
23
+ store: IdentityStore;
24
+ pf: PicoFramework;
25
+ getBaseUrl: () => string;
26
+ identity: IdentityService;
27
+ }
28
+
29
+ function findPico(pf: PicoFramework, picoId: string): Pico | undefined {
30
+ return pf.loadedPicos().find((p) => p.id === picoId);
31
+ }
32
+
33
+ async function resolveDidcommEndpointForDid(
34
+ identity: IdentityService,
35
+ did: string,
36
+ remoteDidcommEndpoint?: string
37
+ ): Promise<string> {
38
+ if (remoteDidcommEndpoint) {
39
+ return remoteDidcommEndpoint;
40
+ }
41
+ const doc = await identity.resolveDid("", did);
42
+ return extractDidcommEndpoint(doc);
43
+ }
44
+
45
+ async function postJwe(endpoint: string, jwe: string): Promise<void> {
46
+ const res = await fetch(endpoint, {
47
+ method: "POST",
48
+ headers: { "Content-Type": "application/didcomm-encrypted+json" },
49
+ body: jwe,
50
+ });
51
+ if (!res.ok) {
52
+ const detail = await res.text();
53
+ throw new IdentityError(
54
+ `DIDComm POST failed: HTTP ${res.status} ${detail}`,
55
+ res.status
56
+ );
57
+ }
58
+ }
59
+
60
+ async function deliverRotateNotice(
61
+ deps: SkyRotationDeps,
62
+ fromPicoId: string,
63
+ toPeerDid: string,
64
+ remoteWebvhDid: string | undefined,
65
+ remoteDidcommEndpoint: string | undefined,
66
+ body: SkyRotateBody,
67
+ fromPrior?: string
68
+ ): Promise<void> {
69
+ const fromWebvh = await deps.store.getWebvhDid(fromPicoId);
70
+ const sub = (await deps.store.listPeerSubscriptions(fromPicoId)).find(
71
+ (s) => s.remotePeerDid === toPeerDid || s.remoteDid === toPeerDid
72
+ );
73
+ const fromPeer = sub?.peerDid;
74
+ if (!fromPeer) {
75
+ throw new IdentityError(
76
+ `No local peer DID for subscription to ${toPeerDid}`,
77
+ 404
78
+ );
79
+ }
80
+
81
+ const message: DidCommPlainMessage = {
82
+ id: `rotate-${Date.now()}`,
83
+ typ: "application/didcomm-plain+json",
84
+ type: SKY_ROTATE,
85
+ from: fromPeer,
86
+ to: [toPeerDid],
87
+ body,
88
+ created_time: Math.floor(Date.now() / 1000),
89
+ ...(fromPrior ? { from_prior: fromPrior } : {}),
90
+ };
91
+
92
+ const packed = await packDidCommMessage(
93
+ fromPicoId,
94
+ message,
95
+ fromPeer,
96
+ toPeerDid,
97
+ deps.store,
98
+ { resolveDid: (did) => deps.identity.resolveDid("", did) }
99
+ );
100
+
101
+ const endpoint = await resolveDidcommEndpointForDid(
102
+ deps.identity,
103
+ remoteWebvhDid || toPeerDid,
104
+ remoteDidcommEndpoint
105
+ );
106
+ await postJwe(endpoint, packed);
107
+ }
108
+
109
+ /** Notify established peers that this pico's did:webvh location changed. */
110
+ export async function notifyPeersOfWebvhRotation(
111
+ deps: SkyRotationDeps,
112
+ picoId: string,
113
+ relocation: RelocateWebvhResult
114
+ ): Promise<number> {
115
+ const baseUrl = deps.getBaseUrl().replace(/\/$/, "");
116
+ const body: SkyRotateBody = {
117
+ sky_version: "1.0",
118
+ prior_webvh_did: relocation.priorDid,
119
+ new_webvh_did: relocation.newDid,
120
+ new_tx_host: baseUrl,
121
+ new_didcomm_endpoint: relocation.didcommEndpoint,
122
+ };
123
+
124
+ const subs = await deps.store.listPeerSubscriptions(picoId);
125
+ let sent = 0;
126
+ for (const sub of subs) {
127
+ const remotePeer = sub.remotePeerDid || sub.remoteDid;
128
+ if (!remotePeer) {
129
+ continue;
130
+ }
131
+ try {
132
+ await deliverRotateNotice(
133
+ deps,
134
+ picoId,
135
+ remotePeer,
136
+ sub.remoteWebvhDid,
137
+ sub.remoteDidcommEndpoint,
138
+ body,
139
+ relocation.priorDid !== relocation.newDid ? relocation.priorDid : undefined
140
+ );
141
+ sent += 1;
142
+ } catch (err) {
143
+ const msg = err instanceof Error ? err.message : String(err);
144
+ console.warn(
145
+ `[portable-move] SKY rotate to ${remotePeer} failed (import continues): ${msg}`
146
+ );
147
+ }
148
+ }
149
+ return sent;
150
+ }
151
+
152
+ /** Apply a SKY rotate message on the recipient pico. */
153
+ export async function handleSkyRotateAtIngress(
154
+ deps: SkyRotationDeps,
155
+ recipientPicoId: string,
156
+ message: DidCommPlainMessage
157
+ ): Promise<Record<string, unknown>> {
158
+ const senderDid = message.from;
159
+ if (!senderDid) {
160
+ throw new IdentityError("SKY rotate missing from", 400);
161
+ }
162
+
163
+ const rotate = parseSkyRotateBody(message.body);
164
+ const sub = await deps.store.findPeerSubscriptionBySenderDid(
165
+ recipientPicoId,
166
+ senderDid
167
+ );
168
+ if (!sub) {
169
+ throw new IdentityError("unknown_subscription", 404);
170
+ }
171
+
172
+ await linkRemotePeer(deps.store, recipientPicoId, sub.subscriptionId, {
173
+ remotePeerDid: senderDid,
174
+ remoteWebvhDid: rotate.new_webvh_did,
175
+ remoteTxHost: rotate.new_tx_host,
176
+ remoteDidcommEndpoint: rotate.new_didcomm_endpoint,
177
+ });
178
+
179
+ const pending: PendingRotation[] =
180
+ (await deps.store.getPendingRotations(recipientPicoId)) || [];
181
+ pending.push({
182
+ priorDid: rotate.prior_webvh_did,
183
+ newDid: rotate.new_webvh_did,
184
+ peerDid: senderDid,
185
+ subscriptionId: sub.subscriptionId,
186
+ receivedAt: new Date().toISOString(),
187
+ });
188
+ await deps.store.putPendingRotations(recipientPicoId, pending);
189
+
190
+ const pico = findPico(deps.pf, recipientPicoId);
191
+ if (pico) {
192
+ await pico.event({
193
+ eci: pico.id,
194
+ domain: "wrangler",
195
+ name: "webvh_peer_rotated",
196
+ data: {
197
+ attrs: skyRotateToWranglerAttrs(rotate, {
198
+ Id: sub.subscriptionId,
199
+ peer_did: senderDid,
200
+ }),
201
+ },
202
+ time: Date.now(),
203
+ });
204
+ }
205
+
206
+ return {
207
+ status: "ok",
208
+ subscriptionId: sub.subscriptionId,
209
+ new_webvh_did: rotate.new_webvh_did,
210
+ };
211
+ }
@@ -1,5 +1,6 @@
1
1
  import { PicoDb, PicoDbKey } from "pico-framework";
2
2
  import { dbDel, dbGet, dbList, dbPut } from "./dbHelpers";
3
+ import { peerDid4Matches } from "./peerDid4";
3
4
  import {
4
5
  CachedDidDoc,
5
6
  DidCommRoutes,
@@ -321,11 +322,14 @@ export async function migrateFromDidO(_picoId: string): Promise<void> {
321
322
  return;
322
323
  }
323
324
 
324
- /** Match did:peer short/long forms (numalgo 0/2). */
325
+ /** Match did:peer short/long forms (numalgo 0/2/4). */
325
326
  function peerDidMatches(stored: string, incoming: string): boolean {
326
327
  if (stored === incoming) {
327
328
  return true;
328
329
  }
330
+ if (stored.startsWith("did:peer:4") || incoming.startsWith("did:peer:4")) {
331
+ return peerDid4Matches(stored, incoming);
332
+ }
329
333
  const storedShort = peerDidShortForm(stored);
330
334
  const incomingShort = peerDidShortForm(incoming);
331
335
  return storedShort.length > 0 && storedShort === incomingShort;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Keep wrangler subscription ent buses aligned with engine identity store after import.
3
+ */
4
+
5
+ import { Pico, PicoFramework } from "pico-framework";
6
+ import { IdentityStore } from "./store";
7
+ import type { PeerSubscriptionRecord } from "./types";
8
+
9
+ const SUBSCRIPTION_RID = "io.picolabs.subscription";
10
+
11
+ function busId(bus: Record<string, unknown>): string | undefined {
12
+ const id = bus["Id"];
13
+ return typeof id === "string" ? id : undefined;
14
+ }
15
+
16
+ function mergeIdentityIntoBus(
17
+ bus: Record<string, unknown>,
18
+ rec: PeerSubscriptionRecord
19
+ ): Record<string, unknown> {
20
+ const out: Record<string, unknown> = { ...bus, layer2: true };
21
+ if (rec.rxEci) {
22
+ out["Rx"] = rec.rxEci;
23
+ }
24
+ if (rec.peerDid) {
25
+ out["Rx_did"] = rec.peerDid;
26
+ }
27
+ if (rec.remotePeerDid || rec.remoteDid) {
28
+ out["Tx_did"] =
29
+ out["Tx_did"] || rec.remoteWebvhDid || rec.remotePeerDid || rec.remoteDid;
30
+ }
31
+ if (rec.remoteWebvhDid) {
32
+ out["Tx_did"] = rec.remoteWebvhDid;
33
+ }
34
+ if (rec.remoteTxHost) {
35
+ out["Tx_host"] = rec.remoteTxHost;
36
+ }
37
+ return out;
38
+ }
39
+
40
+ function findBusInPools(
41
+ id: string,
42
+ pools: Record<string, unknown>[]
43
+ ): Record<string, unknown> | undefined {
44
+ return pools.find((b) => busId(b) === id);
45
+ }
46
+
47
+ /** Merge identity peer subscriptions into ent:established (Layer 2 DID relationships). */
48
+ export async function syncLayer2EstablishedFromIdentity(
49
+ store: IdentityStore,
50
+ pf: PicoFramework,
51
+ picoId: string
52
+ ): Promise<void> {
53
+ const pico = pf.getPico(picoId);
54
+ if (!pico?.rulesets[SUBSCRIPTION_RID]) {
55
+ return;
56
+ }
57
+
58
+ const peerSubs = await store.listPeerSubscriptions(picoId);
59
+ if (peerSubs.length === 0) {
60
+ return;
61
+ }
62
+
63
+ const establishedRaw = await pico.getEnt(SUBSCRIPTION_RID, "established");
64
+ let list: Record<string, unknown>[] = Array.isArray(establishedRaw)
65
+ ? establishedRaw.map((b) =>
66
+ b && typeof b === "object" ? { ...(b as Record<string, unknown>) } : {}
67
+ )
68
+ : [];
69
+
70
+ const inbound = await pico.getEnt(SUBSCRIPTION_RID, "inbound");
71
+ const outbound = await pico.getEnt(SUBSCRIPTION_RID, "outbound");
72
+ const pools: Record<string, unknown>[] = [
73
+ ...(Array.isArray(inbound)
74
+ ? inbound.filter((b) => b && typeof b === "object") as Record<string, unknown>[]
75
+ : []),
76
+ ...(Array.isArray(outbound)
77
+ ? outbound.filter((b) => b && typeof b === "object") as Record<string, unknown>[]
78
+ : []),
79
+ ];
80
+
81
+ for (const rec of peerSubs) {
82
+ const id = rec.subscriptionId;
83
+ let idx = list.findIndex((b) => busId(b) === id);
84
+ if (idx >= 0) {
85
+ list[idx] = mergeIdentityIntoBus(list[idx], rec);
86
+ continue;
87
+ }
88
+ const fromPool = findBusInPools(id, pools);
89
+ if (fromPool || rec.remotePeerDid || rec.remoteWebvhDid) {
90
+ list.push(
91
+ mergeIdentityIntoBus(fromPool || { Id: id }, rec)
92
+ );
93
+ }
94
+ }
95
+
96
+ await pico.putEnt(SUBSCRIPTION_RID, "established", list);
97
+ }