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

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 (231) hide show
  1. package/README.md +22 -4
  2. package/calendly/README.md +29 -0
  3. package/calendly/mcp.json +1 -1
  4. package/cloudflare/lib/assets.mjs +1 -1
  5. package/cloudflare/lib/cms-forms.mjs +1 -1
  6. package/core/persistent-state.d.ts +4 -1
  7. package/core/persistent-state.js +55 -21
  8. package/dist/admin-surfaces/callback-field-inbox.d.ts +1 -6
  9. package/dist/admin-surfaces/connections/connections.d.ts +2 -6
  10. package/dist/admin-surfaces/connections/index.d.ts +3 -2
  11. package/dist/admin-surfaces/index.d.ts +3 -1
  12. package/dist/connect/access-token-tool.d.ts +1 -1
  13. package/dist/connect/access-token-tool.js +1 -1
  14. package/dist/connect/catalog.d.ts +26 -0
  15. package/dist/connect/catalog.js +42 -0
  16. package/dist/connect/connect-tool.d.ts +2 -294
  17. package/dist/connect/connect-tool.js +2 -53
  18. package/dist/connect/contracts.d.ts +257 -0
  19. package/dist/connect/contracts.js +2 -0
  20. package/dist/connect/credential-cards.d.ts +2 -0
  21. package/dist/connect/credential-cards.js +7 -4
  22. package/dist/connect/grant-signed-in-defaults.js +1 -1
  23. package/dist/connect/host-deps.d.ts +32 -0
  24. package/dist/connect/host-deps.js +35 -0
  25. package/dist/connect/import-access-token.js +1 -1
  26. package/dist/connect/index.d.ts +7 -2
  27. package/dist/connect/index.js +5 -2
  28. package/dist/connect/installed-plugin.d.ts +28 -0
  29. package/dist/connect/installed-plugin.js +19 -0
  30. package/dist/connect/new-site-agent-plugin-tokens.d.ts +88 -0
  31. package/dist/connect/new-site-agent-plugin-tokens.js +107 -0
  32. package/dist/connect/plugin-host/index.d.ts +1 -2
  33. package/dist/connect/plugin-host/index.js +18 -9
  34. package/dist/connect/token-sign-in.d.ts +1 -14
  35. package/dist/connect/token-sign-in.js +4 -23
  36. package/dist/core/export-props.d.ts +10 -0
  37. package/dist/core/export-props.js +31 -0
  38. package/dist/core/folder-zip-error.d.ts +5 -0
  39. package/dist/core/folder-zip-error.js +8 -0
  40. package/dist/core/host-incompatible-error.d.ts +8 -0
  41. package/dist/core/host-incompatible-error.js +9 -0
  42. package/dist/core/identity-namespace.d.ts +27 -16
  43. package/dist/core/identity-namespace.js +25 -22
  44. package/dist/core/plugin-display-name.d.ts +7 -0
  45. package/dist/core/plugin-display-name.js +11 -0
  46. package/dist/core/provider-plugin-link.d.ts +7 -0
  47. package/dist/core/provider-plugin-link.js +5 -0
  48. package/dist/{connect → core}/token-map.d.ts +11 -1
  49. package/dist/{connect → core}/token-map.js +15 -0
  50. package/dist/core/token-sign-in-list.d.ts +18 -0
  51. package/dist/core/token-sign-in-list.js +23 -0
  52. package/dist/core/update-error.d.ts +8 -0
  53. package/dist/core/update-error.js +9 -0
  54. package/dist/{lifecycle → core}/update-plan.d.ts +1 -1
  55. package/dist/ffmpeg-transcode/adapter.d.ts +74 -0
  56. package/dist/ffmpeg-transcode/adapter.js +155 -0
  57. package/dist/folder-zip-node.d.ts +2 -1
  58. package/dist/folder-zip-node.js +6 -5
  59. package/dist/folder-zip.d.ts +0 -4
  60. package/dist/folder-zip.js +1 -7
  61. package/dist/index.d.ts +3 -1
  62. package/dist/lifecycle/activation.d.ts +39 -3
  63. package/dist/lifecycle/activation.js +467 -418
  64. package/dist/lifecycle/automatic-use-offer.d.ts +62 -0
  65. package/dist/lifecycle/automatic-use-offer.js +52 -0
  66. package/dist/lifecycle/automatic-use.d.ts +33 -1
  67. package/dist/lifecycle/automatic-use.js +157 -38
  68. package/dist/lifecycle/bundled-source-archive.d.ts +1 -1
  69. package/dist/lifecycle/capability-projection.d.ts +0 -1
  70. package/dist/lifecycle/capability-projection.js +92 -23
  71. package/dist/lifecycle/compatibility-metadata.d.ts +1 -0
  72. package/dist/lifecycle/compatibility-metadata.js +6 -1
  73. package/dist/lifecycle/compatibility.d.ts +1 -8
  74. package/dist/lifecycle/compatibility.js +1 -8
  75. package/dist/lifecycle/credential-card-metadata.d.ts +2 -2
  76. package/dist/lifecycle/exports.d.ts +2 -45
  77. package/dist/lifecycle/exports.js +1 -30
  78. package/dist/lifecycle/host-tools/identity.d.ts +5 -4
  79. package/dist/lifecycle/host-tools/identity.js +5 -5
  80. package/dist/lifecycle/host-tools/ports.d.ts +10 -1
  81. package/dist/lifecycle/host-tools/search-tool.js +18 -8
  82. package/dist/lifecycle/host-tools/skill-tool.js +1 -1
  83. package/dist/lifecycle/index.d.ts +20 -17
  84. package/dist/lifecycle/index.js +5 -4
  85. package/dist/lifecycle/install-from-url.d.ts +1 -2
  86. package/dist/lifecycle/install.d.ts +4 -34
  87. package/dist/lifecycle/install.js +3 -3
  88. package/dist/lifecycle/installed-package-index.d.ts +1 -1
  89. package/dist/lifecycle/installed-package-index.js +4 -4
  90. package/dist/lifecycle/layout.d.ts +21 -25
  91. package/dist/lifecycle/layout.js +79 -0
  92. package/dist/lifecycle/manifest.d.ts +10 -7
  93. package/dist/lifecycle/manifest.js +20 -15
  94. package/dist/lifecycle/mcp-provisioning.d.ts +1 -1
  95. package/dist/lifecycle/metadata.d.ts +6 -3
  96. package/dist/lifecycle/metadata.js +2 -1
  97. package/dist/lifecycle/package-paths.js +59 -56
  98. package/dist/lifecycle/persistent-state.d.ts +10 -1
  99. package/dist/lifecycle/persistent-state.js +4 -2
  100. package/dist/lifecycle/ports.d.ts +18 -6
  101. package/dist/lifecycle/resolve-agent-plugin-refs.d.ts +2 -14
  102. package/dist/lifecycle/retire-bundled.d.ts +1 -1
  103. package/dist/lifecycle/search-projection.d.ts +3 -1
  104. package/dist/lifecycle/search-projection.js +7 -3
  105. package/dist/lifecycle/search.d.ts +1 -0
  106. package/dist/lifecycle/seed-bundled.d.ts +86 -1
  107. package/dist/lifecycle/seed-bundled.js +48 -84
  108. package/dist/lifecycle/set-enabled.d.ts +1 -13
  109. package/dist/lifecycle/set-enabled.js +11 -7
  110. package/dist/lifecycle/trusted-plugin-files.d.ts +1 -1
  111. package/dist/lifecycle/trusted-plugin-files.js +33 -30
  112. package/dist/lifecycle/types.d.ts +13 -34
  113. package/dist/lifecycle/uninstall.d.ts +1 -33
  114. package/dist/lifecycle/update-store.d.ts +0 -7
  115. package/dist/lifecycle/update-store.js +1 -8
  116. package/dist/lifecycle/update.d.ts +1 -1
  117. package/dist/lifecycle/update.js +60 -10
  118. package/dist/lifecycle/yauzl-archive-reader.d.ts +7 -2
  119. package/dist/lifecycle/yauzl-archive-reader.js +11 -6
  120. package/dist/manifest.d.ts +4 -8
  121. package/dist/react/AgentPluginDetailsModal.d.ts +187 -0
  122. package/dist/react/AgentPluginDetailsModal.js +29 -0
  123. package/dist/react/agent-plugin-install-port.d.ts +24 -0
  124. package/dist/react/agent-plugin-install-port.js +15 -0
  125. package/dist/react/installed-skills-composer-source.d.ts +60 -0
  126. package/dist/react/installed-skills-composer-source.js +111 -0
  127. package/dist/react/use-agent-plugins.hooks.d.ts +211 -0
  128. package/dist/react/use-agent-plugins.hooks.js +128 -0
  129. package/dist/site/activation-effects.d.ts +17 -0
  130. package/dist/site/activation-effects.js +31 -0
  131. package/dist/site/admin-surfaces/capabilities.d.ts +29 -0
  132. package/dist/site/admin-surfaces/capabilities.js +30 -0
  133. package/dist/site/admin-surfaces/delivery-bindings.d.ts +81 -0
  134. package/dist/site/admin-surfaces/delivery-bindings.js +161 -0
  135. package/dist/site/admin-surfaces/forms.d.ts +28 -0
  136. package/dist/site/admin-surfaces/forms.js +29 -0
  137. package/dist/site/admin-surfaces/handlers.d.ts +61 -0
  138. package/dist/site/admin-surfaces/handlers.js +35 -0
  139. package/dist/site/admin-surfaces/public-config.d.ts +12 -0
  140. package/dist/site/admin-surfaces/public-config.js +28 -0
  141. package/dist/site/analytics-provider-registry.d.ts +87 -0
  142. package/dist/site/analytics-provider-registry.js +87 -0
  143. package/dist/site/archive-reader-abi.d.ts +35 -0
  144. package/dist/site/archive-reader-abi.js +25 -0
  145. package/dist/site/auth-schemes.d.ts +110 -0
  146. package/dist/site/auth-schemes.js +119 -0
  147. package/dist/site/automatic-agent-plugins.d.ts +200 -0
  148. package/dist/site/automatic-agent-plugins.js +277 -0
  149. package/dist/site/bundled-contribution-sources.d.ts +24 -0
  150. package/dist/site/bundled-contribution-sources.js +17 -0
  151. package/dist/site/bundled-id-upgrade.d.ts +115 -0
  152. package/dist/site/bundled-id-upgrade.js +169 -0
  153. package/dist/site/customize-tool.d.ts +39 -0
  154. package/dist/site/customize-tool.js +31 -0
  155. package/dist/site/deploy-split-activation.d.ts +28 -0
  156. package/dist/site/deploy-split-activation.js +21 -0
  157. package/dist/site/exports/diagnostics.d.ts +37 -0
  158. package/dist/site/exports/diagnostics.js +55 -0
  159. package/dist/site/exports/runtime.d.ts +54 -0
  160. package/dist/site/exports/runtime.js +196 -0
  161. package/dist/site/exports/source.d.ts +42 -0
  162. package/dist/site/exports/source.js +58 -0
  163. package/dist/site/host-plugin-guidance.d.ts +137 -0
  164. package/dist/site/host-plugin-guidance.js +223 -0
  165. package/dist/site/host-signals.d.ts +78 -0
  166. package/dist/site/host-signals.js +83 -0
  167. package/dist/site/install-tool.d.ts +69 -0
  168. package/dist/site/install-tool.js +192 -0
  169. package/dist/site/install-upload.d.ts +175 -0
  170. package/dist/site/install-upload.js +324 -0
  171. package/dist/site/memory-i18n.d.ts +5 -0
  172. package/dist/site/memory-i18n.js +176 -0
  173. package/dist/site/memory.d.ts +80 -0
  174. package/dist/site/memory.js +83 -0
  175. package/dist/site/plugin-memory.d.ts +80 -0
  176. package/dist/site/plugin-memory.js +86 -0
  177. package/dist/site/provider-plugin-link.d.ts +112 -0
  178. package/dist/site/provider-plugin-link.js +100 -0
  179. package/dist/site/retired-plugin-tool-aliases.d.ts +40 -0
  180. package/dist/site/retired-plugin-tool-aliases.js +41 -0
  181. package/dist/site/service-ports.d.ts +108 -0
  182. package/dist/site/service-ports.js +2 -0
  183. package/dist/site/set-enabled.d.ts +80 -0
  184. package/dist/site/set-enabled.js +42 -0
  185. package/dist/site/soon-lock.d.ts +83 -0
  186. package/dist/site/soon-lock.js +78 -0
  187. package/dist/site/supersession.d.ts +61 -0
  188. package/dist/site/supersession.js +122 -0
  189. package/dist/site/uninstall-tool.d.ts +136 -0
  190. package/dist/site/uninstall-tool.js +203 -0
  191. package/dist/site/update-effects.d.ts +47 -0
  192. package/dist/site/update-effects.js +49 -0
  193. package/ffmpeg-transcode/plugin.json +16 -0
  194. package/github/source-control/backup-push.mjs +66 -46
  195. package/github/source-control/commit-site.mjs +112 -65
  196. package/github/source-control/write-files.mjs +86 -53
  197. package/github-pages/targets/github-pages.mjs +294 -233
  198. package/google-workspace/form-destinations/mapping.mjs +15 -7
  199. package/google-workspace/form-destinations/sheets.mjs +4 -2
  200. package/google-workspace/plugin.json +1 -0
  201. package/kuinetic/CHANGELOG.md +4 -0
  202. package/kuinetic/plugin.json +4 -1
  203. package/kuinetic/skills/kuinetic/SKILL.md +1 -2
  204. package/package.json +295 -18
  205. package/persistent-state.d.ts +4 -1
  206. package/resend/adapters/resend.mjs +5 -2
  207. package/resend/plugin.json +1 -1
  208. package/s3-compatible/jini-deploy-targets.json +1 -1
  209. package/s3-compatible/object-stores/s3-compatible.mjs +27 -4
  210. package/s3-compatible/targets/s3-compatible.mjs +3 -3
  211. package/site-import/plugin.json +3 -3
  212. package/site-import/skills/site-import/SKILL.md +62 -54
  213. package/site-import/skills/site-import/references/content-mapping.md +26 -20
  214. package/slide-design/plugin.json +1 -1
  215. package/slide-design/skills/slide-design/SKILL.md +8 -2
  216. package/ui-ux-design/CHANGELOG.md +6 -0
  217. package/ui-ux-design/plugin.json +1 -1
  218. package/ui-ux-design/skills/gstack-design/SKILL.md +6 -6
  219. package/ui-ux-design/skills/ui-ux-design/SKILL.md +3 -2
  220. package/ui-ux-design/skills/ui-ux-design/references/chrome-mobile-test-matrix.md +14 -12
  221. package/ui-ux-design/skills/ui-ux-design/references/ui-loop.md +16 -17
  222. package/vercel/NOTES.md +2 -1
  223. package/vercel/object-stores/vercel-blob.mjs +3 -4
  224. package/vercel/targets/vercel.mjs +425 -351
  225. package/core/commerce-server.d.ts +0 -2
  226. package/core/commerce-server.mjs +0 -2
  227. package/dist/admin-surfaces/connections/ports.d.ts +0 -110
  228. package/dist/admin-surfaces/connections/ports.js +0 -2
  229. /package/dist/{lifecycle → core}/install-errors.d.ts +0 -0
  230. /package/dist/{lifecycle → core}/install-errors.js +0 -0
  231. /package/dist/{lifecycle → core}/update-plan.js +0 -0
