@jini-ai/agent-plugins 0.7.3-next.2 → 0.7.4

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 (234) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +22 -4
  3. package/calendly/README.md +29 -0
  4. package/calendly/mcp.json +1 -1
  5. package/cloudflare/lib/assets.mjs +1 -1
  6. package/cloudflare/lib/cms-forms.mjs +1 -1
  7. package/core/persistent-state.d.ts +4 -1
  8. package/core/persistent-state.js +55 -21
  9. package/dist/admin-surfaces/callback-field-inbox.d.ts +1 -6
  10. package/dist/admin-surfaces/connections/connections.d.ts +2 -6
  11. package/dist/admin-surfaces/connections/index.d.ts +3 -2
  12. package/dist/admin-surfaces/index.d.ts +3 -1
  13. package/dist/connect/access-token-tool.d.ts +1 -1
  14. package/dist/connect/access-token-tool.js +1 -1
  15. package/dist/connect/catalog.d.ts +26 -0
  16. package/dist/connect/catalog.js +42 -0
  17. package/dist/connect/connect-tool.d.ts +2 -294
  18. package/dist/connect/connect-tool.js +2 -53
  19. package/dist/connect/contracts.d.ts +257 -0
  20. package/dist/connect/contracts.js +2 -0
  21. package/dist/connect/credential-cards.d.ts +2 -0
  22. package/dist/connect/credential-cards.js +7 -4
  23. package/dist/connect/credential-save-tool.js +2 -3
  24. package/dist/connect/grant-signed-in-defaults.js +1 -1
  25. package/dist/connect/host-deps.d.ts +32 -0
  26. package/dist/connect/host-deps.js +35 -0
  27. package/dist/connect/import-access-token.js +1 -1
  28. package/dist/connect/index.d.ts +7 -2
  29. package/dist/connect/index.js +5 -2
  30. package/dist/connect/installed-plugin.d.ts +28 -0
  31. package/dist/connect/installed-plugin.js +19 -0
  32. package/dist/connect/new-site-agent-plugin-tokens.d.ts +88 -0
  33. package/dist/connect/new-site-agent-plugin-tokens.js +107 -0
  34. package/dist/connect/plugin-host/index.d.ts +1 -2
  35. package/dist/connect/plugin-host/index.js +18 -9
  36. package/dist/connect/token-sign-in.d.ts +1 -14
  37. package/dist/connect/token-sign-in.js +4 -23
  38. package/dist/core/export-props.d.ts +10 -0
  39. package/dist/core/export-props.js +31 -0
  40. package/dist/core/folder-zip-error.d.ts +5 -0
  41. package/dist/core/folder-zip-error.js +8 -0
  42. package/dist/core/host-incompatible-error.d.ts +8 -0
  43. package/dist/core/host-incompatible-error.js +9 -0
  44. package/dist/core/identity-namespace.d.ts +27 -16
  45. package/dist/core/identity-namespace.js +25 -22
  46. package/dist/core/plugin-display-name.d.ts +7 -0
  47. package/dist/core/plugin-display-name.js +11 -0
  48. package/dist/core/provider-plugin-link.d.ts +7 -0
  49. package/dist/core/provider-plugin-link.js +5 -0
  50. package/dist/{connect → core}/token-map.d.ts +11 -1
  51. package/dist/{connect → core}/token-map.js +15 -0
  52. package/dist/core/token-sign-in-list.d.ts +18 -0
  53. package/dist/core/token-sign-in-list.js +23 -0
  54. package/dist/core/update-error.d.ts +8 -0
  55. package/dist/core/update-error.js +9 -0
  56. package/dist/{lifecycle → core}/update-plan.d.ts +1 -1
  57. package/dist/ffmpeg-transcode/adapter.d.ts +74 -0
  58. package/dist/ffmpeg-transcode/adapter.js +155 -0
  59. package/dist/folder-zip-node.d.ts +2 -1
  60. package/dist/folder-zip-node.js +6 -5
  61. package/dist/folder-zip.d.ts +0 -4
  62. package/dist/folder-zip.js +1 -7
  63. package/dist/index.d.ts +3 -1
  64. package/dist/lifecycle/activation.d.ts +39 -3
  65. package/dist/lifecycle/activation.js +467 -418
  66. package/dist/lifecycle/automatic-use-offer.d.ts +62 -0
  67. package/dist/lifecycle/automatic-use-offer.js +52 -0
  68. package/dist/lifecycle/automatic-use.d.ts +33 -1
  69. package/dist/lifecycle/automatic-use.js +159 -38
  70. package/dist/lifecycle/bundled-source-archive.d.ts +1 -1
  71. package/dist/lifecycle/capability-projection.d.ts +0 -1
  72. package/dist/lifecycle/capability-projection.js +92 -23
  73. package/dist/lifecycle/compatibility-metadata.d.ts +1 -0
  74. package/dist/lifecycle/compatibility-metadata.js +6 -1
  75. package/dist/lifecycle/compatibility.d.ts +1 -8
  76. package/dist/lifecycle/compatibility.js +1 -8
  77. package/dist/lifecycle/credential-card-metadata.d.ts +2 -2
  78. package/dist/lifecycle/exports.d.ts +2 -45
  79. package/dist/lifecycle/exports.js +1 -30
  80. package/dist/lifecycle/host-tools/identity.d.ts +5 -4
  81. package/dist/lifecycle/host-tools/identity.js +5 -5
  82. package/dist/lifecycle/host-tools/ports.d.ts +10 -1
  83. package/dist/lifecycle/host-tools/search-tool.js +18 -8
  84. package/dist/lifecycle/host-tools/skill-tool.js +1 -1
  85. package/dist/lifecycle/index.d.ts +20 -17
  86. package/dist/lifecycle/index.js +5 -4
  87. package/dist/lifecycle/install-from-url.d.ts +1 -2
  88. package/dist/lifecycle/install.d.ts +4 -34
  89. package/dist/lifecycle/install.js +3 -3
  90. package/dist/lifecycle/installed-package-index.d.ts +1 -1
  91. package/dist/lifecycle/installed-package-index.js +4 -4
  92. package/dist/lifecycle/layout.d.ts +21 -25
  93. package/dist/lifecycle/layout.js +79 -0
  94. package/dist/lifecycle/manifest.d.ts +10 -7
  95. package/dist/lifecycle/manifest.js +20 -15
  96. package/dist/lifecycle/mcp-provisioning.d.ts +1 -1
  97. package/dist/lifecycle/metadata.d.ts +6 -3
  98. package/dist/lifecycle/metadata.js +2 -1
  99. package/dist/lifecycle/package-paths.js +59 -56
  100. package/dist/lifecycle/persistent-state.d.ts +10 -1
  101. package/dist/lifecycle/persistent-state.js +4 -2
  102. package/dist/lifecycle/ports.d.ts +18 -6
  103. package/dist/lifecycle/resolve-agent-plugin-refs.d.ts +2 -14
  104. package/dist/lifecycle/retire-bundled.d.ts +1 -1
  105. package/dist/lifecycle/search-projection.d.ts +17 -3
  106. package/dist/lifecycle/search-projection.js +8 -8
  107. package/dist/lifecycle/search.d.ts +1 -0
  108. package/dist/lifecycle/search.js +2 -2
  109. package/dist/lifecycle/seed-bundled.d.ts +86 -1
  110. package/dist/lifecycle/seed-bundled.js +48 -84
  111. package/dist/lifecycle/set-enabled.d.ts +1 -13
  112. package/dist/lifecycle/set-enabled.js +11 -7
  113. package/dist/lifecycle/trusted-plugin-files.d.ts +1 -1
  114. package/dist/lifecycle/trusted-plugin-files.js +33 -30
  115. package/dist/lifecycle/types.d.ts +13 -34
  116. package/dist/lifecycle/uninstall.d.ts +1 -33
  117. package/dist/lifecycle/update-store.d.ts +0 -7
  118. package/dist/lifecycle/update-store.js +1 -8
  119. package/dist/lifecycle/update.d.ts +1 -1
  120. package/dist/lifecycle/update.js +60 -10
  121. package/dist/lifecycle/yauzl-archive-reader.d.ts +7 -2
  122. package/dist/lifecycle/yauzl-archive-reader.js +11 -6
  123. package/dist/manifest.d.ts +4 -8
  124. package/dist/react/AgentPluginDetailsModal.d.ts +187 -0
  125. package/dist/react/AgentPluginDetailsModal.js +29 -0
  126. package/dist/react/agent-plugin-install-port.d.ts +24 -0
  127. package/dist/react/agent-plugin-install-port.js +15 -0
  128. package/dist/react/installed-skills-composer-source.d.ts +60 -0
  129. package/dist/react/installed-skills-composer-source.js +111 -0
  130. package/dist/react/use-agent-plugins.hooks.d.ts +211 -0
  131. package/dist/react/use-agent-plugins.hooks.js +128 -0
  132. package/dist/site/activation-effects.d.ts +17 -0
  133. package/dist/site/activation-effects.js +31 -0
  134. package/dist/site/admin-surfaces/capabilities.d.ts +29 -0
  135. package/dist/site/admin-surfaces/capabilities.js +30 -0
  136. package/dist/site/admin-surfaces/delivery-bindings.d.ts +81 -0
  137. package/dist/site/admin-surfaces/delivery-bindings.js +161 -0
  138. package/dist/site/admin-surfaces/forms.d.ts +28 -0
  139. package/dist/site/admin-surfaces/forms.js +29 -0
  140. package/dist/site/admin-surfaces/handlers.d.ts +61 -0
  141. package/dist/site/admin-surfaces/handlers.js +35 -0
  142. package/dist/site/admin-surfaces/public-config.d.ts +12 -0
  143. package/dist/site/admin-surfaces/public-config.js +28 -0
  144. package/dist/site/analytics-provider-registry.d.ts +87 -0
  145. package/dist/site/analytics-provider-registry.js +87 -0
  146. package/dist/site/archive-reader-abi.d.ts +35 -0
  147. package/dist/site/archive-reader-abi.js +25 -0
  148. package/dist/site/auth-schemes.d.ts +110 -0
  149. package/dist/site/auth-schemes.js +119 -0
  150. package/dist/site/automatic-agent-plugins.d.ts +200 -0
  151. package/dist/site/automatic-agent-plugins.js +277 -0
  152. package/dist/site/bundled-contribution-sources.d.ts +24 -0
  153. package/dist/site/bundled-contribution-sources.js +17 -0
  154. package/dist/site/bundled-id-upgrade.d.ts +115 -0
  155. package/dist/site/bundled-id-upgrade.js +169 -0
  156. package/dist/site/customize-tool.d.ts +39 -0
  157. package/dist/site/customize-tool.js +31 -0
  158. package/dist/site/deploy-split-activation.d.ts +28 -0
  159. package/dist/site/deploy-split-activation.js +21 -0
  160. package/dist/site/exports/diagnostics.d.ts +37 -0
  161. package/dist/site/exports/diagnostics.js +55 -0
  162. package/dist/site/exports/runtime.d.ts +54 -0
  163. package/dist/site/exports/runtime.js +196 -0
  164. package/dist/site/exports/source.d.ts +42 -0
  165. package/dist/site/exports/source.js +58 -0
  166. package/dist/site/host-plugin-guidance.d.ts +137 -0
  167. package/dist/site/host-plugin-guidance.js +223 -0
  168. package/dist/site/host-signals.d.ts +78 -0
  169. package/dist/site/host-signals.js +83 -0
  170. package/dist/site/install-tool.d.ts +69 -0
  171. package/dist/site/install-tool.js +192 -0
  172. package/dist/site/install-upload.d.ts +175 -0
  173. package/dist/site/install-upload.js +324 -0
  174. package/dist/site/memory-i18n.d.ts +5 -0
  175. package/dist/site/memory-i18n.js +176 -0
  176. package/dist/site/memory.d.ts +80 -0
  177. package/dist/site/memory.js +83 -0
  178. package/dist/site/plugin-memory.d.ts +80 -0
  179. package/dist/site/plugin-memory.js +86 -0
  180. package/dist/site/provider-plugin-link.d.ts +112 -0
  181. package/dist/site/provider-plugin-link.js +100 -0
  182. package/dist/site/retired-plugin-tool-aliases.d.ts +40 -0
  183. package/dist/site/retired-plugin-tool-aliases.js +41 -0
  184. package/dist/site/service-ports.d.ts +108 -0
  185. package/dist/site/service-ports.js +2 -0
  186. package/dist/site/set-enabled.d.ts +80 -0
  187. package/dist/site/set-enabled.js +42 -0
  188. package/dist/site/soon-lock.d.ts +83 -0
  189. package/dist/site/soon-lock.js +78 -0
  190. package/dist/site/supersession.d.ts +61 -0
  191. package/dist/site/supersession.js +122 -0
  192. package/dist/site/uninstall-tool.d.ts +136 -0
  193. package/dist/site/uninstall-tool.js +203 -0
  194. package/dist/site/update-effects.d.ts +47 -0
  195. package/dist/site/update-effects.js +49 -0
  196. package/ffmpeg-transcode/plugin.json +16 -0
  197. package/github/source-control/backup-push.mjs +66 -46
  198. package/github/source-control/commit-site.mjs +112 -65
  199. package/github/source-control/write-files.mjs +86 -53
  200. package/github-pages/targets/github-pages.mjs +294 -233
  201. package/google-workspace/form-destinations/mapping.mjs +15 -7
  202. package/google-workspace/form-destinations/sheets.mjs +4 -2
  203. package/google-workspace/plugin.json +1 -0
  204. package/kuinetic/CHANGELOG.md +4 -0
  205. package/kuinetic/plugin.json +4 -1
  206. package/kuinetic/skills/kuinetic/SKILL.md +1 -2
  207. package/package.json +295 -18
  208. package/persistent-state.d.ts +4 -1
  209. package/resend/adapters/resend.mjs +5 -2
  210. package/resend/plugin.json +1 -1
  211. package/s3-compatible/jini-deploy-targets.json +1 -1
  212. package/s3-compatible/object-stores/s3-compatible.mjs +27 -4
  213. package/s3-compatible/targets/s3-compatible.mjs +3 -3
  214. package/site-import/plugin.json +3 -3
  215. package/site-import/skills/site-import/SKILL.md +62 -54
  216. package/site-import/skills/site-import/references/content-mapping.md +26 -20
  217. package/slide-design/plugin.json +1 -1
  218. package/slide-design/skills/slide-design/SKILL.md +8 -2
  219. package/ui-ux-design/CHANGELOG.md +6 -0
  220. package/ui-ux-design/plugin.json +1 -1
  221. package/ui-ux-design/skills/gstack-design/SKILL.md +6 -6
  222. package/ui-ux-design/skills/ui-ux-design/SKILL.md +3 -2
  223. package/ui-ux-design/skills/ui-ux-design/references/chrome-mobile-test-matrix.md +14 -12
  224. package/ui-ux-design/skills/ui-ux-design/references/ui-loop.md +16 -17
  225. package/vercel/NOTES.md +2 -1
  226. package/vercel/object-stores/vercel-blob.mjs +3 -4
  227. package/vercel/targets/vercel.mjs +425 -351
  228. package/core/commerce-server.d.ts +0 -2
  229. package/core/commerce-server.mjs +0 -2
  230. package/dist/admin-surfaces/connections/ports.d.ts +0 -110
  231. package/dist/admin-surfaces/connections/ports.js +0 -2
  232. /package/dist/{lifecycle → core}/install-errors.d.ts +0 -0
  233. /package/dist/{lifecycle → core}/install-errors.js +0 -0
  234. /package/dist/{lifecycle → core}/update-plan.js +0 -0
