@ipab/cli 0.1.0-rc.1 → 0.1.0-rc.11

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 (285) hide show
  1. package/README.md +234 -9
  2. package/dist/app-authoring.d.ts +15 -0
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +144 -58
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-definition.d.ts +52 -57
  7. package/dist/app-definition.d.ts.map +1 -1
  8. package/dist/app-definition.js +33 -38
  9. package/dist/app-definition.js.map +1 -1
  10. package/dist/app-prebuild.d.ts +18 -0
  11. package/dist/app-prebuild.d.ts.map +1 -1
  12. package/dist/app-prebuild.js +46 -0
  13. package/dist/app-prebuild.js.map +1 -1
  14. package/dist/app-templates.d.ts +0 -1
  15. package/dist/app-templates.d.ts.map +1 -1
  16. package/dist/app-templates.js +8 -46
  17. package/dist/app-templates.js.map +1 -1
  18. package/dist/assembly.d.ts +7 -0
  19. package/dist/assembly.d.ts.map +1 -0
  20. package/dist/assembly.js +130 -0
  21. package/dist/assembly.js.map +1 -0
  22. package/dist/authoring.d.ts +7 -8
  23. package/dist/authoring.d.ts.map +1 -1
  24. package/dist/authoring.js +59 -16
  25. package/dist/authoring.js.map +1 -1
  26. package/dist/builtins/skill.ipab.car +0 -0
  27. package/dist/builtins/template.bundle-viewer.car +0 -0
  28. package/dist/builtins/template.check.car +0 -0
  29. package/dist/builtins/template.node.car +0 -0
  30. package/dist/builtins/template.web-app.car +0 -0
  31. package/dist/builtins.d.ts.map +1 -1
  32. package/dist/builtins.js +1 -23
  33. package/dist/builtins.js.map +1 -1
  34. package/dist/bundled-skills.d.ts +14 -0
  35. package/dist/bundled-skills.d.ts.map +1 -0
  36. package/dist/bundled-skills.js +34 -0
  37. package/dist/bundled-skills.js.map +1 -0
  38. package/dist/cli.d.ts +8 -2
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +1967 -258
  41. package/dist/cli.js.map +1 -1
  42. package/dist/config-secret.d.ts +3 -0
  43. package/dist/config-secret.d.ts.map +1 -0
  44. package/dist/config-secret.js +12 -0
  45. package/dist/config-secret.js.map +1 -0
  46. package/dist/config.d.ts +11 -2
  47. package/dist/config.d.ts.map +1 -1
  48. package/dist/config.js +166 -8
  49. package/dist/config.js.map +1 -1
  50. package/dist/content-provider.d.ts +32 -0
  51. package/dist/content-provider.d.ts.map +1 -0
  52. package/dist/content-provider.js +222 -0
  53. package/dist/content-provider.js.map +1 -0
  54. package/dist/context-types.d.ts +12 -0
  55. package/dist/context-types.d.ts.map +1 -0
  56. package/dist/context-types.js +2 -0
  57. package/dist/context-types.js.map +1 -0
  58. package/dist/context.d.ts +26 -1
  59. package/dist/context.d.ts.map +1 -1
  60. package/dist/context.js +54 -10
  61. package/dist/context.js.map +1 -1
  62. package/dist/daemon-ui.d.ts +93 -0
  63. package/dist/daemon-ui.d.ts.map +1 -0
  64. package/dist/daemon-ui.js +713 -0
  65. package/dist/daemon-ui.js.map +1 -0
  66. package/dist/daemon.d.ts +21 -0
  67. package/dist/daemon.d.ts.map +1 -0
  68. package/dist/daemon.js +317 -0
  69. package/dist/daemon.js.map +1 -0
  70. package/dist/doctor.d.ts +32 -0
  71. package/dist/doctor.d.ts.map +1 -0
  72. package/dist/doctor.js +688 -0
  73. package/dist/doctor.js.map +1 -0
  74. package/dist/errors.d.ts +1 -8
  75. package/dist/errors.d.ts.map +1 -1
  76. package/dist/errors.js +1 -20
  77. package/dist/errors.js.map +1 -1
  78. package/dist/get.d.ts +3 -0
  79. package/dist/get.d.ts.map +1 -0
  80. package/dist/get.js +80 -0
  81. package/dist/get.js.map +1 -0
  82. package/dist/history.d.ts.map +1 -1
  83. package/dist/history.js +6 -14
  84. package/dist/history.js.map +1 -1
  85. package/dist/host-error.d.ts +9 -0
  86. package/dist/host-error.d.ts.map +1 -0
  87. package/dist/host-error.js +21 -0
  88. package/dist/host-error.js.map +1 -0
  89. package/dist/identity.d.ts +16 -0
  90. package/dist/identity.d.ts.map +1 -0
  91. package/dist/identity.js +119 -0
  92. package/dist/identity.js.map +1 -0
  93. package/dist/ipc.d.ts +5 -2
  94. package/dist/ipc.d.ts.map +1 -1
  95. package/dist/ipc.js +124 -12
  96. package/dist/ipc.js.map +1 -1
  97. package/dist/kubo-install.d.ts +26 -0
  98. package/dist/kubo-install.d.ts.map +1 -0
  99. package/dist/kubo-install.js +724 -0
  100. package/dist/kubo-install.js.map +1 -0
  101. package/dist/kubo-peering.d.ts +11 -0
  102. package/dist/kubo-peering.d.ts.map +1 -0
  103. package/dist/kubo-peering.js +93 -0
  104. package/dist/kubo-peering.js.map +1 -0
  105. package/dist/kubo-peers.d.ts +12 -0
  106. package/dist/kubo-peers.d.ts.map +1 -0
  107. package/dist/kubo-peers.js +119 -0
  108. package/dist/kubo-peers.js.map +1 -0
  109. package/dist/kubo-release.d.ts +22 -0
  110. package/dist/kubo-release.d.ts.map +1 -0
  111. package/dist/kubo-release.js +176 -0
  112. package/dist/kubo-release.js.map +1 -0
  113. package/dist/kubo-topology.d.ts +19 -0
  114. package/dist/kubo-topology.d.ts.map +1 -0
  115. package/dist/kubo-topology.js +113 -0
  116. package/dist/kubo-topology.js.map +1 -0
  117. package/dist/kubo.d.ts +85 -0
  118. package/dist/kubo.d.ts.map +1 -0
  119. package/dist/kubo.js +755 -0
  120. package/dist/kubo.js.map +1 -0
  121. package/dist/pins.d.ts +16 -18
  122. package/dist/pins.d.ts.map +1 -1
  123. package/dist/pins.js +144 -106
  124. package/dist/pins.js.map +1 -1
  125. package/dist/pivot-rpc.d.ts +62 -0
  126. package/dist/pivot-rpc.d.ts.map +1 -0
  127. package/dist/pivot-rpc.js +407 -0
  128. package/dist/pivot-rpc.js.map +1 -0
  129. package/dist/pivot-service.d.ts +16 -0
  130. package/dist/pivot-service.d.ts.map +1 -0
  131. package/dist/pivot-service.js +50 -0
  132. package/dist/pivot-service.js.map +1 -0
  133. package/dist/publish-source.d.ts +3 -0
  134. package/dist/publish-source.d.ts.map +1 -0
  135. package/dist/publish-source.js +85 -0
  136. package/dist/publish-source.js.map +1 -0
  137. package/dist/runtime.d.ts +2 -0
  138. package/dist/runtime.d.ts.map +1 -1
  139. package/dist/runtime.js +9 -4
  140. package/dist/runtime.js.map +1 -1
  141. package/dist/search-index.d.ts +64 -0
  142. package/dist/search-index.d.ts.map +1 -0
  143. package/dist/search-index.js +409 -0
  144. package/dist/search-index.js.map +1 -0
  145. package/dist/search-service.d.ts +23 -0
  146. package/dist/search-service.d.ts.map +1 -0
  147. package/dist/search-service.js +116 -0
  148. package/dist/search-service.js.map +1 -0
  149. package/dist/skill-definition.d.ts +6 -0
  150. package/dist/skill-definition.d.ts.map +1 -0
  151. package/dist/skill-definition.js +38 -0
  152. package/dist/skill-definition.js.map +1 -0
  153. package/dist/skill-source.d.ts +9 -0
  154. package/dist/skill-source.d.ts.map +1 -0
  155. package/dist/skill-source.js +24 -0
  156. package/dist/skill-source.js.map +1 -0
  157. package/dist/skills.d.ts +104 -0
  158. package/dist/skills.d.ts.map +1 -0
  159. package/dist/skills.js +894 -0
  160. package/dist/skills.js.map +1 -0
  161. package/dist/source-bundle.d.ts +3 -8
  162. package/dist/source-bundle.d.ts.map +1 -1
  163. package/dist/source-bundle.js +17 -12
  164. package/dist/source-bundle.js.map +1 -1
  165. package/dist/space-path.d.ts +3 -0
  166. package/dist/space-path.d.ts.map +1 -0
  167. package/dist/space-path.js +17 -0
  168. package/dist/space-path.js.map +1 -0
  169. package/dist/space.d.ts +16 -4
  170. package/dist/space.d.ts.map +1 -1
  171. package/dist/space.js +170 -24
  172. package/dist/space.js.map +1 -1
  173. package/dist/state-storage-windows.d.ts +2 -0
  174. package/dist/state-storage-windows.d.ts.map +1 -0
  175. package/dist/state-storage-windows.js +114 -0
  176. package/dist/state-storage-windows.js.map +1 -0
  177. package/dist/state-storage.d.ts +5 -0
  178. package/dist/state-storage.d.ts.map +1 -0
  179. package/dist/state-storage.js +333 -0
  180. package/dist/state-storage.js.map +1 -0
  181. package/dist/state.d.ts +135 -13
  182. package/dist/state.d.ts.map +1 -1
  183. package/dist/state.js +577 -92
  184. package/dist/state.js.map +1 -1
  185. package/dist/swarm-envelope.d.ts +57 -0
  186. package/dist/swarm-envelope.d.ts.map +1 -0
  187. package/dist/swarm-envelope.js +299 -0
  188. package/dist/swarm-envelope.js.map +1 -0
  189. package/dist/swarm-files.d.ts +6 -0
  190. package/dist/swarm-files.d.ts.map +1 -0
  191. package/dist/swarm-files.js +116 -0
  192. package/dist/swarm-files.js.map +1 -0
  193. package/dist/swarm-meta.d.ts +15 -0
  194. package/dist/swarm-meta.d.ts.map +1 -0
  195. package/dist/swarm-meta.js +68 -0
  196. package/dist/swarm-meta.js.map +1 -0
  197. package/dist/swarm-observations.d.ts +40 -0
  198. package/dist/swarm-observations.d.ts.map +1 -0
  199. package/dist/swarm-observations.js +271 -0
  200. package/dist/swarm-observations.js.map +1 -0
  201. package/dist/swarm.d.ts +537 -0
  202. package/dist/swarm.d.ts.map +1 -0
  203. package/dist/swarm.js +4991 -0
  204. package/dist/swarm.js.map +1 -0
  205. package/dist/template-definition.d.ts +47 -52
  206. package/dist/template-definition.d.ts.map +1 -1
  207. package/dist/template-definition.js +36 -41
  208. package/dist/template-definition.js.map +1 -1
  209. package/dist/template-paths.d.ts +7 -0
  210. package/dist/template-paths.d.ts.map +1 -0
  211. package/dist/template-paths.js +23 -0
  212. package/dist/template-paths.js.map +1 -0
  213. package/dist/template-presentation.d.ts +20 -0
  214. package/dist/template-presentation.d.ts.map +1 -0
  215. package/dist/template-presentation.js +133 -0
  216. package/dist/template-presentation.js.map +1 -0
  217. package/dist/template-source.d.ts +4 -1
  218. package/dist/template-source.d.ts.map +1 -1
  219. package/dist/template-source.js +11 -4
  220. package/dist/template-source.js.map +1 -1
  221. package/dist/templates.d.ts +11 -0
  222. package/dist/templates.d.ts.map +1 -0
  223. package/dist/templates.js +53 -0
  224. package/dist/templates.js.map +1 -0
  225. package/dist/unixfs-tree.d.ts +67 -0
  226. package/dist/unixfs-tree.d.ts.map +1 -0
  227. package/dist/unixfs-tree.js +329 -0
  228. package/dist/unixfs-tree.js.map +1 -0
  229. package/package.json +14 -7
  230. package/src/app-authoring.ts +240 -76
  231. package/src/app-definition.ts +33 -39
  232. package/src/app-prebuild.ts +61 -0
  233. package/src/app-templates.ts +17 -73
  234. package/src/assembly.ts +185 -0
  235. package/src/authoring.ts +99 -18
  236. package/src/builtins.ts +2 -27
  237. package/src/bundled-skills.ts +60 -0
  238. package/src/cli.ts +2461 -323
  239. package/src/config-secret.ts +14 -0
  240. package/src/config.ts +214 -8
  241. package/src/content-provider.ts +299 -0
  242. package/src/context-types.ts +11 -0
  243. package/src/context.ts +98 -10
  244. package/src/daemon-ui.ts +812 -0
  245. package/src/daemon.ts +386 -0
  246. package/src/doctor.ts +1092 -0
  247. package/src/errors.ts +1 -25
  248. package/src/get.ts +91 -0
  249. package/src/history.ts +5 -15
  250. package/src/host-error.ts +26 -0
  251. package/src/identity.ts +175 -0
  252. package/src/ipc.ts +160 -11
  253. package/src/kubo-install.ts +936 -0
  254. package/src/kubo-peering.ts +126 -0
  255. package/src/kubo-peers.ts +144 -0
  256. package/src/kubo-release.ts +230 -0
  257. package/src/kubo-topology.ts +148 -0
  258. package/src/kubo.ts +1088 -0
  259. package/src/pins.ts +188 -126
  260. package/src/pivot-rpc.ts +601 -0
  261. package/src/pivot-service.ts +87 -0
  262. package/src/publish-source.ts +103 -0
  263. package/src/runtime.ts +16 -4
  264. package/src/search-index.ts +560 -0
  265. package/src/search-service.ts +152 -0
  266. package/src/skill-definition.ts +53 -0
  267. package/src/skill-source.ts +29 -0
  268. package/src/skills.ts +1236 -0
  269. package/src/source-bundle.ts +26 -13
  270. package/src/space-path.ts +30 -0
  271. package/src/space.ts +230 -42
  272. package/src/state-storage-windows.ts +134 -0
  273. package/src/state-storage.ts +378 -0
  274. package/src/state.ts +875 -108
  275. package/src/swarm-envelope.ts +461 -0
  276. package/src/swarm-files.ts +126 -0
  277. package/src/swarm-meta.ts +98 -0
  278. package/src/swarm-observations.ts +393 -0
  279. package/src/swarm.ts +7392 -0
  280. package/src/template-definition.ts +36 -41
  281. package/src/template-paths.ts +43 -0
  282. package/src/template-presentation.ts +151 -0
  283. package/src/template-source.ts +19 -5
  284. package/src/templates.ts +77 -0
  285. package/src/unixfs-tree.ts +401 -0