@@ -0,0 +1,277 @@
1
+ import { buildDomainRegistrations, indexCatalogById, requireInputRecord, requireString, optionalString, ToolInputError } from '@jini-ai/core';
2
+ const chatKey = (context) => JSON.stringify([context.principal.id, context.conversationId]);
3
+ /** Release a detached, settled controller without deleting a replacement with the same id. O(1). */
4
+ function releaseDetached(entry, turns) {
5
+ if (!entry.pending && !entry.attempts.size && turns.get(entry.turnId) === entry)
6
+ turns.delete(entry.turnId);
7
+ }
8
+ /** Keep the successful turn snapshot across attempts; failed preparation remains retryable. */
9
+ function preflight({ entry }, _options = {}) {
10
+ entry.preflight ??= entry.controller.prepare({ query: entry.context.query, loaded: entry.context.pinned,
11
+ ...(entry.context.maxPromptArgBytes !== undefined && { maxPromptArgBytes: entry.context.maxPromptArgBytes }) })
12
+ .catch(error => { entry.preflight = undefined; throw error; });
13
+ return entry.preflight;
14
+ }
15
+ /** Fold a terminal attempt's late answer for this chat into the new turn, consuming it once. @complexity O(excluded). */
16
+ function withLateAnswer({ context }, lateAnswers) {
17
+ const lateAnswer = lateAnswers.get(chatKey(context));
18
+ if (!lateAnswer)
19
+ return context;
20
+ lateAnswers.delete(chatKey(context));
21
+ return { ...context, state: { ...lateAnswer, excluded: [...new Set([...context.state.excluded, ...lateAnswer.excluded])] } };
22
+ }
23
+ /** Attach a restarted attempt to its live turn's controller; refuses another principal, chat or turn.
24
+ * @throws Error('Agent Plugin run is unavailable') on any identity mismatch. @complexity O(1). */
25
+ function rejoin({ existing, runId, messageId, context }, { runs }) {
26
+ if (existing.context.principal.id !== context.principal.id || existing.context.conversationId !== context.conversationId || (messageId !== undefined && existing.turnId !== messageId))
27
+ throw new Error('Agent Plugin run is unavailable');
28
+ existing.context = context;
29
+ existing.attempts.add(runId);
30
+ runs.set(runId, existing);
31
+ return existing;
32
+ }
33
+ const attemptKey = (scope) => JSON.stringify([scope.runId, scope.attempt, scope.principalId]);
34
+ function createPluginChoiceAsk({ deps, surfaces, askAgentPluginChoice, context, abort }, { getEntry, approve }) {
35
+ return async ({ matches }) => {
36
+ const entry = getEntry();
37
+ entry.pending = true;
38
+ try {
39
+ const preference = await deps.preferences.snapshot({ workspaceId: deps.workspaceId, principalId: context.principal.id });
40
+ if (preference.mode !== 'ask')
41
+ throw new ToolInputError({ message: deps.copy.preferenceBeforeAnswer });
42
+ const answer = await askAgentPluginChoice({ surfaces, principalId: context.principal.id,
43
+ workspaceId: deps.workspaceId, conversationId: context.conversationId, preferenceRevisionSeq: preference.revisionSeq,
44
+ selected: context.state.decision?.selected ?? [],
45
+ // A retry can replace this attempt while the card is open; its receipt belongs to the
46
+ // current transcript emitter, just like the later plugin-state publication below.
47
+ emitSurface: async (emission) => {
48
+ // Detached turns already hand late consent to the next turn below. A terminal
49
+ // lifecycle refuses emissions; recording must not turn that valid consent into an error.
50
+ if (emission.channel === 'user_message' && !entry.attempts.size)
51
+ return;
52
+ await entry.context.emitSurface(emission);
53
+ }, signal: abort.signal, matches });
54
+ if (answer.action !== 'skip') {
55
+ const current = await deps.preferences.snapshot({ workspaceId: deps.workspaceId, principalId: context.principal.id });
56
+ if (current.mode !== preference.mode || current.revisionSeq !== preference.revisionSeq)
57
+ throw new ToolInputError({ message: deps.copy.preferenceAfterAnswer });
58
+ approve(preference.revisionSeq);
59
+ }
60
+ return answer;
61
+ }
62
+ catch (error) {
63
+ // Preflight callers keep the turn running after a failed choice. Preserve the domain's
64
+ // person-facing refusal in the transcript; raw provider/filesystem errors stay private.
65
+ if (error instanceof ToolInputError)
66
+ await entry.context.emitSurface({ channel: 'text_delta', payload: { delta: `\n\n${error.message}\n\n` } });
67
+ throw error;
68
+ }
69
+ finally {
70
+ entry.pending = false;
71
+ }
72
+ };
73
+ }
74
+ /** The automatic resolver port: rechecks activation and trust on every read. Off plugins are read
75
+ * only when Jini's explicit loader asks with `allowInactiveGuidance`; automatic delivery omits it,
76
+ * so a plugin switched off after ranking is never inlined. Read-only setup guidance is not activation,
77
+ * authorization or delivery. O(1) plus one resolver read.
78
+ */
79
+ export function bindAutomaticGuidanceResolver({ workspaceLayout, resolveGuidance }, _optional = {}) {
80
+ return ({ pluginId, ...request }, { allowInactiveGuidance = false } = {}) => resolveGuidance({ pluginRefIds: [pluginId], workspaceLayout }, { ...request, deliveryMode: 'inject', allowInactiveGuidance });
81
+ }
82
+ /** One logical turn's controller wired to the existing catalog, resolver, consent card and settings ports. */
83
+ function createEntry({ mode, context, turnId, runId }, { deps, surfaces, askAgentPluginChoice, lateAnswers }) {
84
+ const abort = new AbortController();
85
+ const maturities = new Map();
86
+ let approvedPreferenceRevisionSeq;
87
+ let entry;
88
+ const controller = deps.createAutomaticAgentPluginUse({ mode, state: deps.readChatAgentPluginState({ value: context.state }), ports: {
89
+ formatPluginToolPointer: deps.formatPluginToolPointer,
90
+ list: async () => {
91
+ const candidates = await deps.list({});
92
+ maturities.clear();
93
+ for (const candidate of candidates)
94
+ if (candidate.enabled)
95
+ maturities.set(candidate.pluginId, candidate.maturity);
96
+ return candidates;
97
+ },
98
+ rank: (input) => deps.rank({ query: input.query.slice(0, 16000), candidates: input.candidates, limit: input.limit }, { automatic: true }),
99
+ resolve: deps.resolveForEntry({ workspaceId: deps.workspaceId }),
100
+ ask: createPluginChoiceAsk({ deps, surfaces, askAgentPluginChoice, context, abort }, { getEntry: () => entry, approve: revisionSeq => { approvedPreferenceRevisionSeq = revisionSeq; } }),
101
+ saveAuto: () => deps.preferences.saveAuto({ workspaceId: deps.workspaceId, principalId: context.principal.id,
102
+ ...(approvedPreferenceRevisionSeq !== undefined && { expectedRevisionSeq: approvedPreferenceRevisionSeq }) }),
103
+ publish: async (value) => {
104
+ if (abort.signal.aborted)
105
+ return;
106
+ if (!entry.attempts.size)
107
+ lateAnswers.set(chatKey(context), value.state);
108
+ await entry.context.publish({ conversationId: context.conversationId, ...value });
109
+ },
110
+ } });
111
+ entry = { turnId, controller, context, abort, pending: false, attempts: new Set([runId]), maturities, offerIds: new Map() };
112
+ return entry;
113
+ }
114
+ // Existing per-plugin tools read their boot-time source, not the run's consent/exclusion owner.
115
+ // This small id loader uses the SAME trusted pinned-ref resolver as the capability backstop.
116
+ function buildPluginGuidanceRegistration({ runs, turns, deps }, _optional = {}) {
117
+ return buildDomainRegistrations({
118
+ domain: 'agent-plugin-guidance', catalogModule: deps.catalogModule,
119
+ catalog: indexCatalogById({ catalog: deps.catalog }),
120
+ metadata: deps.metadata,
121
+ derivedRisk: deps.derivedRisk,
122
+ handlers: { load_agent_plugin: context => loadPluginGuidance(context, { runs, turns, deps }) },
123
+ })[0];
124
+ }
125
+ async function loadPluginGuidance({ input: raw, run, principal, signal }, { runs, turns, deps }) {
126
+ const input = requireInputRecord({ input: raw });
127
+ const pluginId = requireString({ input, key: 'pluginId' });
128
+ if (Object.keys(input).some(key => !['pluginId', 'skill', 'file'].includes(key)))
129
+ throw new ToolInputError({ message: 'Only pluginId, skill and file are accepted' });
130
+ const skill = optionalString({ input, key: 'skill' });
131
+ const file = optionalString({ input, key: 'file' });
132
+ const entry = runs.get(run.id);
133
+ if (!entry || entry.context.principal.id !== principal.id)
134
+ throw new Error('Agent Plugin run is unavailable');
135
+ const result = await entry.controller.load({ pluginId, signal, ...(skill === undefined ? {} : { skill }), ...(file === undefined ? {} : { file }) }).finally(() => releaseDetached(entry, turns));
136
+ const notes = deps.copy.loadNotes({ pluginId });
137
+ const maturity = entry.maturities.get(pluginId);
138
+ return { pluginId, ...result, ...(maturity ? { maturity } : {}), ...(result.status !== 'loaded' ? { note: notes[result.status] } : {}) };
139
+ }
140
+ /** Bind an attempt to its logical turn; return its shared preflight note. Identity mismatches
141
+ * throw before using consent. Settings/catalog effects stay in their existing ports.
142
+ * @complexity O(1) ownership lookup plus the automatic-use owner's catalog work.
143
+ */
144
+ async function bind({ runId, messageId, context }, state) {
145
+ const { deps, surfaces, askAgentPluginChoice, runs, turns, lateAnswers } = state;
146
+ // core.interface definitions are in this existing boot chain, after the UI-tab definitions.
147
+ await deps.siteTitleReady;
148
+ const mode = await deps.preferences.mode({ workspaceId: deps.workspaceId, principalId: context.principal.id });
149
+ if (context.signal.aborted)
150
+ return undefined;
151
+ // A restarted attempt still owns the same pending/answered question. Reuse the controller's
152
+ // serialized preparation instead of rebuilding consent from the frozen request state.
153
+ // Check after setup awaits so simultaneous starts cannot replace one another's controller.
154
+ const turnId = messageId ?? runId;
155
+ const existing = runs.get(runId) ?? turns.get(turnId);
156
+ if (existing)
157
+ return rejoin({ existing, runId, ...(messageId === undefined ? {} : { messageId }), context }, { runs });
158
+ const current = withLateAnswer({ context }, lateAnswers);
159
+ const entry = createEntry({ mode, context: current, turnId, runId }, { deps, surfaces, askAgentPluginChoice, lateAnswers });
160
+ turns.set(turnId, entry);
161
+ runs.set(runId, entry);
162
+ // An Off event clears an earlier usage strip without reading the catalog or loading guidance.
163
+ if (mode === 'off') {
164
+ try {
165
+ await current.publish({ conversationId: current.conversationId, state: current.state, plugins: [] });
166
+ }
167
+ catch (error) {
168
+ releaseDetached(entry, turns);
169
+ throw error;
170
+ }
171
+ }
172
+ return entry;
173
+ }
174
+ async function start({ runId, messageId, context }, state) {
175
+ const { turns } = state;
176
+ const entry = await bind({ runId, messageId, context }, state);
177
+ if (!entry)
178
+ return '';
179
+ try {
180
+ return await preflight({ entry });
181
+ }
182
+ finally {
183
+ releaseDetached(entry, turns);
184
+ }
185
+ }
186
+ /** Draft guidance for one live attempt without recording delivery. Ownership (principal, chat,
187
+ * turn) binds exactly as `start` does; the host owns the attempt scope, offer id and liveness.
188
+ * The first successful offer id is cached per attempt, so a repeated offer cannot re-key a receipt;
189
+ * a replacement attempt has another key and never inherits it. @complexity O(1) plus the owner's draft.
190
+ */
191
+ async function offer({ runId, messageId, context, scope, offerId, isAttemptLive }, state) {
192
+ const { turns } = state;
193
+ if (scope.runId !== runId || scope.principalId !== context.principal.id)
194
+ throw new Error('Agent Plugin run is unavailable');
195
+ const entry = await bind({ runId, messageId, context }, state);
196
+ if (!entry)
197
+ throw new Error('Agent Plugin preparation was cancelled');
198
+ const key = attemptKey(scope);
199
+ try {
200
+ const drafted = await entry.controller.offer({ scope, offerId: entry.offerIds.get(key) ?? offerId, isAttemptLive, input: { query: context.query, loaded: context.pinned, signal: context.signal } });
201
+ entry.offerIds.set(key, drafted.offerId);
202
+ return drafted;
203
+ }
204
+ finally {
205
+ releaseDetached(entry, turns);
206
+ }
207
+ }
208
+ /** Record the delivered ids of this attempt's offer. Only a live alias of the same principal may
209
+ * commit; Jini refuses a retired, replaced or older attempt and replays a same-choice receipt. */
210
+ async function commit({ scope, offerId, deliveredIds }, { signal } = {}, { runs, turns }) {
211
+ const entry = runs.get(scope.runId);
212
+ if (!entry || entry.context.principal.id !== scope.principalId)
213
+ throw new Error('Agent Plugin run is unavailable');
214
+ try {
215
+ return await entry.controller.commit({ scope, offerId, deliveredIds }, signal ? { signal } : {});
216
+ }
217
+ finally {
218
+ releaseDetached(entry, turns);
219
+ }
220
+ }
221
+ async function prepareGuidance({ run, tool, signal }, { runs, turns, deps }) {
222
+ const entry = runs.get(run.id);
223
+ if (!entry)
224
+ return '';
225
+ try {
226
+ return await entry.controller.prepare({ ...(tool.metadata?.guidanceCapabilities ? { capabilities: tool.metadata.guidanceCapabilities } : {}), signal });
227
+ }
228
+ catch (error) {
229
+ deps.warn(error);
230
+ return '';
231
+ }
232
+ finally {
233
+ releaseDetached(entry, turns);
234
+ }
235
+ }
236
+ /** Dispose an attempt alias. Durable attempt replacement retains a pending exchange until its
237
+ * answer/normal exchange expiry; explicit disposal aborts it. O(1), no persistent writes.
238
+ */
239
+ function forget({ runId }, { preservePending = false } = {}, { runs, turns }) {
240
+ const entry = runs.get(runId);
241
+ if (!entry)
242
+ return;
243
+ runs.delete(runId);
244
+ entry.attempts.delete(runId);
245
+ if (entry.attempts.size || (preservePending && entry.pending))
246
+ return;
247
+ entry.abort.abort();
248
+ if (turns.get(entry.turnId) === entry)
249
+ turns.delete(entry.turnId);
250
+ }
251
+ /** Logical-turn controllers share preflight and the actual authorized tool gate. Cleanup is explicit.
252
+ * @returns start/forget, the read-only guidance loader and the tool preparation hook.
253
+ * @complexity O(1) identity lookup; one controller per live turn, one late answer per chat.
254
+ */
255
+ export function createScopedAutomaticPluginRuns({ deps, surfaces, askAgentPluginChoice }, _options = {}) {
256
+ const turns = new Map();
257
+ const runs = new Map();
258
+ // A terminal attempt cannot publish its late answer. Hand it to the next turn in this chat.
259
+ const lateAnswers = new Map();
260
+ const state = { deps, surfaces, askAgentPluginChoice, runs, turns, lateAnswers };
261
+ const loadRegistration = buildPluginGuidanceRegistration({ runs, turns, deps });
262
+ if (loadRegistration === undefined)
263
+ throw new Error('Agent Plugin guidance has no load tool registration');
264
+ return {
265
+ start: (input, _optional = {}) => start(input, state),
266
+ offer: (input, _optional = {}) => offer(input, state),
267
+ commit: (input, optional = {}) => commit(input, optional, state),
268
+ prepareGuidance: (input) => prepareGuidance(input, state),
269
+ loadRegistration,
270
+ forget: (input, optional = {}) => forget(input, optional, state),
271
+ guidanceIds: ({ runId }, _optional = {}) => runs.get(runId)?.controller.guidanceIds({}) ?? [],
272
+ };
273
+ }
274
+ export function createAutomaticPluginRuns({ deps, surfaces, askAgentPluginChoice }, _options = {}) {
275
+ return createScopedAutomaticPluginRuns({ deps: { ...deps, resolveForEntry: () => deps.resolve }, surfaces, askAgentPluginChoice });
276
+ }
277
+ //# sourceMappingURL=automatic-agent-plugins.js.map
@@ -0,0 +1,24 @@
1
+ import type { TrustedPluginPackage } from "@jini-ai/agent-plugins/lifecycle";
2
+ /**
3
+ * @file The hermetic bundled-contribution source policy: which product-owned plugin source packages
4
+ * contribute a given manifest file. The host injects its `retired` bundled plugin ids (its catalog) and
5
+ * binds the result as its `sources` port; see `README.md` `## Wiring`.
6
+ */
7
+ /** The host's bound bundled-source policy, as the readers that take `sources` consume it. */
8
+ export type BundledContributionSources = (required: {
9
+ readonly sourceRoot: string;
10
+ readonly filename: string;
11
+ }) => readonly TrustedPluginPackage[];
12
+ /** Hermetic bundled contribution sources, in plugin-id order. Requires both the package
13
+ * manifest and category file; stale retired packages and non-packages never contribute. Only pass
14
+ * product-owned source roots, never operator-writable installed directories. Synchronous so CLI
15
+ * help and async category loaders use the same selection policy. @complexity O(p) directories.
16
+ * @param required - `retired`: the host's retired bundled plugin ids (any id-keyed set or map), which never contribute.
17
+ * @example listBundledContributionSources({ sourceRoot, filename: "plugin-data.json", retired: new Set(["old-id"]) });
18
+ */
19
+ export declare function listBundledContributionSources(required: {
20
+ readonly sourceRoot: string;
21
+ readonly filename: string;
22
+ readonly retired: Pick<ReadonlySet<string>, "has">;
23
+ }, _optional?: Record<string, never>): readonly TrustedPluginPackage[];
24
+ //# sourceMappingURL=bundled-contribution-sources.d.ts.map
@@ -0,0 +1,17 @@
1
+ import { existsSync, readdirSync } from "node:fs";
2
+ import path from "node:path";
3
+ /** Hermetic bundled contribution sources, in plugin-id order. Requires both the package
4
+ * manifest and category file; stale retired packages and non-packages never contribute. Only pass
5
+ * product-owned source roots, never operator-writable installed directories. Synchronous so CLI
6
+ * help and async category loaders use the same selection policy. @complexity O(p) directories.
7
+ * @param required - `retired`: the host's retired bundled plugin ids (any id-keyed set or map), which never contribute.
8
+ * @example listBundledContributionSources({ sourceRoot, filename: "plugin-data.json", retired: new Set(["old-id"]) });
9
+ */
10
+ export function listBundledContributionSources(required, _optional = {}) {
11
+ return readdirSync(required.sourceRoot, { withFileTypes: true })
12
+ .filter(entry => entry.isDirectory() && !required.retired.has(entry.name))
13
+ .map(entry => ({ pluginId: entry.name, packageRoot: path.join(required.sourceRoot, entry.name) }))
14
+ .filter(plugin => existsSync(path.join(plugin.packageRoot, "plugin.json")) && existsSync(path.join(plugin.packageRoot, required.filename)))
15
+ .sort((a, b) => a.pluginId.localeCompare(b.pluginId, "en"));
16
+ }
17
+ //# sourceMappingURL=bundled-contribution-sources.js.map
@@ -0,0 +1,115 @@
1
+ import type { FilesystemPort } from "../lifecycle/index.js";
2
+ import type { WorkspaceMigrationOwnership } from "../../core/persistent-state.js";
3
+ /** Local id -> the pre-rename and canonical publisher-qualified ids. */
4
+ export type BundledPluginRenames = ReadonlyMap<string, {
5
+ readonly from: string;
6
+ readonly to: string;
7
+ }>;
8
+ /** Folder (inside the workspace root) holding moved pre-rename revisions. */
9
+ export declare const BUNDLED_ID_UPGRADE_BACKUP_DIRNAME = ".bundled-id-upgrade";
10
+ /** One installed revision, as the lifecycle owner indexes it. */
11
+ export interface InstalledRevision {
12
+ readonly pluginId: string;
13
+ readonly id?: string | undefined;
14
+ readonly archiveDigest: string;
15
+ readonly packageRoot: string;
16
+ }
17
+ /** The lifecycle reads and the one filesystem move this step needs, injected by the host's lifecycle binding. */
18
+ export interface BundledIdUpgradePort {
19
+ readonly listInstalledPlugins: (required: {
20
+ workspaceRoot: string;
21
+ }) => Promise<readonly InstalledRevision[]>;
22
+ readonly readBundledAgentPluginDigests: (required: {
23
+ workspaceRoot: string;
24
+ }) => Promise<ReadonlyMap<string, string>>;
25
+ readonly packAgentPluginDirectory: (required: {
26
+ sourceDir: string;
27
+ }) => Promise<{
28
+ readonly sha256: string;
29
+ }>;
30
+ /** Raw `plugin.json` text of this build's bundled source for one local id. */
31
+ readonly readBundledSourceManifest: (required: {
32
+ pluginId: string;
33
+ }) => Promise<string>;
34
+ readonly filesystem: Pick<FilesystemPort, "chmod" | "mkdir" | "rename" | "stat">;
35
+ }
36
+ /** A moved revision: where it lived and where its saved copy is now. */
37
+ export interface MovedRevision {
38
+ readonly packageRoot: string;
39
+ readonly savedAt: string;
40
+ }
41
+ export type BundledIdUpgradeOutcome = {
42
+ readonly status: "upgraded";
43
+ readonly pluginId: string;
44
+ readonly to: string;
45
+ readonly moved: readonly MovedRevision[];
46
+ } | {
47
+ readonly status: "held";
48
+ readonly pluginId: string;
49
+ readonly to: string;
50
+ readonly reason: string;
51
+ } | {
52
+ readonly status: "restored";
53
+ readonly pluginId: string;
54
+ readonly to: string;
55
+ readonly moved: readonly MovedRevision[];
56
+ };
57
+ /**
58
+ * Moves pre-rename bundled revisions aside after verifying the ledgered current revision.
59
+ * @param required.renamed - The host's rename map (it owns which ids moved).
60
+ * @returns One outcome per renamed plugin that still has a pre-rename revision installed; empty
61
+ * (after one directory listing) once a site is upgraded.
62
+ * @throws Nothing for a single plugin: its fault becomes a `held` outcome. Listing faults propagate
63
+ * to the caller, which treats the whole step as optional.
64
+ * @complexity O(r) revisions listed; O(f) file reads to re-pack each ledgered current revision.
65
+ */
66
+ export declare function upgradeRenamedBundledPlugins(required: {
67
+ readonly workspaceRoot: string;
68
+ readonly port: BundledIdUpgradePort;
69
+ readonly renamed: BundledPluginRenames;
70
+ /** Host wording for a revision whose digest the bundled ledger does not name (not installed by the host's own build). */
71
+ readonly ledgerMismatchReason: string;
72
+ }, _optional?: Record<string, never>): Promise<BundledIdUpgradeOutcome[]>;
73
+ /** Puts back the revisions of every upgrade whose canonical package did not seed, so the site keeps
74
+ * the copy it had rather than no copy at all. `restored` is reported only once every put-back rename
75
+ * succeeded. A failed put-back leaves the saved copy where it is and reports `held`: the site is not
76
+ * repaired yet, and saying `restored` would hide a missing package.
77
+ * @complexity O(m) renames for m moved revisions. */
78
+ export declare function restoreUnseededUpgrades(required: {
79
+ readonly outcomes: readonly BundledIdUpgradeOutcome[];
80
+ readonly seededIds: ReadonlySet<string>;
81
+ readonly filesystem: BundledIdUpgradePort["filesystem"];
82
+ }, _optional?: Record<string, never>): Promise<BundledIdUpgradeOutcome[]>;
83
+ /** Runs a caller's window while holding one workspace's migration lock (the host injects the lock effect). */
84
+ export type WorkspaceLockRunner = <T>(required: {
85
+ readonly workspaceRoot: string;
86
+ readonly run: (held: {
87
+ readonly ownership: WorkspaceMigrationOwnership;
88
+ }) => Promise<T>;
89
+ }) => Promise<T>;
90
+ /**
91
+ * One lock ordering for the publisher-ID move, the seed and the put-back: the workspace migration
92
+ * lock is taken first and held across all three, so no migration or second boot can run between a
93
+ * move and its seed or restore. The seed receives the held `ownership` (its nested layout migration
94
+ * runs under it, never reacquiring) and the held ids (they never reach install). Per-plugin locks
95
+ * are only taken inside, under this one.
96
+ * @throws What the injected lock or seed throws; the lock is released either way, and moved copies
97
+ * are put back first when the seed itself throws.
98
+ * @complexity As {@link upgradeRenamedBundledPlugins} plus one seed and O(m) put-back renames.
99
+ */
100
+ export declare function seedWithBundledIdUpgrade<R extends {
101
+ readonly outcomes: readonly {
102
+ readonly pluginId: string;
103
+ readonly status: string;
104
+ }[];
105
+ }>(required: Parameters<typeof upgradeRenamedBundledPlugins>[0] & {
106
+ readonly withWorkspaceLock: WorkspaceLockRunner;
107
+ readonly seed: (required: {
108
+ readonly ownership: WorkspaceMigrationOwnership;
109
+ readonly heldPluginIds: ReadonlyMap<string, string>;
110
+ }) => Promise<R>;
111
+ }, _optional?: Record<string, never>): Promise<{
112
+ readonly seeded: R;
113
+ readonly idUpgrades: BundledIdUpgradeOutcome[];
114
+ }>;
115
+ //# sourceMappingURL=bundled-id-upgrade.d.ts.map
@@ -0,0 +1,169 @@
1
+ /**
2
+ * @file Bundled plugin publisher-ID upgrade: a host maintenance step with verified bundled replacements.
3
+ *
4
+ * A bundled package set can move to a new publisher id while its local name (the activation key) does
5
+ * not change. The install admission then sees a different publisher in the same slot and refuses the
6
+ * canonical package (`PLUGIN_ID_CONFLICT`). Without this step every existing site keeps its
7
+ * pre-rename copy forever and logs one seed failure per plugin per boot. The host injects the rename
8
+ * map (`renamed`: local id -> pre-rename and canonical publisher-qualified ids) and the held-reason
9
+ * wording for a copy its own build did not install.
10
+ *
11
+ * The step runs just before seeding. For each renamed local id it moves the installed pre-rename
12
+ * revisions out of the live package root, but only when the ledgered revision is PROVABLY the one the host's
13
+ * build shipped:
14
+ * 1. its manifest declares exactly the pre-rename id, not some other publisher;
15
+ * 2. its digest is the one the bundled-digest ledger recorded, i.e. the host build's own seed put it
16
+ * there (an upload or a different build's copy is not in the ledger);
17
+ * 3. re-packing its files reproduces that digest, so nobody edited it after install;
18
+ * 4. this build's bundled source really ships the canonical id, so seeding has a replacement.
19
+ * Historical revisions with the same pre-rename id move aside without being trusted as content.
20
+ * An unverified current revision is left exactly where it is and reported in plain words.
21
+ *
22
+ * Only the package bytes move. Activation is keyed by the short name and the plugin's `data/` and
23
+ * `memory/` folders sit beside `package/`, so the owner's switch, settings, data and memory stay.
24
+ * The moved copy is kept under `<workspace>/.bundled-id-upgrade/<id>/<digest>` (dot-prefixed, so the
25
+ * package index never reads it as a plugin) and is put back when the replacement does not seed.
26
+ */
27
+ import path from "node:path";
28
+ /** Folder (inside the workspace root) holding moved pre-rename revisions. */
29
+ export const BUNDLED_ID_UPGRADE_BACKUP_DIRNAME = ".bundled-id-upgrade";
30
+ /**
31
+ * Moves pre-rename bundled revisions aside after verifying the ledgered current revision.
32
+ * @param required.renamed - The host's rename map (it owns which ids moved).
33
+ * @returns One outcome per renamed plugin that still has a pre-rename revision installed; empty
34
+ * (after one directory listing) once a site is upgraded.
35
+ * @throws Nothing for a single plugin: its fault becomes a `held` outcome. Listing faults propagate
36
+ * to the caller, which treats the whole step as optional.
37
+ * @complexity O(r) revisions listed; O(f) file reads to re-pack each ledgered current revision.
38
+ */
39
+ export async function upgradeRenamedBundledPlugins(required, _optional = {}) {
40
+ const { renamed } = required;
41
+ const installed = await required.port.listInstalledPlugins({ workspaceRoot: required.workspaceRoot });
42
+ const blocked = [...renamed].filter(([pluginId, ids]) => blockersOf({ installed, pluginId, to: ids.to }).length > 0);
43
+ if (blocked.length === 0)
44
+ return [];
45
+ const ledger = await required.port.readBundledAgentPluginDigests({ workspaceRoot: required.workspaceRoot });
46
+ const outcomes = [];
47
+ for (const [pluginId, ids] of blocked) {
48
+ const outcome = await upgradeOne({ workspaceRoot: required.workspaceRoot, port: required.port, ledgerMismatchReason: required.ledgerMismatchReason, ledger, pluginId, ids, blockers: blockersOf({ installed, pluginId, to: ids.to }) })
49
+ .catch(() => ({ status: "held", pluginId, to: ids.to, reason: "its installed copy could not be checked" }));
50
+ if (outcome !== undefined)
51
+ outcomes.push(outcome);
52
+ }
53
+ return outcomes;
54
+ }
55
+ /** Same-slot revisions that would make Jini refuse the canonical id. */
56
+ function blockersOf({ installed, pluginId, to }) {
57
+ return installed.filter(revision => revision.pluginId === pluginId && revision.id !== to);
58
+ }
59
+ /** Verifies every blocker's publisher and the ledgered current revision's bytes, then moves them all, or none. `undefined`: this build does
60
+ * not ship the canonical package, so seeding will not try it and nothing needs to move. */
61
+ async function upgradeOne(input) {
62
+ const { port, pluginId, ids } = input;
63
+ if (await bundledSourceId({ port, pluginId }) !== ids.to)
64
+ return undefined;
65
+ for (const revision of input.blockers) {
66
+ const reason = await unverifiedReason({ port, ledger: input.ledger, revision, from: ids.from });
67
+ if (reason !== undefined)
68
+ return { status: "held", pluginId, to: ids.to, reason };
69
+ }
70
+ if (!input.blockers.some(revision => revision.archiveDigest === input.ledger.get(pluginId)))
71
+ return { status: "held", pluginId, to: ids.to, reason: input.ledgerMismatchReason };
72
+ const moved = [];
73
+ for (const revision of input.blockers) {
74
+ const savedAt = path.join(input.workspaceRoot, BUNDLED_ID_UPGRADE_BACKUP_DIRNAME, pluginId, revision.archiveDigest);
75
+ await moveFrozenTree({ filesystem: port.filesystem, from: revision.packageRoot, to: savedAt });
76
+ moved.push({ packageRoot: revision.packageRoot, savedAt });
77
+ }
78
+ return { status: "upgraded", pluginId, to: ids.to, moved };
79
+ }
80
+ /** The qualified id this build's bundled source declares for one local id, if any. */
81
+ async function bundledSourceId({ port, pluginId }) {
82
+ let manifest;
83
+ try {
84
+ manifest = JSON.parse(await port.readBundledSourceManifest({ pluginId }));
85
+ }
86
+ catch {
87
+ return undefined;
88
+ }
89
+ const id = manifest.extensions?.jini?.id;
90
+ return typeof id === "string" ? id : undefined;
91
+ }
92
+ /** Why an installed revision's publisher or the ledgered current revision's bytes prevent the upgrade. */
93
+ async function unverifiedReason({ port, ledger, revision, from }) {
94
+ if (revision.id !== from)
95
+ return `its installed copy is published as '${revision.id ?? "an unnamed publisher"}', not '${from}'`;
96
+ if (ledger.get(revision.pluginId) !== revision.archiveDigest)
97
+ return undefined;
98
+ const repacked = await port.packAgentPluginDirectory({ sourceDir: revision.packageRoot });
99
+ if (repacked.sha256 !== revision.archiveDigest)
100
+ return "its installed files were changed after install";
101
+ return undefined;
102
+ }
103
+ /** Puts back the revisions of every upgrade whose canonical package did not seed, so the site keeps
104
+ * the copy it had rather than no copy at all. `restored` is reported only once every put-back rename
105
+ * succeeded. A failed put-back leaves the saved copy where it is and reports `held`: the site is not
106
+ * repaired yet, and saying `restored` would hide a missing package.
107
+ * @complexity O(m) renames for m moved revisions. */
108
+ export async function restoreUnseededUpgrades(required, _optional = {}) {
109
+ const result = [];
110
+ for (const outcome of required.outcomes) {
111
+ if (outcome.status !== "upgraded" || required.seededIds.has(outcome.pluginId)) {
112
+ result.push(outcome);
113
+ continue;
114
+ }
115
+ let allPutBack = true;
116
+ for (const revision of outcome.moved) {
117
+ // One failed put-back must not stop the others; each kept saved copy stays for the next start.
118
+ await moveFrozenTree({ filesystem: required.filesystem, from: revision.savedAt, to: revision.packageRoot }).catch(() => { allPutBack = false; });
119
+ }
120
+ result.push(allPutBack ? { ...outcome, status: "restored" } : { status: "held", pluginId: outcome.pluginId, to: outcome.to, reason: RESTORE_PENDING_REASON });
121
+ }
122
+ return result;
123
+ }
124
+ const RESTORE_PENDING_REASON = "its earlier copy could not be put back yet; the saved copy is kept for the next start";
125
+ /**
126
+ * One lock ordering for the publisher-ID move, the seed and the put-back: the workspace migration
127
+ * lock is taken first and held across all three, so no migration or second boot can run between a
128
+ * move and its seed or restore. The seed receives the held `ownership` (its nested layout migration
129
+ * runs under it, never reacquiring) and the held ids (they never reach install). Per-plugin locks
130
+ * are only taken inside, under this one.
131
+ * @throws What the injected lock or seed throws; the lock is released either way, and moved copies
132
+ * are put back first when the seed itself throws.
133
+ * @complexity As {@link upgradeRenamedBundledPlugins} plus one seed and O(m) put-back renames.
134
+ */
135
+ export async function seedWithBundledIdUpgrade(required, _optional = {}) {
136
+ const { withWorkspaceLock, seed, ...upgradeInput } = required;
137
+ return withWorkspaceLock({ workspaceRoot: required.workspaceRoot, run: async ({ ownership }) => {
138
+ // Optional step: a listing fault moves nothing, and seeding then reports each conflict itself.
139
+ const upgrades = await upgradeRenamedBundledPlugins(upgradeInput).catch(() => []);
140
+ const heldPluginIds = new Map(upgrades.flatMap(outcome => outcome.status === "held" ? [[outcome.pluginId, outcome.reason]] : []));
141
+ const restore = (seededIds) => restoreUnseededUpgrades({ outcomes: upgrades, seededIds, filesystem: required.port.filesystem });
142
+ let seeded;
143
+ try {
144
+ seeded = await seed({ ownership, heldPluginIds });
145
+ }
146
+ catch (error) {
147
+ await restore(new Set());
148
+ throw error;
149
+ }
150
+ const seededIds = new Set(seeded.outcomes.flatMap(outcome => outcome.status === "seeded" ? [outcome.pluginId] : []));
151
+ return { seeded, idUpgrades: upgrades.length === 0 ? [] : await restore(seededIds) };
152
+ } });
153
+ }
154
+ /** Renames a frozen (0o555) package tree: a directory move needs write permission on the directory
155
+ * itself, so it is opened for the move and its original mode put back afterwards. */
156
+ async function moveFrozenTree({ filesystem, from, to }) {
157
+ const mode = (await filesystem.stat(from)).mode & 0o777;
158
+ await filesystem.mkdir(path.dirname(to), { recursive: true, mode: 0o700 });
159
+ await filesystem.chmod(from, mode | 0o700);
160
+ try {
161
+ await filesystem.rename(from, to);
162
+ }
163
+ catch (error) {
164
+ await filesystem.chmod(from, mode).catch(() => undefined);
165
+ throw error;
166
+ }
167
+ await filesystem.chmod(to, mode).catch(() => undefined);
168
+ }
169
+ //# sourceMappingURL=bundled-id-upgrade.js.map
@@ -0,0 +1,39 @@
1
+ import type { AgentPluginIdentityReadOptions } from "../core/identity-namespace.js";
2
+ /** Chat customization reuses Jini's package fork and the admin upload preview/install owner. */
3
+ import { type ToolExecutionContext } from "@jini-ai/core";
4
+ import type { AgentPluginLayout } from "@jini-ai/core/contracts/headless/plugin-host";
5
+ /** The install tool's deps this fork reads: the site layout and the bound workspace. */
6
+ export interface CustomizeAgentPluginDeps {
7
+ readonly agentPluginLayout: Pick<AgentPluginLayout, "forWorkspace">;
8
+ readonly workspaceId: string;
9
+ }
10
+ /** The lifecycle owner's calls this fork uses; the host passes its bound lifecycle functions. */
11
+ export interface CustomizeAgentPluginLifecycle<P extends {
12
+ readonly pluginId: string;
13
+ readonly packageRoot: string;
14
+ }, B> {
15
+ readonly listInstalledPlugins: (required: {
16
+ readonly workspaceRoot: string;
17
+ }) => Promise<readonly P[]>;
18
+ readonly readBundledAgentPluginDigests: (required: {
19
+ readonly workspaceRoot: string;
20
+ }) => Promise<B>;
21
+ readonly preferBundledAgentPluginDigests: (installed: readonly P[], bundled: B) => readonly P[];
22
+ readonly maxAgentPluginInstallArchiveBytes: () => number;
23
+ }
24
+ /**
25
+ * Prepare a fork after the install tool's authorization; publication stays with that tool's owner.
26
+ * @param required Host deps, the actual assistant tool context and the host's lifecycle calls.
27
+ * @returns ZIP bytes for the existing install flow. Never writes an installed package.
28
+ * @throws {ToolInputError} Unknown/ambiguous source or invalid edit.
29
+ * @complexity O(p + e log e + b) for p installed packages, e files and bounded bytes b; no network.
30
+ */
31
+ export declare function prepareCustomizedAgentPluginArchive<P extends {
32
+ readonly pluginId: string;
33
+ readonly packageRoot: string;
34
+ }, B>({ deps, ctx, lifecycle }: {
35
+ deps: CustomizeAgentPluginDeps;
36
+ ctx: ToolExecutionContext;
37
+ lifecycle: CustomizeAgentPluginLifecycle<P, B>;
38
+ }, options?: Pick<AgentPluginIdentityReadOptions, "legacyIdentity">): Promise<Uint8Array>;
39
+ //# sourceMappingURL=customize-tool.d.ts.map