@jini-ai/integrations 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 (187) hide show
  1. package/README.md +1 -0
  2. package/dist/api-connections/bundled-client-namespace.d.ts +24 -0
  3. package/dist/api-connections/bundled-client-namespace.js +22 -0
  4. package/dist/api-connections/connect.d.ts +2 -10
  5. package/dist/api-connections/contribution.d.ts +71 -0
  6. package/dist/api-connections/contribution.js +69 -0
  7. package/dist/api-connections/form-delivery-connection.d.ts +68 -0
  8. package/dist/api-connections/form-delivery-connection.js +73 -0
  9. package/dist/api-connections/hosted-mcp/contracts.d.ts +4 -171
  10. package/dist/api-connections/hosted-mcp/index.d.ts +2 -0
  11. package/dist/api-connections/hosted-mcp/oauth-row-writes.d.ts +3 -1
  12. package/dist/api-connections/hosted-mcp/oauth-row-writes.js +6 -3
  13. package/dist/api-connections/hosted-mcp/shared-sign-in.d.ts +2 -1
  14. package/dist/api-connections/hosted-mcp/sign-in-configuration.js +1 -1
  15. package/dist/api-connections/hosted-mcp/sign-in-discovery.js +1 -1
  16. package/dist/api-connections/hosted-mcp/sign-in-flow.d.ts +9 -3
  17. package/dist/api-connections/hosted-mcp/sign-in-flow.js +6 -6
  18. package/dist/api-connections/hosted-mcp/sign-in-provider.d.ts +16 -4
  19. package/dist/api-connections/hosted-mcp/sign-in-provider.js +3 -3
  20. package/dist/api-connections/hosted-mcp/sign-in-status.d.ts +13 -2
  21. package/dist/api-connections/hosted-mcp/sign-in-status.js +17 -4
  22. package/dist/api-connections/hosted-mcp/sign-in.d.ts +1 -1
  23. package/dist/api-connections/hosted-mcp/sign-in.js +28 -30
  24. package/dist/api-connections/shared-api.d.ts +87 -0
  25. package/dist/api-connections/shared-api.js +135 -0
  26. package/dist/api-connections/shared-oauth-disconnect.d.ts +73 -0
  27. package/dist/api-connections/shared-oauth-disconnect.js +41 -0
  28. package/dist/api-connections/shared-owner.d.ts +107 -0
  29. package/dist/api-connections/shared-owner.js +79 -0
  30. package/dist/api-connections/vault-stores.d.ts +110 -0
  31. package/dist/api-connections/vault-stores.js +202 -0
  32. package/dist/credentialed-http/auth-schemes.d.ts +2 -9
  33. package/dist/credentialed-http/tools/index.d.ts +30 -0
  34. package/dist/credentialed-http/tools/index.js +19 -0
  35. package/dist/credentialed-http/tools/tool-registrations.js +0 -1
  36. package/dist/custom-credentials/agent-tools.d.ts +79 -0
  37. package/dist/custom-credentials/agent-tools.js +98 -0
  38. package/dist/custom-credentials/card-token.d.ts +15 -0
  39. package/dist/custom-credentials/card-token.js +35 -0
  40. package/dist/custom-credentials/credential-ports.d.ts +70 -0
  41. package/dist/custom-credentials/credential-ports.js +41 -0
  42. package/dist/custom-credentials/credential-recovery.d.ts +20 -0
  43. package/dist/custom-credentials/credential-recovery.js +22 -0
  44. package/dist/custom-credentials/credentialed-request.d.ts +83 -0
  45. package/dist/custom-credentials/credentialed-request.js +93 -0
  46. package/dist/custom-credentials/custom-credential-create-ui.d.ts +106 -0
  47. package/dist/custom-credentials/custom-credential-create-ui.js +136 -0
  48. package/dist/custom-credentials/custom-credential-set-token-ui.d.ts +84 -0
  49. package/dist/custom-credentials/custom-credential-set-token-ui.js +104 -0
  50. package/dist/custom-credentials/delete-request-confirmation-ui.d.ts +33 -0
  51. package/dist/custom-credentials/delete-request-confirmation-ui.js +35 -0
  52. package/dist/custom-credentials/provider-settings-card.d.ts +109 -0
  53. package/dist/custom-credentials/provider-settings-card.js +166 -0
  54. package/dist/custom-credentials/write-files-validation.d.ts +102 -0
  55. package/dist/custom-credentials/write-files-validation.js +202 -0
  56. package/dist/media-providers/catalog-projection.d.ts +29 -0
  57. package/dist/media-providers/catalog-projection.js +45 -0
  58. package/dist/media-providers/catalog.d.ts +6 -3
  59. package/dist/media-providers/catalog.js +4 -3
  60. package/dist/media-providers/configurable-catalog.d.ts +9 -0
  61. package/dist/media-providers/configurable-catalog.js +70 -0
  62. package/dist/media-providers/dispatch/builtin-vendors.js +0 -2
  63. package/dist/media-providers/dispatch/credentials.d.ts +4 -1
  64. package/dist/media-providers/dispatch/credentials.js +3 -2
  65. package/dist/media-providers/dispatch/engine.d.ts +1 -1
  66. package/dist/media-providers/dispatch/engine.js +17 -5
  67. package/dist/media-providers/dispatch/index.d.ts +3 -2
  68. package/dist/media-providers/dispatch/index.js +2 -2
  69. package/dist/media-providers/dispatch/media-provider-registry.d.ts +23 -4
  70. package/dist/media-providers/dispatch/media-provider-registry.js +26 -11
  71. package/dist/media-providers/dispatch/media-wire.d.ts +14 -0
  72. package/dist/media-providers/dispatch/media-wire.js +22 -0
  73. package/dist/media-providers/dispatch/node.d.ts +5 -0
  74. package/dist/media-providers/dispatch/node.js +5 -1
  75. package/dist/media-providers/dispatch/openai-compatible.d.ts +3 -1
  76. package/dist/media-providers/dispatch/openai-compatible.js +1 -1
  77. package/dist/media-providers/dispatch/operation-runtime.js +5 -4
  78. package/dist/media-providers/dispatch/outbound.d.ts +28 -3
  79. package/dist/media-providers/dispatch/outbound.js +10 -3
  80. package/dist/media-providers/dispatch/providers/custom-image.js +1 -1
  81. package/dist/media-providers/dispatch/providers/imagerouter.js +1 -1
  82. package/dist/media-providers/dispatch/providers/nanobanana.js +1 -1
  83. package/dist/media-providers/dispatch/providers/openrouter.js +1 -1
  84. package/dist/media-providers/dispatch/ssrf-guard.js +2 -2
  85. package/dist/media-providers/dispatch/types.d.ts +13 -4
  86. package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
  87. package/dist/media-providers/index.d.ts +2 -0
  88. package/dist/media-providers/providers.d.ts +9 -5
  89. package/dist/media-providers/providers.js +9 -12
  90. package/dist/media-providers/sqlite-task-store.d.ts +4 -4
  91. package/dist/media-providers/task-store.d.ts +1 -1
  92. package/dist/media-providers/task-store.js +1 -1
  93. package/dist/media-providers/types.d.ts +0 -36
  94. package/dist/media-providers/ui-defaults.js +0 -4
  95. package/dist/react/admin-credentials/AdminByokKeyPanel.d.ts +130 -0
  96. package/dist/react/admin-credentials/AdminByokKeyPanel.js +115 -0
  97. package/dist/react/admin-credentials/byok-footer-status.d.ts +37 -0
  98. package/dist/react/admin-credentials/byok-footer-status.js +25 -0
  99. package/dist/react/credentials/OtherCredentialsSection.d.ts +36 -0
  100. package/dist/react/credentials/OtherCredentialsSection.hooks.d.ts +55 -0
  101. package/dist/react/credentials/OtherCredentialsSection.hooks.js +26 -0
  102. package/dist/react/credentials/OtherCredentialsSection.js +120 -0
  103. package/dist/react/credentials/access-token-forms.d.ts +219 -0
  104. package/dist/react/credentials/access-token-forms.js +114 -0
  105. package/dist/react/credentials/credential-copy.d.ts +17 -0
  106. package/dist/react/credentials/credential-copy.js +7 -0
  107. package/dist/react/credentials/other-credential-stores.d.ts +115 -0
  108. package/dist/react/credentials/other-credential-stores.js +76 -0
  109. package/dist/react/site-key/SiteKeyRecoveryCard.d.ts +16 -0
  110. package/dist/react/site-key/SiteKeyRecoveryCard.js +36 -0
  111. package/dist/react/site-key/SiteKeyTab.d.ts +100 -0
  112. package/dist/react/site-key/SiteKeyTab.js +127 -0
  113. package/dist/react/site-key/hooks/use-site-key-recovery.hooks.d.ts +77 -0
  114. package/dist/react/site-key/hooks/use-site-key-recovery.hooks.js +126 -0
  115. package/dist/react/site-key/hooks/use-site-key.hooks.d.ts +120 -0
  116. package/dist/react/site-key/hooks/use-site-key.hooks.js +95 -0
  117. package/dist/react/webhooks/IntegrationDeliveries.d.ts +41 -0
  118. package/dist/react/webhooks/IntegrationDeliveries.js +24 -0
  119. package/dist/react/webhooks/Integrations.d.ts +73 -0
  120. package/dist/react/webhooks/Integrations.js +97 -0
  121. package/dist/react/webhooks/hooks/use-integration-deliveries.hooks.d.ts +59 -0
  122. package/dist/react/webhooks/hooks/use-integration-deliveries.hooks.js +11 -0
  123. package/dist/react/webhooks/hooks/use-integrations.hooks.d.ts +119 -0
  124. package/dist/react/webhooks/hooks/use-integrations.hooks.js +129 -0
  125. package/dist/react/webhooks/rules.d.ts +118 -0
  126. package/dist/react/webhooks/rules.js +103 -0
  127. package/dist/saved-requests/execute.js +2 -3
  128. package/dist/saved-requests/types.d.ts +4 -1
  129. package/dist/secrets/index.d.ts +3 -0
  130. package/dist/secrets/index.js +3 -0
  131. package/dist/secrets/ports.d.ts +25 -0
  132. package/dist/secrets/ports.js +2 -0
  133. package/dist/secrets/types.d.ts +10 -0
  134. package/dist/secrets/types.js +2 -0
  135. package/dist/vendor-credentials/abort-guarded-repo.d.ts +14 -0
  136. package/dist/vendor-credentials/abort-guarded-repo.js +41 -0
  137. package/dist/vendor-credentials/project-scope.d.ts +43 -0
  138. package/dist/vendor-credentials/project-scope.js +32 -0
  139. package/dist/vendor-credentials/vault-adapter.d.ts +147 -0
  140. package/dist/vendor-credentials/vault-adapter.js +195 -0
  141. package/dist/web-screenshot/capture-files.d.ts +44 -0
  142. package/dist/web-screenshot/capture-files.js +62 -0
  143. package/dist/web-screenshot/capture-retention.d.ts +157 -0
  144. package/dist/web-screenshot/capture-retention.js +134 -0
  145. package/dist/web-screenshot/capture-root-file-lock.d.ts +20 -0
  146. package/dist/web-screenshot/capture-root-file-lock.js +15 -0
  147. package/dist/web-screenshot/desktop-page-capture.d.ts +37 -0
  148. package/dist/web-screenshot/desktop-page-capture.js +62 -0
  149. package/dist/web-screenshot/own-site-opener.d.ts +40 -0
  150. package/dist/web-screenshot/own-site-opener.js +27 -0
  151. package/dist/web-screenshot/screenshot-image.d.ts +11 -0
  152. package/dist/web-screenshot/screenshot-image.js +12 -0
  153. package/dist/web-screenshot/web-screenshot.d.ts +188 -0
  154. package/dist/web-screenshot/web-screenshot.js +329 -0
  155. package/dist/webhooks/delivery.d.ts +16 -0
  156. package/dist/webhooks/delivery.js +41 -1
  157. package/dist/webhooks/ports.d.ts +1 -29
  158. package/dist/webhooks/signing.keyring.d.ts +1 -1
  159. package/dist/webhooks/site/delivery.d.ts +60 -0
  160. package/dist/webhooks/site/delivery.js +45 -0
  161. package/dist/webhooks/site/http.memory.d.ts +51 -0
  162. package/dist/webhooks/site/http.memory.js +28 -0
  163. package/dist/webhooks/site/repo.memory.d.ts +136 -0
  164. package/dist/webhooks/site/repo.memory.js +215 -0
  165. package/dist/webhooks/site/seal-aad-invariant.d.ts +26 -0
  166. package/dist/webhooks/site/seal-aad-invariant.js +61 -0
  167. package/dist/webhooks/site/seal-aad-invariant.node.d.ts +42 -0
  168. package/dist/webhooks/site/seal-aad-invariant.node.js +52 -0
  169. package/dist/webhooks/site/signing.d.ts +28 -0
  170. package/dist/webhooks/site/signing.js +27 -0
  171. package/dist/webhooks/site/signing.keyring.d.ts +29 -0
  172. package/dist/webhooks/site/signing.keyring.js +30 -0
  173. package/dist/webhooks/site/subscriptions.d.ts +118 -0
  174. package/dist/webhooks/site/subscriptions.js +98 -0
  175. package/dist/webhooks/sql/index.d.ts +4 -0
  176. package/dist/webhooks/sql/index.js +2 -0
  177. package/dist/webhooks/sql/repo.rows.d.ts +47 -0
  178. package/dist/webhooks/sql/repo.rows.js +2 -0
  179. package/dist/webhooks/sql/webhook-repo.d.ts +152 -0
  180. package/dist/webhooks/sql/webhook-repo.js +308 -0
  181. package/dist/webhooks/subscriptions.d.ts +3 -1
  182. package/dist/webhooks/subscriptions.js +4 -1
  183. package/dist/webhooks/tools/tool-handlers.js +2 -1
  184. package/dist/webhooks/types.d.ts +6 -10
  185. package/package.json +517 -12
  186. package/dist/media-providers/dispatch/providers/grok.d.ts +0 -55
  187. package/dist/media-providers/dispatch/providers/grok.js +0 -116