package/dist/skills.js ADDED
@@ -0,0 +1,894 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { execFile, spawn } from "node:child_process";
3
+ import { lstat, mkdir, readFile, readdir, rm } from "node:fs/promises";
4
+ import { basename, dirname, isAbsolute, join, resolve, delimiter, } from "node:path";
5
+ import { homedir } from "node:os";
6
+ import { fileURLToPath } from "node:url";
7
+ import { promisify } from "node:util";
8
+ import { CID } from "multiformats/cid";
9
+ import { relativePath } from "./space.js";
10
+ import { swarmUrl } from "./config.js";
11
+ import { HostError, message, object } from "./errors.js";
12
+ import { nodeError, scaffoldFiles } from "./authoring.js";
13
+ import { getBundle } from "./get.js";
14
+ import { privateDirectory, readPrivate, withPrivateLock, writePrivate, } from "./swarm-files.js";
15
+ import { swarmHeader, swarmSkills, syncPivotReplicationAndIndex, syncSwarmRegistry, syncSwarmTemplates, } from "./swarm.js";
16
+ export const skillsInstaller = "skills@1.9.1";
17
+ export const bundledSkillOrigin = "bundled:ipab";
18
+ const ledgerBytes = 64 * 1024 * 1024;
19
+ async function saveLedger(directory, ledger) {
20
+ if (Buffer.byteLength(JSON.stringify(ledger)) > ledgerBytes)
21
+ throw new HostError("Skills attribution exceeds its 64 MiB limit; preserve the existing ledger and installations.");
22
+ await writePrivate(directory, "installations.json", ledger);
23
+ }
24
+ export function requireSkillsNode(version = process.versions.node) {
25
+ const [major = 0, minor = 0] = version.split(".").map(Number);
26
+ if (major < 22 || (major === 22 && minor < 20))
27
+ throw new HostError("Skills operations require Node >=22.20.0, the minimum supported IPAB runtime, for the pinned official skills@1.9.1 installer.");
28
+ }
29
+ async function npxCommand() {
30
+ if (process.platform !== "win32")
31
+ return { command: "npx", prefix: [] };
32
+ // Avoid cmd.exe interpolation of local paths; use npm's actual npx entry.
33
+ for (const directory of [
34
+ dirname(process.execPath),
35
+ ...(process.env.PATH ?? "").split(delimiter),
36
+ ]) {
37
+ const entry = join(directory, "node_modules", "npm", "bin", "npx-cli.js");
38
+ try {
39
+ if ((await lstat(entry)).isFile())
40
+ return { command: process.execPath, prefix: [entry] };
41
+ }
42
+ catch (cause) {
43
+ if (!nodeError(cause, "ENOENT"))
44
+ throw cause;
45
+ }
46
+ }
47
+ throw new HostError("Cannot locate npm's npx-cli.js. Install npm alongside Node before synchronizing Skills.");
48
+ }
49
+ export const officialSkillsPort = {
50
+ home: homedir(),
51
+ async catalog() {
52
+ requireSkillsNode();
53
+ const api = await import("skills");
54
+ return {
55
+ supported: api.getSupportedAgents(),
56
+ detected: (await api.detectAgents({ cwd: process.cwd() })).agents,
57
+ };
58
+ },
59
+ async install(source, identity, agent, env) {
60
+ requireSkillsNode();
61
+ const { command, prefix } = await npxCommand();
62
+ return new Promise((accept, reject) => {
63
+ const child = spawn(command, [
64
+ ...prefix,
65
+ "--yes",
66
+ "--package",
67
+ skillsInstaller,
68
+ "skills",
69
+ "add",
70
+ source,
71
+ "--global",
72
+ "--agent",
73
+ agent,
74
+ "--skill",
75
+ identity,
76
+ "--copy",
77
+ "--yes",
78
+ "--json",
79
+ ], {
80
+ shell: false,
81
+ cwd: fileURLToPath(new URL("..", import.meta.url)),
82
+ windowsHide: true,
83
+ detached: process.platform !== "win32",
84
+ env: {
85
+ ...env,
86
+ DISABLE_TELEMETRY: "1",
87
+ DO_NOT_TRACK: "1",
88
+ npm_config_ignore_scripts: "true",
89
+ NPM_CONFIG_IGNORE_SCRIPTS: "true",
90
+ npm_config_audit: "false",
91
+ NPM_CONFIG_AUDIT: "false",
92
+ npm_config_fund: "false",
93
+ NPM_CONFIG_FUND: "false",
94
+ },
95
+ stdio: ["ignore", "pipe", "pipe"],
96
+ });
97
+ let stdout = "";
98
+ let stderr = "";
99
+ let excessive = false;
100
+ let interrupted = 0;
101
+ let failure;
102
+ let stopping;
103
+ const stop = () => {
104
+ if (!child.pid || stopping)
105
+ return;
106
+ const pid = child.pid;
107
+ stopping = (async () => {
108
+ if (process.platform === "win32") {
109
+ try {
110
+ await promisify(execFile)(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "taskkill.exe"), ["/PID", String(pid), "/T", "/F"]);
111
+ }
112
+ catch (cause) {
113
+ if (child.exitCode === null && child.signalCode === null)
114
+ throw cause;
115
+ }
116
+ }
117
+ else {
118
+ try {
119
+ process.kill(-pid, "SIGKILL");
120
+ }
121
+ catch (cause) {
122
+ if (!nodeError(cause, "ESRCH"))
123
+ throw cause;
124
+ }
125
+ }
126
+ })();
127
+ void stopping.catch((cause) => {
128
+ failure =
129
+ cause instanceof Error
130
+ ? cause
131
+ : new Error("Cannot stop Skills installer process tree.", {
132
+ cause,
133
+ });
134
+ });
135
+ };
136
+ const fail = (cause) => {
137
+ failure ??=
138
+ cause instanceof Error
139
+ ? cause
140
+ : new Error("Skills installer failed.", { cause });
141
+ stop();
142
+ };
143
+ const interrupt = () => {
144
+ interrupted = 130;
145
+ stop();
146
+ };
147
+ const terminate = () => {
148
+ interrupted = 143;
149
+ stop();
150
+ };
151
+ const cleanup = () => {
152
+ process.removeListener("SIGINT", interrupt);
153
+ process.removeListener("SIGTERM", terminate);
154
+ };
155
+ process.once("SIGINT", interrupt);
156
+ process.once("SIGTERM", terminate);
157
+ const collect = (chunk, error) => {
158
+ if (stdout.length + stderr.length + chunk.length > 1024 * 1024) {
159
+ excessive = true;
160
+ stop();
161
+ }
162
+ else if (error)
163
+ stderr += chunk.toString();
164
+ else
165
+ stdout += chunk.toString();
166
+ };
167
+ child.stdout.on("data", (chunk) => {
168
+ collect(chunk, false);
169
+ });
170
+ child.stderr.on("data", (chunk) => {
171
+ collect(chunk, true);
172
+ });
173
+ child.stdout.once("error", fail);
174
+ child.stderr.once("error", fail);
175
+ child.once("error", fail);
176
+ child.once("close", (code) => {
177
+ cleanup();
178
+ void (async () => {
179
+ await stopping;
180
+ if (failure)
181
+ throw failure;
182
+ if (excessive)
183
+ throw new HostError("Skills installer output exceeded its limit; pending attribution was preserved.");
184
+ accept({ code: interrupted || (code ?? 1), stdout, stderr });
185
+ })().catch(reject);
186
+ });
187
+ });
188
+ },
189
+ };
190
+ function pathKey(path) {
191
+ const absolute = resolve(path);
192
+ return process.platform === "win32" ? absolute.toLowerCase() : absolute;
193
+ }
194
+ async function safeAncestors(path) {
195
+ for (let current = resolve(path);; current = dirname(current)) {
196
+ try {
197
+ const stat = await lstat(current);
198
+ if (stat.isSymbolicLink() || !stat.isDirectory())
199
+ throw new HostError(`Protected Skill path crosses a symlink, junction or file: ${current}`);
200
+ }
201
+ catch (cause) {
202
+ if (!nodeError(cause, "ENOENT"))
203
+ throw cause;
204
+ }
205
+ if (current === dirname(current))
206
+ return;
207
+ }
208
+ }
209
+ function hash(bytes) {
210
+ return createHash("sha256").update(bytes).digest("hex");
211
+ }
212
+ export async function skillFingerprint(path) {
213
+ await safeAncestors(path);
214
+ try {
215
+ const stat = await lstat(path);
216
+ if (stat.isSymbolicLink() || !stat.isDirectory())
217
+ throw new HostError(`Protected Skill path is not a regular directory: ${path}`);
218
+ }
219
+ catch (cause) {
220
+ if (nodeError(cause, "ENOENT"))
221
+ return null;
222
+ throw cause;
223
+ }
224
+ const files = new Map();
225
+ let total = 0;
226
+ const visit = async (directory, prefix, depth) => {
227
+ if (depth > 64)
228
+ throw new HostError("Installed Skill exceeds depth limit.");
229
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
230
+ const name = prefix + entry.name;
231
+ if (files.size >= 4096)
232
+ throw new HostError("Installed Skill exceeds file limit.");
233
+ if (entry.isSymbolicLink())
234
+ throw new HostError(`Protected Skill contains a symlink/junction: ${join(directory, entry.name)}`);
235
+ if (entry.isDirectory()) {
236
+ files.set(`${name}/`, "directory");
237
+ await visit(join(directory, entry.name), `${name}/`, depth + 1);
238
+ }
239
+ else if (entry.isFile()) {
240
+ if ((await lstat(join(directory, entry.name))).size + total >
241
+ 64 * 1024 * 1024)
242
+ throw new HostError("Installed Skill exceeds byte limit.");
243
+ const data = await readFile(join(directory, entry.name));
244
+ total += data.length;
245
+ if (total > 64 * 1024 * 1024)
246
+ throw new HostError("Installed Skill exceeds byte limit.");
247
+ files.set(name, hash(data));
248
+ }
249
+ else
250
+ throw new HostError(`Protected Skill contains a special file: ${name}`);
251
+ }
252
+ };
253
+ await visit(path, "", 0);
254
+ return Object.fromEntries(files);
255
+ }
256
+ function equal(left, right) {
257
+ if (!left || !right)
258
+ return left === right;
259
+ const keys = Object.keys(left);
260
+ return (keys.length === Object.keys(right).length &&
261
+ keys.every((key) => left[key] === right[key]));
262
+ }
263
+ // Version-specific prediction is only for interruption/conflict checks. The
264
+ // official installer alone writes agent destinations.
265
+ async function expectedFiles(source) {
266
+ const files = (await skillFingerprint(source));
267
+ for (const path of Object.keys(files)) {
268
+ const parts = path.replace(/\/$/, "").split("/");
269
+ if (parts.some((part, index) => part === "metadata.json" ||
270
+ ((index < parts.length - 1 || path.endsWith("/")) &&
271
+ [".git", "__pycache__", "__pypackages__"].includes(part))))
272
+ delete files[path];
273
+ }
274
+ return files;
275
+ }
276
+ function recoverable(files, installation) {
277
+ const pending = installation.pending;
278
+ return Boolean(pending &&
279
+ (!files ||
280
+ Object.entries(files).every(([path, value]) => value === pending.expected[path] || value === pending.before?.[path])));
281
+ }
282
+ function targetPath(agent, identity, home) {
283
+ // Pinned v1.9.1 API exposes declared directories; these two universal agents
284
+ // explicitly opt out of global canonical reads in that exact installer.
285
+ const canonical = agent.universal && !["antigravity", "antigravity-cli"].includes(agent.id);
286
+ return join(canonical ? join(home, ".agents", "skills") : agent.globalSkillsDir, identity);
287
+ }
288
+ function locations(supported, home, identity) {
289
+ return [
290
+ ...new Map([
291
+ join(home, ".agents", "skills", identity),
292
+ ...supported
293
+ .filter((agent) => agent.globalSkillsDir)
294
+ .flatMap((agent) => [
295
+ join(agent.globalSkillsDir, identity),
296
+ targetPath(agent, identity, home),
297
+ ]),
298
+ ].map((path) => [pathKey(path), path])).values(),
299
+ ];
300
+ }
301
+ function ledgerString(value, label, maximum = 4096) {
302
+ if (typeof value !== "string" ||
303
+ !value ||
304
+ value.length > maximum ||
305
+ [...value].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127))
306
+ throw new HostError(`Invalid ${label} in Skills attribution ledger.`);
307
+ return value;
308
+ }
309
+ function ledgerStrings(value, label) {
310
+ if (!Array.isArray(value) || !value.length || value.length > 4096)
311
+ throw new HostError(`Invalid ${label} in Skills attribution ledger.`);
312
+ const values = value.map((item) => ledgerString(item, label));
313
+ if (new Set(values).size !== values.length)
314
+ throw new HostError(`Duplicate ${label} in Skills attribution ledger.`);
315
+ return values;
316
+ }
317
+ function ledgerCid(value) {
318
+ const cid = ledgerString(value, "payload CID", 128);
319
+ try {
320
+ CID.parse(cid);
321
+ }
322
+ catch {
323
+ throw new HostError("Invalid payload CID in Skills attribution ledger.");
324
+ }
325
+ return cid;
326
+ }
327
+ function ledgerFingerprint(value, label) {
328
+ const data = object(value, label);
329
+ if (Object.keys(data).length > 4096)
330
+ throw new HostError(`Oversized ${label}.`);
331
+ const entries = Object.entries(data).map(([path, digest]) => {
332
+ relativePath(path.endsWith("/") ? path.slice(0, -1) : path);
333
+ if (typeof digest !== "string" ||
334
+ (path.endsWith("/")
335
+ ? digest !== "directory"
336
+ : !/^[a-f0-9]{64}$/u.test(digest)))
337
+ throw new HostError(`Invalid ${label} entry "${path}".`);
338
+ return [path, digest];
339
+ });
340
+ const files = Object.fromEntries(entries);
341
+ for (const [path] of entries) {
342
+ const parts = path.replace(/\/$/u, "").split("/");
343
+ for (let count = 1; count < parts.length; count++)
344
+ if (files[`${parts.slice(0, count).join("/")}/`] !== "directory")
345
+ throw new HostError(`Invalid ${label} parent directory.`);
346
+ }
347
+ return files;
348
+ }
349
+ export function parseSkillsLedger(value) {
350
+ if (value === undefined)
351
+ return { v: 1, installations: {} };
352
+ const data = object(value, "Skills attribution ledger");
353
+ if (data.v !== 1)
354
+ throw new HostError("Unsupported Skills attribution ledger; preserve it before recovery.");
355
+ const installations = {};
356
+ for (const [key, value] of Object.entries(object(data.installations, "Skills installations"))) {
357
+ const item = object(value, "Skill installation");
358
+ const path = ledgerString(item.path, "installation path");
359
+ const identity = ledgerString(item.identity, "installation identity", 64);
360
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(identity) ||
361
+ !isAbsolute(path) ||
362
+ basename(path) !== identity ||
363
+ key !== pathKey(path))
364
+ throw new HostError("Invalid Skills attribution identity/path; refusing to overwrite installs.");
365
+ const installation = {
366
+ swarm: item.swarm === bundledSkillOrigin
367
+ ? bundledSkillOrigin
368
+ : swarmUrl(ledgerString(item.swarm, "Swarm URL")),
369
+ path,
370
+ identity,
371
+ name: relativePath(ledgerString(item.name, "shared Name", 256)),
372
+ cid: ledgerCid(item.cid),
373
+ agents: ledgerStrings(item.agents, "agent IDs"),
374
+ files: ledgerFingerprint(item.files, "Installed Skill fingerprint"),
375
+ };
376
+ if (installation.agents.some((agent) => !/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(agent)))
377
+ throw new HostError("Invalid agent ID in Skills attribution ledger.");
378
+ if (item.pending !== undefined) {
379
+ const pending = object(item.pending, "Pending Skill installation");
380
+ installation.pending = {
381
+ before: pending.before === null
382
+ ? null
383
+ : ledgerFingerprint(pending.before, "Previous Skill fingerprint"),
384
+ expected: ledgerFingerprint(pending.expected, "Expected Skill fingerprint"),
385
+ };
386
+ if (!/^[a-f0-9]{64}$/u.test(installation.pending.expected["SKILL.md"] ?? ""))
387
+ throw new HostError("Expected Skill fingerprint requires a regular root SKILL.md.");
388
+ }
389
+ else if (!/^[a-f0-9]{64}$/u.test(installation.files["SKILL.md"] ?? ""))
390
+ throw new HostError("Installed Skill fingerprint requires a regular root SKILL.md.");
391
+ if (item.retentions !== undefined) {
392
+ if (!Array.isArray(item.retentions))
393
+ throw new HostError("Invalid Skill Store retentions.");
394
+ const stores = new Set();
395
+ installation.retentions = item.retentions.map((value) => {
396
+ const receipt = object(value, "Skill Store retention");
397
+ const store = ledgerString(receipt.store, "Store identity", 64);
398
+ if (!/^[a-f0-9]{64}$/u.test(store) || stores.has(store))
399
+ throw new HostError("Invalid or duplicate Skill Store identity.");
400
+ stores.add(store);
401
+ return {
402
+ store,
403
+ roots: ledgerStrings(receipt.roots, "retained roots").map(ledgerCid),
404
+ };
405
+ });
406
+ }
407
+ installations[key] = installation;
408
+ }
409
+ return { v: 1, installations };
410
+ }
411
+ export async function syncDaemonSkills(context, swarm, port = officialSkillsPort, refresh = true) {
412
+ if (refresh)
413
+ await swarmHeader(context, swarm, true, "local-first");
414
+ context.forceRefresh = false;
415
+ const result = await manageSkills(context, swarm, {
416
+ sync: true,
417
+ names: [],
418
+ agents: [],
419
+ overrideExisting: false,
420
+ dryRun: false,
421
+ yes: true,
422
+ tty: false,
423
+ confirm: () => Promise.resolve(false),
424
+ preview: (text) => context.diagnostic?.(`[${swarm}] ${text}`),
425
+ }, port);
426
+ for (const entry of result.results)
427
+ context.diagnostic?.(`[${swarm}] Skill ${entry.name} (${entry.agent}): ${entry.status}${entry.error ? `: ${entry.error}` : ""}`);
428
+ if (!result.ok)
429
+ throw new HostError("Skills synchronization failed; inspect conflicts and installer diagnostics above. Existing protected installations were preserved.");
430
+ return result.items.length;
431
+ }
432
+ export async function syncDaemonSwarm(context, swarm, port = officialSkillsPort, report) {
433
+ const header = await swarmHeader(context, swarm, true, "local-first");
434
+ context.forceRefresh = false;
435
+ const headerInfo = header;
436
+ const summary = {
437
+ headCid: headerInfo.head?.root ?? null,
438
+ stateCid: headerInfo.stateCid ?? null,
439
+ skills: { status: "skipped", count: 0, error: null },
440
+ templates: { status: "skipped", count: 0, error: null },
441
+ registry: { status: "skipped", count: 0, error: null },
442
+ };
443
+ const errors = [];
444
+ for (const [label, task] of [
445
+ ["pivot-index", () => syncPivotReplicationAndIndex(context, swarm, header)],
446
+ ["skills", () => syncDaemonSkills(context, swarm, port, false)],
447
+ ["templates", () => syncSwarmTemplates(context, swarm, header)],
448
+ ["registry", () => syncSwarmRegistry(context, swarm, header)],
449
+ ]) {
450
+ try {
451
+ const count = await task();
452
+ if (label !== "pivot-index")
453
+ summary[label] = {
454
+ status: "ok",
455
+ count: typeof count === "number" ? count : 0,
456
+ error: null,
457
+ };
458
+ }
459
+ catch (cause) {
460
+ const detail = message(cause);
461
+ context.diagnostic?.(`[${swarm}] ${label} sync failed: ${detail}`);
462
+ if (label !== "pivot-index")
463
+ summary[label] = { status: "error", count: 0, error: detail };
464
+ errors.push(`${label}: ${detail}`);
465
+ }
466
+ }
467
+ report?.(summary);
468
+ if (errors.length)
469
+ throw new HostError(`Swarm sync incomplete (${errors.join("; ")}).`);
470
+ return summary;
471
+ }
472
+ function installRetention(path) {
473
+ return `skills-install:${hash(Buffer.from(pathKey(path)))}`;
474
+ }
475
+ function storeIdentity(context) {
476
+ const configuration = context.store.configuration;
477
+ return hash(Buffer.from(JSON.stringify([
478
+ pathKey(configuration.dataDir),
479
+ pathKey(configuration.coordinationDir ??
480
+ join(configuration.dataDir, "retention")),
481
+ ])));
482
+ }
483
+ function recordRetention(installation, store, roots) {
484
+ installation.retentions = [
485
+ ...(installation.retentions ?? []).filter((receipt) => receipt.store !== store),
486
+ { store, roots: [...new Set(roots)] },
487
+ ];
488
+ }
489
+ export async function inspectBundledSkill(source, port) {
490
+ const catalog = await port.catalog();
491
+ const supported = catalog.supported.filter((agent) => agent.globalSkillsDir !== null);
492
+ const agents = catalog.detected.filter((agent) => supported.some((entry) => entry.id === agent.id));
493
+ if (!agents.length)
494
+ return {
495
+ status: "not-checked",
496
+ repairable: false,
497
+ message: "No globally supported Agents detected for the bundled IPAB Skill.",
498
+ guidance: "Install an Agent, then run ipab doctor --fix.",
499
+ };
500
+ const directory = join(port.home, ".ipab", "skills");
501
+ await safeAncestors(directory);
502
+ const ledger = parseSkillsLedger(await readPrivate(directory, "installations.json", [], ledgerBytes));
503
+ const current = new Map();
504
+ const problems = [];
505
+ for (const saved of Object.values(ledger.installations))
506
+ if (saved.identity === "ipab" && saved.swarm !== bundledSkillOrigin)
507
+ problems.push(`IPAB Skill belongs to ${saved.swarm}; use skills sync for that source.`);
508
+ for (const path of locations(supported, port.home, "ipab")) {
509
+ const files = await skillFingerprint(path);
510
+ current.set(pathKey(path), files);
511
+ const saved = ledger.installations[pathKey(path)];
512
+ if (files &&
513
+ (!saved || (!equal(files, saved.files) && !recoverable(files, saved))))
514
+ problems.push(`Custom or locally edited IPAB Skill: ${path}`);
515
+ }
516
+ const targets = agents.map((agent) => {
517
+ const path = targetPath(agent, "ipab", port.home);
518
+ const saved = ledger.installations[pathKey(path)];
519
+ return {
520
+ path,
521
+ id: agent.id,
522
+ current: Boolean(current.get(pathKey(path)) &&
523
+ saved?.cid === source.cid &&
524
+ saved.agents.includes(agent.id) &&
525
+ !saved.pending),
526
+ };
527
+ });
528
+ const description = targets
529
+ .map((target) => `${target.id} (${target.path})`)
530
+ .join(", ");
531
+ return {
532
+ status: problems.length
533
+ ? "invalid"
534
+ : targets.every((target) => target.current)
535
+ ? "ok"
536
+ : "missing",
537
+ repairable: !problems.length && targets.some((target) => !target.current),
538
+ message: `Bundled IPAB Skill ${source.cid}, installer ${skillsInstaller}: ${description}.${problems.length ? ` ${problems.join(" ")}` : ""}`,
539
+ guidance: problems.length
540
+ ? "Preserve the existing installation; resolve its ownership or local edits before retrying. --yes never overrides conflicts."
541
+ : targets.every((target) => target.current)
542
+ ? ""
543
+ : "Run ipab doctor --fix to install/update the CLI-bundled Skill globally for these Agents (no Swarm required; hooks/scripts are not executed).",
544
+ };
545
+ }
546
+ export async function manageSkills(context, swarm, options, port = officialSkillsPort) {
547
+ const catalog = await port.catalog();
548
+ const supported = catalog.supported.filter((agent) => agent.globalSkillsDir !== null);
549
+ const ids = [
550
+ ...new Set(options.agents.length ? options.agents : ["universal"]),
551
+ ];
552
+ const agents = ids.map((id) => {
553
+ const agent = supported.find((agent) => agent.id === id);
554
+ if (!agent)
555
+ throw new HostError(`Agent "${id}" is not globally supported by ${skillsInstaller}.`);
556
+ return agent;
557
+ });
558
+ const parent = await privateDirectory(port.home, ".ipab");
559
+ const directory = await privateDirectory(parent, "skills");
560
+ await safeAncestors(directory);
561
+ return withPrivateLock(directory, async () => {
562
+ const ledger = parseSkillsLedger(await readPrivate(directory, "installations.json", [], ledgerBytes));
563
+ const currentStore = "bundledSkill" in context ? undefined : storeIdentity(context);
564
+ const retainInstallation = async (installation) => {
565
+ if ("bundledSkill" in context)
566
+ return;
567
+ const owner = installRetention(installation.path);
568
+ await context.store.retain(owner, [installation.cid]);
569
+ await context.store.confirmRetained(owner, [installation.cid]);
570
+ };
571
+ const commitInstallation = async (installation, files) => {
572
+ await retainInstallation(installation);
573
+ installation.files = files;
574
+ delete installation.pending;
575
+ if (currentStore)
576
+ recordRetention(installation, currentStore, [installation.cid]);
577
+ await saveLedger(directory, ledger);
578
+ if ("bundledSkill" in context)
579
+ return;
580
+ const owner = installRetention(installation.path);
581
+ await context.store.recoverOwner(owner, [installation.cid]);
582
+ await context.store.reconcile(owner, [installation.cid]);
583
+ };
584
+ const owner = `skills-discovery:${hash(Buffer.from(swarm))}`;
585
+ let staging;
586
+ try {
587
+ if (!("bundledSkill" in context))
588
+ await context.store.recoverOwner(owner, []);
589
+ const discovered = "bundledSkill" in context
590
+ ? [{ name: "ipab", identity: "ipab", cid: context.bundledSkill.cid }]
591
+ : await swarmSkills(context, swarm, options.names, owner);
592
+ const items = [];
593
+ const snapshots = new Map();
594
+ for (const skill of discovered) {
595
+ const problems = [];
596
+ const targets = new Set(agents.map((agent) => pathKey(targetPath(agent, skill.identity, port.home))));
597
+ const canOverride = (path) => options.sync &&
598
+ options.overrideExisting &&
599
+ targets.has(pathKey(path));
600
+ for (const saved of Object.values(ledger.installations).filter((entry) => entry.identity === skill.identity))
601
+ if (saved.swarm !== swarm || saved.name !== skill.name)
602
+ problems.push(`Cross-source collision with ${saved.swarm} / ${saved.name} at ${saved.path}`);
603
+ const paths = [
604
+ ...new Set([
605
+ ...locations(supported, port.home, skill.identity),
606
+ ...Object.values(ledger.installations)
607
+ .filter((entry) => entry.identity === skill.identity)
608
+ .map((entry) => entry.path),
609
+ ]),
610
+ ];
611
+ const current = new Map();
612
+ for (const path of paths) {
613
+ try {
614
+ const files = await skillFingerprint(path);
615
+ current.set(pathKey(path), files);
616
+ snapshots.set(pathKey(path), files);
617
+ const saved = ledger.installations[pathKey(path)];
618
+ if (files && !saved && !canOverride(path))
619
+ problems.push(`Non-IPAB-managed installation: ${path}`);
620
+ if (saved &&
621
+ files &&
622
+ !canOverride(path) &&
623
+ !equal(files, saved.files) &&
624
+ !recoverable(files, saved))
625
+ problems.push(`Local edits or removed managed installation: ${path}`);
626
+ }
627
+ catch (cause) {
628
+ problems.push(message(cause));
629
+ }
630
+ }
631
+ const statuses = agents.map((agent) => {
632
+ const path = targetPath(agent, skill.identity, port.home);
633
+ const saved = ledger.installations[pathKey(path)];
634
+ const files = current.get(pathKey(path)) ?? null;
635
+ return {
636
+ id: agent.id,
637
+ path,
638
+ ...(saved ? { previousCid: saved.cid } : {}),
639
+ status: !files
640
+ ? "not installed"
641
+ : canOverride(path) &&
642
+ (!saved ||
643
+ (!equal(files, saved.files) && !recoverable(files, saved)))
644
+ ? "overwrite"
645
+ : saved?.pending
646
+ ? "pending"
647
+ : saved?.cid === skill.cid && saved.agents.includes(agent.id)
648
+ ? "current"
649
+ : "update",
650
+ };
651
+ });
652
+ const own = Object.values(ledger.installations).filter((entry) => entry.swarm === swarm &&
653
+ entry.name === skill.name &&
654
+ current.get(pathKey(entry.path)) !== null);
655
+ items.push({
656
+ ...skill,
657
+ agents: statuses,
658
+ problems,
659
+ status: problems.length
660
+ ? "conflict / local edits"
661
+ : statuses.length
662
+ ? statuses.every((agent) => agent.status === "current")
663
+ ? "current"
664
+ : statuses.some((agent) => agent.status === "update" ||
665
+ agent.status === "pending" ||
666
+ agent.status === "overwrite")
667
+ ? "update"
668
+ : "not installed"
669
+ : own.length
670
+ ? own.every((entry) => entry.cid === skill.cid && !entry.pending)
671
+ ? "current"
672
+ : "update"
673
+ : "not installed",
674
+ });
675
+ }
676
+ const result = {
677
+ swarm,
678
+ installer: skillsInstaller,
679
+ agents: ids,
680
+ dryRun: options.dryRun,
681
+ items,
682
+ orphaned: Object.values(ledger.installations)
683
+ .filter((entry) => entry.swarm === swarm &&
684
+ !discovered.some((skill) => skill.name === entry.name &&
685
+ skill.identity === entry.identity))
686
+ .map((installation) => ({
687
+ ...installation,
688
+ status: "source removed",
689
+ })),
690
+ results: [],
691
+ ok: true,
692
+ };
693
+ if (!options.sync)
694
+ return result;
695
+ const selected = items.filter((skill) => !options.names.length ||
696
+ options.names.includes(skill.name) ||
697
+ options.names.includes(skill.identity));
698
+ staging = join(directory, `source-${randomUUID()}`);
699
+ await mkdir(staging, { mode: 0o700 });
700
+ const sources = new Map();
701
+ for (const skill of selected) {
702
+ const source = "bundledSkill" in context
703
+ ? await scaffoldFiles(join(staging, skill.identity), context.bundledSkill.files)
704
+ : await getBundle(context.store, skill.cid, join(staging, skill.identity));
705
+ sources.set(skill.identity, source);
706
+ for (const agent of skill.agents) {
707
+ if (agent.status === "current" || skill.problems.length)
708
+ continue;
709
+ const before = (await skillFingerprint(agent.path)) ?? {};
710
+ const after = await expectedFiles(source);
711
+ agent.changes = {
712
+ added: Object.keys(after).filter((path) => !Object.hasOwn(before, path)),
713
+ updated: Object.keys(after).filter((path) => Object.hasOwn(before, path) && before[path] !== after[path]),
714
+ removed: Object.keys(before).filter((path) => !Object.hasOwn(after, path)),
715
+ };
716
+ }
717
+ }
718
+ const changes = selected.flatMap((skill) => skill.agents
719
+ .filter((agent) => agent.status !== "current")
720
+ .map((agent) => `${skill.name} ${agent.previousCid ?? "(none)"} → ${skill.cid}: ${agent.status} → ${agent.id} (${agent.path})${agent.changes ? `\n add: ${agent.changes.added.join(", ") || "(none)"}; change: ${agent.changes.updated.join(", ") || "(none)"}; remove: ${agent.changes.removed.join(", ") || "(none)"}` : ""}`));
721
+ options.preview([
722
+ `Source ${swarm === bundledSkillOrigin ? "CLI" : "Swarm"}: ${swarm}`,
723
+ `Official installer: npx --yes --package ${skillsInstaller} skills add LOCAL --global --copy --yes --json`,
724
+ `Agents: ${ids.join(", ")}`,
725
+ ...changes,
726
+ ...selected.flatMap((skill) => skill.problems.map((problem) => `CONFLICT ${skill.name}: ${problem}`)),
727
+ "Downloaded Skill hooks/scripts are not executed. The authorized third-party installer runs with your permissions; IPAB is not a sandbox.",
728
+ ].join("\n"));
729
+ if (selected.some((skill) => skill.problems.length)) {
730
+ result.ok = false;
731
+ return result;
732
+ }
733
+ if (options.dryRun)
734
+ return result;
735
+ if (changes.length &&
736
+ !options.yes &&
737
+ (!options.tty ||
738
+ !(await options.confirm(`Authorize ${skillsInstaller} and the changes above?`))))
739
+ throw new HostError("Skill sync requires --yes or interactive consent. Use --override-existing to authorize replacing existing Skills; source and link conflicts remain protected.");
740
+ for (const skill of selected) {
741
+ const source = sources.get(skill.identity);
742
+ const targets = new Set(skill.agents.map((agent) => pathKey(agent.path)));
743
+ const canOverride = (path) => options.overrideExisting && targets.has(pathKey(path));
744
+ for (const agent of skill.agents) {
745
+ const key = pathKey(agent.path);
746
+ try {
747
+ await safeAncestors(agent.path);
748
+ let before = await skillFingerprint(agent.path);
749
+ const old = ledger.installations[key];
750
+ if (canOverride(agent.path) &&
751
+ !equal(before, snapshots.get(key) ?? null))
752
+ throw new HostError(`Installation changed since preview: ${agent.path}`);
753
+ if (agent.status === "current") {
754
+ if (!old || !before || !equal(before, old.files))
755
+ throw new HostError(`Installation changed since preview: ${agent.path}`);
756
+ await commitInstallation(old, before);
757
+ continue;
758
+ }
759
+ const expected = await expectedFiles(source);
760
+ if (old?.pending &&
761
+ equal(before, old.pending.expected) &&
762
+ old.cid === skill.cid &&
763
+ old.swarm === swarm &&
764
+ old.name === skill.name) {
765
+ old.agents = [...new Set([...old.agents, agent.id])];
766
+ await commitInstallation(old, before);
767
+ agent.status = "current";
768
+ skill.status = skill.agents.every((entry) => entry.status === "current")
769
+ ? "current"
770
+ : "update";
771
+ result.results.push({
772
+ name: skill.name,
773
+ agent: agent.id,
774
+ status: "recovered",
775
+ path: agent.path,
776
+ });
777
+ continue;
778
+ }
779
+ if (before &&
780
+ ((!old && !canOverride(agent.path)) ||
781
+ (old &&
782
+ (old.swarm !== swarm ||
783
+ old.name !== skill.name ||
784
+ (!canOverride(agent.path) &&
785
+ !equal(before, old.files) &&
786
+ !recoverable(before, old))))))
787
+ throw new HostError(`Installation changed since preview: ${agent.path}`);
788
+ // Recheck every alias/collateral location immediately before invoking
789
+ // the overwriting installer, not merely before the consent prompt.
790
+ for (const path of locations(supported, port.home, skill.identity)) {
791
+ const files = await skillFingerprint(path);
792
+ const saved = ledger.installations[pathKey(path)];
793
+ if (canOverride(path) &&
794
+ !equal(files, snapshots.get(pathKey(path)) ?? null))
795
+ throw new HostError(`Protected installation changed since preview: ${path}`);
796
+ if (files &&
797
+ ((!saved && !canOverride(path)) ||
798
+ (saved &&
799
+ (saved.swarm !== swarm ||
800
+ saved.name !== skill.name ||
801
+ (!canOverride(path) &&
802
+ !equal(files, saved.files) &&
803
+ !recoverable(files, saved))))))
804
+ throw new HostError(`Protected installation changed since preview: ${path}`);
805
+ }
806
+ before = await skillFingerprint(agent.path);
807
+ if (canOverride(agent.path) &&
808
+ !equal(before, snapshots.get(key) ?? null))
809
+ throw new HostError(`Installation changed since preview: ${agent.path}`);
810
+ const pending = {
811
+ name: skill.name,
812
+ cid: skill.cid,
813
+ identity: skill.identity,
814
+ swarm,
815
+ path: agent.path,
816
+ agents: [...new Set([...(old?.agents ?? []), agent.id])],
817
+ files: old?.files ?? {},
818
+ pending: { before, expected },
819
+ retentions: (old?.retentions ?? []).map((receipt) => ({
820
+ store: receipt.store,
821
+ roots: [...receipt.roots],
822
+ })),
823
+ };
824
+ const previousRoots = pending.retentions?.find((receipt) => receipt.store === currentStore)?.roots ?? [];
825
+ if (currentStore)
826
+ recordRetention(pending, currentStore, [
827
+ ...previousRoots,
828
+ skill.cid,
829
+ ]);
830
+ ledger.installations[key] = pending;
831
+ await retainInstallation(pending);
832
+ await saveLedger(directory, ledger);
833
+ const installed = await port.install(source, skill.identity, agent.id, context.env);
834
+ const actual = await skillFingerprint(agent.path);
835
+ if ([130, 143].includes(installed.code))
836
+ throw new HostError("Skill sync interrupted; pending attribution and source content were preserved. Retry the same sync.", installed.code, "ABORTED");
837
+ const receipts = JSON.parse(installed.stdout);
838
+ if (!Array.isArray(receipts) || receipts.length !== 1)
839
+ throw new HostError("Official installer returned an invalid receipt; pending attribution preserved.");
840
+ const receipt = object(receipts[0], "Official installer receipt");
841
+ if (installed.code !== 0 ||
842
+ receipt.status !== "installed" ||
843
+ receipt.name !== skill.identity ||
844
+ typeof receipt.path !== "string" ||
845
+ pathKey(receipt.path) !== key ||
846
+ !Array.isArray(receipt.agents) ||
847
+ !receipt.agents.includes(supported.find((entry) => entry.id === agent.id).name) ||
848
+ !actual ||
849
+ !equal(actual, expected))
850
+ throw new HostError(`Official installer did not confirm the expected installation (exit ${installed.code}). Pending attribution preserved. ${installed.stderr.slice(-1000)}`);
851
+ await commitInstallation(pending, actual);
852
+ snapshots.set(key, actual);
853
+ agent.status = "current";
854
+ skill.status = skill.agents.every((entry) => entry.status === "current")
855
+ ? "current"
856
+ : "update";
857
+ result.results.push({
858
+ name: skill.name,
859
+ agent: agent.id,
860
+ status: "installed",
861
+ path: agent.path,
862
+ });
863
+ }
864
+ catch (cause) {
865
+ result.ok = false;
866
+ agent.status = "failed";
867
+ skill.status = skill.agents.some((entry) => entry.status === "current")
868
+ ? "partial / failed"
869
+ : "failed";
870
+ result.results.push({
871
+ name: skill.name,
872
+ agent: agent.id,
873
+ status: "failed",
874
+ path: agent.path,
875
+ error: message(cause),
876
+ });
877
+ if (cause instanceof HostError && cause.code === "ABORTED")
878
+ return result;
879
+ }
880
+ }
881
+ }
882
+ return result;
883
+ }
884
+ finally {
885
+ if (staging)
886
+ await rm(staging, { recursive: true, force: true });
887
+ if (!("bundledSkill" in context)) {
888
+ await context.store.recoverOwner(owner, []);
889
+ await context.store.reconcile(owner, []);
890
+ }
891
+ }
892
+ });
893
+ }
894
+ //# sourceMappingURL=skills.js.map