@jini-ai/agent-plugins 0.4.6 → 0.4.8

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 (152) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +48 -0
  3. package/dist/admin-surfaces/action-dispatcher.d.ts +37 -0
  4. package/dist/admin-surfaces/action-dispatcher.js +69 -0
  5. package/dist/admin-surfaces/action-schema.d.ts +56 -0
  6. package/dist/admin-surfaces/action-schema.js +167 -0
  7. package/dist/admin-surfaces/action-tools.d.ts +40 -0
  8. package/dist/admin-surfaces/action-tools.js +52 -0
  9. package/dist/admin-surfaces/callback-field-inbox.d.ts +35 -0
  10. package/dist/admin-surfaces/callback-field-inbox.js +53 -0
  11. package/dist/admin-surfaces/capability-declarations.d.ts +41 -0
  12. package/dist/admin-surfaces/capability-declarations.js +102 -0
  13. package/dist/admin-surfaces/contribution.d.ts +49 -0
  14. package/dist/admin-surfaces/contribution.js +30 -0
  15. package/dist/admin-surfaces/delivery-bindings.d.ts +76 -0
  16. package/dist/admin-surfaces/delivery-bindings.js +99 -0
  17. package/dist/admin-surfaces/descriptor.d.ts +69 -0
  18. package/dist/admin-surfaces/descriptor.js +196 -0
  19. package/dist/admin-surfaces/external-links.d.ts +45 -0
  20. package/dist/admin-surfaces/external-links.js +70 -0
  21. package/dist/admin-surfaces/host-validator.d.ts +62 -0
  22. package/dist/admin-surfaces/host-validator.js +87 -0
  23. package/dist/admin-surfaces/index.d.ts +23 -0
  24. package/dist/admin-surfaces/index.js +21 -0
  25. package/dist/admin-surfaces/protocol.d.ts +103 -0
  26. package/dist/admin-surfaces/protocol.js +25 -0
  27. package/dist/admin-surfaces/sandbox.d.ts +78 -0
  28. package/dist/admin-surfaces/sandbox.js +92 -0
  29. package/dist/admin-surfaces/settings-value.d.ts +28 -0
  30. package/dist/admin-surfaces/settings-value.js +45 -0
  31. package/dist/admin-surfaces/surface-capabilities.d.ts +167 -0
  32. package/dist/admin-surfaces/surface-capabilities.js +215 -0
  33. package/dist/admin-surfaces/surface-client.d.ts +116 -0
  34. package/dist/admin-surfaces/surface-client.js +219 -0
  35. package/dist/admin-surfaces/surface-handlers.d.ts +111 -0
  36. package/dist/admin-surfaces/surface-handlers.js +172 -0
  37. package/dist/admin-surfaces/theme.d.ts +59 -0
  38. package/dist/admin-surfaces/theme.js +57 -0
  39. package/dist/folder-zip-node.d.ts +11 -0
  40. package/dist/folder-zip-node.js +84 -0
  41. package/dist/folder-zip.d.ts +38 -0
  42. package/dist/folder-zip.js +134 -0
  43. package/dist/lifecycle/automatic-use.d.ts +79 -0
  44. package/dist/lifecycle/automatic-use.js +165 -0
  45. package/dist/lifecycle/compatibility-metadata.d.ts +19 -0
  46. package/dist/lifecycle/compatibility-metadata.js +45 -0
  47. package/dist/lifecycle/compatibility.d.ts +52 -0
  48. package/dist/lifecycle/compatibility.js +60 -0
  49. package/dist/lifecycle/fetch-archive.js +26 -24
  50. package/dist/lifecycle/index.d.ts +14 -2
  51. package/dist/lifecycle/index.js +8 -1
  52. package/dist/lifecycle/install-errors.d.ts +14 -0
  53. package/dist/lifecycle/install-errors.js +9 -0
  54. package/dist/lifecycle/install.d.ts +2 -13
  55. package/dist/lifecycle/install.js +12 -123
  56. package/dist/lifecycle/installed-package-index.d.ts +15 -0
  57. package/dist/lifecycle/installed-package-index.js +128 -0
  58. package/dist/lifecycle/installed-package-roots.js +28 -20
  59. package/dist/lifecycle/manifest.d.ts +14 -0
  60. package/dist/lifecycle/manifest.js +115 -100
  61. package/dist/lifecycle/package-paths.js +3 -3
  62. package/dist/lifecycle/ports.d.ts +1 -1
  63. package/dist/lifecycle/provider-contribution.d.ts +65 -0
  64. package/dist/lifecycle/provider-contribution.js +93 -0
  65. package/dist/lifecycle/resolve-agent-plugin-refs.js +19 -6
  66. package/dist/lifecycle/retire-bundled.js +20 -18
  67. package/dist/lifecycle/search.d.ts +6 -1
  68. package/dist/lifecycle/search.js +45 -7
  69. package/dist/lifecycle/set-enabled.d.ts +2 -1
  70. package/dist/lifecycle/set-enabled.js +52 -8
  71. package/dist/lifecycle/skill-file-reader.js +85 -71
  72. package/dist/lifecycle/tools/capabilities.d.ts +199 -0
  73. package/dist/lifecycle/tools/capabilities.js +213 -0
  74. package/dist/lifecycle/tools/definition.d.ts +32 -0
  75. package/dist/lifecycle/tools/definition.js +33 -0
  76. package/dist/lifecycle/tools/index.d.ts +10 -0
  77. package/dist/lifecycle/tools/index.js +10 -0
  78. package/dist/lifecycle/tools/manifest.d.ts +33 -0
  79. package/dist/lifecycle/tools/manifest.js +89 -0
  80. package/dist/lifecycle/tools/projection.d.ts +90 -0
  81. package/dist/lifecycle/tools/projection.js +283 -0
  82. package/dist/lifecycle/types.d.ts +2 -0
  83. package/dist/lifecycle/uninstall.d.ts +3 -1
  84. package/dist/lifecycle/uninstall.js +51 -27
  85. package/dist/lifecycle/update-plan.d.ts +18 -0
  86. package/dist/lifecycle/update-plan.js +22 -0
  87. package/dist/lifecycle/update-store.d.ts +71 -0
  88. package/dist/lifecycle/update-store.js +150 -0
  89. package/dist/lifecycle/update.d.ts +55 -0
  90. package/dist/lifecycle/update.js +321 -0
  91. package/dist/manifest.d.ts +2 -1
  92. package/dist/manifest.js +2 -1
  93. package/package.json +50 -6
  94. package/ui-ux-design/plugin.json +8 -2
  95. package/dist/index.d.ts.map +0 -1
  96. package/dist/index.js.map +0 -1
  97. package/dist/lifecycle/activation.d.ts.map +0 -1
  98. package/dist/lifecycle/activation.js.map +0 -1
  99. package/dist/lifecycle/bundled-digests.d.ts.map +0 -1
  100. package/dist/lifecycle/bundled-digests.js.map +0 -1
  101. package/dist/lifecycle/bundled-source-archive.d.ts.map +0 -1
  102. package/dist/lifecycle/bundled-source-archive.js.map +0 -1
  103. package/dist/lifecycle/capability-projection.d.ts.map +0 -1
  104. package/dist/lifecycle/capability-projection.js.map +0 -1
  105. package/dist/lifecycle/contribution-loader.d.ts.map +0 -1
  106. package/dist/lifecycle/contribution-loader.js.map +0 -1
  107. package/dist/lifecycle/fetch-archive.d.ts.map +0 -1
  108. package/dist/lifecycle/fetch-archive.js.map +0 -1
  109. package/dist/lifecycle/index.d.ts.map +0 -1
  110. package/dist/lifecycle/index.js.map +0 -1
  111. package/dist/lifecycle/install-from-url.d.ts.map +0 -1
  112. package/dist/lifecycle/install-from-url.js.map +0 -1
  113. package/dist/lifecycle/install.d.ts.map +0 -1
  114. package/dist/lifecycle/install.js.map +0 -1
  115. package/dist/lifecycle/installed-package-roots.d.ts.map +0 -1
  116. package/dist/lifecycle/installed-package-roots.js.map +0 -1
  117. package/dist/lifecycle/layout.d.ts.map +0 -1
  118. package/dist/lifecycle/layout.js.map +0 -1
  119. package/dist/lifecycle/manifest.d.ts.map +0 -1
  120. package/dist/lifecycle/manifest.js.map +0 -1
  121. package/dist/lifecycle/mcp-provisioning.d.ts.map +0 -1
  122. package/dist/lifecycle/mcp-provisioning.js.map +0 -1
  123. package/dist/lifecycle/node.d.ts.map +0 -1
  124. package/dist/lifecycle/node.js.map +0 -1
  125. package/dist/lifecycle/package-paths.d.ts.map +0 -1
  126. package/dist/lifecycle/package-paths.js.map +0 -1
  127. package/dist/lifecycle/persistent-state.d.ts.map +0 -1
  128. package/dist/lifecycle/persistent-state.js.map +0 -1
  129. package/dist/lifecycle/ports.d.ts.map +0 -1
  130. package/dist/lifecycle/ports.js.map +0 -1
  131. package/dist/lifecycle/resolve-agent-plugin-refs.d.ts.map +0 -1
  132. package/dist/lifecycle/resolve-agent-plugin-refs.js.map +0 -1
  133. package/dist/lifecycle/retire-bundled.d.ts.map +0 -1
  134. package/dist/lifecycle/retire-bundled.js.map +0 -1
  135. package/dist/lifecycle/search.d.ts.map +0 -1
  136. package/dist/lifecycle/search.js.map +0 -1
  137. package/dist/lifecycle/seed-bundled.d.ts.map +0 -1
  138. package/dist/lifecycle/seed-bundled.js.map +0 -1
  139. package/dist/lifecycle/set-enabled.d.ts.map +0 -1
  140. package/dist/lifecycle/set-enabled.js.map +0 -1
  141. package/dist/lifecycle/skill-file-reader.d.ts.map +0 -1
  142. package/dist/lifecycle/skill-file-reader.js.map +0 -1
  143. package/dist/lifecycle/trusted-plugin-files.d.ts.map +0 -1
  144. package/dist/lifecycle/trusted-plugin-files.js.map +0 -1
  145. package/dist/lifecycle/types.d.ts.map +0 -1
  146. package/dist/lifecycle/types.js.map +0 -1
  147. package/dist/lifecycle/uninstall.d.ts.map +0 -1
  148. package/dist/lifecycle/uninstall.js.map +0 -1
  149. package/dist/lifecycle/yauzl-archive-reader.d.ts.map +0 -1
  150. package/dist/lifecycle/yauzl-archive-reader.js.map +0 -1
  151. package/dist/manifest.d.ts.map +0 -1
  152. package/dist/manifest.js.map +0 -1