@@ -0,0 +1,33 @@
1
+ import type { HumanConfirmSpec } from "@jini-ai/core/contracts/site/human-confirm";
2
+ /**
3
+ * @file The confirmation dialog `tool-registrations.ts` raises before running a DELETE through a
4
+ * saved custom credential (2026-08-31, owner decision: "the only thing we maybe should be worried
5
+ * about is deletion, but we can gate that with MCP-UI"). Structurally mirrors
6
+ * the host's `contracts/core/human-confirm.ts` — see that file's own header for the mechanism this one
7
+ * reuses rather than reinventing (a held-open `SurfaceExchangeStore` exchange, `askOnce`, a
8
+ * confirm/cancel tool action carrying `SURFACE_EXCHANGE_ID_PARAM` back to the SAME tool call).
9
+ *
10
+ * Differs from that file only in WHAT the dialog shows and WHERE it is keyed: there is no existing
11
+ * row/version to re-version against here (a DELETE-through-credential is a live outbound call, not an
12
+ * edit to a host-owned entity) — so the `ui://` URI is keyed by the exchange id alone, the same
13
+ * reasoning `features/deployments/publish-agent-tools.ts`'s own `publishConfirmationUri` gives for the
14
+ * identical "nothing to re-version" shape.
15
+ */
16
+ /**
17
+ * Describes the dialog naming exactly what is about to be sent — label, resolved host, method, and
18
+ * path — per the owner's own requirement ("showing the operator the label, the resolved host, the
19
+ * method and the full path so they can see exactly what is about to be destroyed").
20
+ *
21
+ * The shared transport owns the exchange deadline (`SurfaceExchange.expiresAtMs()`), so the chat
22
+ * counts the card down and closes it when the parked call stops waiting.
23
+ *
24
+ * @complexity O(1) — a handful of fixed-size field reads.
25
+ */
26
+ export declare function describeDeleteRequestApproval({ label, host, path, toolId, irreversibleDescription }: {
27
+ label: string;
28
+ host: string;
29
+ path: string;
30
+ toolId: string;
31
+ irreversibleDescription: string;
32
+ }, _optional?: {}): HumanConfirmSpec;
33
+ //# sourceMappingURL=delete-request-confirmation-ui.d.ts.map
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @file The confirmation dialog `tool-registrations.ts` raises before running a DELETE through a
3
+ * saved custom credential (2026-08-31, owner decision: "the only thing we maybe should be worried
4
+ * about is deletion, but we can gate that with MCP-UI"). Structurally mirrors
5
+ * the host's `contracts/core/human-confirm.ts` — see that file's own header for the mechanism this one
6
+ * reuses rather than reinventing (a held-open `SurfaceExchangeStore` exchange, `askOnce`, a
7
+ * confirm/cancel tool action carrying `SURFACE_EXCHANGE_ID_PARAM` back to the SAME tool call).
8
+ *
9
+ * Differs from that file only in WHAT the dialog shows and WHERE it is keyed: there is no existing
10
+ * row/version to re-version against here (a DELETE-through-credential is a live outbound call, not an
11
+ * edit to a host-owned entity) — so the `ui://` URI is keyed by the exchange id alone, the same
12
+ * reasoning `features/deployments/publish-agent-tools.ts`'s own `publishConfirmationUri` gives for the
13
+ * identical "nothing to re-version" shape.
14
+ */
15
+ /**
16
+ * Describes the dialog naming exactly what is about to be sent — label, resolved host, method, and
17
+ * path — per the owner's own requirement ("showing the operator the label, the resolved host, the
18
+ * method and the full path so they can see exactly what is about to be destroyed").
19
+ *
20
+ * The shared transport owns the exchange deadline (`SurfaceExchange.expiresAtMs()`), so the chat
21
+ * counts the card down and closes it when the parked call stops waiting.
22
+ *
23
+ * @complexity O(1) — a handful of fixed-size field reads.
24
+ */
25
+ export function describeDeleteRequestApproval({ label, host, path, toolId, irreversibleDescription }, _optional = {}) {
26
+ return {
27
+ toolId, errorCode: "CUSTOM_CREDENTIALS",
28
+ title: `Send a DELETE through '${label}'?`,
29
+ description: irreversibleDescription,
30
+ details: [{ label: "Credential", value: label }, { label: "Host", value: host }, { label: "Method", value: "DELETE" }, { label: "Path", value: path }],
31
+ warning: "This is irreversible if the provider actually deletes something. Double-check the path above before confirming.",
32
+ danger: true, confirmLabel: "Send DELETE",
33
+ };
34
+ }
35
+ //# sourceMappingURL=delete-request-confirmation-ui.js.map
@@ -0,0 +1,109 @@
1
+ import type { ProviderKeyUsage } from "@jini-ai/core/contracts/site/plugins-host";
2
+ import { type ToolExecutionContext, type ToolHandler } from "@jini-ai/core";
3
+ import type { AssistantSurfaceDeps } from "@jini-ai/core/contracts/site/daemon-surface-exchanges";
4
+ import type { PluginProviderSettingField } from "@jini-ai/core/contracts/plugin-sdk";
5
+ import type { SecretCardForm, SurfaceCardApp } from "@jini-ai/core/contracts/cards";
6
+ import type { PluginCredentialCard } from "@jini-ai/core/contracts/credentials";
7
+ import type { CustomCredentialSecretCards } from "../credentialed-http/tools/credential-tool-host.js";
8
+ /**
9
+ * @file The assistant's key card for a PROVIDER plugin's settings (2026-10-25): an agent plugin
10
+ * declares a credential card with `saveKind: "provider-settings"` and `saveTarget: <provider plugin
11
+ * id>`, and `credential_save` (kind plugin-provider) opens it. The form's fields are the provider
12
+ * plugin's own manifest-declared settings (public values, declared defaults and choices, masked
13
+ * secrets); the agent plugin only supplies the copy (title, intro, help link). A submission saves
14
+ * through the host's shared provider-settings save rule (the admin Settings card's rule and store),
15
+ * so a key typed here lands in the same row, never in a credential row, the transcript or model input.
16
+ * Core names no vendor: every word on the card comes from the two manifests.
17
+ */
18
+ /** Host ports, bound by the composition root to the shared save rule and `ProviderConfigSource`. */
19
+ export interface ProviderSettingsCardPorts {
20
+ readonly usage?: (required: {
21
+ pluginId: string;
22
+ }) => Promise<ProviderKeyUsage>;
23
+ /** The provider plugin's declared settings; undefined when it is not installed or declares none. */
24
+ readonly fields: (required: {
25
+ pluginId: string;
26
+ }) => Promise<readonly PluginProviderSettingField[] | undefined>;
27
+ /** Saved public values and the NAMES of saved secrets; null when nothing is saved or it is unreadable. */
28
+ readonly readSettings: (required: {
29
+ pluginId: string;
30
+ }) => Promise<{
31
+ settings: Readonly<Record<string, string>>;
32
+ secretNames: readonly string[];
33
+ } | null>;
34
+ /** The shared save rule: writes, or returns the refusal text without writing. */
35
+ readonly save: (required: {
36
+ pluginId: string;
37
+ values: Readonly<Record<string, string>>;
38
+ }) => Promise<Saved | {
39
+ refusal: string;
40
+ }>;
41
+ /** The admin Settings card's save permission (`admin.plugins.enable`). */
42
+ readonly authorize: (ctx: ToolExecutionContext) => Promise<void>;
43
+ }
44
+ /** The host's identity for the provider-settings card: the tool id it answers as (`credential_save`),
45
+ * its `ui://` namespace and the app names its form and outcome report. */
46
+ export interface ProviderSettingsCardIdentity {
47
+ readonly toolId: string;
48
+ readonly uriNamespace: string;
49
+ readonly formApp: SurfaceCardApp;
50
+ readonly outcomeApp: SurfaceCardApp;
51
+ }
52
+ type SavedView = Awaited<ReturnType<ProviderSettingsCardPorts["readSettings"]>>;
53
+ type Prep = {
54
+ pluginId: string;
55
+ card?: PluginCredentialCard | undefined;
56
+ fields: readonly PluginProviderSettingField[];
57
+ saved: SavedView;
58
+ usage?: ProviderKeyUsage | undefined;
59
+ };
60
+ type Saved = {
61
+ configured?: boolean;
62
+ store: "project" | "site";
63
+ keyId?: string;
64
+ usedByThisSite?: boolean;
65
+ usedBy?: readonly string[];
66
+ appliesAt?: "now" | "restart" | "failed";
67
+ message?: string;
68
+ };
69
+ export type ProviderSettingsSaveResult = {
70
+ saved: true;
71
+ pluginId: string;
72
+ store: "project" | "site";
73
+ configured?: boolean;
74
+ appliesAt: "now" | "restart" | "failed";
75
+ message?: string;
76
+ keyId?: string;
77
+ usedByThisSite?: boolean;
78
+ usedBy?: readonly string[];
79
+ ask?: string;
80
+ } | {
81
+ saved: false;
82
+ reason: string;
83
+ message?: string | undefined;
84
+ };
85
+ /** The card: plugin copy over the provider's declared fields. @complexity O(f) declared fields. */
86
+ export declare function buildProviderSettingsForm({ prep, app }: {
87
+ prep: Prep;
88
+ app: SurfaceCardApp;
89
+ }, _optional?: {}): SecretCardForm;
90
+ /** Submitted controls → declared setting values (a "Custom…" choice takes its text field). @complexity O(f). */
91
+ export declare function readProviderSettingsValues({ fields, values }: {
92
+ fields: readonly PluginProviderSettingField[];
93
+ values: Readonly<Record<string, unknown>>;
94
+ }): Record<string, string>;
95
+ /**
96
+ * The `provider-settings` save adapter for `credential_save`. Input: `{ pluginId }` (the card's
97
+ * saveTarget), resolved by `routePluginCard`; never a value.
98
+ * @complexity O(f) per card plus one settings read and one save.
99
+ */
100
+ export declare function buildProviderSettingsCredentialHandler({ ports, surfaces, loadCards, cards, identity }: {
101
+ ports: ProviderSettingsCardPorts;
102
+ surfaces: AssistantSurfaceDeps;
103
+ loadCards: () => Promise<readonly PluginCredentialCard[]>;
104
+ /** The host's secret-card engine and its ask-then-report exchange helper. */
105
+ cards: CustomCredentialSecretCards;
106
+ identity: ProviderSettingsCardIdentity;
107
+ }, _optional?: {}): ToolHandler;
108
+ export {};
109
+ //# sourceMappingURL=provider-settings-card.d.ts.map
@@ -0,0 +1,166 @@
1
+ import { requireInputRecord, requireString, ToolInputError } from "@jini-ai/core";
2
+ /** The select option that reveals a field's free-text twin (`allowCustom`). */
3
+ const CUSTOM = "__custom";
4
+ const customName = ({ name }, _optional = {}) => `${name}__custom`;
5
+ /** All controls retain the provider's conditional requirement metadata. */
6
+ function fieldRequirements({ field }, _options = {}) {
7
+ return {
8
+ ...(field.requiredUnless ? { requiredUnless: field.requiredUnless } : {}),
9
+ ...(field.requiredWhen ? { requiredWhen: field.requiredWhen } : {}),
10
+ };
11
+ }
12
+ /** A declared public field with choices: a select (plus "Custom…" and its text field when allowed). */
13
+ function choiceFields({ field, value }) {
14
+ const custom = isCustomChoice({ field, value });
15
+ const select = choiceSelectOf({ field, selected: custom && field.allowCustom ? CUSTOM : value ?? field.default });
16
+ if (!field.allowCustom)
17
+ return [select];
18
+ return [select, customTextOf({ field, value: custom ? value : undefined })];
19
+ }
20
+ /** A saved value that is none of the declared choices (so it was typed into "Custom…"). */
21
+ function isCustomChoice({ field, value }, _optional = {}) {
22
+ return Boolean(value) && !field.options.some((option) => option.value === value);
23
+ }
24
+ /** The select over the declared choices, plus the "Custom…" choice when allowed. */
25
+ function choiceSelectOf({ field, selected }, _optional = {}) {
26
+ const options = field.options;
27
+ return { kind: "enum", name: field.name, label: field.label, required: field.required === true,
28
+ ...fieldRequirements({ field }),
29
+ options: [...options, ...(field.allowCustom ? [{ value: CUSTOM, label: "Custom…" }] : [])], ...(selected !== undefined ? { value: selected } : {}) };
30
+ }
31
+ /** The free-text twin of a select that allows a custom value; `value` is set only for a custom choice. */
32
+ function customTextOf({ field, value }, _optional = {}) {
33
+ return { kind: "string", name: customName({ name: field.name }), label: `Custom ${field.label.toLowerCase()}`, ...(field.hint ? { hint: field.hint } : {}), ...(value ? { value } : {}) };
34
+ }
35
+ /** A secret control never carries its value; conditional blanks reach the shared server save rule. */
36
+ function secretFieldOf({ field, saved, required }) {
37
+ const kept = saved?.secretNames.includes(field.name) === true;
38
+ const hint = [field.hint, kept ? "Leave blank to keep the saved one." : undefined].filter(Boolean).join(" ");
39
+ return { kind: "string", name: field.name, label: field.label, secret: true, required, ...(kept ? { hasSavedValue: true } : {}),
40
+ ...(field.requiredUnless ? { requiredUnless: field.requiredUnless } : {}),
41
+ ...(field.requiredWhen ? { requiredWhen: field.requiredWhen } : {}),
42
+ allowBlank: !required || kept || Boolean(field.requiredUnless || field.requiredWhen), ...(hint ? { hint } : {}) };
43
+ }
44
+ /** One declared field → its form controls. A saved secret may be left blank to keep it. */
45
+ function formFieldsOf({ field, saved }) {
46
+ // Conditional fields keep their base requirement; the form evaluates it as the public choice changes.
47
+ const required = field.required === true;
48
+ if (field.secret)
49
+ return [secretFieldOf({ field, saved, required })];
50
+ const value = saved?.settings[field.name] || undefined;
51
+ if (field.options?.length)
52
+ return choiceFields({ field, value });
53
+ const initial = value ?? field.default;
54
+ return [{ kind: "string", name: field.name, label: field.label, required, ...fieldRequirements({ field }),
55
+ ...(field.hint ? { hint: field.hint } : {}), ...(initial ? { value: initial } : {}) }];
56
+ }
57
+ /** The declared card's help, key-entry hint and purposes; values never come from saved settings. */
58
+ function providerCardDetails({ card }, _optional = {}) {
59
+ const details = [];
60
+ if (!card)
61
+ return details;
62
+ if (card.helpUrl)
63
+ details.push({ label: card.helpLabel ?? "Help", value: card.helpUrl });
64
+ if (card.keyHint)
65
+ details.push({ label: "Where to find it", value: card.keyHint });
66
+ if (card.usedFor?.length)
67
+ details.push({ label: "Used for", value: card.usedFor.join("; ") });
68
+ return details;
69
+ }
70
+ /** Explain a site-only replacement before the person enters a different project's key. */
71
+ function otherSiteKeyNotice({ usage, label }, _optional = {}) {
72
+ if (!usage || usage.store !== "project" || usage.usedByThisSite || usage.usedBy.length === 0)
73
+ return "";
74
+ return ` Your project's saved ${label} key is used by ${usage.usedBy.join(", ")}. A key entered here is used by this site only.`;
75
+ }
76
+ /** The card: plugin copy over the provider's declared fields. @complexity O(f) declared fields. */
77
+ export function buildProviderSettingsForm({ prep, app }, _optional = {}) {
78
+ const { card } = prep;
79
+ const otherUse = otherSiteKeyNotice({ usage: prep.usage, label: card?.label ?? "provider" });
80
+ return {
81
+ title: card?.title ?? "Connect provider",
82
+ description: `${card?.intro ? card.intro + " " : ""}Keys are sealed on the server the moment you submit — the assistant never sees them.${otherUse}`,
83
+ details: providerCardDetails({ card }),
84
+ submitLabel: "Save",
85
+ fields: prep.fields.flatMap((field) => formFieldsOf({ field, saved: prep.saved })),
86
+ app,
87
+ };
88
+ }
89
+ /** Submitted controls → declared setting values (a "Custom…" choice takes its text field). @complexity O(f). */
90
+ export function readProviderSettingsValues({ fields, values }) {
91
+ const out = {};
92
+ for (const field of fields) {
93
+ const chosen = values[field.name] === CUSTOM ? values[customName({ name: field.name })] : values[field.name];
94
+ if (typeof chosen === "string")
95
+ out[field.name] = chosen;
96
+ }
97
+ return out;
98
+ }
99
+ /** Model-facing projection: where it saved and when it applies, never a value. */
100
+ function resultOf({ run, pluginId }) {
101
+ if (run.status === "saved" && run.saved)
102
+ return { saved: true, pluginId, ...run.saved, appliesAt: run.saved.appliesAt ?? "restart" };
103
+ if (run.status === "failed")
104
+ return { saved: false, reason: "error", message: run.safeMessage };
105
+ if (run.status === "blank")
106
+ return { saved: false, reason: "invalid", message: "A required key was left blank. Nothing was saved." };
107
+ return { saved: false, reason: run.status };
108
+ }
109
+ /** A committed save can need browser reload or provider startup without becoming a failed save. */
110
+ function savedMessage({ result }, _optional = {}) {
111
+ if (result.appliesAt === "failed")
112
+ return result.message ?? "Saved, but the provider could not start. Check the plugin settings and save again.";
113
+ let location = "Saved for this site.";
114
+ if (result.store !== "site") {
115
+ location = result.usedBy?.length
116
+ ? `Saved. Used by ${result.usedBy.join(", ")}. Other sites pick it up within 30 seconds.`
117
+ : "Saved to your project — not used by any site yet.";
118
+ }
119
+ if (!result.configured)
120
+ return location;
121
+ return location + (result.appliesAt === "now" ? " Now sending." : " Reload open pages or restart this site to finish applying the saved settings.");
122
+ }
123
+ function outcomeOf({ result, title, app }) {
124
+ const message = result.saved ? savedMessage({ result }) : result.message;
125
+ if (message === undefined)
126
+ return undefined;
127
+ return { title, state: result.saved && result.appliesAt !== "failed" ? "success" : "failure", app,
128
+ message };
129
+ }
130
+ /** Thrown with fixed refusal text from the shared rule (names fields, never values). */
131
+ class ProviderSettingsRefusedError extends Error {
132
+ }
133
+ /**
134
+ * The `provider-settings` save adapter for `credential_save`. Input: `{ pluginId }` (the card's
135
+ * saveTarget), resolved by `routePluginCard`; never a value.
136
+ * @complexity O(f) per card plus one settings read and one save.
137
+ */
138
+ export function buildProviderSettingsCredentialHandler({ ports, surfaces, loadCards, cards, identity }, _optional = {}) {
139
+ return async (ctx, options = {}) => {
140
+ const pluginId = requireString({ input: requireInputRecord({ input: ctx.input }), key: "pluginId" });
141
+ const card = cards.defineSecretCardTool({
142
+ toolId: identity.toolId,
143
+ prepare: async () => {
144
+ await ports.authorize(ctx);
145
+ const fields = await ports.fields({ pluginId });
146
+ if (!fields)
147
+ throw new ToolInputError({ message: `The provider plugin '${pluginId}' is not installed or declares no settings. Install and enable it first (plugins_list, plugins_set_enabled).` });
148
+ const declared = (await loadCards()).find((entry) => entry.saveKind === "provider-settings" && entry.saveTarget === pluginId);
149
+ return { pluginId, fields, usage: await ports.usage?.({ pluginId }), saved: await ports.readSettings({ pluginId }), ...(declared ? { card: declared } : {}) };
150
+ },
151
+ form: ({ prep }) => buildProviderSettingsForm({ prep, app: identity.formApp }),
152
+ save: async ({ values, prep }) => {
153
+ const outcome = await ports.save({ pluginId, values: readProviderSettingsValues({ fields: prep.fields, values }) });
154
+ if ("refusal" in outcome)
155
+ throw new ProviderSettingsRefusedError(outcome.refusal);
156
+ return outcome;
157
+ },
158
+ result: ({ run }) => resultOf({ run, pluginId }),
159
+ outcome: ({ prep, run }) => outcomeOf({ result: resultOf({ run, pluginId }), title: prep.card?.title ?? "Provider settings", app: identity.outcomeApp }),
160
+ }, { uriHost: identity.uriNamespace, frameSize: ["100%", "460px"],
161
+ // The refusal names fields only (shared rule); every other failure keeps the engine's fixed text.
162
+ safeError: (error) => error instanceof ProviderSettingsRefusedError ? error.message : "Saving failed. Nothing was saved." });
163
+ return card.handler({ surfaceExchanges: surfaces.surfaceExchanges, askThenReport: cards.askThenReport })(ctx, options);
164
+ };
165
+ }
166
+ //# sourceMappingURL=provider-settings-card.js.map
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Bounds on one `custom_credential_write_files` call. Concrete numbers, each justified rather than
3
+ * left unbounded (an operator-controlled write into a real repository must never be unbounded — same
4
+ * reasoning `agent-plugins/install.ts`'s own `LIMITS` gives for its structurally identical problem):
5
+ *
6
+ * - `maxFiles`: the confirmation dialog this tool opens (`file-write confirmation`) lists
7
+ * every path by name so a human can actually read and approve each one before anything is written;
8
+ * past a few dozen rows that review stops being real. The one caller that exists today (a
9
+ * bundled hosting plugin's skill) writes exactly 2 files. 25 is generous headroom above that for any plausible
10
+ * future caller while keeping the dialog reviewable.
11
+ * - `maxPathLength`: far beyond any real repository path, while still bounding one hostile field.
12
+ * - `maxFileBytes`: every known caller writes small hand-authored or LLM-authored text config
13
+ * (a platform config file, a GitHub Actions workflow YAML) — 1 MiB is generous for that class of file while
14
+ * keeping a single blob-creation request body bounded.
15
+ * - `maxTotalBytes`: bounds the call's AGGREGATE payload independent of how the per-file cap is
16
+ * split across files — the same "per-item cap AND total cap" shape `agent-plugins/install.ts`'s
17
+ * `maxFileBytes`/`maxTotalExtractedBytes` pair uses for the identical reason.
18
+ */
19
+ export declare const WRITE_FILES_LIMITS: {
20
+ readonly maxFiles: 25;
21
+ readonly maxPathLength: 1024;
22
+ readonly maxFileBytes: 1048576;
23
+ readonly maxTotalBytes: number;
24
+ };
25
+ /** One validated, normalized file this call will write. */
26
+ export interface NormalizedWriteFile {
27
+ readonly path: string;
28
+ readonly content: string;
29
+ }
30
+ /** The host-independent half {@link validateWriteFilesInput} returns. */
31
+ export interface WriteFilesRequest {
32
+ readonly branch: string;
33
+ readonly commitMessage: string;
34
+ readonly files: readonly NormalizedWriteFile[];
35
+ }
36
+ /** The fully validated call: {@link WriteFilesRequest} plus the {@link validateRepositoryTarget} target. */
37
+ export interface ValidatedWriteFilesInput extends WriteFilesRequest {
38
+ readonly owner: string;
39
+ readonly repo: string;
40
+ }
41
+ /**
42
+ * Owner and repo for the git host that will receive the write: the host's own rules (its plugin
43
+ * module's `validateTarget`, e.g. "invalid GitHub owner 'x'"), then the generic one-path-segment
44
+ * rule. See this file's header for why this runs after the provider is picked.
45
+ *
46
+ * @throws {CustomCredentialValidationError} Either value is not a string or fails a rule.
47
+ * @complexity O(1).
48
+ */
49
+ export declare function validateRepositoryTarget(target: {
50
+ owner: unknown;
51
+ repo: unknown;
52
+ repositoryTargetError: (required: {
53
+ owner: string;
54
+ repo: string;
55
+ }, optional?: {
56
+ validateTarget?: (required: {
57
+ owner: string;
58
+ repo: string;
59
+ }) => string | null;
60
+ }) => string | null;
61
+ }, { validateTarget }?: {
62
+ validateTarget?: (required: {
63
+ owner: string;
64
+ repo: string;
65
+ }) => string | null;
66
+ }): {
67
+ owner: string;
68
+ repo: string;
69
+ };
70
+ export declare function validateBranch({ value }: {
71
+ value: unknown;
72
+ }, _optional?: {}): string;
73
+ export declare function validateCommitMessage({ value }: {
74
+ value: unknown;
75
+ }, _optional?: {}): string;
76
+ /**
77
+ * Rejects an absolute path, a NUL byte, a Windows drive prefix, a lexical `..`/`.` segment, or a
78
+ * path naming/nesting under `.git` — BEFORE any network call. See this file's header for why this
79
+ * is the lexical half only of `package-paths.ts`'s `normalizePackageEntryPath`, with one addition
80
+ * that function has no analog for.
81
+ *
82
+ * @throws {CustomCredentialValidationError} The path is unsafe by construction.
83
+ * @complexity O(n) in the path's own length.
84
+ */
85
+ export declare function normalizeWriteFilePath({ rawPath }: {
86
+ rawPath: string;
87
+ }, _optional?: {}): string;
88
+ /**
89
+ * The entry point every `custom_credential_write_files` call validates through before the credential
90
+ * is resolved or any network call is made — `branch`/`commitMessage` shape, plus every file's path
91
+ * safety and the count/size caps. Owner/repo wait for the host ({@link validateRepositoryTarget}). Mirrors this domain's own established
92
+ * ordering (see this file's header) of "shape/security validation before permission check or I/O".
93
+ *
94
+ * @throws {CustomCredentialValidationError} Any field fails its own validation.
95
+ * @complexity O(n) in the number of files, plus O(m) in each file's own content length.
96
+ */
97
+ export declare function validateWriteFilesInput(input: {
98
+ branch: unknown;
99
+ commitMessage: unknown;
100
+ files: unknown;
101
+ }, _optional?: Record<string, never>): WriteFilesRequest;
102
+ //# sourceMappingURL=write-files-validation.d.ts.map
@@ -0,0 +1,202 @@
1
+ import { isNonArrayRecord } from "@jini-ai/core";
2
+ import { CustomCredentialValidationError } from "../credentialed-http/sets/store.js";
3
+ /**
4
+ * @file Shape/path/size validation for `custom_credential_write_files` — every check here runs
5
+ * BEFORE the credential is resolved or any network call is made, mirroring this domain's own
6
+ * established ordering (`tool-registrations.ts`'s `rejectUnexpectedSetTokenFields`/
7
+ * `requireUsernameOrClearSentinel` both run before `requireToolPermission`/any I/O) and
8
+ * `Jini packages/agent-plugins/src/lifecycle/package-paths.ts`'s "cheap majority of attempts caught before any
9
+ * filesystem call" split.
10
+ *
11
+ * Owner and repo are the one exception to "before the credential is resolved": their rules belong to
12
+ * the git host (`repositoryTargetError` in `@jini-ai/devops/source-control`: the host plugin's own
13
+ * `validateTarget`, then a generic one-path-segment rule), and the host is known only from the saved
14
+ * credential's base URL. So {@link validateRepositoryTarget} runs once the caller has picked the
15
+ * provider from that URL, still before any decrypt, network call or dialog.
16
+ *
17
+ * `BRANCH_PATTERN`/`MAX_COMMIT_MESSAGE_LENGTH` are byte-identical to
18
+ * `features/source-control/commit-site.ts`'s own constants of the same name — copied, not imported,
19
+ * per this codebase's established convention for a tiny cross-feature constant.
20
+ *
21
+ * The path-safety rule set is the LEXICAL half of `package-paths.ts`'s `normalizePackageEntryPath`
22
+ * (reject NUL, absolute paths, a Windows drive prefix, `..` segments) — never its filesystem half
23
+ * (`assertContainedOnDisk`'s `realpath` containment check), because there is no local filesystem
24
+ * write here to protect: every validated path becomes a `path` field in a git-tree entry on the host, a
25
+ * remote API call this process never resolves against its own disk. One rule has no
26
+ * `package-paths.ts` analog: a normalized path that IS (or is nested under) `.git` — case-insensitively
27
+ * — is refused outright. That directory name is git's own reserved metadata location; committing a
28
+ * tracked FILE at a path like `.git/config` or `.GIT/hooks/pre-commit` is exactly the shape of the
29
+ * case-insensitive-filesystem `.git` collision class git itself started refusing at clone/checkout
30
+ * time (CVE-2021-21300 and related) — refusing it here, at write time, is cheap and closes the same
31
+ * hole from the other direction for any client that has not been patched.
32
+ */
33
+ /** Git branch name — permissive (real branch names allow far more), but refuses whitespace/control
34
+ * characters before the value reaches a URL path segment. */
35
+ const BRANCH_PATTERN = /^[A-Za-z0-9._/-]{1,250}$/;
36
+ const MAX_COMMIT_MESSAGE_LENGTH = 500;
37
+ /**
38
+ * Bounds on one `custom_credential_write_files` call. Concrete numbers, each justified rather than
39
+ * left unbounded (an operator-controlled write into a real repository must never be unbounded — same
40
+ * reasoning `agent-plugins/install.ts`'s own `LIMITS` gives for its structurally identical problem):
41
+ *
42
+ * - `maxFiles`: the confirmation dialog this tool opens (`file-write confirmation`) lists
43
+ * every path by name so a human can actually read and approve each one before anything is written;
44
+ * past a few dozen rows that review stops being real. The one caller that exists today (a
45
+ * bundled hosting plugin's skill) writes exactly 2 files. 25 is generous headroom above that for any plausible
46
+ * future caller while keeping the dialog reviewable.
47
+ * - `maxPathLength`: far beyond any real repository path, while still bounding one hostile field.
48
+ * - `maxFileBytes`: every known caller writes small hand-authored or LLM-authored text config
49
+ * (a platform config file, a GitHub Actions workflow YAML) — 1 MiB is generous for that class of file while
50
+ * keeping a single blob-creation request body bounded.
51
+ * - `maxTotalBytes`: bounds the call's AGGREGATE payload independent of how the per-file cap is
52
+ * split across files — the same "per-item cap AND total cap" shape `agent-plugins/install.ts`'s
53
+ * `maxFileBytes`/`maxTotalExtractedBytes` pair uses for the identical reason.
54
+ */
55
+ export const WRITE_FILES_LIMITS = {
56
+ maxFiles: 25,
57
+ maxPathLength: 1024,
58
+ maxFileBytes: 1_048_576,
59
+ maxTotalBytes: 4 * 1_048_576,
60
+ };
61
+ /**
62
+ * Owner and repo for the git host that will receive the write: the host's own rules (its plugin
63
+ * module's `validateTarget`, e.g. "invalid GitHub owner 'x'"), then the generic one-path-segment
64
+ * rule. See this file's header for why this runs after the provider is picked.
65
+ *
66
+ * @throws {CustomCredentialValidationError} Either value is not a string or fails a rule.
67
+ * @complexity O(1).
68
+ */
69
+ export function validateRepositoryTarget(target, { validateTarget } = {}) {
70
+ if (typeof target.owner !== "string")
71
+ throw new CustomCredentialValidationError(`invalid owner '${String(target.owner)}'`);
72
+ if (typeof target.repo !== "string")
73
+ throw new CustomCredentialValidationError(`invalid repo '${String(target.repo)}'`);
74
+ const error = target.repositoryTargetError({ owner: target.owner, repo: target.repo }, validateTarget === undefined ? {} : { validateTarget });
75
+ if (error !== null)
76
+ throw new CustomCredentialValidationError(error);
77
+ return { owner: target.owner, repo: target.repo };
78
+ }
79
+ export function validateBranch({ value }, _optional = {}) {
80
+ if (typeof value !== "string" || !BRANCH_PATTERN.test(value)) {
81
+ throw new CustomCredentialValidationError(`invalid branch name '${typeof value === "string" ? value.slice(0, 60) : String(value)}'`);
82
+ }
83
+ // BRANCH_PATTERN alone would admit these — `.`, `-`, and `/` are all in its character class — but a
84
+ // `..` or empty `/`-separated segment is a dot-segment the URL constructor normalizes away, so a
85
+ // branch like '../tags/release' would silently retarget the ref read/update into another namespace.
86
+ const segments = value.split("/");
87
+ if (segments.some((segment) => segment === "" || segment === "..")) {
88
+ throw new CustomCredentialValidationError(`invalid branch name '${value.slice(0, 60)}' — must not contain an empty or '..' path segment`);
89
+ }
90
+ return value;
91
+ }
92
+ export function validateCommitMessage({ value }, _optional = {}) {
93
+ if (typeof value !== "string" || value.trim() === "" || value.length > MAX_COMMIT_MESSAGE_LENGTH) {
94
+ throw new CustomCredentialValidationError(`commitMessage must be 1-${MAX_COMMIT_MESSAGE_LENGTH} characters`);
95
+ }
96
+ return value;
97
+ }
98
+ /** Rejects a `.git`-named or `.git/`-nested path, case-insensitively — see this file's header for
99
+ * the collision class this closes. Applied AFTER lexical normalization, so `./.git`/`.GIT/x` are
100
+ * both caught the same way regardless of how the caller spelled the segment. */
101
+ function isReservedGitPath({ normalized }, _optional = {}) {
102
+ return normalized.split("/").some(segment => segment.toLowerCase() === ".git");
103
+ }
104
+ /**
105
+ * Rejects an absolute path, a NUL byte, a Windows drive prefix, a lexical `..`/`.` segment, or a
106
+ * path naming/nesting under `.git` — BEFORE any network call. See this file's header for why this
107
+ * is the lexical half only of `package-paths.ts`'s `normalizePackageEntryPath`, with one addition
108
+ * that function has no analog for.
109
+ *
110
+ * @throws {CustomCredentialValidationError} The path is unsafe by construction.
111
+ * @complexity O(n) in the path's own length.
112
+ */
113
+ export function normalizeWriteFilePath({ rawPath }, _optional = {}) {
114
+ if (rawPath.length > WRITE_FILES_LIMITS.maxPathLength) {
115
+ throw new CustomCredentialValidationError(`file path exceeds the ${WRITE_FILES_LIMITS.maxPathLength}-character cap: '${rawPath.slice(0, 80)}...'`);
116
+ }
117
+ if (rawPath.includes("\0")) {
118
+ throw new CustomCredentialValidationError(`file path contains a NUL byte: '${rawPath.slice(0, 80)}'`);
119
+ }
120
+ const portable = rawPath.replaceAll("\\", "/");
121
+ if (portable.startsWith("/") || /^[a-zA-Z]:/.test(portable)) {
122
+ throw new CustomCredentialValidationError(`file path must be relative, not absolute: '${rawPath}'`);
123
+ }
124
+ const segments = portable.split("/");
125
+ if (segments.some((segment) => segment === "..")) {
126
+ throw new CustomCredentialValidationError(`file path escapes the repository root: '${rawPath}'`);
127
+ }
128
+ const normalized = segments.filter((segment) => segment !== "." && segment !== "").join("/");
129
+ if (normalized === "") {
130
+ throw new CustomCredentialValidationError(`file path is empty or resolves to nothing: '${rawPath}'`);
131
+ }
132
+ if (isReservedGitPath({ normalized })) {
133
+ throw new CustomCredentialValidationError(`file path names or nests under the reserved '.git' directory: '${rawPath}'`);
134
+ }
135
+ return normalized;
136
+ }
137
+ function requireStringFileEntry({ raw }, _optional = {}) {
138
+ const entry = { value: raw };
139
+ if (!isNonArrayRecord(entry) || typeof entry.value.path !== "string" || typeof entry.value.content !== "string") {
140
+ throw new CustomCredentialValidationError("each entry in 'files' must be an object with a string 'path' and a string 'content'");
141
+ }
142
+ return { path: entry.value.path, content: entry.value.content };
143
+ }
144
+ function addFileBytesWithinLimits({ normalized, content, totalBytes }, _optional = {}) {
145
+ const bytes = Buffer.byteLength(content, "utf8");
146
+ if (bytes > WRITE_FILES_LIMITS.maxFileBytes) {
147
+ throw new CustomCredentialValidationError(`file '${normalized}' is ${bytes} bytes, over the ${WRITE_FILES_LIMITS.maxFileBytes}-byte per-file cap`);
148
+ }
149
+ const nextTotalBytes = totalBytes + bytes;
150
+ if (nextTotalBytes > WRITE_FILES_LIMITS.maxTotalBytes) {
151
+ throw new CustomCredentialValidationError(`'files' totals over the ${WRITE_FILES_LIMITS.maxTotalBytes}-byte aggregate cap`);
152
+ }
153
+ return nextTotalBytes;
154
+ }
155
+ /**
156
+ * Validates and normalizes the `files` array: shape, per-file path safety, per-file and aggregate
157
+ * size caps, the file-count cap, and duplicate-path detection within the same call — mirroring
158
+ * `agent-plugins/install.ts`'s own "duplicate archive entry... refusing a second write over an
159
+ * already-vetted first one" rule, adapted from an archive's entries to this call's own file list.
160
+ *
161
+ * @throws {CustomCredentialValidationError} Any shape, path, or size violation.
162
+ * @complexity O(n) in the number of files, plus O(m) in each file's own content length.
163
+ */
164
+ function validateFiles({ rawFiles }, _optional = {}) {
165
+ if (!Array.isArray(rawFiles) || rawFiles.length === 0) {
166
+ throw new CustomCredentialValidationError("'files' must be a non-empty array of {path, content} objects");
167
+ }
168
+ if (rawFiles.length > WRITE_FILES_LIMITS.maxFiles) {
169
+ throw new CustomCredentialValidationError(`'files' has ${rawFiles.length} entries, over the ${WRITE_FILES_LIMITS.maxFiles}-file cap`);
170
+ }
171
+ const seen = new Set();
172
+ const files = [];
173
+ let totalBytes = 0;
174
+ for (const raw of rawFiles) {
175
+ const { path, content } = requireStringFileEntry({ raw });
176
+ const normalized = normalizeWriteFilePath({ rawPath: path });
177
+ if (seen.has(normalized)) {
178
+ throw new CustomCredentialValidationError(`duplicate file path '${normalized}' — refusing a second write over an already-vetted first one`);
179
+ }
180
+ seen.add(normalized);
181
+ totalBytes = addFileBytesWithinLimits({ normalized, content, totalBytes });
182
+ files.push({ path: normalized, content });
183
+ }
184
+ return files;
185
+ }
186
+ /**
187
+ * The entry point every `custom_credential_write_files` call validates through before the credential
188
+ * is resolved or any network call is made — `branch`/`commitMessage` shape, plus every file's path
189
+ * safety and the count/size caps. Owner/repo wait for the host ({@link validateRepositoryTarget}). Mirrors this domain's own established
190
+ * ordering (see this file's header) of "shape/security validation before permission check or I/O".
191
+ *
192
+ * @throws {CustomCredentialValidationError} Any field fails its own validation.
193
+ * @complexity O(n) in the number of files, plus O(m) in each file's own content length.
194
+ */
195
+ export function validateWriteFilesInput(input, _optional = {}) {
196
+ return {
197
+ branch: validateBranch({ value: input.branch }),
198
+ commitMessage: validateCommitMessage({ value: input.commitMessage }),
199
+ files: validateFiles({ rawFiles: input.files }),
200
+ };
201
+ }
202
+ //# sourceMappingURL=write-files-validation.js.map