@@ -100,78 +100,199 @@ export class AgentPluginActivationsBusyError extends Error {
100
100
  this.name = "AgentPluginActivationsBusyError";
101
101
  }
102
102
  }
103
- function buildModule(ports) {
104
- const randomUUID = () => ports.ids.newId();
105
- const mkdir = ports.filesystem.mkdir.bind(ports.filesystem);
106
- const open = ports.filesystem.open.bind(ports.filesystem);
107
- const readFile = ports.filesystem.readFile.bind(ports.filesystem);
108
- const rename = ports.filesystem.rename.bind(ports.filesystem);
109
- const rm = ports.filesystem.rm.bind(ports.filesystem);
110
- const EMPTY_ACTIVATIONS = { schemaVersion: 1, plugins: {} };
111
- /**
112
- * Same grammar `layout.ts` guards path segments with — an id that reaches this module is used as
113
- * an object key, not a path, but validating in both places keeps a future caller from being the
114
- * first one to find out the two disagreed.
115
- */
116
- const SAFE_PLUGIN_ID_PATTERN = /^[a-z0-9]+(?:[-.][a-z0-9]+)*$/;
117
- /**
118
- * Whether a plugin may be discovered, registered as a tool, or injected into a run.
119
- *
120
- * @param activations - This workspace's record, as returned by {@link readAgentPluginActivations}.
121
- * @param pluginId - The plugin's manifest `name`.
122
- * @returns `false` only when an explicit record says `enabled: false`. See this file's header for
123
- * why an absent record means active.
124
- * @complexity O(1).
125
- *
126
- * `Object.hasOwn`, not a plain lookup: `activations.plugins` comes straight from `JSON.parse` (via
127
- * `normalizeActivations`), so it still carries `Object.prototype`, and an id like `constructor` or
128
- * `hasownproperty` passes the plugin-name grammar and would otherwise resolve to an inherited
129
- * value rather than a missing entry — see `resolveAgentPluginActivation`'s identical guard.
130
- */
131
- function isAgentPluginActive(activations, pluginId) {
132
- if (!Object.hasOwn(activations.plugins, pluginId))
133
- return true;
134
- return activations.plugins[pluginId].enabled;
135
- }
136
- /**
137
- * Filters any list of plugin-shaped values down to the ones this workspace has active.
138
- *
139
- * Takes the id accessor rather than a concrete type so the three gate sites — which hold
140
- * `InstalledAgentPlugin`s, `AgentPluginToolSource`s, and capability cards respectively — all share
141
- * one implementation of the rule instead of three `filter` calls that could drift apart on what
142
- * "active" means.
143
- *
144
- * @complexity O(n) in the list length.
145
- */
146
- function filterActiveAgentPlugins(activations, items, pluginIdOf) {
147
- return items.filter((item) => isAgentPluginActive(activations, pluginIdOf(item)));
148
- }
103
+ const EMPTY_ACTIVATIONS = { schemaVersion: 1, plugins: {} };
104
+ /**
105
+ * Same grammar `layout.ts` guards path segments with — an id that reaches this module is used as
106
+ * an object key, not a path, but validating in both places keeps a future caller from being the
107
+ * first one to find out the two disagreed.
108
+ */
109
+ const SAFE_PLUGIN_ID_PATTERN = /^[a-z0-9]+(?:[-.][a-z0-9]+)*$/;
110
+ /**
111
+ * Whether a plugin may be discovered, registered as a tool, or injected into a run.
112
+ *
113
+ * @param activations - This workspace's record, as returned by {@link readAgentPluginActivations}.
114
+ * @param pluginId - The plugin's manifest `name`.
115
+ * @returns `false` only when an explicit record says `enabled: false`. See this file's header for
116
+ * why an absent record means active.
117
+ * @complexity O(1).
118
+ *
119
+ * `Object.hasOwn`, not a plain lookup: `activations.plugins` comes straight from `JSON.parse` (via
120
+ * `normalizeActivations`), so it still carries `Object.prototype`, and an id like `constructor` or
121
+ * `hasownproperty` passes the plugin-name grammar and would otherwise resolve to an inherited
122
+ * value rather than a missing entry — see `resolveAgentPluginActivation`'s identical guard.
123
+ */
124
+ function isAgentPluginActive(activations, pluginId) {
125
+ if (!Object.hasOwn(activations.plugins, pluginId))
126
+ return true;
127
+ return activations.plugins[pluginId].enabled;
128
+ }
129
+ /**
130
+ * Filters any list of plugin-shaped values down to the ones this workspace has active.
131
+ *
132
+ * Takes the id accessor rather than a concrete type so the three gate sites — which hold
133
+ * `InstalledAgentPlugin`s, `AgentPluginToolSource`s, and capability cards respectively — all share
134
+ * one implementation of the rule instead of three `filter` calls that could drift apart on what
135
+ * "active" means.
136
+ *
137
+ * @complexity O(n) in the list length.
138
+ */
139
+ function filterActiveAgentPlugins(activations, items, pluginIdOf) {
140
+ return items.filter((item) => isAgentPluginActive(activations, pluginIdOf(item)));
141
+ }
142
+ function errorCode(error) {
143
+ if (typeof error !== "object" || error === null || !("code" in error))
144
+ return undefined;
145
+ const code = error.code;
146
+ return typeof code === "string" ? code : undefined;
147
+ }
148
+ /**
149
+ * A short, log-safe rendering of a thrown value. Carries the error's own message (which for a
150
+ * filesystem fault names this workspace's own path — a host path, so a caller that surfaces this
151
+ * must keep it in a server-side log and out of any model- or user-facing payload).
152
+ */
153
+ function describeError(error) {
154
+ return error instanceof Error ? error.message : String(error);
155
+ }
156
+ /**
157
+ * Turns a lock failure from {@link withExclusiveFileLock} into {@link AgentPluginActivationsBusyError};
158
+ * any other error (including a thrown {@link AgentPluginActivationsUnreadableError} from the read
159
+ * inside the callback) passes through unchanged. @complexity O(1).
160
+ */
161
+ function toActivationsBusyError(lockPath, error) {
162
+ if (error instanceof FileLockTimeoutError)
163
+ return new AgentPluginActivationsBusyError({ lockPath: lockPath, holder: error.holder, lost: false });
164
+ if (error instanceof FileLockLostError)
165
+ return new AgentPluginActivationsBusyError({ lockPath: lockPath, holder: undefined, lost: true });
166
+ return error;
167
+ }
168
+ /**
169
+ * Whether the RAW entry for `pluginId` records `origin: "bundled"` — read raw so a malformed
170
+ * entry's provenance still survives a toggle. `Object.hasOwn`, not a plain lookup, for the same
171
+ * `Object.prototype` reason {@link resolveAgentPluginActivation} uses it. @complexity O(1).
172
+ */
173
+ function isRecordedAsBundled(bag, pluginId) {
174
+ if (!Object.hasOwn(bag, pluginId))
175
+ return false;
176
+ const entry = bag[pluginId];
177
+ return isPlainObject(entry) && entry.origin === "bundled";
178
+ }
179
+ /**
180
+ * Whether `value` is a plain (non-null, non-array) object — the shape every one of this file's
181
+ * JSON-adjacent values (the activations envelope, and each individual plugin entry) must have
182
+ * before its own fields are worth looking at.
183
+ */
184
+ function isPlainObject(value) {
185
+ return typeof value === "object" && value !== null && !Array.isArray(value);
186
+ }
187
+ /**
188
+ * The `plugins` bag out of an already-`JSON.parse`d activations value, or `undefined` when the
189
+ * top-level envelope doesn't match this schema version at all (wrong shape, wrong
190
+ * `schemaVersion`, or a non-object `plugins`) — collapsing the three top-level shape gates
191
+ * {@link normalizeActivations} used to inline into one lookup its loop can build on.
192
+ */
193
+ function extractPluginsBag(value) {
194
+ if (!isPlainObject(value) || value.schemaVersion !== 1 || !isPlainObject(value.plugins))
195
+ return undefined;
196
+ return value.plugins;
197
+ }
198
+ /**
199
+ * Fills in an activation record's optional fields from a (validated-boolean-`enabled`) raw entry.
200
+ * Pure defaulting: no field here can fail validation, only fall back to a safe default — matching
201
+ * the file's own "fail-OPEN per malformed field, never per entry" discipline (see this file's
202
+ * header).
203
+ */
204
+ function withActivationDefaults(record, enabled) {
205
+ return {
206
+ enabled,
207
+ origin: record.origin === "bundled" ? "bundled" : "operator-installed",
208
+ updatedAt: typeof record.updatedAt === "string" ? record.updatedAt : new Date(0).toISOString(),
209
+ updatedBy: typeof record.updatedBy === "string" ? record.updatedBy : "unknown",
210
+ };
211
+ }
212
+ /**
213
+ * One `plugins` entry, normalized — or `undefined` when it does not match the shape (bad plugin
214
+ * id, non-object entry, or a non-boolean `enabled`), so {@link normalizeActivations}'s loop stays a
215
+ * simple accumulate-or-skip.
216
+ */
217
+ function normalizeActivationEntry(pluginId, entry) {
218
+ if (!SAFE_PLUGIN_ID_PATTERN.test(pluginId))
219
+ return undefined;
220
+ const record = isPlainObject(entry) ? entry : undefined;
221
+ if (record === undefined || typeof record.enabled !== "boolean")
222
+ return undefined;
223
+ return withActivationDefaults(record, record.enabled);
224
+ }
225
+ /**
226
+ * Validates an already-`JSON.parse`d activations value, dropping anything that does not match the
227
+ * shape. Pure, so the parsing rules are assertable without touching a filesystem.
228
+ *
229
+ * Per-entry rather than all-or-nothing: one malformed entry must not discard the operator's other,
230
+ * perfectly good decisions.
231
+ *
232
+ * @complexity O(p) in the entry count.
233
+ */
234
+ function normalizeActivations(value) {
149
235
  /**
150
- * Reads one workspace's activation record.
151
- *
152
- * @param workspaceRoot - `AgentPluginWorkspaceLayout.root`, never an instance-level path.
153
- * @returns The parsed record, or an empty one when the file does not exist yet — which is the
154
- * normal state for a workspace that has never installed or been seeded anything.
155
- * @throws Nothing for a missing, unreadable, malformed, or wrong-version file: all of those return
156
- * an empty record. That is fail-OPEN, and it is the correct direction here specifically because this
157
- * reader is used for DISCOVERY only — nothing that SPENDS a capability or WRITES the file uses it
158
- * — the per-call tool gate and run-start injection both use the
159
- * fail-CLOSED {@link resolveAgentPluginActivation}, and every writer below reads the strict raw bag
160
- * and refuses outright on an unreadable file (see this file's header, "Writers never rewrite what
161
- * they could not read").
162
- * @complexity O(p) in the recorded plugin count.
236
+ * Provenance is a fact about how the package arrived, not about this decision (comment kept
237
+ * from the pre-F1.1 version): an existing value is preserved rather than overwritten by a
238
+ * toggle. Read raw (`isRecordedAsBundled`), not through normalization, so a malformed sibling
239
+ * entry does not lose its own provenance either.
163
240
  */
164
- async function readAgentPluginActivations(workspaceRoot) {
165
- /**
166
- * `Object.hasOwn`, not a plain lookup: the bag comes straight from `JSON.parse`, so it still
167
- * carries `Object.prototype`, and several ids that pass the name grammar (`constructor`,
168
- * `toString`, ...) would otherwise resolve to an inherited function rather than a missing entry.
169
- */
170
- const document = await readActivationsDocument(workspaceRoot);
171
- return document.kind === "entries" ? normalizePluginsBag(document.entries) : EMPTY_ACTIVATIONS;
241
+ const plugins = extractPluginsBag(value);
242
+ if (plugins === undefined)
243
+ return EMPTY_ACTIVATIONS;
244
+ return normalizePluginsBag(plugins);
245
+ }
246
+ /**
247
+ * The per-entry accumulate-or-skip loop itself, split out of {@link normalizeActivations} so
248
+ * {@link readAgentPluginActivations} can run it over an ALREADY shape-checked bag rather than
249
+ * re-deriving one — one implementation of "which entries survive", not two.
250
+ *
251
+ * @complexity O(p) in the entry count.
252
+ */
253
+ function normalizePluginsBag(plugins) {
254
+ const normalized = {};
255
+ for (const [pluginId, entry] of Object.entries(plugins)) {
256
+ const record = normalizeActivationEntry(pluginId, entry);
257
+ if (record !== undefined)
258
+ normalized[pluginId] = record;
259
+ }
260
+ return { schemaVersion: 1, plugins: normalized };
261
+ }
262
+ /**
263
+ * Refuse a malformed target entry rather than guessing operator-installed origin. Guessing would
264
+ * defeat bundled uninstall refusal and make seeding confuse a fabricated record with consent.
265
+ * An undetermined entry stays intact. recordBundledAgentPluginIfAbsent reaches this writer only
266
+ * when the target key is genuinely absent, so it does not repair a malformed decision either.
267
+ * @throws {AgentPluginActivationsUnreadableError} The target entry exists but cannot normalize.
268
+ * @complexity O(1).
269
+ */
270
+ function assertTargetEntryReadable(workspaceRoot, current, pluginId) {
271
+ if (!Object.hasOwn(current, pluginId))
272
+ return;
273
+ if (normalizeActivationEntry(pluginId, current[pluginId]) !== undefined)
274
+ return;
275
+ throw new AgentPluginActivationsUnreadableError({ filePath: path.join(workspaceRoot, ACTIVATIONS_FILENAME), reason: `${ACTIVATIONS_FILENAME} holds an unreadable record for '${pluginId}', so it cannot be safely toggled` });
276
+ }
277
+ /**
278
+ * `updatedBy` of every record the boot seeder writes.
279
+ */
280
+ const SEED_ACTOR = "system:seed";
281
+ /**
282
+ * Whether a RAW entry is the seeder's own disabled record that no operator has touched since.
283
+ * @complexity O(1).
284
+ */
285
+ function isUntouchedDisabledSeed(entry) {
286
+ return isPlainObject(entry) && entry.enabled === false && entry.updatedBy === SEED_ACTOR;
287
+ }
288
+ function assertPluginId(pluginId) {
289
+ if (!SAFE_PLUGIN_ID_PATTERN.test(pluginId) || pluginId.length > 64) {
290
+ throw new Error(`agent-plugin activation: '${pluginId}' is not a valid Agent Plugin id`);
172
291
  }
292
+ }
293
+ function createActivationsDocumentReader(readFile) {
173
294
  /**
174
- * Reads and shape-checks the activations file once, for BOTH readers above and below — so the
295
+ * Reads and shape-checks the activations file once, for both the lenient and strict readers — so the
175
296
  * lenient and the strict view can never drift apart on what parses, only on what they do about a
176
297
  * fault.
177
298
  *
@@ -181,7 +302,7 @@ function buildModule(ports) {
181
302
  * state, not a fault. Anything else (EACCES, ENOTDIR, EIO, EMFILE, ...) is a real failure to
182
303
  * read a file that may well hold a decision.
183
304
  */
184
- async function readActivationsDocument(workspaceRoot) {
305
+ return async function readActivationsDocument(workspaceRoot) {
185
306
  let raw;
186
307
  try {
187
308
  raw = await readFile(path.join(workspaceRoot, ACTIVATIONS_FILENAME), "utf8");
@@ -203,41 +324,39 @@ function buildModule(ports) {
203
324
  return { kind: "unreadable", reason: `${ACTIVATIONS_FILENAME} is not a schemaVersion 1 activations document` };
204
325
  }
205
326
  return { kind: "entries", entries };
206
- }
207
- function errorCode(error) {
208
- if (typeof error !== "object" || error === null || !("code" in error))
209
- return undefined;
210
- const code = error.code;
211
- return typeof code === "string" ? code : undefined;
212
- }
213
- /**
214
- * A short, log-safe rendering of a thrown value. Carries the error's own message (which for a
215
- * filesystem fault names this workspace's own path — a host path, so a caller that surfaces this
216
- * must keep it in a server-side log and out of any model- or user-facing payload).
217
- */
218
- function describeError(error) {
219
- return error instanceof Error ? error.message : String(error);
220
- }
221
- /**
222
- * Turns a lock failure from {@link withExclusiveFileLock} into {@link AgentPluginActivationsBusyError};
223
- * any other error (including a thrown {@link AgentPluginActivationsUnreadableError} from the read
224
- * inside the callback) passes through unchanged. @complexity O(1).
225
- */
226
- function toActivationsBusyError(lockPath, error) {
227
- if (error instanceof FileLockTimeoutError)
228
- return new AgentPluginActivationsBusyError({ lockPath: lockPath, holder: error.holder, lost: false });
229
- if (error instanceof FileLockLostError)
230
- return new AgentPluginActivationsBusyError({ lockPath: lockPath, holder: undefined, lost: true });
231
- return error;
232
- }
327
+ };
328
+ }
329
+ /**
330
+ * Read phase: the lenient discovery read and the strict reads every writer and the tool gate use,
331
+ * all over one shape-checked document read. No lock is taken here; writers call the strict read
332
+ * only inside their own locked turn.
333
+ */
334
+ function createActivationReads(args, _optional = {}) {
335
+ const { ports } = args;
336
+ const readActivationsDocument = createActivationsDocumentReader(ports.filesystem.readFile.bind(ports.filesystem));
233
337
  /**
234
- * Logs a stale lock's removal — server-side only, since the path and pid are host detail.
235
- * @complexity O(1).
338
+ * Reads one workspace's activation record.
339
+ *
340
+ * @param workspaceRoot - `AgentPluginWorkspaceLayout.root`, never an instance-level path.
341
+ * @returns The parsed record, or an empty one when the file does not exist yet — which is the
342
+ * normal state for a workspace that has never installed or been seeded anything.
343
+ * @throws Nothing for a missing, unreadable, malformed, or wrong-version file: all of those return
344
+ * an empty record. That is fail-OPEN, and it is the correct direction here specifically because this
345
+ * reader is used for DISCOVERY only — nothing that SPENDS a capability or WRITES the file uses it
346
+ * — the per-call tool gate and run-start injection both use the
347
+ * fail-CLOSED {@link resolveAgentPluginActivation}, and every writer below reads the strict raw bag
348
+ * and refuses outright on an unreadable file (see this file's header, "Writers never rewrite what
349
+ * they could not read").
350
+ * @complexity O(p) in the recorded plugin count.
236
351
  */
237
- function warnStaleActivationsLockRemoved(lockPath, holder) {
238
- ports.onEvent?.({ event: "stale-activation-lock-removed", message: (holder !== undefined
239
- ? `[agent-plugins] removed a stale activations.json lock left by pid ${holder.pid} on ${holder.hostname} (acquired ${holder.acquiredAt}): ${lockPath}`
240
- : `[agent-plugins] removed a stale activations.json lock with an unreadable holder: ${lockPath}`) });
352
+ async function readAgentPluginActivations(workspaceRoot) {
353
+ /**
354
+ * `Object.hasOwn`, not a plain lookup: the bag comes straight from `JSON.parse`, so it still
355
+ * carries `Object.prototype`, and several ids that pass the name grammar (`constructor`,
356
+ * `toString`, ...) would otherwise resolve to an inherited function rather than a missing entry.
357
+ */
358
+ const document = await readActivationsDocument(workspaceRoot);
359
+ return document.kind === "entries" ? normalizePluginsBag(document.entries) : EMPTY_ACTIVATIONS;
241
360
  }
242
361
  /**
243
362
  * The strict read every writer uses: `absent` (no file yet) is an empty bag, same as
@@ -254,33 +373,6 @@ function buildModule(ports) {
254
373
  }
255
374
  return document.kind === "entries" ? document.entries : {};
256
375
  }
257
- /**
258
- * Whether the RAW entry for `pluginId` records `origin: "bundled"` — read raw so a malformed
259
- * entry's provenance still survives a toggle. `Object.hasOwn`, not a plain lookup, for the same
260
- * `Object.prototype` reason {@link resolveAgentPluginActivation} uses it. @complexity O(1).
261
- */
262
- function isRecordedAsBundled(bag, pluginId) {
263
- if (!Object.hasOwn(bag, pluginId))
264
- return false;
265
- const entry = bag[pluginId];
266
- return isPlainObject(entry) && entry.origin === "bundled";
267
- }
268
- /**
269
- * Pre-flight for a caller about to do work whose record it must then write — the boot seeder calls
270
- * this BEFORE installing anything, so a bundled package never lands on disk without the activation
271
- * record that would keep it inactive.
272
- *
273
- * Also proves the cross-process write lock can actually be taken right now, and clears a stale one
274
- * left by a crashed process — the same lock every real writer below takes (this file's header,
275
- * "Concurrency", ACROSS processes).
276
- *
277
- * @throws {AgentPluginActivationsUnreadableError} The file exists but cannot be read.
278
- * @throws {AgentPluginActivationsBusyError} The lock could not be taken within 15s.
279
- * @complexity Same as {@link readPluginsBagStrict}, plus one lock acquisition/release.
280
- */
281
- async function assertAgentPluginActivationsWritable(workspaceRoot) {
282
- await lockedActivationsWrite(workspaceRoot, () => readPluginsBagStrict(workspaceRoot));
283
- }
284
376
  /**
285
377
  * The fail-CLOSED provenance read `uninstall.ts`'s bundled refusal uses in place of the lenient
286
378
  * {@link readAgentPluginActivations} — so a corrupt file refuses an uninstall rather than reading as
@@ -325,94 +417,224 @@ function buildModule(ports) {
325
417
  return record.enabled ? { verdict: "active" } : { verdict: "inactive" };
326
418
  }
327
419
  /**
328
- * Whether `value` is a plain (non-null, non-array) object — the shape every one of this file's
329
- * JSON-adjacent values (the activations envelope, and each individual plugin entry) must have
330
- * before its own fields are worth looking at.
420
+ * Whether `pluginId`'s record is an operator's own "off" (any disabled record but the seeder's), the
421
+ * one a conditional enable leaves as it is. A read, no lock: callers that must not race a toggle
422
+ * hold the plugin lock every switch takes. @complexity Same as {@link readPluginsBagStrict}.
331
423
  */
332
- function isPlainObject(value) {
333
- return typeof value === "object" && value !== null && !Array.isArray(value);
424
+ async function isAgentPluginDisabledByOperator(workspaceRoot, pluginId) {
425
+ const bag = await readPluginsBagStrict(workspaceRoot);
426
+ return Object.hasOwn(bag, pluginId) && normalizeActivationEntry(pluginId, bag[pluginId])?.enabled === false && !isUntouchedDisabledSeed(bag[pluginId]);
334
427
  }
428
+ return { readActivationsDocument, readAgentPluginActivations, readPluginsBagStrict, isAgentPluginRecordedAsBundled, resolveAgentPluginActivation, isAgentPluginDisabledByOperator };
429
+ }
430
+ /**
431
+ * Lock phase: the per-workspace in-process chain composed in front of the cross-process file lock.
432
+ * One instance per module, so every writer of a host context shares the same chain.
433
+ */
434
+ function createActivationLock(args, _optional = {}) {
435
+ const { ports } = args;
436
+ const mkdir = ports.filesystem.mkdir.bind(ports.filesystem);
335
437
  /**
336
- * The `plugins` bag out of an already-`JSON.parse`d activations value, or `undefined` when the
337
- * top-level envelope doesn't match this schema version at all (wrong shape, wrong
338
- * `schemaVersion`, or a non-object `plugins`) — collapsing the three top-level shape gates
339
- * {@link normalizeActivations} used to inline into one lookup its loop can build on.
438
+ * Logs a stale lock's removal — server-side only, since the path and pid are host detail.
439
+ * @complexity O(1).
340
440
  */
341
- function extractPluginsBag(value) {
342
- if (!isPlainObject(value) || value.schemaVersion !== 1 || !isPlainObject(value.plugins))
343
- return undefined;
344
- return value.plugins;
441
+ function warnStaleActivationsLockRemoved(lockPath, holder) {
442
+ ports.onEvent?.({ event: "stale-activation-lock-removed", message: (holder !== undefined
443
+ ? `[agent-plugins] removed a stale activations.json lock left by pid ${holder.pid} on ${holder.hostname} (acquired ${holder.acquiredAt}): ${lockPath}`
444
+ : `[agent-plugins] removed a stale activations.json lock with an unreadable holder: ${lockPath}`) });
345
445
  }
346
446
  /**
347
- * Fills in an activation record's optional fields from a (validated-boolean-`enabled`) raw entry.
348
- * Pure defaulting: no field here can fail validation, only fall back to a safe default — matching
349
- * the file's own "fail-OPEN per malformed field, never per entry" discipline (see this file's
350
- * header).
447
+ * The tail of each workspace's in-flight write chain, keyed by resolved root so two spellings of one
448
+ * directory share a chain. An entry is dropped once its chain drains.
351
449
  */
352
- function withActivationDefaults(record, enabled) {
353
- return {
354
- enabled,
355
- origin: record.origin === "bundled" ? "bundled" : "operator-installed",
356
- updatedAt: typeof record.updatedAt === "string" ? record.updatedAt : new Date(0).toISOString(),
357
- updatedBy: typeof record.updatedBy === "string" ? record.updatedBy : "unknown",
358
- };
359
- }
450
+ const pendingActivationWrites = new Map();
360
451
  /**
361
- * One `plugins` entry, normalized — or `undefined` when it does not match the shape (bad plugin
362
- * id, non-object entry, or a non-boolean `enabled`), so {@link normalizeActivations}'s loop stays a
363
- * simple accumulate-or-skip.
452
+ * Runs one read-modify-write of a workspace's activations file only after every earlier one in this
453
+ * process has settled — see this file's header, "Concurrency", for the erased-decision race this
454
+ * closes and the cross-process race it does not.
455
+ *
456
+ * A write that throws does not jam the chain: the tail swallows the outcome, and the caller still
457
+ * receives its own rejection.
458
+ *
459
+ * @complexity O(1) bookkeeping, plus waiting for the writes queued ahead of it.
364
460
  */
365
- function normalizeActivationEntry(pluginId, entry) {
366
- if (!SAFE_PLUGIN_ID_PATTERN.test(pluginId))
367
- return undefined;
368
- const record = isPlainObject(entry) ? entry : undefined;
369
- if (record === undefined || typeof record.enabled !== "boolean")
370
- return undefined;
371
- return withActivationDefaults(record, record.enabled);
461
+ async function serializeActivationsWrite(workspaceRoot, write) {
462
+ const key = path.resolve(workspaceRoot);
463
+ const result = (pendingActivationWrites.get(key) ?? Promise.resolve()).then(write);
464
+ const tail = result.then(() => undefined, () => undefined);
465
+ pendingActivationWrites.set(key, tail);
466
+ try {
467
+ return await result;
468
+ }
469
+ finally {
470
+ if (pendingActivationWrites.get(key) === tail)
471
+ pendingActivationWrites.delete(key);
472
+ }
372
473
  }
373
474
  /**
374
- * Validates an already-`JSON.parse`d activations value, dropping anything that does not match the
375
- * shape. Pure, so the parsing rules are assertable without touching a filesystem.
376
- *
377
- * Per-entry rather than all-or-nothing: one malformed entry must not discard the operator's other,
378
- * perfectly good decisions.
475
+ * Composes the in-process chain with the cross-process lock, in that order — see this file's
476
+ * header, "Concurrency", ACROSS processes, for why the chain stays in front and why no exported
477
+ * function here may call another one from inside `write`.
379
478
  *
380
- * @complexity O(p) in the entry count.
479
+ * @throws {AgentPluginActivationsBusyError} The lock could not be taken within 15s, or was lost
480
+ * before `write` finished — either way nothing `write` did was written.
481
+ * @complexity `serializeActivationsWrite`'s queueing cost, plus one lock acquisition/release.
381
482
  */
382
- function normalizeActivations(value) {
383
- /**
384
- * Provenance is a fact about how the package arrived, not about this decision (comment kept
385
- * from the pre-F1.1 version): an existing value is preserved rather than overwritten by a
386
- * toggle. Read raw (`isRecordedAsBundled`), not through normalization, so a malformed sibling
387
- * entry does not lose its own provenance either.
388
- */
389
- const plugins = extractPluginsBag(value);
390
- if (plugins === undefined)
391
- return EMPTY_ACTIVATIONS;
392
- return normalizePluginsBag(plugins);
483
+ async function lockedActivationsWrite(workspaceRoot, write) {
484
+ return serializeActivationsWrite(workspaceRoot, async () => {
485
+ await mkdir(workspaceRoot, { recursive: true, mode: 0o700 });
486
+ const lockPath = path.join(workspaceRoot, ACTIVATIONS_LOCK_FILENAME);
487
+ try {
488
+ return await ports.fileLock.withFileLock({ lockPath, run: write }, {
489
+ timeoutMs: 15_000, staleMs: 10_000, pollMs: 10,
490
+ filesystem: ports.filesystem, clock: ports.clock, monotonicMs: () => ports.clock.monotonicMs(),
491
+ process: ports.process,
492
+ token: () => ports.ids.newId(), hostname: () => ports.process.hostname({}),
493
+ sleep: ({ durationMs }) => ports.clock.sleep({ ms: durationMs }),
494
+ onStaleLockRemoved: ({ holder }) => warnStaleActivationsLockRemoved(lockPath, holder),
495
+ });
496
+ }
497
+ catch (error) {
498
+ throw toActivationsBusyError(lockPath, error);
499
+ }
500
+ });
393
501
  }
502
+ return { lockedActivationsWrite };
503
+ }
504
+ /**
505
+ * Commits the raw bag with temp-write, fsync, lock re-check, rename, then a best-effort directory
506
+ * fsync. Callers must already hold the activation lock.
507
+ */
508
+ function createAtomicActivationWriter(ports) {
509
+ const randomUUID = () => ports.ids.newId();
510
+ const open = ports.filesystem.open.bind(ports.filesystem);
511
+ const rename = ports.filesystem.rename.bind(ports.filesystem);
512
+ const rm = ports.filesystem.rm.bind(ports.filesystem);
394
513
  /**
395
- * The per-entry accumulate-or-skip loop itself, split out of {@link normalizeActivations} so
396
- * {@link readAgentPluginActivations} can run it over an ALREADY shape-checked bag rather than
397
- * re-deriving one — one implementation of "which entries survive", not two.
398
- *
399
- * @complexity O(p) in the entry count.
514
+ * Best-effort fsync of a directory, so a rename that just landed in it survives a power loss rather
515
+ * than leaving a 0-byte or missing `activations.json` on the next boot (R5). Skipped entirely on
516
+ * win32, where a directory cannot be opened for this. Every failure is swallowed: the rename has
517
+ * already landed by the time this runs, so surfacing a failure here would tell the caller its write
518
+ * did not succeed when it did.
519
+ * @complexity One open, one fsync, one close.
400
520
  */
401
- function normalizePluginsBag(plugins) {
402
- const normalized = {};
403
- for (const [pluginId, entry] of Object.entries(plugins)) {
404
- const record = normalizeActivationEntry(pluginId, entry);
405
- if (record !== undefined)
406
- normalized[pluginId] = record;
521
+ async function syncDirectoryBestEffort(dir) {
522
+ if (ports.process.platform === "win32")
523
+ return;
524
+ try {
525
+ const handle = await open(dir, "r");
526
+ try {
527
+ await handle.sync();
528
+ }
529
+ finally {
530
+ await handle.close();
531
+ }
532
+ }
533
+ catch {
407
534
  }
408
- return { schemaVersion: 1, plugins: normalized };
409
535
  }
410
536
  /**
411
- * Records an operator's explicit activation decision for one plugin.
537
+ * Write-temp-then-`rename`, so a concurrent reader sees either the whole previous file or the whole
538
+ * new one and never a truncated JSON document. Same discipline `install.ts`'s `publish()` uses for
539
+ * a package tree, applied to a single small file.
412
540
  *
413
- * Reads and writes the RAW `plugins` bag, not the normalized view — see this file's header,
414
- * "Writers never rewrite what they could not read" — so a malformed sibling entry (or any field a
415
- * future schema version adds) survives this write byte-for-byte.
541
+ * Takes the RAW `plugins` bag rather than a full {@link AgentPluginActivations} — every caller now
542
+ * builds one from a strict raw read (this file's header, "Writers never rewrite what they could not
543
+ * read"), so this is the one place that wraps it back in the `{ schemaVersion: 1, plugins }`
544
+ * envelope for serialization.
545
+ *
546
+ * Durability: the temp file is fsync'd before the rename, and the workspace
547
+ * directory is best-effort fsync'd after — see this file's header and `syncDirectoryBestEffort`'s
548
+ * own doc for why a power loss must never leave a 0-byte `activations.json` behind.
549
+ *
550
+ * `lock.assertHeld()` runs immediately before the rename — the fail-closed check that stops a
551
+ * holder who stalled past the stale threshold from committing after another process already judged
552
+ * it stale (this file's header, "failure modes").
553
+ *
554
+ * @throws {FileLockLostError} `lock` no longer owns the cross-process lock; `lockedActivationsWrite`
555
+ * maps this to {@link AgentPluginActivationsBusyError}.
556
+ * @complexity One open, one write, one fsync, one rename, one best-effort directory fsync.
557
+ */
558
+ return async function writeActivationsAtomically(workspaceRoot, plugins, lock) {
559
+ const finalPath = path.join(workspaceRoot, ACTIVATIONS_FILENAME);
560
+ const tempPath = `${finalPath}.tmp-${ports.process.pid}-${randomUUID()}`;
561
+ try {
562
+ /**
563
+ * Best-effort only — see this function's own doc.
564
+ */
565
+ const handle = await open(tempPath, "wx", 0o600);
566
+ try {
567
+ await handle.writeFile(`${JSON.stringify({ schemaVersion: 1, plugins }, null, 2)}\n`, "utf8");
568
+ await handle.sync();
569
+ }
570
+ finally {
571
+ await handle.close();
572
+ }
573
+ await lock.assertHeld({});
574
+ await rename(tempPath, finalPath);
575
+ }
576
+ catch (error) {
577
+ await rm(tempPath, { force: true });
578
+ throw error;
579
+ }
580
+ await syncDirectoryBestEffort(workspaceRoot);
581
+ };
582
+ }
583
+ function createDurableActivationWrites(args, _optional = {}) {
584
+ const { ports } = args;
585
+ const writeActivationsAtomically = createAtomicActivationWriter(ports);
586
+ /**
587
+ * The write half of {@link setAgentPluginActivation}, over a bag the caller has ALREADY read strictly
588
+ * inside its own {@link lockedActivationsWrite} turn — so {@link recordBundledAgentPluginIfAbsent} can
589
+ * decide and write within one turn instead of re-entering the chain or the lock, either of which
590
+ * would wait on itself (this file's header, "Concurrency").
591
+ *
592
+ * @complexity O(p) in the recorded plugin count — the whole (small) file is rewritten.
593
+ */
594
+ async function writeActivationDecision(current, required, optional, lock) {
595
+ const { workspaceRoot, pluginId, enabled, actor } = required;
596
+ assertTargetEntryReadable(workspaceRoot, current, pluginId);
597
+ const plugins = {
598
+ ...current,
599
+ [pluginId]: {
600
+ enabled,
601
+ origin: optional.origin ?? (isRecordedAsBundled(current, pluginId) ? "bundled" : "operator-installed"),
602
+ updatedAt: (optional.now?.({}) ?? new Date(ports.clock.nowMs())).toISOString(),
603
+ updatedBy: actor,
604
+ },
605
+ };
606
+ await writeActivationsAtomically(workspaceRoot, plugins, lock);
607
+ return normalizePluginsBag(plugins);
608
+ }
609
+ return { writeActivationDecision, writeActivationsAtomically };
610
+ }
611
+ /** Operator writers: explicit decisions, mirror reconcile, record removal, and the writable pre-flight. */
612
+ function createOperatorActivationWrites(args, _optional = {}) {
613
+ const { readPluginsBagStrict } = args.reads;
614
+ const { lockedActivationsWrite } = args.lock;
615
+ const { writeActivationDecision, writeActivationsAtomically } = args.durable;
616
+ /**
617
+ * Pre-flight for a caller about to do work whose record it must then write — the boot seeder calls
618
+ * this BEFORE installing anything, so a bundled package never lands on disk without the activation
619
+ * record that would keep it inactive.
620
+ *
621
+ * Also proves the cross-process write lock can actually be taken right now, and clears a stale one
622
+ * left by a crashed process — the same lock every real writer below takes (this file's header,
623
+ * "Concurrency", ACROSS processes).
624
+ *
625
+ * @throws {AgentPluginActivationsUnreadableError} The file exists but cannot be read.
626
+ * @throws {AgentPluginActivationsBusyError} The lock could not be taken within 15s.
627
+ * @complexity Same as {@link readPluginsBagStrict}, plus one lock acquisition/release.
628
+ */
629
+ async function assertAgentPluginActivationsWritable(workspaceRoot) {
630
+ await lockedActivationsWrite(workspaceRoot, () => readPluginsBagStrict(workspaceRoot));
631
+ }
632
+ /**
633
+ * Records an operator's explicit activation decision for one plugin.
634
+ *
635
+ * Reads and writes the RAW `plugins` bag, not the normalized view — see this file's header,
636
+ * "Writers never rewrite what they could not read" — so a malformed sibling entry (or any field a
637
+ * future schema version adds) survives this write byte-for-byte.
416
638
  *
417
639
  * @throws {Error} If `pluginId` does not match the Agent Plugins name grammar.
418
640
  * @throws {AgentPluginActivationsUnreadableError} The file exists but cannot be read.
@@ -444,43 +666,49 @@ function buildModule(ports) {
444
666
  });
445
667
  }
446
668
  /**
447
- * The write half of {@link setAgentPluginActivation}, over a bag the caller has ALREADY read strictly
448
- * inside its own {@link lockedActivationsWrite} turn — so {@link recordBundledAgentPluginIfAbsent} can
449
- * decide and write within one turn instead of re-entering the chain or the lock, either of which
450
- * would wait on itself (this file's header, "Concurrency").
669
+ * Removes a plugin's activation record entirely, rather than leaving a disabled tombstone.
451
670
  *
452
- * @complexity O(p) in the recorded plugin count — the whole (small) file is rewritten.
453
- */
454
- async function writeActivationDecision(current, required, optional, lock) {
455
- const { workspaceRoot, pluginId, enabled, actor } = required;
456
- assertTargetEntryReadable(workspaceRoot, current, pluginId);
457
- const plugins = {
458
- ...current,
459
- [pluginId]: {
460
- enabled,
461
- origin: optional.origin ?? (isRecordedAsBundled(current, pluginId) ? "bundled" : "operator-installed"),
462
- updatedAt: (optional.now?.({}) ?? new Date(ports.clock.nowMs())).toISOString(),
463
- updatedBy: actor,
464
- },
465
- };
466
- await writeActivationsAtomically(workspaceRoot, plugins, lock);
467
- return normalizePluginsBag(plugins);
468
- }
469
- /**
470
- * Refuse a malformed target entry rather than guessing operator-installed origin. Guessing would
471
- * defeat bundled uninstall refusal and make seeding confuse a fabricated record with consent.
472
- * An undetermined entry stays intact. recordBundledAgentPluginIfAbsent reaches this writer only
473
- * when the target key is genuinely absent, so it does not repair a malformed decision either.
474
- * @throws {AgentPluginActivationsUnreadableError} The target entry exists but cannot normalize.
475
- * @complexity O(1).
671
+ * Callers: `uninstall.ts`'s `uninstallAgentPlugin()`, on a successful uninstall (see that file's own
672
+ * header for the full decision), and `retire-bundled.ts`, for a retired bundled plugin's leftover
673
+ * record when no package of it is installed.
674
+ * Short version: a tombstone (`enabled: false` left behind after the bytes are gone) would invert
675
+ * this file's own "absent means active, because an operator's own install IS the consent" rule
676
+ * (this file's header, above) the moment the SAME plugin id is ever reinstalled — the fresh install
677
+ * would silently inherit a stale disabled flag about bytes that no longer exist. Deleting the record
678
+ * makes a future reinstall of this id start exactly where any first-ever install starts.
679
+ *
680
+ * A no-op, not an error, when no record exists — matches `recordBundledAgentPluginIfAbsent`'s own
681
+ * idempotent style; a caller uninstalling a plugin that was never explicitly toggled should not have
682
+ * to special-case "there was nothing to clear".
683
+ *
684
+ * @throws {Error} If `pluginId` does not match the Agent Plugins name grammar.
685
+ * @throws {AgentPluginActivationsUnreadableError} The file exists but cannot be read — an unreadable
686
+ * file might well hold a record for `pluginId`, so treating that as "nothing to delete" could mean
687
+ * silently leaving a decision in place that this call was supposed to remove.
688
+ * @throws {AgentPluginActivationsBusyError} The cross-process write lock could not be taken or was
689
+ * lost; nothing was written.
690
+ * @complexity O(p) in the recorded plugin count — the whole (small) file is rewritten, same as every
691
+ * other write in this file.
476
692
  */
477
- function assertTargetEntryReadable(workspaceRoot, current, pluginId) {
478
- if (!Object.hasOwn(current, pluginId))
479
- return;
480
- if (normalizeActivationEntry(pluginId, current[pluginId]) !== undefined)
481
- return;
482
- throw new AgentPluginActivationsUnreadableError({ filePath: path.join(workspaceRoot, ACTIVATIONS_FILENAME), reason: `${ACTIVATIONS_FILENAME} holds an unreadable record for '${pluginId}', so it cannot be safely toggled` });
693
+ async function deleteAgentPluginActivation(required) {
694
+ const { workspaceRoot, pluginId } = required;
695
+ assertPluginId(pluginId);
696
+ await lockedActivationsWrite(workspaceRoot, async (lock) => {
697
+ const current = await readPluginsBagStrict(workspaceRoot);
698
+ if (!Object.hasOwn(current, pluginId))
699
+ return;
700
+ const remaining = { ...current };
701
+ delete remaining[pluginId];
702
+ await writeActivationsAtomically(workspaceRoot, remaining, lock);
703
+ });
483
704
  }
705
+ return { assertAgentPluginActivationsWritable, setAgentPluginActivation, reconcileAgentPluginActivation, deleteAgentPluginActivation };
706
+ }
707
+ /** Bundled writers: the boot seeder's no-overwrite record and the retire path's conditional enable. */
708
+ function createBundledActivationWrites(args, _optional = {}) {
709
+ const { readPluginsBagStrict } = args.reads;
710
+ const { lockedActivationsWrite } = args.lock;
711
+ const { writeActivationDecision } = args.durable;
484
712
  /**
485
713
  * Writes the initial `{ enabled: false, origin: "bundled" }` record for a plugin the host itself placed
486
714
  * on disk — and does nothing at all if any record already exists.
@@ -520,26 +748,6 @@ function buildModule(ports) {
520
748
  return { recorded: true };
521
749
  });
522
750
  }
523
- /**
524
- * `updatedBy` of every record the boot seeder writes.
525
- */
526
- const SEED_ACTOR = "system:seed";
527
- /**
528
- * Whether a RAW entry is the seeder's own disabled record that no operator has touched since.
529
- * @complexity O(1).
530
- */
531
- function isUntouchedDisabledSeed(entry) {
532
- return isPlainObject(entry) && entry.enabled === false && entry.updatedBy === SEED_ACTOR;
533
- }
534
- /**
535
- * Whether `pluginId`'s record is an operator's own "off" (any disabled record but the seeder's), the
536
- * one a conditional enable leaves as it is. A read, no lock: callers that must not race a toggle
537
- * hold the plugin lock every switch takes. @complexity Same as {@link readPluginsBagStrict}.
538
- */
539
- async function isAgentPluginDisabledByOperator(workspaceRoot, pluginId) {
540
- const bag = await readPluginsBagStrict(workspaceRoot);
541
- return Object.hasOwn(bag, pluginId) && normalizeActivationEntry(pluginId, bag[pluginId])?.enabled === false && !isUntouchedDisabledSeed(bag[pluginId]);
542
- }
543
751
  /**
544
752
  * Switches a bundled plugin ON unless an operator has explicitly turned it off — for
545
753
  * `retire-bundled.ts`, which moves a retired plugin's users onto its successor.
@@ -569,173 +777,14 @@ function buildModule(ports) {
569
777
  return "enabled";
570
778
  });
571
779
  }
572
- /**
573
- * Removes a plugin's activation record entirely, rather than leaving a disabled tombstone.
574
- *
575
- * Callers: `uninstall.ts`'s `uninstallAgentPlugin()`, on a successful uninstall (see that file's own
576
- * header for the full decision), and `retire-bundled.ts`, for a retired bundled plugin's leftover
577
- * record when no package of it is installed.
578
- * Short version: a tombstone (`enabled: false` left behind after the bytes are gone) would invert
579
- * this file's own "absent means active, because an operator's own install IS the consent" rule
580
- * (this file's header, above) the moment the SAME plugin id is ever reinstalled — the fresh install
581
- * would silently inherit a stale disabled flag about bytes that no longer exist. Deleting the record
582
- * makes a future reinstall of this id start exactly where any first-ever install starts.
583
- *
584
- * A no-op, not an error, when no record exists — matches `recordBundledAgentPluginIfAbsent`'s own
585
- * idempotent style; a caller uninstalling a plugin that was never explicitly toggled should not have
586
- * to special-case "there was nothing to clear".
587
- *
588
- * @throws {Error} If `pluginId` does not match the Agent Plugins name grammar.
589
- * @throws {AgentPluginActivationsUnreadableError} The file exists but cannot be read — an unreadable
590
- * file might well hold a record for `pluginId`, so treating that as "nothing to delete" could mean
591
- * silently leaving a decision in place that this call was supposed to remove.
592
- * @throws {AgentPluginActivationsBusyError} The cross-process write lock could not be taken or was
593
- * lost; nothing was written.
594
- * @complexity O(p) in the recorded plugin count — the whole (small) file is rewritten, same as every
595
- * other write in this file.
596
- */
597
- async function deleteAgentPluginActivation(required) {
598
- const { workspaceRoot, pluginId } = required;
599
- assertPluginId(pluginId);
600
- await lockedActivationsWrite(workspaceRoot, async (lock) => {
601
- const current = await readPluginsBagStrict(workspaceRoot);
602
- if (!Object.hasOwn(current, pluginId))
603
- return;
604
- const remaining = { ...current };
605
- delete remaining[pluginId];
606
- await writeActivationsAtomically(workspaceRoot, remaining, lock);
607
- });
608
- }
609
- function assertPluginId(pluginId) {
610
- if (!SAFE_PLUGIN_ID_PATTERN.test(pluginId) || pluginId.length > 64) {
611
- throw new Error(`agent-plugin activation: '${pluginId}' is not a valid Agent Plugin id`);
612
- }
613
- }
614
- /**
615
- * The tail of each workspace's in-flight write chain, keyed by resolved root so two spellings of one
616
- * directory share a chain. An entry is dropped once its chain drains.
617
- */
618
- const pendingActivationWrites = new Map();
619
- /**
620
- * Runs one read-modify-write of a workspace's activations file only after every earlier one in this
621
- * process has settled — see this file's header, "Concurrency", for the erased-decision race this
622
- * closes and the cross-process race it does not.
623
- *
624
- * A write that throws does not jam the chain: the tail swallows the outcome, and the caller still
625
- * receives its own rejection.
626
- *
627
- * @complexity O(1) bookkeeping, plus waiting for the writes queued ahead of it.
628
- */
629
- async function serializeActivationsWrite(workspaceRoot, write) {
630
- const key = path.resolve(workspaceRoot);
631
- const result = (pendingActivationWrites.get(key) ?? Promise.resolve()).then(write);
632
- const tail = result.then(() => undefined, () => undefined);
633
- pendingActivationWrites.set(key, tail);
634
- try {
635
- return await result;
636
- }
637
- finally {
638
- if (pendingActivationWrites.get(key) === tail)
639
- pendingActivationWrites.delete(key);
640
- }
641
- }
642
- /**
643
- * Composes the in-process chain with the cross-process lock, in that order — see this file's
644
- * header, "Concurrency", ACROSS processes, for why the chain stays in front and why no exported
645
- * function here may call another one from inside `write`.
646
- *
647
- * @throws {AgentPluginActivationsBusyError} The lock could not be taken within 15s, or was lost
648
- * before `write` finished — either way nothing `write` did was written.
649
- * @complexity `serializeActivationsWrite`'s queueing cost, plus one lock acquisition/release.
650
- */
651
- async function lockedActivationsWrite(workspaceRoot, write) {
652
- return serializeActivationsWrite(workspaceRoot, async () => {
653
- await mkdir(workspaceRoot, { recursive: true, mode: 0o700 });
654
- const lockPath = path.join(workspaceRoot, ACTIVATIONS_LOCK_FILENAME);
655
- try {
656
- return await ports.fileLock.withFileLock({ lockPath, run: write }, {
657
- timeoutMs: 15_000, staleMs: 10_000, pollMs: 10,
658
- filesystem: ports.filesystem, clock: ports.clock, monotonicMs: () => ports.clock.monotonicMs(),
659
- process: ports.process,
660
- token: () => ports.ids.newId(), hostname: () => ports.process.hostname({}),
661
- sleep: ({ durationMs }) => ports.clock.sleep({ ms: durationMs }),
662
- onStaleLockRemoved: ({ holder }) => warnStaleActivationsLockRemoved(lockPath, holder),
663
- });
664
- }
665
- catch (error) {
666
- throw toActivationsBusyError(lockPath, error);
667
- }
668
- });
669
- }
670
- /**
671
- * Write-temp-then-`rename`, so a concurrent reader sees either the whole previous file or the whole
672
- * new one and never a truncated JSON document. Same discipline `install.ts`'s `publish()` uses for
673
- * a package tree, applied to a single small file.
674
- *
675
- * Takes the RAW `plugins` bag rather than a full {@link AgentPluginActivations} — every caller now
676
- * builds one from a strict raw read (this file's header, "Writers never rewrite what they could not
677
- * read"), so this is the one place that wraps it back in the `{ schemaVersion: 1, plugins }`
678
- * envelope for serialization.
679
- *
680
- * Durability: the temp file is fsync'd before the rename, and the workspace
681
- * directory is best-effort fsync'd after — see this file's header and `syncDirectoryBestEffort`'s
682
- * own doc for why a power loss must never leave a 0-byte `activations.json` behind.
683
- *
684
- * `lock.assertHeld()` runs immediately before the rename — the fail-closed check that stops a
685
- * holder who stalled past the stale threshold from committing after another process already judged
686
- * it stale (this file's header, "failure modes").
687
- *
688
- * @throws {FileLockLostError} `lock` no longer owns the cross-process lock; `lockedActivationsWrite`
689
- * maps this to {@link AgentPluginActivationsBusyError}.
690
- * @complexity One open, one write, one fsync, one rename, one best-effort directory fsync.
691
- */
692
- async function writeActivationsAtomically(workspaceRoot, plugins, lock) {
693
- const finalPath = path.join(workspaceRoot, ACTIVATIONS_FILENAME);
694
- const tempPath = `${finalPath}.tmp-${ports.process.pid}-${randomUUID()}`;
695
- try {
696
- /**
697
- * Best-effort only — see this function's own doc.
698
- */
699
- const handle = await open(tempPath, "wx", 0o600);
700
- try {
701
- await handle.writeFile(`${JSON.stringify({ schemaVersion: 1, plugins }, null, 2)}\n`, "utf8");
702
- await handle.sync();
703
- }
704
- finally {
705
- await handle.close();
706
- }
707
- await lock.assertHeld({});
708
- await rename(tempPath, finalPath);
709
- }
710
- catch (error) {
711
- await rm(tempPath, { force: true });
712
- throw error;
713
- }
714
- await syncDirectoryBestEffort(workspaceRoot);
715
- }
716
- /**
717
- * Best-effort fsync of a directory, so a rename that just landed in it survives a power loss rather
718
- * than leaving a 0-byte or missing `activations.json` on the next boot (R5). Skipped entirely on
719
- * win32, where a directory cannot be opened for this. Every failure is swallowed: the rename has
720
- * already landed by the time this runs, so surfacing a failure here would tell the caller its write
721
- * did not succeed when it did.
722
- * @complexity One open, one fsync, one close.
723
- */
724
- async function syncDirectoryBestEffort(dir) {
725
- if (ports.process.platform === "win32")
726
- return;
727
- try {
728
- const handle = await open(dir, "r");
729
- try {
730
- await handle.sync();
731
- }
732
- finally {
733
- await handle.close();
734
- }
735
- }
736
- catch {
737
- }
738
- }
780
+ return { recordBundledAgentPluginIfAbsent, enableBundledAgentPluginUnlessOperatorDisabled };
781
+ }
782
+ function buildModule(ports) {
783
+ const reads = createActivationReads({ ports });
784
+ const phases = { reads, lock: createActivationLock({ ports }), durable: createDurableActivationWrites({ ports }) };
785
+ const { readAgentPluginActivations, isAgentPluginRecordedAsBundled, isAgentPluginDisabledByOperator, resolveAgentPluginActivation } = reads;
786
+ const { assertAgentPluginActivationsWritable, setAgentPluginActivation, reconcileAgentPluginActivation, deleteAgentPluginActivation } = createOperatorActivationWrites(phases);
787
+ const { recordBundledAgentPluginIfAbsent, enableBundledAgentPluginUnlessOperatorDisabled } = createBundledActivationWrites(phases);
739
788
  return { reconcileAgentPluginActivation, isAgentPluginActive, filterActiveAgentPlugins, readAgentPluginActivations, assertAgentPluginActivationsWritable, isAgentPluginRecordedAsBundled, isAgentPluginDisabledByOperator, resolveAgentPluginActivation, normalizeActivations, setAgentPluginActivation, recordBundledAgentPluginIfAbsent, enableBundledAgentPluginUnlessOperatorDisabled, deleteAgentPluginActivation };
740
789
  }
741
790
  const instances = new WeakMap();