@@ -0,0 +1,78 @@
1
+ /**
2
+ * @file The isolation contract a host applies when it renders and serves an admin surface: the
3
+ * iframe attributes, the Content-Security-Policy and headers for each served surface file, the mount
4
+ * nonce, and the short-lived, never-cached bootstrap envelope.
5
+ *
6
+ * Why these are pure helpers instead of host code: every host must apply the SAME strict values, and
7
+ * the values are the security boundary (no same-origin, no inline script, no direct network access
8
+ * unless the descriptor declared and validation accepted an https origin). Hosts call these and only
9
+ * choose routes.
10
+ */
11
+ import type { AdminSurfaceDescriptor } from './descriptor.js';
12
+ import { type AdminSurfaceBootstrap } from './protocol.js';
13
+ /**
14
+ * The attributes for the `<iframe>` that renders a surface. `sandbox` is exactly `allow-scripts`:
15
+ * the frame gets an opaque origin, so it cannot read the host's cookies, storage or DOM.
16
+ * @complexity O(1).
17
+ */
18
+ export declare function adminSurfaceFrameAttributes(required: {
19
+ readonly src: string;
20
+ readonly title: string;
21
+ }, _optional?: Record<string, never>): {
22
+ readonly src: string;
23
+ readonly title: string;
24
+ readonly sandbox: "allow-scripts";
25
+ readonly referrerPolicy: "no-referrer";
26
+ };
27
+ /**
28
+ * The CSP for every file of one surface. Starts from `default-src 'none'`; scripts, styles, images
29
+ * and fonts may come from the surface's own files; `connect-src` and `frame-src` are closed unless the
30
+ * descriptor declared validated https origins. The `sandbox` directive keeps the document sandboxed
31
+ * even when opened directly rather than through the host's iframe.
32
+ * @complexity O(c) declared CSP sources.
33
+ */
34
+ export declare function adminSurfaceContentSecurityPolicy(required: {
35
+ readonly descriptor: Pick<AdminSurfaceDescriptor, 'csp'>;
36
+ }, _optional?: Record<string, never>): string;
37
+ /**
38
+ * Response headers for one served surface file. Script files carry `Access-Control-Allow-Origin: *`
39
+ * because a module script requested by an opaque-origin document is a cross-origin CORS fetch; the
40
+ * files are static plugin code fetched without credentials, so they must never contain secrets.
41
+ * @complexity O(c) declared CSP sources.
42
+ */
43
+ export declare function adminSurfaceFileHeaders(required: {
44
+ readonly descriptor: Pick<AdminSurfaceDescriptor, 'csp'>;
45
+ readonly path: string;
46
+ }, _optional?: Record<string, never>): Readonly<Record<string, string>>;
47
+ /** One rendered surface: the nonce its messages must echo (they must also come from origin "null").
48
+ * @complexity O(1). */
49
+ export declare function createAdminSurfaceMount(required: {
50
+ readonly surfaceId: string;
51
+ }, optional?: {
52
+ readonly randomBytes?: (input: {
53
+ readonly length: number;
54
+ }) => Uint8Array;
55
+ }): {
56
+ surfaceId: string;
57
+ mountId: string;
58
+ };
59
+ /**
60
+ * The envelope a host server returns for one surface render. Its lifetime is fixed at
61
+ * {@link BOOTSTRAP_TTL_MS}, not caller-chosen: bootstrap data may include a short-lived access token.
62
+ * @complexity O(1).
63
+ */
64
+ export declare function createAdminSurfaceBootstrap<D>(required: {
65
+ readonly surfaceId: string;
66
+ readonly data: D;
67
+ readonly nowMs: number;
68
+ }, _optional?: Record<string, never>): AdminSurfaceBootstrap<D>;
69
+ /** Headers for the bootstrap response: never stored by the browser or any intermediary cache.
70
+ * @complexity O(1). */
71
+ export declare function adminSurfaceBootstrapHeaders(_required?: Record<string, never>, _optional?: Record<string, never>): Readonly<Record<string, string>>;
72
+ /** True while the bootstrap may still be used.
73
+ * @complexity O(1). */
74
+ export declare function isAdminSurfaceBootstrapCurrent(required: {
75
+ readonly bootstrap: Pick<AdminSurfaceBootstrap, 'expiresAt'>;
76
+ readonly nowMs: number;
77
+ }, _optional?: Record<string, never>): boolean;
78
+ //# sourceMappingURL=sandbox.d.ts.map
@@ -0,0 +1,92 @@
1
+ import { ADMIN_SURFACE_SANDBOX } from './protocol.js';
2
+ /** Bootstrap data is meant to live for one render: one minute, fixed so no host can lengthen it. */
3
+ const BOOTSTRAP_TTL_MS = 60_000;
4
+ const CONTENT_TYPES = {
5
+ html: 'text/html; charset=utf-8',
6
+ mjs: 'text/javascript; charset=utf-8',
7
+ js: 'text/javascript; charset=utf-8',
8
+ css: 'text/css; charset=utf-8',
9
+ json: 'application/json; charset=utf-8',
10
+ };
11
+ /**
12
+ * The attributes for the `<iframe>` that renders a surface. `sandbox` is exactly `allow-scripts`:
13
+ * the frame gets an opaque origin, so it cannot read the host's cookies, storage or DOM.
14
+ * @complexity O(1).
15
+ */
16
+ export function adminSurfaceFrameAttributes(required, _optional = {}) {
17
+ return { src: required.src, title: required.title, sandbox: ADMIN_SURFACE_SANDBOX, referrerPolicy: 'no-referrer' };
18
+ }
19
+ /**
20
+ * The CSP for every file of one surface. Starts from `default-src 'none'`; scripts, styles, images
21
+ * and fonts may come from the surface's own files; `connect-src` and `frame-src` are closed unless the
22
+ * descriptor declared validated https origins. The `sandbox` directive keeps the document sandboxed
23
+ * even when opened directly rather than through the host's iframe.
24
+ * @complexity O(c) declared CSP sources.
25
+ */
26
+ export function adminSurfaceContentSecurityPolicy(required, _optional = {}) {
27
+ const extra = (directive) => required.descriptor.csp[directive] ?? [];
28
+ const own = (directive) => [`'self'`, ...extra(directive)].join(' ');
29
+ const closed = (directive) => (extra(directive).length ? extra(directive).join(' ') : `'none'`);
30
+ return [
31
+ `default-src 'none'`,
32
+ `script-src ${own('script-src')}`,
33
+ `style-src ${own('style-src')}`,
34
+ `img-src ${own('img-src')}`,
35
+ `font-src ${own('font-src')}`,
36
+ `connect-src ${closed('connect-src')}`,
37
+ `frame-src ${closed('frame-src')}`,
38
+ `form-action 'none'`,
39
+ `base-uri 'none'`,
40
+ `frame-ancestors 'self'`,
41
+ `sandbox ${ADMIN_SURFACE_SANDBOX}`,
42
+ ].join('; ');
43
+ }
44
+ /**
45
+ * Response headers for one served surface file. Script files carry `Access-Control-Allow-Origin: *`
46
+ * because a module script requested by an opaque-origin document is a cross-origin CORS fetch; the
47
+ * files are static plugin code fetched without credentials, so they must never contain secrets.
48
+ * @complexity O(c) declared CSP sources.
49
+ */
50
+ export function adminSurfaceFileHeaders(required, _optional = {}) {
51
+ const extension = required.path.slice(required.path.lastIndexOf('.') + 1);
52
+ const script = extension === 'mjs' || extension === 'js';
53
+ return {
54
+ 'Content-Type': CONTENT_TYPES[extension] ?? 'application/octet-stream',
55
+ 'Content-Security-Policy': adminSurfaceContentSecurityPolicy({ descriptor: required.descriptor }),
56
+ 'X-Content-Type-Options': 'nosniff',
57
+ 'Referrer-Policy': 'no-referrer',
58
+ 'Cache-Control': 'no-cache',
59
+ ...(script ? { 'Access-Control-Allow-Origin': '*' } : {}),
60
+ };
61
+ }
62
+ /** One rendered surface: the nonce its messages must echo (they must also come from origin "null").
63
+ * @complexity O(1). */
64
+ export function createAdminSurfaceMount(required, optional = {}) {
65
+ const randomBytes = optional.randomBytes ?? (({ length }) => globalThis.crypto.getRandomValues(new Uint8Array(length)));
66
+ const mountId = Array.from(randomBytes({ length: 16 }), (byte) => byte.toString(16).padStart(2, '0')).join('');
67
+ return { surfaceId: required.surfaceId, mountId };
68
+ }
69
+ /**
70
+ * The envelope a host server returns for one surface render. Its lifetime is fixed at
71
+ * {@link BOOTSTRAP_TTL_MS}, not caller-chosen: bootstrap data may include a short-lived access token.
72
+ * @complexity O(1).
73
+ */
74
+ export function createAdminSurfaceBootstrap(required, _optional = {}) {
75
+ return { surfaceId: required.surfaceId, issuedAt: required.nowMs, expiresAt: required.nowMs + BOOTSTRAP_TTL_MS, data: required.data };
76
+ }
77
+ /** Headers for the bootstrap response: never stored by the browser or any intermediary cache.
78
+ * @complexity O(1). */
79
+ export function adminSurfaceBootstrapHeaders(_required = {}, _optional = {}) {
80
+ return {
81
+ 'Content-Type': 'application/json; charset=utf-8',
82
+ 'Cache-Control': 'no-store',
83
+ Pragma: 'no-cache',
84
+ 'X-Content-Type-Options': 'nosniff',
85
+ };
86
+ }
87
+ /** True while the bootstrap may still be used.
88
+ * @complexity O(1). */
89
+ export function isAdminSurfaceBootstrapCurrent(required, _optional = {}) {
90
+ return required.nowMs < required.bootstrap.expiresAt;
91
+ }
92
+ //# sourceMappingURL=sandbox.js.map
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @file The one check every plugin-written settings value passes before a host stores it: plugin
3
+ * state (`./surface-capabilities.ts`) and a delivery binding's config (`./delivery-bindings.ts`).
4
+ *
5
+ * Why it is shared: both are plugin-chosen JSON the host persists and later hands back (to the
6
+ * plugin's tools, or to the delivery adapter), so both need the same guarantees — plain JSON only,
7
+ * bounded depth and size, and never a token the plugin obtained — and must not drift apart.
8
+ */
9
+ import { type AgentPluginCapabilityGate, type AgentPluginStateValue } from '../lifecycle/tools/capabilities.js';
10
+ export declare const ADMIN_SURFACE_STATE_LIMITS: Readonly<{
11
+ maxKeyLength: 128;
12
+ maxValueBytes: number;
13
+ maxDepth: 16;
14
+ }>;
15
+ export declare const STATE_CREDENTIAL_MESSAGE = "The plugin tried to save a connection credential in its settings; nothing was saved.";
16
+ /**
17
+ * The value the host stores: serialized once, scanned and size-checked on that text, then parsed
18
+ * back, so what is stored is exactly what was checked (the plugin cannot change it afterwards).
19
+ * @param required.gate - The call's capability gate (its token memory drives the scan).
20
+ * @param required.value - The plugin's value, unchecked.
21
+ * @throws Error when the value is not plain JSON, is too large, or mentions an obtained token.
22
+ * @complexity O(n) in the serialized size.
23
+ */
24
+ export declare function storedStateValue(required: {
25
+ readonly gate: AgentPluginCapabilityGate;
26
+ readonly value: unknown;
27
+ }, _optional?: Record<string, never>): AgentPluginStateValue;
28
+ //# sourceMappingURL=settings-value.d.ts.map
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @file The one check every plugin-written settings value passes before a host stores it: plugin
3
+ * state (`./surface-capabilities.ts`) and a delivery binding's config (`./delivery-bindings.ts`).
4
+ *
5
+ * Why it is shared: both are plugin-chosen JSON the host persists and later hands back (to the
6
+ * plugin's tools, or to the delivery adapter), so both need the same guarantees — plain JSON only,
7
+ * bounded depth and size, and never a token the plugin obtained — and must not drift apart.
8
+ */
9
+ import { PLUGIN_STATE_MAX_KEY_LENGTH } from '../lifecycle/tools/capabilities.js';
10
+ export const ADMIN_SURFACE_STATE_LIMITS = Object.freeze({ maxKeyLength: PLUGIN_STATE_MAX_KEY_LENGTH, maxValueBytes: 16 * 1024, maxDepth: 16 });
11
+ export const STATE_CREDENTIAL_MESSAGE = 'The plugin tried to save a connection credential in its settings; nothing was saved.';
12
+ function isStateScalar(value) {
13
+ return value === null || typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value));
14
+ }
15
+ /** True for plain JSON data only: no undefined, functions, NaN, class instances or deep nesting. @complexity O(n) nodes. */
16
+ function isStateValue(value, depth) {
17
+ if (isStateScalar(value))
18
+ return true;
19
+ if (typeof value !== 'object' || depth >= ADMIN_SURFACE_STATE_LIMITS.maxDepth)
20
+ return false;
21
+ if (Array.isArray(value))
22
+ return value.every((item) => isStateValue(item, depth + 1));
23
+ const prototype = Object.getPrototypeOf(value);
24
+ return (prototype === Object.prototype || prototype === null) && Object.values(value).every((item) => isStateValue(item, depth + 1));
25
+ }
26
+ /**
27
+ * The value the host stores: serialized once, scanned and size-checked on that text, then parsed
28
+ * back, so what is stored is exactly what was checked (the plugin cannot change it afterwards).
29
+ * @param required.gate - The call's capability gate (its token memory drives the scan).
30
+ * @param required.value - The plugin's value, unchecked.
31
+ * @throws Error when the value is not plain JSON, is too large, or mentions an obtained token.
32
+ * @complexity O(n) in the serialized size.
33
+ */
34
+ export function storedStateValue(required, _optional = {}) {
35
+ const { gate, value } = required;
36
+ if (!isStateValue(value, 0))
37
+ throw new Error('A settings value must be plain JSON data (no undefined, functions, NaN or class instances).');
38
+ const text = JSON.stringify(value);
39
+ if (new TextEncoder().encode(text).byteLength > ADMIN_SURFACE_STATE_LIMITS.maxValueBytes)
40
+ throw new Error(`A settings value may be at most ${ADMIN_SURFACE_STATE_LIMITS.maxValueBytes} bytes of JSON.`);
41
+ if (gate.mentionsToken({ value: text }))
42
+ throw new Error(STATE_CREDENTIAL_MESSAGE);
43
+ return JSON.parse(text);
44
+ }
45
+ //# sourceMappingURL=settings-value.js.map
@@ -0,0 +1,167 @@
1
+ /**
2
+ * @file The host capability ports a plugin's admin-surface handlers receive, and the per-call
3
+ * session that wraps them. Jini defines the shapes and the checks; the host implements the ports
4
+ * (connections backed by its API-connection service, state by its own store, public config by its
5
+ * own settings) and Jini never names a provider.
6
+ *
7
+ * Why surfaces get more than tools: account actions (connect, reconnect, switch account, disconnect)
8
+ * and saving a chosen resource are admin actions a person takes on a settings screen, so they exist
9
+ * here and never on the executable-tool port. Why every check sits here and not only in the host:
10
+ * the surfaces file is the shipped, digest-checked allowlist, so the session refuses anything the
11
+ * surface did not declare (a connection, a start parameter, a callback field, a config name) before
12
+ * the host sees it, and a host that answers with more than the port promises (a connection ref, raw
13
+ * scopes, undeclared callback fields) is cut back to the declared shape. Like the tool session it
14
+ * revokes everything once the plugin is disabled and withholds results and errors that mention a
15
+ * token the plugin obtained (in this call, an earlier one, or one of its tools); it also refuses to persist
16
+ * such a token in plugin state.
17
+ */
18
+ import { type AgentPluginStateReader, type AgentPluginStateValue, type AgentPluginToolCapabilities, type AgentPluginToolCapabilityScope, type IssuedTokenMemory } from '../lifecycle/tools/capabilities.js';
19
+ import type { AdminSurfaceCapabilityDeclarations } from './capability-declarations.js';
20
+ import { type AdminSurfaceDeliveryBindings } from './delivery-bindings.js';
21
+ export { ADMIN_SURFACE_STATE_LIMITS, STATE_CREDENTIAL_MESSAGE } from './settings-value.js';
22
+ /** Mirrors the API-connection lifecycle (`ApiConnectionStatus`); only `connected` serves access tokens. */
23
+ export type AdminSurfaceConnectionState = 'connected' | 'reconnect-required' | 'revocation-pending' | 'disconnected';
24
+ /**
25
+ * The API-connection start intent each account action maps to (`ApiConnectionIntent` in
26
+ * `@jini-ai/integrations/api-connections`, mirrored because agent-plugins does not depend on it), so a
27
+ * host passes `ADMIN_SURFACE_ACTION_INTENTS[action]` straight to `start`. `reconnect` and `add-scopes`
28
+ * are a same-account `connect` with the scope sets the handler passes (`add-scopes` re-consents for
29
+ * more of them); `switch` stages another account.
30
+ */
31
+ export declare const ADMIN_SURFACE_ACTION_INTENTS: Readonly<{
32
+ readonly connect: "connect";
33
+ readonly reconnect: "connect";
34
+ readonly switch: "switch-account";
35
+ readonly 'add-scopes': "connect";
36
+ }>;
37
+ export type AdminSurfaceConnectionAction = keyof typeof ADMIN_SURFACE_ACTION_INTENTS;
38
+ /**
39
+ * The honest remote outcome of a disconnect, the same values as `ApiConnectionRemoteRevocation`:
40
+ * never `confirmed` unless the provider confirmed it.
41
+ */
42
+ export type AdminSurfaceRevocationOutcome = 'confirmed' | 'pending' | 'not-needed';
43
+ /** Token-free status. Scope sets are the plugin's own ids, never raw provider scopes. */
44
+ export interface AdminSurfaceConnectionStatus {
45
+ readonly connectionId: string;
46
+ readonly status: AdminSurfaceConnectionState;
47
+ readonly accountLabel: string | null;
48
+ readonly grantedScopeSetIds: readonly string[];
49
+ /** The account a staged switch would move to, awaiting `confirmSwitch`. */
50
+ readonly pendingSwitchAccountLabel: string | null;
51
+ /** Why the latest sign-in did not complete and what to do next, as the HOST's own lowercase
52
+ * hyphenated codes (for example `access-denied` / `reconnect`), never provider text; `null` when
53
+ * the latest attempt succeeded or none is recorded. A value that is not a safe code becomes `null`. */
54
+ readonly lastSignInAttempt: AdminSurfaceSignInAttempt | null;
55
+ }
56
+ /** The outcome codes of a sign-in attempt that did not complete. */
57
+ export interface AdminSurfaceSignInAttempt {
58
+ readonly code: string;
59
+ readonly nextAction: string;
60
+ }
61
+ /** A sign-in the person opens (a button on hosted, the system browser on desktop). */
62
+ export interface AdminSurfaceAuthorizationStart {
63
+ readonly authorizationUrl: string;
64
+ /** Opaque id for `takeCallbackFields` once the sign-in completed: the connection service's attempt
65
+ * id, never the authorization `state`. */
66
+ readonly attemptId: string;
67
+ readonly expiresAt: string;
68
+ }
69
+ export interface AdminSurfaceConnections {
70
+ /** A fresh access token for one of the surface's declared connections; never a refresh token. */
71
+ getAccessToken(required: {
72
+ readonly connectionId: string;
73
+ }, optional?: Record<string, never>): Promise<string>;
74
+ status(required: {
75
+ readonly connectionId: string;
76
+ }, optional?: Record<string, never>): Promise<AdminSurfaceConnectionStatus>;
77
+ begin(required: {
78
+ readonly connectionId: string;
79
+ readonly action: AdminSurfaceConnectionAction;
80
+ }, optional?: {
81
+ readonly scopeSetIds?: readonly string[];
82
+ readonly startParams?: Readonly<Record<string, string>>;
83
+ }): Promise<AdminSurfaceAuthorizationStart>;
84
+ confirmSwitch(required: {
85
+ readonly connectionId: string;
86
+ }, optional?: Record<string, never>): Promise<AdminSurfaceConnectionStatus>;
87
+ cancelSwitch(required: {
88
+ readonly connectionId: string;
89
+ }, optional?: Record<string, never>): Promise<AdminSurfaceConnectionStatus>;
90
+ disconnect(required: {
91
+ readonly connectionId: string;
92
+ }, optional?: Record<string, never>): Promise<AdminSurfaceConnectionStatus & {
93
+ readonly revocation: AdminSurfaceRevocationOutcome;
94
+ }>;
95
+ /** The declared callback fields of a completed sign-in, once; `null` when absent, taken or not completed.
96
+ * Still untrusted: verify them through the provider's API before saving anything. */
97
+ takeCallbackFields(required: {
98
+ readonly connectionId: string;
99
+ readonly attemptId: string;
100
+ }, optional?: Record<string, never>): Promise<Readonly<Record<string, string>> | null>;
101
+ }
102
+ export type AdminSurfaceStateValue = AgentPluginStateValue;
103
+ /** Plugin- and workspace-scoped JSON values (the host keys them by the session's scope). The plugin's
104
+ * tools read the same store through the read-only `AgentPluginStateReader`; only surfaces write. */
105
+ export interface AdminSurfaceState extends AgentPluginStateReader {
106
+ set(required: {
107
+ readonly key: string;
108
+ readonly value: AdminSurfaceStateValue;
109
+ }, optional?: Record<string, never>): Promise<void>;
110
+ delete(required: {
111
+ readonly key: string;
112
+ }, optional?: Record<string, never>): Promise<void>;
113
+ }
114
+ /** Host-supplied public values (an app id, a browser key) for names the surface declares; `null` when unset. */
115
+ export interface AdminSurfacePublicConfig {
116
+ get(required: {
117
+ readonly name: string;
118
+ }, optional?: Record<string, never>): Promise<string | null>;
119
+ }
120
+ /** Only form identity and display text, never fields, recipients or submission data. */
121
+ export interface AdminSurfaceForm {
122
+ readonly slug: string;
123
+ readonly title: string;
124
+ }
125
+ /** Workspace-scoped discovery. The session returns at most 200 choices; titles are capped at 1024 characters. */
126
+ export interface AdminSurfaceForms {
127
+ list(required: Record<string, never>, optional?: Record<string, never>): Promise<readonly AdminSurfaceForm[]>;
128
+ }
129
+ export type AdminSurfaceCapabilities = Pick<AgentPluginToolCapabilities, 'http' | 'limiter' | 'artifacts'> & {
130
+ readonly connections: AdminSurfaceConnections;
131
+ readonly state: AdminSurfaceState;
132
+ readonly publicConfig: AdminSurfacePublicConfig;
133
+ /** The workspace's form-delivery bindings (`./delivery-bindings.ts`). Optional for the host; a handler
134
+ * gets it only when its surface declares `deliveryAdapters` and the host provides it. */
135
+ readonly deliveryBindings?: AdminSurfaceDeliveryBindings;
136
+ /** Absent unless both the host supplies it and this surface declares `forms: ["list"]`. */
137
+ readonly forms?: AdminSurfaceForms;
138
+ };
139
+ /** Host port: builds one call's capabilities for the loaded plugin, workspace and admin principal. */
140
+ export type AdminSurfaceCapabilitiesPort = (required: AgentPluginToolCapabilityScope, optional?: Record<string, never>) => AdminSurfaceCapabilities;
141
+ /**
142
+ * Opens the capability session for one admin-surface handler call.
143
+ * @param required.capabilities - The host's ports for this call (already scoped to plugin, workspace, principal).
144
+ * @param required.isLive - False once the plugin's surface handlers are revoked.
145
+ * @param required.declared - The surface's own capability declarations (the allowlists).
146
+ * @param required.issued - The plugin's token memory, shared by all its calls (tools included).
147
+ * @param optional.actorId - The signed-in admin; account actions are refused without one.
148
+ * @returns Wrapped capabilities plus the shared `release` (result) and `sanitize` (error) gates.
149
+ * @complexity O(1) to open; each check is bounded by the declared lists and the value caps.
150
+ */
151
+ export declare function openAdminSurfaceCapabilitySession(required: {
152
+ readonly capabilities: AdminSurfaceCapabilities;
153
+ readonly isLive: () => boolean;
154
+ readonly declared: AdminSurfaceCapabilityDeclarations;
155
+ readonly issued: IssuedTokenMemory;
156
+ }, optional?: {
157
+ readonly actorId?: string;
158
+ }): {
159
+ capabilities: AdminSurfaceCapabilities;
160
+ release: <T>({ value }: {
161
+ readonly value: T;
162
+ }) => T;
163
+ sanitize: ({ error }: {
164
+ readonly error: unknown;
165
+ }) => unknown;
166
+ };
167
+ //# sourceMappingURL=surface-capabilities.d.ts.map
@@ -0,0 +1,215 @@
1
+ /**
2
+ * @file The host capability ports a plugin's admin-surface handlers receive, and the per-call
3
+ * session that wraps them. Jini defines the shapes and the checks; the host implements the ports
4
+ * (connections backed by its API-connection service, state by its own store, public config by its
5
+ * own settings) and Jini never names a provider.
6
+ *
7
+ * Why surfaces get more than tools: account actions (connect, reconnect, switch account, disconnect)
8
+ * and saving a chosen resource are admin actions a person takes on a settings screen, so they exist
9
+ * here and never on the executable-tool port. Why every check sits here and not only in the host:
10
+ * the surfaces file is the shipped, digest-checked allowlist, so the session refuses anything the
11
+ * surface did not declare (a connection, a start parameter, a callback field, a config name) before
12
+ * the host sees it, and a host that answers with more than the port promises (a connection ref, raw
13
+ * scopes, undeclared callback fields) is cut back to the declared shape. Like the tool session it
14
+ * revokes everything once the plugin is disabled and withholds results and errors that mention a
15
+ * token the plugin obtained (in this call, an earlier one, or one of its tools); it also refuses to persist
16
+ * such a token in plugin state.
17
+ */
18
+ import { checkedStateKey, guardSharedCapabilities, guardStateReader, openCapabilityGate, } from '../lifecycle/tools/capabilities.js';
19
+ import { guardDeliveryBindings } from './delivery-bindings.js';
20
+ import { storedStateValue } from './settings-value.js';
21
+ // Moved to `./settings-value.ts` so delivery-binding config shares the exact checks; re-exported so callers keep importing them here.
22
+ export { ADMIN_SURFACE_STATE_LIMITS, STATE_CREDENTIAL_MESSAGE } from './settings-value.js';
23
+ /**
24
+ * The API-connection start intent each account action maps to (`ApiConnectionIntent` in
25
+ * `@jini-ai/integrations/api-connections`, mirrored because agent-plugins does not depend on it), so a
26
+ * host passes `ADMIN_SURFACE_ACTION_INTENTS[action]` straight to `start`. `reconnect` and `add-scopes`
27
+ * are a same-account `connect` with the scope sets the handler passes (`add-scopes` re-consents for
28
+ * more of them); `switch` stages another account.
29
+ */
30
+ export const ADMIN_SURFACE_ACTION_INTENTS = Object.freeze({
31
+ connect: 'connect', reconnect: 'connect', switch: 'switch-account', 'add-scopes': 'connect',
32
+ });
33
+ const ACTIONS = Object.keys(ADMIN_SURFACE_ACTION_INTENTS);
34
+ const SCOPE_SET_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
35
+ const ATTEMPT_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
36
+ const MAX_SCOPE_SETS = 16;
37
+ const MAX_START_PARAM_LENGTH = 2048;
38
+ /** Names in messages come from plugin code: cut them so a message stays a message. */
39
+ const named = (value) => String(value).slice(0, 64);
40
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
41
+ function declaredConnection(declared, connectionId) {
42
+ const found = declared.find((connection) => connection.id === connectionId);
43
+ if (found === undefined)
44
+ throw new Error(`This admin surface does not declare connection '${named(connectionId)}', so its handlers cannot use it. Declare it in the surface's connections.`);
45
+ return found;
46
+ }
47
+ /** A copy of the start parameters, every name declared for this connection and every value a bounded string. @complexity O(p). */
48
+ function checkedStartParams(connection, startParams) {
49
+ if (!isRecord(startParams))
50
+ throw new Error('Start parameters must be an object of strings.');
51
+ for (const [name, value] of Object.entries(startParams)) {
52
+ if (!connection.startParams.includes(name))
53
+ throw new Error(`Start parameter '${named(name)}' is not declared for connection '${connection.id}' on this admin surface.`);
54
+ if (typeof value !== 'string' || value.length > MAX_START_PARAM_LENGTH)
55
+ throw new Error(`Start parameter '${name}' must be a string of at most ${MAX_START_PARAM_LENGTH} characters.`);
56
+ }
57
+ return { ...startParams };
58
+ }
59
+ function checkedScopeSetIds(scopeSetIds) {
60
+ const valid = Array.isArray(scopeSetIds) && scopeSetIds.length <= MAX_SCOPE_SETS && scopeSetIds.every((id) => typeof id === 'string' && SCOPE_SET_ID_PATTERN.test(id));
61
+ if (!valid)
62
+ throw new Error(`Scope sets must be at most ${MAX_SCOPE_SETS} short ids.`);
63
+ return [...scopeSetIds];
64
+ }
65
+ /** The begin options the host receives: only the ones the handler passed, checked and copied. */
66
+ function beginOptions(connection, optional = {}) {
67
+ return {
68
+ ...(optional.scopeSetIds !== undefined && { scopeSetIds: checkedScopeSetIds(optional.scopeSetIds) }),
69
+ ...(optional.startParams !== undefined && { startParams: checkedStartParams(connection, optional.startParams) }),
70
+ };
71
+ }
72
+ const SAFE_CODE_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
73
+ const MAX_SAFE_CODE_LENGTH = 64;
74
+ const isSafeCode = (value) => typeof value === 'string' && value.length <= MAX_SAFE_CODE_LENGTH && SAFE_CODE_PATTERN.test(value);
75
+ /** Only `code` and `nextAction`, and only when both are safe codes: a host that forwarded provider
76
+ * text (an error description) by mistake must not put it in front of the person or the plugin. */
77
+ function toSignInAttempt(attempt) {
78
+ if (typeof attempt !== 'object' || attempt === null)
79
+ return null;
80
+ const { code, nextAction } = attempt;
81
+ return isSafeCode(code) && isSafeCode(nextAction) ? { code, nextAction } : null;
82
+ }
83
+ /** The status shape the port promises, whatever else the host's object carried. */
84
+ function toStatus(connectionId, status) {
85
+ return {
86
+ connectionId, status: status.status, accountLabel: status.accountLabel ?? null,
87
+ grantedScopeSetIds: [...status.grantedScopeSetIds], pendingSwitchAccountLabel: status.pendingSwitchAccountLabel ?? null,
88
+ lastSignInAttempt: toSignInAttempt(status.lastSignInAttempt),
89
+ };
90
+ }
91
+ /** Only this connection's declared callback fields, as strings; anything else the host returned is dropped. */
92
+ function declaredCallbackFields(connection, fields) {
93
+ if (fields === null)
94
+ return null;
95
+ return Object.fromEntries(connection.callbackFields.filter((name) => typeof fields[name] === 'string').map((name) => [name, fields[name]]));
96
+ }
97
+ /** Account actions run for a person; a call without one (a background route) is refused. */
98
+ function requireActor(actorId) {
99
+ if (actorId === undefined)
100
+ throw new Error('Account actions need a signed-in admin. Open the surface from an authenticated admin page and retry.');
101
+ }
102
+ /**
103
+ * A token is handed out (to a handler, and through bootstrap data to the frame) only for a signed-in
104
+ * admin: a route without one must not mint a bearer token a frame keeps until it expires. Disabling
105
+ * the plugin cannot recall a token already handed out; disconnecting revokes it at the provider.
106
+ */
107
+ function requireTokenActor(actorId) {
108
+ if (actorId === undefined)
109
+ throw new Error('Connection access needs a signed-in admin. Open the surface from an authenticated admin page and retry.');
110
+ }
111
+ /** The read side: a token (noted for the scans) and token-free status. */
112
+ function readConnections({ gate, host, declared, actorId }) {
113
+ return {
114
+ getAccessToken: gate.guard(async ({ connectionId }) => {
115
+ const { id } = declaredConnection(declared, connectionId);
116
+ requireTokenActor(actorId);
117
+ return gate.noteToken({ token: await host.getAccessToken({ connectionId: id }) });
118
+ }),
119
+ status: gate.guard(async ({ connectionId }) => {
120
+ const { id } = declaredConnection(declared, connectionId);
121
+ return toStatus(id, await host.status({ connectionId: id }));
122
+ }),
123
+ takeCallbackFields: gate.guard(async ({ connectionId, attemptId }) => {
124
+ const connection = declaredConnection(declared, connectionId);
125
+ if (typeof attemptId !== 'string' || !ATTEMPT_ID_PATTERN.test(attemptId))
126
+ throw new Error('The sign-in attempt id is not valid; start the sign-in again.');
127
+ return declaredCallbackFields(connection, await host.takeCallbackFields({ connectionId: connection.id, attemptId }));
128
+ }),
129
+ };
130
+ }
131
+ /** The account actions: declared connection, declared start parameters, a signed-in admin. */
132
+ function actConnections({ gate, host, declared, actorId }) {
133
+ const forActor = (connectionId) => { requireActor(actorId); return declaredConnection(declared, connectionId); };
134
+ const statusAction = (run) => gate.guard(async ({ connectionId }) => {
135
+ const { id } = forActor(connectionId);
136
+ return toStatus(id, await run({ connectionId: id }));
137
+ });
138
+ return {
139
+ begin: gate.guard(async ({ connectionId, action }, optional) => {
140
+ const connection = forActor(connectionId);
141
+ if (!ACTIONS.includes(action))
142
+ throw new Error(`Account action '${named(action)}' is not one of ${ACTIONS.join(', ')}.`);
143
+ const started = await host.begin({ connectionId: connection.id, action }, beginOptions(connection, optional));
144
+ return { authorizationUrl: started.authorizationUrl, attemptId: started.attemptId, expiresAt: started.expiresAt };
145
+ }),
146
+ confirmSwitch: statusAction((input) => host.confirmSwitch(input)),
147
+ cancelSwitch: statusAction((input) => host.cancelSwitch(input)),
148
+ disconnect: gate.guard(async ({ connectionId }) => {
149
+ const { id } = forActor(connectionId);
150
+ const outcome = await host.disconnect({ connectionId: id });
151
+ return { ...toStatus(id, outcome), revocation: outcome.revocation };
152
+ }),
153
+ };
154
+ }
155
+ function guardState(gate, host) {
156
+ return Object.freeze({
157
+ ...guardStateReader({ gate, state: host }),
158
+ set: gate.guard(async ({ key, value }) => host.set({ key: checkedStateKey({ key }), value: storedStateValue({ gate, value }) })),
159
+ delete: gate.guard(({ key }) => host.delete({ key: checkedStateKey({ key }) })),
160
+ });
161
+ }
162
+ function guardPublicConfig(gate, host, declared) {
163
+ return Object.freeze({
164
+ get: gate.guard(async ({ name }) => {
165
+ if (!declared.includes(name))
166
+ throw new Error(`This admin surface does not declare public config '${named(name)}'. Declare it in the surface's publicConfig.`);
167
+ return host.get({ name });
168
+ }),
169
+ });
170
+ }
171
+ /** Read-only discovery shares revocation and actor checks with other surface-only ports. Unknown
172
+ * host fields never reach a handler; collection and string caps bound the disclosure.
173
+ * @complexity O(min(f, 200)) time/space for f host forms, one workspace read. */
174
+ function guardForms(required, optional = {}) {
175
+ const { gate, host } = required;
176
+ return Object.freeze({
177
+ list: gate.guard(async (_input, _options = {}) => {
178
+ requireActor(optional.actorId);
179
+ const forms = await host.list({});
180
+ return forms.slice(0, 200).map(({ slug, title }) => {
181
+ if (typeof slug !== 'string' || slug.length === 0 || slug.length > 64 || typeof title !== 'string')
182
+ throw new Error('The forms host returned an invalid form choice.');
183
+ return { slug, title: title.slice(0, 1024) };
184
+ });
185
+ }),
186
+ });
187
+ }
188
+ /**
189
+ * Opens the capability session for one admin-surface handler call.
190
+ * @param required.capabilities - The host's ports for this call (already scoped to plugin, workspace, principal).
191
+ * @param required.isLive - False once the plugin's surface handlers are revoked.
192
+ * @param required.declared - The surface's own capability declarations (the allowlists).
193
+ * @param required.issued - The plugin's token memory, shared by all its calls (tools included).
194
+ * @param optional.actorId - The signed-in admin; account actions are refused without one.
195
+ * @returns Wrapped capabilities plus the shared `release` (result) and `sanitize` (error) gates.
196
+ * @complexity O(1) to open; each check is bounded by the declared lists and the value caps.
197
+ */
198
+ export function openAdminSurfaceCapabilitySession(required, optional = {}) {
199
+ const { capabilities: host, isLive, declared, issued } = required;
200
+ const gate = openCapabilityGate({ isLive, issued });
201
+ const input = { gate, host: host.connections, declared: declared.connections ?? [], actorId: optional.actorId };
202
+ const { deliveryAdapters } = declared;
203
+ const deliveryBindings = deliveryAdapters === undefined || host.deliveryBindings === undefined ? undefined
204
+ : guardDeliveryBindings({ gate, host: host.deliveryBindings, adapterIds: deliveryAdapters, connectionIds: input.declared.map((connection) => connection.id) }, { actorId: optional.actorId });
205
+ const capabilities = Object.freeze({
206
+ ...guardSharedCapabilities({ gate, host }),
207
+ connections: Object.freeze({ ...readConnections(input), ...actConnections(input) }),
208
+ state: guardState(gate, host.state),
209
+ publicConfig: guardPublicConfig(gate, host.publicConfig, declared.publicConfig ?? []),
210
+ ...(deliveryBindings && { deliveryBindings }),
211
+ ...(declared.forms?.includes('list') && host.forms !== undefined && { forms: guardForms({ gate, host: host.forms }, optional) }),
212
+ });
213
+ return { capabilities, release: gate.release, sanitize: gate.sanitize };
214
+ }
215
+ //# sourceMappingURL=surface-capabilities.js.map