@hunsu/protocol-registry 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,157 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form,
34
+ made available under the License, as indicated by a copyright notice that is
35
+ included in or attached to the work.
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work by
47
+ the copyright owner or by an individual or Legal Entity authorized to submit on
48
+ behalf of the copyright owner. For the purposes of this definition, "submitted"
49
+ means any form of electronic, verbal, or written communication sent to the
50
+ Licensor or its representatives, including but not limited to communication on
51
+ electronic mailing lists, source code control systems, and issue tracking systems
52
+ that are managed by, or on behalf of, the Licensor for the purpose of discussing
53
+ and improving the Work, but excluding communication that is conspicuously marked
54
+ or otherwise designated in writing by the copyright owner as "Not a Contribution."
55
+
56
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
57
+ of whom a Contribution has been received by Licensor and subsequently
58
+ incorporated within the Work.
59
+
60
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
61
+ License, each Contributor hereby grants to You a perpetual, worldwide,
62
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
63
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
64
+ sublicense, and distribute the Work and such Derivative Works in Source or
65
+ Object form.
66
+
67
+ 3. Grant of Patent License. Subject to the terms and conditions of this License,
68
+ each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
69
+ no-charge, royalty-free, irrevocable (except as stated in this section) patent
70
+ license to make, have made, use, offer to sell, sell, import, and otherwise
71
+ transfer the Work, where such license applies only to those patent claims
72
+ licensable by such Contributor that are necessarily infringed by their
73
+ Contribution(s) alone or by combination of their Contribution(s) with the Work
74
+ to which such Contribution(s) was submitted. If You institute patent litigation
75
+ against any entity (including a cross-claim or counterclaim in a lawsuit)
76
+ alleging that the Work or a Contribution incorporated within the Work
77
+ constitutes direct or contributory patent infringement, then any patent licenses
78
+ granted to You under this License for that Work shall terminate as of the date
79
+ such litigation is filed.
80
+
81
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
82
+ Derivative Works thereof in any medium, with or without modifications, and in
83
+ Source or Object form, provided that You meet the following conditions:
84
+
85
+ (a) You must give any other recipients of the Work or Derivative Works a copy of
86
+ this License; and
87
+
88
+ (b) You must cause any modified files to carry prominent notices stating that
89
+ You changed the files; and
90
+
91
+ (c) You must retain, in the Source form of any Derivative Works that You
92
+ distribute, all copyright, patent, trademark, and attribution notices from the
93
+ Source form of the Work, excluding those notices that do not pertain to any part
94
+ of the Derivative Works; and
95
+
96
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then
97
+ any Derivative Works that You distribute must include a readable copy of the
98
+ attribution notices contained within such NOTICE file, excluding those notices
99
+ that do not pertain to any part of the Derivative Works, in at least one of the
100
+ following places: within a NOTICE text file distributed as part of the Derivative
101
+ Works; within the Source form or documentation, if provided along with the
102
+ Derivative Works; or, within a display generated by the Derivative Works, if and
103
+ wherever such third-party notices normally appear. The contents of the NOTICE
104
+ file are for informational purposes only and do not modify the License. You may
105
+ add Your own attribution notices within Derivative Works that You distribute,
106
+ alongside or as an addendum to the NOTICE text from the Work, provided that such
107
+ additional attribution notices cannot be construed as modifying the License.
108
+
109
+ You may add Your own copyright statement to Your modifications and may provide
110
+ additional or different license terms and conditions for use, reproduction, or
111
+ distribution of Your modifications, or for any such Derivative Works as a whole,
112
+ provided Your use, reproduction, and distribution of the Work otherwise complies
113
+ with the conditions stated in this License.
114
+
115
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
116
+ Contribution intentionally submitted for inclusion in the Work by You to the
117
+ Licensor shall be under the terms and conditions of this License, without any
118
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
119
+ supersede or modify the terms of any separate license agreement you may have
120
+ executed with Licensor regarding such Contributions.
121
+
122
+ 6. Trademarks. This License does not grant permission to use the trade names,
123
+ trademarks, service marks, or product names of the Licensor, except as required
124
+ for reasonable and customary use in describing the origin of the Work and
125
+ reproducing the content of the NOTICE file.
126
+
127
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
128
+ writing, Licensor provides the Work (and each Contributor provides its
129
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
130
+ KIND, either express or implied, including, without limitation, any warranties or
131
+ conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
132
+ PARTICULAR PURPOSE. You are solely responsible for determining the
133
+ appropriateness of using or redistributing the Work and assume any risks
134
+ associated with Your exercise of permissions under this License.
135
+
136
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
137
+ tort (including negligence), contract, or otherwise, unless required by
138
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
139
+ writing, shall any Contributor be liable to You for damages, including any
140
+ direct, indirect, special, incidental, or consequential damages of any character
141
+ arising as a result of this License or out of the use or inability to use the
142
+ Work (including but not limited to damages for loss of goodwill, work stoppage,
143
+ computer failure or malfunction, or any and all other commercial damages or
144
+ losses), even if such Contributor has been advised of the possibility of such
145
+ damages.
146
+
147
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
148
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
149
+ acceptance of support, warranty, indemnity, or other liability obligations
150
+ and/or rights consistent with this License. However, in accepting such
151
+ obligations, You may act only on Your own behalf and on Your sole
152
+ responsibility, not on behalf of any other Contributor, and only if You agree to
153
+ indemnify, defend, and hold each Contributor harmless for any liability incurred
154
+ by, or claims asserted against, such Contributor by reason of your accepting any
155
+ such warranty or additional liability.
156
+
157
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,88 @@
1
+ import { type Harness, type HubPackageKind, type HubPackageLock, type HunsuOrigin, type ManagerConfig, type NonEmptyText, type MemberConfig, type SkillSnapshotFile } from "@hunsu/protocol";
2
+ export type { HubPackageKind, HubPackageLock, HunsuOrigin } from "@hunsu/protocol";
3
+ export declare const HUB_PACKAGE_MANIFEST_SCHEMA: "hunsu.hub-package-manifest.v1";
4
+ export declare const MANIFEST_INTEGRITY_PREFIX_V1: "hunsu-json-c14n-v1+sha256:";
5
+ export type TeamPackageManifest = {
6
+ schema: typeof HUB_PACKAGE_MANIFEST_SCHEMA;
7
+ kind: "team";
8
+ key: string;
9
+ version: string;
10
+ team: Harness;
11
+ integrity?: string;
12
+ };
13
+ export type MemberPackageManifest = {
14
+ schema: typeof HUB_PACKAGE_MANIFEST_SCHEMA;
15
+ kind: "member";
16
+ key: string;
17
+ version: string;
18
+ member: MemberConfig;
19
+ integrity?: string;
20
+ };
21
+ export type ManagerPackageManifest = {
22
+ schema: typeof HUB_PACKAGE_MANIFEST_SCHEMA;
23
+ kind: "manager";
24
+ key: string;
25
+ version: string;
26
+ manager: ManagerConfig;
27
+ integrity?: string;
28
+ };
29
+ export type SkillPackageManifest = {
30
+ schema: typeof HUB_PACKAGE_MANIFEST_SCHEMA;
31
+ kind: "skill";
32
+ key: string;
33
+ version: string;
34
+ skill: {
35
+ name: string;
36
+ contentHash: string;
37
+ files?: SkillSnapshotFile[];
38
+ };
39
+ integrity?: string;
40
+ };
41
+ export type HubPackageManifest = TeamPackageManifest | MemberPackageManifest | ManagerPackageManifest | SkillPackageManifest;
42
+ export type HubPackageSummary = {
43
+ origin: string;
44
+ entryKind: "package" | "executor";
45
+ kind: HubPackageKind;
46
+ key: string;
47
+ version: string;
48
+ integrity: string;
49
+ label: string;
50
+ sourcePackageKind: HubPackageKind;
51
+ sourcePackageKey: string;
52
+ sourcePackageVersion: string;
53
+ executorId?: string;
54
+ memberOf?: string[];
55
+ promptTemplateEngine?: string;
56
+ memberCount?: number;
57
+ skillCount?: number;
58
+ pluginRequirementCount?: number;
59
+ };
60
+ export type HubPackageRef = {
61
+ origin: NonEmptyText;
62
+ kind: HubPackageKind;
63
+ key: NonEmptyText;
64
+ version: NonEmptyText;
65
+ };
66
+ export type HttpHubPackageResolverOptions = {
67
+ origins: HunsuOrigin[];
68
+ fetch?: typeof fetch;
69
+ };
70
+ export type ResolvedHubPackageManifest = {
71
+ lock: HubPackageLock;
72
+ manifest: HubPackageManifest;
73
+ integrity: string;
74
+ origin: HunsuOrigin;
75
+ };
76
+ export declare function hubSeedPackageManifests(): HubPackageManifest[];
77
+ export declare function canonicalizeManifest(manifest: HubPackageManifest | unknown): string;
78
+ export declare function computeManifestIntegrity(manifest: HubPackageManifest | unknown): string;
79
+ export declare function verifyManifestIntegrity(manifest: HubPackageManifest | unknown, integrity: string): boolean;
80
+ export declare function resolveHubPackageManifestFromOrigin(lock: HubPackageLock, options: HttpHubPackageResolverOptions): Promise<ResolvedHubPackageManifest>;
81
+ export declare function hubPackageManifestUrl(originUrl: string, kind: HubPackageKind, key: string, version: string): string;
82
+ export declare function hubPackageEntityRef(origin: string, key: string): string;
83
+ export declare function hubPackageVersionRef(origin: string, key: string, version: string): string;
84
+ export declare function hubPackageHumanUrl(originUrl: string, lock: HubPackageLock): string;
85
+ export declare function parseHubPackageRefFromUrl(rawUrl: string): HubPackageRef;
86
+ export declare function summarizeHubPackageManifest(manifest: HubPackageManifest, origin: string): HubPackageSummary;
87
+ export declare function hydrateTeamPackage(manifest: HubPackageManifest): Harness;
88
+ export declare function assertValidHubPackageManifest(manifest: unknown): asserts manifest is HubPackageManifest;
package/dist/index.js ADDED
@@ -0,0 +1,478 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createDefaultHarness, createDefaultManagerConfig, createDefaultMemberConfig, harnessEntityFromSnapshot, makeNonEmptyText, validateHarnessEntity, validateManagerConfig, validateMemberConfig } from "@hunsu/protocol";
3
+ export const HUB_PACKAGE_MANIFEST_SCHEMA = "hunsu.hub-package-manifest.v1";
4
+ export const MANIFEST_INTEGRITY_PREFIX_V1 = "hunsu-json-c14n-v1+sha256:";
5
+ export function hubSeedPackageManifests() {
6
+ return [
7
+ superloopyCrewManifest(),
8
+ skillsCurationManifest(),
9
+ defaultHunsuManagerManifest(),
10
+ ideaHelperManagerManifest(),
11
+ researcherManagerManifest(),
12
+ researcherSkillManifest()
13
+ ];
14
+ }
15
+ function superloopyCrewManifest() {
16
+ const harness = createDefaultHarness("Plan a convergent crew run using only direct Members visible to this Team.");
17
+ harness.members = [
18
+ createDefaultMemberConfig("build", "Implement the selected task with focused changes."),
19
+ createDefaultMemberConfig("review", "Review the implementation for regressions and missed requirements."),
20
+ createDefaultMemberConfig("test", "Run targeted checks and summarize evidence."),
21
+ createDefaultMemberConfig("gate", "Decide whether the result is ready to finalize."),
22
+ createDefaultMemberConfig("audit", "Audit risks, hidden assumptions, and release notes."),
23
+ createDefaultMemberConfig("navigation", "Keep the crew oriented around the selected Destination.")
24
+ ];
25
+ return {
26
+ schema: HUB_PACKAGE_MANIFEST_SCHEMA,
27
+ kind: "team",
28
+ key: "team.superloopy.crew",
29
+ version: "1.0.2",
30
+ team: harnessEntityFromSnapshot(harness)
31
+ };
32
+ }
33
+ function skillsCurationManifest() {
34
+ const harness = createDefaultHarness("Curate reusable Codex skills and validate installation metadata before publication.");
35
+ const skillsCatalog = {
36
+ kind: "skillMeta",
37
+ name: requireMetadataText("skills-catalog", "team.skills-curation.discover.skills[0].name"),
38
+ source: requireMetadataText("github:vercel-labs/skills", "team.skills-curation.discover.skills[0].source"),
39
+ agent: "codex"
40
+ };
41
+ harness.members = [
42
+ createDefaultMemberConfig("discover", "Find candidate skills and summarize their purpose.", [skillsCatalog]),
43
+ createDefaultMemberConfig("curate", "Normalize skill metadata and prepare installable entries."),
44
+ createDefaultMemberConfig("verify", "Check skill instructions and installation evidence.")
45
+ ];
46
+ return {
47
+ schema: HUB_PACKAGE_MANIFEST_SCHEMA,
48
+ kind: "team",
49
+ key: "team.skills-curation",
50
+ version: "1.0.2",
51
+ team: harnessEntityFromSnapshot(harness)
52
+ };
53
+ }
54
+ function defaultHunsuManagerManifest() {
55
+ return {
56
+ schema: HUB_PACKAGE_MANIFEST_SCHEMA,
57
+ kind: "manager",
58
+ key: "manager.hunsu.default",
59
+ version: "1.0.0",
60
+ manager: createDefaultManagerConfig()
61
+ };
62
+ }
63
+ function ideaHelperManagerManifest() {
64
+ return {
65
+ schema: HUB_PACKAGE_MANIFEST_SCHEMA,
66
+ kind: "manager",
67
+ key: "manager.idea-helper",
68
+ version: "1.0.0",
69
+ manager: createDefaultManagerConfig("manager.idea-helper", [
70
+ "Help the user explore divergent Hunsu options before committing to an editable draft.",
71
+ "Generate alternatives, tradeoffs, naming choices, and likely downstream implications.",
72
+ "Only edit .hunsu-request files when the user chooses a concrete option."
73
+ ].join(" "))
74
+ };
75
+ }
76
+ function researcherManagerManifest() {
77
+ return {
78
+ schema: HUB_PACKAGE_MANIFEST_SCHEMA,
79
+ kind: "manager",
80
+ key: "manager.researcher",
81
+ version: "1.0.0",
82
+ manager: createDefaultManagerConfig("manager.researcher", [
83
+ "Gather and synthesize context for a proposed Hunsu change before editing draft runtime files.",
84
+ "Prioritize evidence, source boundaries, and unresolved assumptions.",
85
+ "When a file-backed change is requested, edit only the relevant .hunsu-request files."
86
+ ].join(" "), [{
87
+ kind: "skillMeta",
88
+ name: requireMetadataText("researcher", "manager.researcher.skills[0].name"),
89
+ source: requireMetadataText("github:vercel-labs/skills", "manager.researcher.skills[0].source"),
90
+ agent: "codex"
91
+ }])
92
+ };
93
+ }
94
+ function researcherSkillManifest() {
95
+ return {
96
+ schema: HUB_PACKAGE_MANIFEST_SCHEMA,
97
+ kind: "skill",
98
+ key: "skill.researcher",
99
+ version: "1.0.0",
100
+ skill: {
101
+ name: "researcher",
102
+ contentHash: "sha256:vercel-labs-skills-researcher-seed",
103
+ files: [{
104
+ path: requireMetadataText("SKILL.md", "skill.researcher.files[0].path"),
105
+ text: [
106
+ "---",
107
+ "name: researcher",
108
+ "description: Gather evidence, source boundaries, and unresolved assumptions before Hunsu Draft changes.",
109
+ "---",
110
+ "",
111
+ "# Researcher",
112
+ "",
113
+ "Use this seed skill as an installable Hub example based on github:vercel-labs/skills for context gathering and synthesis."
114
+ ].join("\n")
115
+ }]
116
+ }
117
+ };
118
+ }
119
+ export function canonicalizeManifest(manifest) {
120
+ assertValidHubPackageManifest(manifest);
121
+ const { integrity: _integrity, ...manifestWithoutIntegrity } = manifest;
122
+ return JSON.stringify(toCanonicalJsonValue(manifestWithoutIntegrity, "manifest"));
123
+ }
124
+ export function computeManifestIntegrity(manifest) {
125
+ const canonical = canonicalizeManifest(manifest);
126
+ return `${MANIFEST_INTEGRITY_PREFIX_V1}${createHash("sha256").update(canonical, "utf8").digest("hex")}`;
127
+ }
128
+ export function verifyManifestIntegrity(manifest, integrity) {
129
+ if (!integrity.startsWith(MANIFEST_INTEGRITY_PREFIX_V1)) {
130
+ return false;
131
+ }
132
+ try {
133
+ return computeManifestIntegrity(manifest) === integrity;
134
+ }
135
+ catch {
136
+ return false;
137
+ }
138
+ }
139
+ export async function resolveHubPackageManifestFromOrigin(lock, options) {
140
+ if (!lock.integrity.startsWith(MANIFEST_INTEGRITY_PREFIX_V1)) {
141
+ throw new Error(`Unsupported Hub package integrity prefix: ${lock.integrity}`);
142
+ }
143
+ const origin = options.origins.find(candidate => candidate.name === lock.origin);
144
+ if (!origin) {
145
+ throw new Error(`Unknown Origin: ${lock.origin}`);
146
+ }
147
+ if (origin.transport !== "http") {
148
+ throw new Error(`Origin ${origin.name} uses unsupported transport ${origin.transport}`);
149
+ }
150
+ const fetchImpl = options.fetch ?? fetch;
151
+ const response = await fetchImpl(hubPackageManifestUrl(origin.url, lock.kind, lock.key, lock.version));
152
+ if (!response.ok) {
153
+ if (response.status === 404) {
154
+ throw new Error(`Missing Hub package manifest: ${lock.origin}/${lock.kind}/${lock.key}@${lock.version}`);
155
+ }
156
+ throw new Error(`Origin ${origin.name} returned ${response.status} for ${lock.kind}/${lock.key}@${lock.version}`);
157
+ }
158
+ const parsed = await response.json();
159
+ assertValidHubPackageManifest(parsed);
160
+ if (parsed.kind !== lock.kind || parsed.key !== lock.key || parsed.version !== lock.version) {
161
+ throw new Error(`Hub package manifest from ${origin.name} does not match requested ${lock.kind}/${lock.key}@${lock.version}`);
162
+ }
163
+ const integrity = computeManifestIntegrity(parsed);
164
+ if (integrity !== lock.integrity) {
165
+ throw new Error(`Hub package integrity mismatch for ${lock.origin}/${lock.kind}/${lock.key}@${lock.version}: expected ${lock.integrity}, got ${integrity}`);
166
+ }
167
+ return { lock: { ...lock }, manifest: parsed, integrity, origin: { ...origin } };
168
+ }
169
+ export function hubPackageManifestUrl(originUrl, kind, key, version) {
170
+ const base = new URL(originUrl);
171
+ const path = `/v1/packages/${kind}/${encodeURIComponent(key)}/versions/${encodeURIComponent(version)}`;
172
+ return new URL(path, base).toString();
173
+ }
174
+ export function hubPackageEntityRef(origin, key) {
175
+ return `@${origin}/${key}`;
176
+ }
177
+ export function hubPackageVersionRef(origin, key, version) {
178
+ return `${hubPackageEntityRef(origin, key)}@${version}`;
179
+ }
180
+ export function hubPackageHumanUrl(originUrl, lock) {
181
+ const base = new URL(originUrl);
182
+ const path = `/hub/${marketplaceIdForPackageKind(lock.kind)}/${lock.kind}/@${encodeURIComponent(lock.origin)}/${encodeURIComponent(lock.key)}/versions/${encodeURIComponent(lock.version)}`;
183
+ return new URL(path, base).toString();
184
+ }
185
+ export function parseHubPackageRefFromUrl(rawUrl) {
186
+ const url = new URL(rawUrl, "https://hub.local");
187
+ const match = url.pathname.match(/^\/hub\/(executor|hunsu|resources)\/(team|member|manager|skill)\/@([^/]+)\/([^/]+)\/versions\/([^/]+)$/);
188
+ if (!match) {
189
+ throw new Error("Hub package URL must use /hub/:marketplace/:kind/@:origin/:key/versions/:version");
190
+ }
191
+ const marketplaceId = match[1];
192
+ const kind = match[2];
193
+ if (marketplaceId !== marketplaceIdForPackageKind(kind)) {
194
+ throw new Error(`Hub package URL marketplace ${marketplaceId} does not match ${kind}`);
195
+ }
196
+ return {
197
+ origin: requireMetadataText(decodeURIComponent(match[3] ?? ""), "ref.origin"),
198
+ kind,
199
+ key: requireMetadataText(decodeURIComponent(match[4] ?? ""), "ref.key"),
200
+ version: requireMetadataText(decodeURIComponent(match[5] ?? ""), "ref.version")
201
+ };
202
+ }
203
+ function marketplaceIdForPackageKind(kind) {
204
+ if (kind === "manager")
205
+ return "hunsu";
206
+ if (kind === "skill")
207
+ return "resources";
208
+ return "executor";
209
+ }
210
+ function requireMetadataText(value, field) {
211
+ const result = makeNonEmptyText(value, field);
212
+ if (!result.ok) {
213
+ throw new Error(result.error.message);
214
+ }
215
+ return result.value;
216
+ }
217
+ export function summarizeHubPackageManifest(manifest, origin) {
218
+ assertValidHubPackageManifest(manifest);
219
+ const integrity = manifest.integrity ?? computeManifestIntegrity(manifest);
220
+ switch (manifest.kind) {
221
+ case "team": {
222
+ const rootTeam = rootTeamForPackage(manifest.team);
223
+ const resourceCounts = resourceCountsForHarness(manifest.team);
224
+ return {
225
+ origin,
226
+ entryKind: "package",
227
+ kind: manifest.kind,
228
+ key: manifest.key,
229
+ version: manifest.version,
230
+ integrity,
231
+ label: manifest.key,
232
+ sourcePackageKind: manifest.kind,
233
+ sourcePackageKey: manifest.key,
234
+ sourcePackageVersion: manifest.version,
235
+ promptTemplateEngine: rootTeam.planner.promptTemplate.engine,
236
+ memberCount: rootTeam.members.length,
237
+ skillCount: resourceCounts.skill,
238
+ pluginRequirementCount: resourceCounts.plugin
239
+ };
240
+ }
241
+ case "member":
242
+ return {
243
+ origin,
244
+ entryKind: "package",
245
+ kind: manifest.kind,
246
+ key: manifest.key,
247
+ version: manifest.version,
248
+ integrity,
249
+ label: manifest.member.id,
250
+ sourcePackageKind: manifest.kind,
251
+ sourcePackageKey: manifest.key,
252
+ sourcePackageVersion: manifest.version,
253
+ executorId: manifest.member.id,
254
+ promptTemplateEngine: manifest.member.promptTemplate.engine,
255
+ skillCount: manifest.member.skills.length,
256
+ pluginRequirementCount: manifest.member.plugins.length
257
+ };
258
+ case "manager":
259
+ return {
260
+ origin,
261
+ entryKind: "package",
262
+ kind: manifest.kind,
263
+ key: manifest.key,
264
+ version: manifest.version,
265
+ integrity,
266
+ label: manifest.manager.id,
267
+ sourcePackageKind: manifest.kind,
268
+ sourcePackageKey: manifest.key,
269
+ sourcePackageVersion: manifest.version,
270
+ promptTemplateEngine: manifest.manager.promptTemplate.engine,
271
+ skillCount: manifest.manager.skills.length,
272
+ pluginRequirementCount: manifest.manager.plugins.length
273
+ };
274
+ case "skill":
275
+ return {
276
+ origin,
277
+ entryKind: "package",
278
+ kind: manifest.kind,
279
+ key: manifest.key,
280
+ version: manifest.version,
281
+ integrity,
282
+ label: manifest.skill.name,
283
+ sourcePackageKind: manifest.kind,
284
+ sourcePackageKey: manifest.key,
285
+ sourcePackageVersion: manifest.version
286
+ };
287
+ }
288
+ }
289
+ export function hydrateTeamPackage(manifest) {
290
+ assertValidHubPackageManifest(manifest);
291
+ if (manifest.kind !== "team") {
292
+ throw new Error(`Hub package ${manifest.kind}/${manifest.key}@${manifest.version} is not a team package`);
293
+ }
294
+ return cloneJson(manifest.team);
295
+ }
296
+ export function assertValidHubPackageManifest(manifest) {
297
+ const record = requireRecord(manifest, "manifest");
298
+ if (record.schema !== HUB_PACKAGE_MANIFEST_SCHEMA) {
299
+ throw new Error(`Unsupported Hub package manifest schema: ${String(record.schema)}`);
300
+ }
301
+ requireExactKeys(record, ["integrity", "key", "kind", "team", "member", "manager", "schema", "skill", "version"], "manifest");
302
+ const kind = requireHubPackageKind(record.kind, "manifest.kind");
303
+ requireNonEmptyString(record.key, "manifest.key");
304
+ requireNonEmptyString(record.version, "manifest.version");
305
+ if (record.integrity !== undefined) {
306
+ requireNonEmptyString(record.integrity, "manifest.integrity");
307
+ }
308
+ switch (kind) {
309
+ case "team":
310
+ assertValidTeamPayload(record.team);
311
+ if (record.member !== undefined || record.manager !== undefined || record.skill !== undefined) {
312
+ throw new Error("Team package manifest must not include member, manager, or skill payloads");
313
+ }
314
+ return;
315
+ case "member":
316
+ assertValidMemberPayload(record.member);
317
+ if (record.team !== undefined || record.manager !== undefined || record.skill !== undefined) {
318
+ throw new Error("Member package manifest must not include team, manager, or skill payloads");
319
+ }
320
+ return;
321
+ case "manager":
322
+ assertValidManagerPayload(record.manager);
323
+ if (record.team !== undefined || record.member !== undefined || record.skill !== undefined) {
324
+ throw new Error("Manager package manifest must not include team, member, or skill payloads");
325
+ }
326
+ return;
327
+ case "skill":
328
+ assertValidSkillPayload(record.skill);
329
+ if (record.team !== undefined || record.member !== undefined || record.manager !== undefined) {
330
+ throw new Error("Skill package manifest must not include team, member, or manager payloads");
331
+ }
332
+ return;
333
+ }
334
+ }
335
+ function assertValidTeamPayload(value) {
336
+ const graph = validateHarnessEntity(value, "manifest.team");
337
+ if (!graph.ok) {
338
+ throw new Error(`Invalid manifest.team: ${graph.error.message}`);
339
+ }
340
+ }
341
+ function assertValidMemberPayload(value) {
342
+ const member = validateMemberConfig(value, "manifest.member");
343
+ if (!member.ok) {
344
+ throw new Error(`Invalid manifest.member: ${member.error.message}`);
345
+ }
346
+ }
347
+ function assertValidManagerPayload(value) {
348
+ const manager = validateManagerConfig(value, "manifest.manager");
349
+ if (!manager.ok) {
350
+ throw new Error(`Invalid manifest.manager: ${manager.error.message}`);
351
+ }
352
+ }
353
+ function assertValidSkillPayload(value) {
354
+ const record = requireRecord(value, "manifest.skill");
355
+ requireExactKeys(record, ["contentHash", "files", "name"], "manifest.skill");
356
+ requireNonEmptyString(record.name, "manifest.skill.name");
357
+ requireNonEmptyString(record.contentHash, "manifest.skill.contentHash");
358
+ if (record.files !== undefined) {
359
+ if (!Array.isArray(record.files)) {
360
+ throw new Error("manifest.skill.files must be an array");
361
+ }
362
+ for (const [index, file] of record.files.entries()) {
363
+ const item = requireRecord(file, `manifest.skill.files[${index}]`);
364
+ requireExactKeys(item, ["path", "text"], `manifest.skill.files[${index}]`);
365
+ requireNonEmptyString(item.path, `manifest.skill.files[${index}].path`);
366
+ requireString(item.text, `manifest.skill.files[${index}].text`);
367
+ }
368
+ }
369
+ }
370
+ function rootTeamForPackage(team) {
371
+ const rootTeam = team.executors.find((executor) => executor.kind === "team" && executor.id === team.rootTeamId);
372
+ if (!rootTeam) {
373
+ throw new Error(`Team package rootTeamId ${team.rootTeamId} does not reference a Team Executor`);
374
+ }
375
+ return rootTeam;
376
+ }
377
+ function resourceCountsForHarness(harness) {
378
+ const identities = new Set();
379
+ for (const resource of harness.resources) {
380
+ identities.add(resourceIdentity(resource.binding));
381
+ }
382
+ for (const executor of harness.executors) {
383
+ if (executor.kind !== "member") {
384
+ continue;
385
+ }
386
+ for (const binding of executor.resources) {
387
+ identities.add(resourceIdentity(binding));
388
+ }
389
+ }
390
+ let skill = 0;
391
+ let plugin = 0;
392
+ for (const identity of identities) {
393
+ if (identity.startsWith("skill:"))
394
+ skill += 1;
395
+ if (identity.startsWith("plugin:"))
396
+ plugin += 1;
397
+ }
398
+ return { skill, plugin };
399
+ }
400
+ function resourceIdentity(binding) {
401
+ if (binding.kind === "skill") {
402
+ return `skill:${binding.skill.name}`;
403
+ }
404
+ if (binding.kind === "plugin") {
405
+ return `plugin:${binding.plugin.id}`;
406
+ }
407
+ return `package:${binding.lock.kind}:${binding.lock.key}:${binding.lock.version}`;
408
+ }
409
+ function requireHubPackageKind(value, path) {
410
+ if (value === "team" || value === "member" || value === "manager" || value === "skill") {
411
+ return value;
412
+ }
413
+ throw new Error(`${path} must be team, member, manager, or skill`);
414
+ }
415
+ function requireRecord(value, path) {
416
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
417
+ throw new Error(`${path} must be an object`);
418
+ }
419
+ return value;
420
+ }
421
+ function requireExactKeys(record, allowedKeys, path) {
422
+ const missing = allowedKeys.filter(key => key !== "integrity" && key !== "team" && key !== "member" && key !== "manager" && key !== "skill" && key !== "files" && !(key in record));
423
+ if (missing.length > 0) {
424
+ throw new Error(`${path} is missing required keys: ${missing.join(", ")}`);
425
+ }
426
+ const extra = Object.keys(record).filter(key => !allowedKeys.includes(key));
427
+ if (extra.length > 0) {
428
+ throw new Error(`${path} has unsupported keys: ${extra.join(", ")}`);
429
+ }
430
+ }
431
+ function requireString(value, path) {
432
+ if (typeof value !== "string") {
433
+ throw new Error(`${path} must be a string`);
434
+ }
435
+ return value;
436
+ }
437
+ function requireNonEmptyString(value, path) {
438
+ const text = requireString(value, path);
439
+ if (text.trim().length === 0) {
440
+ throw new Error(`${path} must be non-empty`);
441
+ }
442
+ return text;
443
+ }
444
+ function toCanonicalJsonValue(value, path) {
445
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
446
+ return value;
447
+ }
448
+ if (typeof value === "number") {
449
+ if (!Number.isFinite(value)) {
450
+ throw new Error(`${path} must be a finite number`);
451
+ }
452
+ return value;
453
+ }
454
+ if (Array.isArray(value)) {
455
+ return value.map((item, index) => {
456
+ if (item === undefined) {
457
+ throw new Error(`${path}[${index}] must not be undefined`);
458
+ }
459
+ return toCanonicalJsonValue(item, `${path}[${index}]`);
460
+ });
461
+ }
462
+ if (typeof value === "object" && value !== null) {
463
+ const record = value;
464
+ const canonical = {};
465
+ for (const key of Object.keys(record).sort()) {
466
+ const child = record[key];
467
+ if (child === undefined) {
468
+ continue;
469
+ }
470
+ canonical[key] = toCanonicalJsonValue(child, `${path}.${key}`);
471
+ }
472
+ return canonical;
473
+ }
474
+ throw new Error(`${path} must be JSON-serializable`);
475
+ }
476
+ function cloneJson(value) {
477
+ return JSON.parse(JSON.stringify(value));
478
+ }
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@hunsu/protocol-registry",
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "description": "Hunsu Hub package manifests, integrity, and Origin resolution.",
6
+ "license": "Apache-2.0",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": {
10
+ "development": "./src/index.ts",
11
+ "types": "./src/index.ts",
12
+ "import": "./dist/index.js",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "src"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "engines": {
24
+ "node": ">=22.18"
25
+ },
26
+ "dependencies": {
27
+ "@hunsu/protocol": "0.1.0"
28
+ },
29
+ "scripts": {
30
+ "build": "tsc -p tsconfig.build.json",
31
+ "typecheck": "tsc -p tsconfig.json --noEmit"
32
+ }
33
+ }
package/src/index.ts ADDED
@@ -0,0 +1,618 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ createDefaultHarness,
4
+ createDefaultManagerConfig,
5
+ createDefaultMemberConfig,
6
+ harnessEntityFromSnapshot,
7
+ makeNonEmptyText,
8
+ validateHarnessEntity,
9
+ validateManagerConfig,
10
+ validateMemberConfig,
11
+ type Harness,
12
+ type HubPackageKind,
13
+ type HubPackageLock,
14
+ type HunsuOrigin,
15
+ type ManagerConfig,
16
+ type NonEmptyText,
17
+ type MemberConfig,
18
+ type SkillSnapshotFile
19
+ } from "@hunsu/protocol";
20
+
21
+ export type { HubPackageKind, HubPackageLock, HunsuOrigin } from "@hunsu/protocol";
22
+
23
+ export const HUB_PACKAGE_MANIFEST_SCHEMA = "hunsu.hub-package-manifest.v1" as const;
24
+ export const MANIFEST_INTEGRITY_PREFIX_V1 = "hunsu-json-c14n-v1+sha256:" as const;
25
+
26
+ export type TeamPackageManifest = {
27
+ schema: typeof HUB_PACKAGE_MANIFEST_SCHEMA;
28
+ kind: "team";
29
+ key: string;
30
+ version: string;
31
+ team: Harness;
32
+ integrity?: string;
33
+ };
34
+
35
+ export type MemberPackageManifest = {
36
+ schema: typeof HUB_PACKAGE_MANIFEST_SCHEMA;
37
+ kind: "member";
38
+ key: string;
39
+ version: string;
40
+ member: MemberConfig;
41
+ integrity?: string;
42
+ };
43
+
44
+ export type ManagerPackageManifest = {
45
+ schema: typeof HUB_PACKAGE_MANIFEST_SCHEMA;
46
+ kind: "manager";
47
+ key: string;
48
+ version: string;
49
+ manager: ManagerConfig;
50
+ integrity?: string;
51
+ };
52
+
53
+ export type SkillPackageManifest = {
54
+ schema: typeof HUB_PACKAGE_MANIFEST_SCHEMA;
55
+ kind: "skill";
56
+ key: string;
57
+ version: string;
58
+ skill: {
59
+ name: string;
60
+ contentHash: string;
61
+ files?: SkillSnapshotFile[];
62
+ };
63
+ integrity?: string;
64
+ };
65
+
66
+ export type HubPackageManifest = TeamPackageManifest | MemberPackageManifest | ManagerPackageManifest | SkillPackageManifest;
67
+
68
+ export type HubPackageSummary = {
69
+ origin: string;
70
+ entryKind: "package" | "executor";
71
+ kind: HubPackageKind;
72
+ key: string;
73
+ version: string;
74
+ integrity: string;
75
+ label: string;
76
+ sourcePackageKind: HubPackageKind;
77
+ sourcePackageKey: string;
78
+ sourcePackageVersion: string;
79
+ executorId?: string;
80
+ memberOf?: string[];
81
+ promptTemplateEngine?: string;
82
+ memberCount?: number;
83
+ skillCount?: number;
84
+ pluginRequirementCount?: number;
85
+ };
86
+
87
+ export type HubPackageRef = {
88
+ origin: NonEmptyText;
89
+ kind: HubPackageKind;
90
+ key: NonEmptyText;
91
+ version: NonEmptyText;
92
+ };
93
+
94
+ export type HttpHubPackageResolverOptions = {
95
+ origins: HunsuOrigin[];
96
+ fetch?: typeof fetch;
97
+ };
98
+
99
+ export type ResolvedHubPackageManifest = {
100
+ lock: HubPackageLock;
101
+ manifest: HubPackageManifest;
102
+ integrity: string;
103
+ origin: HunsuOrigin;
104
+ };
105
+
106
+ export function hubSeedPackageManifests(): HubPackageManifest[] {
107
+ return [
108
+ superloopyCrewManifest(),
109
+ skillsCurationManifest(),
110
+ defaultHunsuManagerManifest(),
111
+ ideaHelperManagerManifest(),
112
+ researcherManagerManifest(),
113
+ researcherSkillManifest()
114
+ ];
115
+ }
116
+
117
+ function superloopyCrewManifest(): TeamPackageManifest {
118
+ const harness = createDefaultHarness("Plan a convergent crew run using only direct Members visible to this Team.");
119
+ harness.members = [
120
+ createDefaultMemberConfig("build", "Implement the selected task with focused changes."),
121
+ createDefaultMemberConfig("review", "Review the implementation for regressions and missed requirements."),
122
+ createDefaultMemberConfig("test", "Run targeted checks and summarize evidence."),
123
+ createDefaultMemberConfig("gate", "Decide whether the result is ready to finalize."),
124
+ createDefaultMemberConfig("audit", "Audit risks, hidden assumptions, and release notes."),
125
+ createDefaultMemberConfig("navigation", "Keep the crew oriented around the selected Destination.")
126
+ ];
127
+ return {
128
+ schema: HUB_PACKAGE_MANIFEST_SCHEMA,
129
+ kind: "team",
130
+ key: "team.superloopy.crew",
131
+ version: "1.0.2",
132
+ team: harnessEntityFromSnapshot(harness)
133
+ };
134
+ }
135
+
136
+ function skillsCurationManifest(): TeamPackageManifest {
137
+ const harness = createDefaultHarness("Curate reusable Codex skills and validate installation metadata before publication.");
138
+ const skillsCatalog = {
139
+ kind: "skillMeta" as const,
140
+ name: requireMetadataText("skills-catalog", "team.skills-curation.discover.skills[0].name"),
141
+ source: requireMetadataText("github:vercel-labs/skills", "team.skills-curation.discover.skills[0].source"),
142
+ agent: "codex" as const
143
+ };
144
+ harness.members = [
145
+ createDefaultMemberConfig("discover", "Find candidate skills and summarize their purpose.", [skillsCatalog]),
146
+ createDefaultMemberConfig("curate", "Normalize skill metadata and prepare installable entries."),
147
+ createDefaultMemberConfig("verify", "Check skill instructions and installation evidence.")
148
+ ];
149
+ return {
150
+ schema: HUB_PACKAGE_MANIFEST_SCHEMA,
151
+ kind: "team",
152
+ key: "team.skills-curation",
153
+ version: "1.0.2",
154
+ team: harnessEntityFromSnapshot(harness)
155
+ };
156
+ }
157
+
158
+ function defaultHunsuManagerManifest(): ManagerPackageManifest {
159
+ return {
160
+ schema: HUB_PACKAGE_MANIFEST_SCHEMA,
161
+ kind: "manager",
162
+ key: "manager.hunsu.default",
163
+ version: "1.0.0",
164
+ manager: createDefaultManagerConfig()
165
+ };
166
+ }
167
+
168
+ function ideaHelperManagerManifest(): ManagerPackageManifest {
169
+ return {
170
+ schema: HUB_PACKAGE_MANIFEST_SCHEMA,
171
+ kind: "manager",
172
+ key: "manager.idea-helper",
173
+ version: "1.0.0",
174
+ manager: createDefaultManagerConfig(
175
+ "manager.idea-helper",
176
+ [
177
+ "Help the user explore divergent Hunsu options before committing to an editable draft.",
178
+ "Generate alternatives, tradeoffs, naming choices, and likely downstream implications.",
179
+ "Only edit .hunsu-request files when the user chooses a concrete option."
180
+ ].join(" ")
181
+ )
182
+ };
183
+ }
184
+
185
+ function researcherManagerManifest(): ManagerPackageManifest {
186
+ return {
187
+ schema: HUB_PACKAGE_MANIFEST_SCHEMA,
188
+ kind: "manager",
189
+ key: "manager.researcher",
190
+ version: "1.0.0",
191
+ manager: createDefaultManagerConfig(
192
+ "manager.researcher",
193
+ [
194
+ "Gather and synthesize context for a proposed Hunsu change before editing draft runtime files.",
195
+ "Prioritize evidence, source boundaries, and unresolved assumptions.",
196
+ "When a file-backed change is requested, edit only the relevant .hunsu-request files."
197
+ ].join(" "),
198
+ [{
199
+ kind: "skillMeta",
200
+ name: requireMetadataText("researcher", "manager.researcher.skills[0].name"),
201
+ source: requireMetadataText("github:vercel-labs/skills", "manager.researcher.skills[0].source"),
202
+ agent: "codex"
203
+ }]
204
+ )
205
+ };
206
+ }
207
+
208
+ function researcherSkillManifest(): SkillPackageManifest {
209
+ return {
210
+ schema: HUB_PACKAGE_MANIFEST_SCHEMA,
211
+ kind: "skill",
212
+ key: "skill.researcher",
213
+ version: "1.0.0",
214
+ skill: {
215
+ name: "researcher",
216
+ contentHash: "sha256:vercel-labs-skills-researcher-seed",
217
+ files: [{
218
+ path: requireMetadataText("SKILL.md", "skill.researcher.files[0].path"),
219
+ text: [
220
+ "---",
221
+ "name: researcher",
222
+ "description: Gather evidence, source boundaries, and unresolved assumptions before Hunsu Draft changes.",
223
+ "---",
224
+ "",
225
+ "# Researcher",
226
+ "",
227
+ "Use this seed skill as an installable Hub example based on github:vercel-labs/skills for context gathering and synthesis."
228
+ ].join("\n")
229
+ }]
230
+ }
231
+ };
232
+ }
233
+
234
+ type JsonPrimitive = string | number | boolean | null;
235
+ type CanonicalJsonValue = JsonPrimitive | CanonicalJsonValue[] | { [key: string]: CanonicalJsonValue };
236
+
237
+ export function canonicalizeManifest(manifest: HubPackageManifest | unknown): string {
238
+ assertValidHubPackageManifest(manifest);
239
+ const { integrity: _integrity, ...manifestWithoutIntegrity } = manifest;
240
+ return JSON.stringify(toCanonicalJsonValue(manifestWithoutIntegrity, "manifest"));
241
+ }
242
+
243
+ export function computeManifestIntegrity(manifest: HubPackageManifest | unknown): string {
244
+ const canonical = canonicalizeManifest(manifest);
245
+ return `${MANIFEST_INTEGRITY_PREFIX_V1}${createHash("sha256").update(canonical, "utf8").digest("hex")}`;
246
+ }
247
+
248
+ export function verifyManifestIntegrity(manifest: HubPackageManifest | unknown, integrity: string): boolean {
249
+ if (!integrity.startsWith(MANIFEST_INTEGRITY_PREFIX_V1)) {
250
+ return false;
251
+ }
252
+ try {
253
+ return computeManifestIntegrity(manifest) === integrity;
254
+ } catch {
255
+ return false;
256
+ }
257
+ }
258
+
259
+ export async function resolveHubPackageManifestFromOrigin(lock: HubPackageLock, options: HttpHubPackageResolverOptions): Promise<ResolvedHubPackageManifest> {
260
+ if (!lock.integrity.startsWith(MANIFEST_INTEGRITY_PREFIX_V1)) {
261
+ throw new Error(`Unsupported Hub package integrity prefix: ${lock.integrity}`);
262
+ }
263
+ const origin = options.origins.find(candidate => candidate.name === lock.origin);
264
+ if (!origin) {
265
+ throw new Error(`Unknown Origin: ${lock.origin}`);
266
+ }
267
+ if (origin.transport !== "http") {
268
+ throw new Error(`Origin ${origin.name} uses unsupported transport ${origin.transport}`);
269
+ }
270
+ const fetchImpl = options.fetch ?? fetch;
271
+ const response = await fetchImpl(hubPackageManifestUrl(origin.url, lock.kind, lock.key, lock.version));
272
+ if (!response.ok) {
273
+ if (response.status === 404) {
274
+ throw new Error(`Missing Hub package manifest: ${lock.origin}/${lock.kind}/${lock.key}@${lock.version}`);
275
+ }
276
+ throw new Error(`Origin ${origin.name} returned ${response.status} for ${lock.kind}/${lock.key}@${lock.version}`);
277
+ }
278
+ const parsed = await response.json() as unknown;
279
+ assertValidHubPackageManifest(parsed);
280
+ if (parsed.kind !== lock.kind || parsed.key !== lock.key || parsed.version !== lock.version) {
281
+ throw new Error(`Hub package manifest from ${origin.name} does not match requested ${lock.kind}/${lock.key}@${lock.version}`);
282
+ }
283
+ const integrity = computeManifestIntegrity(parsed);
284
+ if (integrity !== lock.integrity) {
285
+ throw new Error(`Hub package integrity mismatch for ${lock.origin}/${lock.kind}/${lock.key}@${lock.version}: expected ${lock.integrity}, got ${integrity}`);
286
+ }
287
+ return { lock: { ...lock }, manifest: parsed, integrity, origin: { ...origin } };
288
+ }
289
+
290
+ export function hubPackageManifestUrl(originUrl: string, kind: HubPackageKind, key: string, version: string): string {
291
+ const base = new URL(originUrl);
292
+ const path = `/v1/packages/${kind}/${encodeURIComponent(key)}/versions/${encodeURIComponent(version)}`;
293
+ return new URL(path, base).toString();
294
+ }
295
+
296
+ export function hubPackageEntityRef(origin: string, key: string): string {
297
+ return `@${origin}/${key}`;
298
+ }
299
+
300
+ export function hubPackageVersionRef(origin: string, key: string, version: string): string {
301
+ return `${hubPackageEntityRef(origin, key)}@${version}`;
302
+ }
303
+
304
+ export function hubPackageHumanUrl(originUrl: string, lock: HubPackageLock): string {
305
+ const base = new URL(originUrl);
306
+ const path = `/hub/${marketplaceIdForPackageKind(lock.kind)}/${lock.kind}/@${encodeURIComponent(lock.origin)}/${encodeURIComponent(lock.key)}/versions/${encodeURIComponent(lock.version)}`;
307
+ return new URL(path, base).toString();
308
+ }
309
+
310
+ export function parseHubPackageRefFromUrl(rawUrl: string): HubPackageRef {
311
+ const url = new URL(rawUrl, "https://hub.local");
312
+ const match = url.pathname.match(/^\/hub\/(executor|hunsu|resources)\/(team|member|manager|skill)\/@([^/]+)\/([^/]+)\/versions\/([^/]+)$/);
313
+ if (!match) {
314
+ throw new Error("Hub package URL must use /hub/:marketplace/:kind/@:origin/:key/versions/:version");
315
+ }
316
+ const marketplaceId = match[1];
317
+ const kind = match[2] as HubPackageKind;
318
+ if (marketplaceId !== marketplaceIdForPackageKind(kind)) {
319
+ throw new Error(`Hub package URL marketplace ${marketplaceId} does not match ${kind}`);
320
+ }
321
+ return {
322
+ origin: requireMetadataText(decodeURIComponent(match[3] ?? ""), "ref.origin"),
323
+ kind,
324
+ key: requireMetadataText(decodeURIComponent(match[4] ?? ""), "ref.key"),
325
+ version: requireMetadataText(decodeURIComponent(match[5] ?? ""), "ref.version")
326
+ };
327
+ }
328
+
329
+ function marketplaceIdForPackageKind(kind: HubPackageKind): "executor" | "hunsu" | "resources" {
330
+ if (kind === "manager") return "hunsu";
331
+ if (kind === "skill") return "resources";
332
+ return "executor";
333
+ }
334
+
335
+ function requireMetadataText(value: unknown, field: string): NonEmptyText {
336
+ const result = makeNonEmptyText(value, field);
337
+ if (!result.ok) {
338
+ throw new Error(result.error.message);
339
+ }
340
+ return result.value;
341
+ }
342
+
343
+ export function summarizeHubPackageManifest(manifest: HubPackageManifest, origin: string): HubPackageSummary {
344
+ assertValidHubPackageManifest(manifest);
345
+ const integrity = manifest.integrity ?? computeManifestIntegrity(manifest);
346
+ switch (manifest.kind) {
347
+ case "team": {
348
+ const rootTeam = rootTeamForPackage(manifest.team);
349
+ const resourceCounts = resourceCountsForHarness(manifest.team);
350
+ return {
351
+ origin,
352
+ entryKind: "package",
353
+ kind: manifest.kind,
354
+ key: manifest.key,
355
+ version: manifest.version,
356
+ integrity,
357
+ label: manifest.key,
358
+ sourcePackageKind: manifest.kind,
359
+ sourcePackageKey: manifest.key,
360
+ sourcePackageVersion: manifest.version,
361
+ promptTemplateEngine: rootTeam.planner.promptTemplate.engine,
362
+ memberCount: rootTeam.members.length,
363
+ skillCount: resourceCounts.skill,
364
+ pluginRequirementCount: resourceCounts.plugin
365
+ };
366
+ }
367
+ case "member":
368
+ return {
369
+ origin,
370
+ entryKind: "package",
371
+ kind: manifest.kind,
372
+ key: manifest.key,
373
+ version: manifest.version,
374
+ integrity,
375
+ label: manifest.member.id,
376
+ sourcePackageKind: manifest.kind,
377
+ sourcePackageKey: manifest.key,
378
+ sourcePackageVersion: manifest.version,
379
+ executorId: manifest.member.id,
380
+ promptTemplateEngine: manifest.member.promptTemplate.engine,
381
+ skillCount: manifest.member.skills.length,
382
+ pluginRequirementCount: manifest.member.plugins.length
383
+ };
384
+ case "manager":
385
+ return {
386
+ origin,
387
+ entryKind: "package",
388
+ kind: manifest.kind,
389
+ key: manifest.key,
390
+ version: manifest.version,
391
+ integrity,
392
+ label: manifest.manager.id,
393
+ sourcePackageKind: manifest.kind,
394
+ sourcePackageKey: manifest.key,
395
+ sourcePackageVersion: manifest.version,
396
+ promptTemplateEngine: manifest.manager.promptTemplate.engine,
397
+ skillCount: manifest.manager.skills.length,
398
+ pluginRequirementCount: manifest.manager.plugins.length
399
+ };
400
+ case "skill":
401
+ return {
402
+ origin,
403
+ entryKind: "package",
404
+ kind: manifest.kind,
405
+ key: manifest.key,
406
+ version: manifest.version,
407
+ integrity,
408
+ label: manifest.skill.name,
409
+ sourcePackageKind: manifest.kind,
410
+ sourcePackageKey: manifest.key,
411
+ sourcePackageVersion: manifest.version
412
+ };
413
+ }
414
+ }
415
+
416
+ export function hydrateTeamPackage(manifest: HubPackageManifest): Harness {
417
+ assertValidHubPackageManifest(manifest);
418
+ if (manifest.kind !== "team") {
419
+ throw new Error(`Hub package ${manifest.kind}/${manifest.key}@${manifest.version} is not a team package`);
420
+ }
421
+ return cloneJson(manifest.team) as Harness;
422
+ }
423
+
424
+ export function assertValidHubPackageManifest(manifest: unknown): asserts manifest is HubPackageManifest {
425
+ const record = requireRecord(manifest, "manifest");
426
+ if (record.schema !== HUB_PACKAGE_MANIFEST_SCHEMA) {
427
+ throw new Error(`Unsupported Hub package manifest schema: ${String(record.schema)}`);
428
+ }
429
+ requireExactKeys(record, ["integrity", "key", "kind", "team", "member", "manager", "schema", "skill", "version"], "manifest");
430
+ const kind = requireHubPackageKind(record.kind, "manifest.kind");
431
+ requireNonEmptyString(record.key, "manifest.key");
432
+ requireNonEmptyString(record.version, "manifest.version");
433
+ if (record.integrity !== undefined) {
434
+ requireNonEmptyString(record.integrity, "manifest.integrity");
435
+ }
436
+ switch (kind) {
437
+ case "team":
438
+ assertValidTeamPayload(record.team);
439
+ if (record.member !== undefined || record.manager !== undefined || record.skill !== undefined) {
440
+ throw new Error("Team package manifest must not include member, manager, or skill payloads");
441
+ }
442
+ return;
443
+ case "member":
444
+ assertValidMemberPayload(record.member);
445
+ if (record.team !== undefined || record.manager !== undefined || record.skill !== undefined) {
446
+ throw new Error("Member package manifest must not include team, manager, or skill payloads");
447
+ }
448
+ return;
449
+ case "manager":
450
+ assertValidManagerPayload(record.manager);
451
+ if (record.team !== undefined || record.member !== undefined || record.skill !== undefined) {
452
+ throw new Error("Manager package manifest must not include team, member, or skill payloads");
453
+ }
454
+ return;
455
+ case "skill":
456
+ assertValidSkillPayload(record.skill);
457
+ if (record.team !== undefined || record.member !== undefined || record.manager !== undefined) {
458
+ throw new Error("Skill package manifest must not include team, member, or manager payloads");
459
+ }
460
+ return;
461
+ }
462
+ }
463
+
464
+ function assertValidTeamPayload(value: unknown): void {
465
+ const graph = validateHarnessEntity(value, "manifest.team");
466
+ if (!graph.ok) {
467
+ throw new Error(`Invalid manifest.team: ${graph.error.message}`);
468
+ }
469
+ }
470
+
471
+ function assertValidMemberPayload(value: unknown): void {
472
+ const member = validateMemberConfig(value, "manifest.member");
473
+ if (!member.ok) {
474
+ throw new Error(`Invalid manifest.member: ${member.error.message}`);
475
+ }
476
+ }
477
+
478
+ function assertValidManagerPayload(value: unknown): void {
479
+ const manager = validateManagerConfig(value, "manifest.manager");
480
+ if (!manager.ok) {
481
+ throw new Error(`Invalid manifest.manager: ${manager.error.message}`);
482
+ }
483
+ }
484
+
485
+ function assertValidSkillPayload(value: unknown): void {
486
+ const record = requireRecord(value, "manifest.skill");
487
+ requireExactKeys(record, ["contentHash", "files", "name"], "manifest.skill");
488
+ requireNonEmptyString(record.name, "manifest.skill.name");
489
+ requireNonEmptyString(record.contentHash, "manifest.skill.contentHash");
490
+ if (record.files !== undefined) {
491
+ if (!Array.isArray(record.files)) {
492
+ throw new Error("manifest.skill.files must be an array");
493
+ }
494
+ for (const [index, file] of record.files.entries()) {
495
+ const item = requireRecord(file, `manifest.skill.files[${index}]`);
496
+ requireExactKeys(item, ["path", "text"], `manifest.skill.files[${index}]`);
497
+ requireNonEmptyString(item.path, `manifest.skill.files[${index}].path`);
498
+ requireString(item.text, `manifest.skill.files[${index}].text`);
499
+ }
500
+ }
501
+ }
502
+
503
+ function rootTeamForPackage(team: Harness): Extract<Harness["executors"][number], { kind: "team" }> {
504
+ const rootTeam = team.executors.find((executor): executor is Extract<Harness["executors"][number], { kind: "team" }> => executor.kind === "team" && executor.id === team.rootTeamId);
505
+ if (!rootTeam) {
506
+ throw new Error(`Team package rootTeamId ${team.rootTeamId} does not reference a Team Executor`);
507
+ }
508
+ return rootTeam;
509
+ }
510
+
511
+ function resourceCountsForHarness(harness: Harness): { skill: number; plugin: number } {
512
+ const identities = new Set<string>();
513
+ for (const resource of harness.resources) {
514
+ identities.add(resourceIdentity(resource.binding));
515
+ }
516
+ for (const executor of harness.executors) {
517
+ if (executor.kind !== "member") {
518
+ continue;
519
+ }
520
+ for (const binding of executor.resources) {
521
+ identities.add(resourceIdentity(binding));
522
+ }
523
+ }
524
+ let skill = 0;
525
+ let plugin = 0;
526
+ for (const identity of identities) {
527
+ if (identity.startsWith("skill:")) skill += 1;
528
+ if (identity.startsWith("plugin:")) plugin += 1;
529
+ }
530
+ return { skill, plugin };
531
+ }
532
+
533
+ function resourceIdentity(binding: Harness["resources"][number]["binding"]): string {
534
+ if (binding.kind === "skill") {
535
+ return `skill:${binding.skill.name}`;
536
+ }
537
+ if (binding.kind === "plugin") {
538
+ return `plugin:${binding.plugin.id}`;
539
+ }
540
+ return `package:${binding.lock.kind}:${binding.lock.key}:${binding.lock.version}`;
541
+ }
542
+
543
+ function requireHubPackageKind(value: unknown, path: string): HubPackageKind {
544
+ if (value === "team" || value === "member" || value === "manager" || value === "skill") {
545
+ return value;
546
+ }
547
+ throw new Error(`${path} must be team, member, manager, or skill`);
548
+ }
549
+
550
+ function requireRecord(value: unknown, path: string): Record<string, unknown> {
551
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
552
+ throw new Error(`${path} must be an object`);
553
+ }
554
+ return value as Record<string, unknown>;
555
+ }
556
+
557
+ function requireExactKeys(record: Record<string, unknown>, allowedKeys: string[], path: string): void {
558
+ const missing = allowedKeys.filter(key => key !== "integrity" && key !== "team" && key !== "member" && key !== "manager" && key !== "skill" && key !== "files" && !(key in record));
559
+ if (missing.length > 0) {
560
+ throw new Error(`${path} is missing required keys: ${missing.join(", ")}`);
561
+ }
562
+ const extra = Object.keys(record).filter(key => !allowedKeys.includes(key));
563
+ if (extra.length > 0) {
564
+ throw new Error(`${path} has unsupported keys: ${extra.join(", ")}`);
565
+ }
566
+ }
567
+
568
+ function requireString(value: unknown, path: string): string {
569
+ if (typeof value !== "string") {
570
+ throw new Error(`${path} must be a string`);
571
+ }
572
+ return value;
573
+ }
574
+
575
+ function requireNonEmptyString(value: unknown, path: string): string {
576
+ const text = requireString(value, path);
577
+ if (text.trim().length === 0) {
578
+ throw new Error(`${path} must be non-empty`);
579
+ }
580
+ return text;
581
+ }
582
+
583
+ function toCanonicalJsonValue(value: unknown, path: string): CanonicalJsonValue {
584
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
585
+ return value;
586
+ }
587
+ if (typeof value === "number") {
588
+ if (!Number.isFinite(value)) {
589
+ throw new Error(`${path} must be a finite number`);
590
+ }
591
+ return value;
592
+ }
593
+ if (Array.isArray(value)) {
594
+ return value.map((item, index) => {
595
+ if (item === undefined) {
596
+ throw new Error(`${path}[${index}] must not be undefined`);
597
+ }
598
+ return toCanonicalJsonValue(item, `${path}[${index}]`);
599
+ });
600
+ }
601
+ if (typeof value === "object" && value !== null) {
602
+ const record = value as Record<string, unknown>;
603
+ const canonical: { [key: string]: CanonicalJsonValue } = {};
604
+ for (const key of Object.keys(record).sort()) {
605
+ const child = record[key];
606
+ if (child === undefined) {
607
+ continue;
608
+ }
609
+ canonical[key] = toCanonicalJsonValue(child, `${path}.${key}`);
610
+ }
611
+ return canonical;
612
+ }
613
+ throw new Error(`${path} must be JSON-serializable`);
614
+ }
615
+
616
+ function cloneJson(value: unknown): unknown {
617
+ return JSON.parse(JSON.stringify(value));
618
+ }