@jini-ai/platform 0.7.3-next.2 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +13 -0
  3. package/dist/download-lock.d.ts +3 -1
  4. package/dist/download-lock.js +4 -6
  5. package/dist/download-maintenance.js +6 -6
  6. package/dist/download-state.js +17 -14
  7. package/dist/download-store.d.ts +34 -10
  8. package/dist/download-store.js +24 -20
  9. package/dist/download-target.d.ts +6 -2
  10. package/dist/download-target.js +7 -7
  11. package/dist/download-transfer.js +18 -12
  12. package/dist/download.js +4 -4
  13. package/dist/fetch-with-timeout.d.ts +0 -53
  14. package/dist/fetch-with-timeout.js +62 -13
  15. package/dist/fs/directory-running-lock.d.ts +4 -0
  16. package/dist/fs/directory-running-lock.js +8 -1
  17. package/dist/fs/directory-workspace.d.ts +2 -1
  18. package/dist/fs/directory-workspace.js +2 -2
  19. package/dist/fs/durable-json.d.ts +3 -16
  20. package/dist/fs/durable-json.js +4 -2
  21. package/dist/fs/guarded-reader.d.ts +10 -0
  22. package/dist/fs/guarded-reader.js +34 -1
  23. package/dist/fs/index.d.ts +4 -0
  24. package/dist/fs/index.js +4 -0
  25. package/dist/fs/leased-directory-move.d.ts +49 -0
  26. package/dist/fs/leased-directory-move.js +31 -0
  27. package/dist/fs/owned-temp-root.d.ts +74 -0
  28. package/dist/fs/owned-temp-root.js +203 -0
  29. package/dist/fs/recent-directories.d.ts +2 -1
  30. package/dist/fs/resolve-directory-target.d.ts +33 -0
  31. package/dist/fs/resolve-directory-target.js +58 -0
  32. package/dist/fs/staged-file.d.ts +40 -0
  33. package/dist/fs/staged-file.js +75 -0
  34. package/dist/fs/strict-containment.d.ts +14 -0
  35. package/dist/fs/strict-containment.js +14 -0
  36. package/dist/image/png-encode.d.ts +41 -0
  37. package/dist/image/png-encode.js +96 -0
  38. package/dist/index.d.ts +3 -1
  39. package/dist/mail/email-template-agent-tools.d.ts +150 -0
  40. package/dist/mail/email-template-agent-tools.js +86 -0
  41. package/dist/mail/email-template-tool-registrations.d.ts +73 -0
  42. package/dist/mail/email-template-tool-registrations.js +66 -0
  43. package/dist/mail/email-template.js +3 -7
  44. package/dist/mail/feedback-route.d.ts +50 -0
  45. package/dist/mail/feedback-route.js +46 -0
  46. package/dist/mail/feedback-setup.d.ts +44 -0
  47. package/dist/mail/feedback-setup.js +53 -0
  48. package/dist/mail/feedback-sources.d.ts +67 -0
  49. package/dist/mail/feedback-sources.js +42 -0
  50. package/dist/mail/index.d.ts +10 -1
  51. package/dist/mail/index.js +4 -0
  52. package/dist/mail/mail-status.d.ts +32 -0
  53. package/dist/mail/mail-status.js +2 -0
  54. package/dist/mail/positional-purpose-gate.d.ts +14 -0
  55. package/dist/mail/positional-purpose-gate.js +18 -0
  56. package/dist/mail/purpose-gate-probe.d.ts +18 -0
  57. package/dist/mail/purpose-gate-probe.js +22 -0
  58. package/dist/mail/purpose-scoped-mailer.d.ts +4 -0
  59. package/dist/mail/purpose-scoped-mailer.js +4 -3
  60. package/dist/mail/resolve-mailer.d.ts +13 -1
  61. package/dist/mail/resolve-mailer.js +11 -5
  62. package/dist/mail/sql/activity.repo.d.ts +20 -0
  63. package/dist/mail/sql/activity.repo.js +133 -0
  64. package/dist/mail/sql/attempts.repo.d.ts +17 -0
  65. package/dist/mail/sql/attempts.repo.js +32 -0
  66. package/dist/mail/sql/capture.repo.d.ts +69 -0
  67. package/dist/mail/sql/capture.repo.js +119 -0
  68. package/dist/mail/sql/feedback-inbox.repo.d.ts +12 -0
  69. package/dist/mail/sql/feedback-inbox.repo.js +32 -0
  70. package/dist/mail/sql/index.d.ts +12 -0
  71. package/dist/mail/sql/index.js +12 -0
  72. package/dist/mail/sql/ledger.repo.d.ts +29 -0
  73. package/dist/mail/sql/ledger.repo.js +57 -0
  74. package/dist/mail/sql/retention.d.ts +23 -0
  75. package/dist/mail/sql/retention.js +53 -0
  76. package/dist/mail/sql/site-feedback-route.d.ts +18 -0
  77. package/dist/mail/sql/site-feedback-route.js +22 -0
  78. package/dist/mail/sql/suppression-admin.repo.d.ts +11 -0
  79. package/dist/mail/sql/suppression-admin.repo.js +76 -0
  80. package/dist/mail/sql/suppression.repo.d.ts +10 -0
  81. package/dist/mail/sql/suppression.repo.js +33 -0
  82. package/dist/mail/test-send.d.ts +147 -0
  83. package/dist/mail/test-send.js +198 -0
  84. package/dist/mail/use-readiness.d.ts +104 -0
  85. package/dist/mail/use-readiness.js +140 -0
  86. package/dist/object-store/local-fs.js +34 -1
  87. package/dist/object-store/site/artifact-provider.d.ts +65 -0
  88. package/dist/object-store/site/artifact-provider.js +37 -0
  89. package/dist/object-store/site/registry.d.ts +110 -0
  90. package/dist/object-store/site/registry.js +93 -0
  91. package/dist/object-store/site/setting.d.ts +34 -0
  92. package/dist/object-store/site/setting.js +32 -0
  93. package/dist/process-probes.d.ts +11 -4
  94. package/dist/process-probes.js +3 -3
  95. package/dist/process-top-footprint.d.ts +1 -1
  96. package/dist/process-top-footprint.js +1 -3
  97. package/dist/process.d.ts +3 -17
  98. package/dist/process.js +3 -2
  99. package/dist/retention/index.d.ts +6 -0
  100. package/dist/retention/index.js +6 -0
  101. package/dist/retention/measure-tree.d.ts +68 -0
  102. package/dist/retention/measure-tree.js +205 -0
  103. package/dist/retention/preview-store.d.ts +12 -0
  104. package/dist/retention/preview-store.js +28 -0
  105. package/dist/retention/routes.d.ts +23 -0
  106. package/dist/retention/routes.js +24 -0
  107. package/dist/retention/runner.d.ts +103 -0
  108. package/dist/retention/runner.js +164 -0
  109. package/dist/secrets/credential-sets/index.d.ts +1 -0
  110. package/dist/secrets/credential-sets/index.js +1 -0
  111. package/dist/secrets/credential-sets/store-vault-guards.d.ts +26 -0
  112. package/dist/secrets/credential-sets/store-vault-guards.js +30 -0
  113. package/dist/secrets/credential-sets/vault.service.d.ts +1 -1
  114. package/dist/secrets/index.d.ts +1 -1
  115. package/dist/secrets/index.js +1 -1
  116. package/dist/secrets/keyring.env.d.ts +1 -1
  117. package/dist/secrets/keyring.env.js +3 -5
  118. package/dist/secrets/keyring.memory.d.ts +4 -1
  119. package/dist/secrets/keyring.memory.js +4 -1
  120. package/dist/secrets/legacy-codecs.d.ts +381 -0
  121. package/dist/secrets/legacy-codecs.js +468 -0
  122. package/dist/secrets/legacy-owner.d.ts +3 -11
  123. package/dist/secrets/root-key/ensure.d.ts +154 -0
  124. package/dist/secrets/root-key/ensure.js +328 -0
  125. package/dist/secrets/root-key/files.d.ts +104 -0
  126. package/dist/secrets/root-key/files.js +166 -0
  127. package/dist/secrets/root-key/material.d.ts +132 -0
  128. package/dist/secrets/root-key/material.js +116 -0
  129. package/dist/secrets/root-key/ordered-keyring.d.ts +157 -0
  130. package/dist/secrets/root-key/ordered-keyring.js +104 -0
  131. package/dist/secrets/root-key/reconcile.d.ts +50 -0
  132. package/dist/secrets/root-key/reconcile.js +147 -0
  133. package/dist/secrets/root-key/site-keyring-errors.d.ts +78 -0
  134. package/dist/secrets/root-key/site-keyring-errors.js +37 -0
  135. package/dist/secrets/root-key/sources.d.ts +79 -0
  136. package/dist/secrets/root-key/sources.js +119 -0
  137. package/dist/secrets/secret-sealer.aesgcm.d.ts +50 -2
  138. package/dist/secrets/secret-sealer.aesgcm.js +107 -19
  139. package/dist/web/tool-registrations.d.ts +67 -0
  140. package/dist/web/tool-registrations.js +44 -0
  141. package/package.json +138 -6
@@ -0,0 +1,42 @@
1
+ /** Vault labels for a provider's webhook signing secret: current first, then the rotation slot.
2
+ * `labelPrefix` is the host's product label; stored labels are persisted, so it never changes. */
3
+ export function mailWebhookSecretLabels({ providerLabel, labelPrefix }) {
4
+ const current = `${labelPrefix} — ${providerLabel} Webhook Secret`;
5
+ return [current, `${current} (previous)`];
6
+ }
7
+ function asParser({ module }, _optional = {}) {
8
+ const feedback = module?.feedback;
9
+ return typeof feedback?.verify === "function" && typeof feedback.parse === "function" ? feedback : undefined;
10
+ }
11
+ /**
12
+ * Parser and label lookups over a freshly loaded adapter registry.
13
+ * @complexity O(a) adapters per lookup, plus one registry load.
14
+ */
15
+ export function createPluginMailFeedbackSources(required) {
16
+ const find = async ({ providerId }) => (await required.loadAdapters()).list().find((adapter) => adapter.descriptor.id === providerId);
17
+ return {
18
+ parserFor: async ({ providerId }) => asParser({ module: (await find({ providerId }))?.module }),
19
+ labelFor: async ({ providerId }) => (await find({ providerId }))?.descriptor.label,
20
+ };
21
+ }
22
+ /**
23
+ * `secretsFor` over the vault: the current then previous secret that are saved, in that order.
24
+ * A vault read failure propagates (the route answers 500 and the provider retries).
25
+ * @complexity Two label lookups per call.
26
+ */
27
+ export function createVaultMailWebhookSecrets(required, _optional = {}) {
28
+ const resolveByLabel = required.resolveByLabel;
29
+ return async ({ providerId }) => {
30
+ const providerLabel = await required.labelFor({ providerId });
31
+ if (providerLabel === undefined)
32
+ return [];
33
+ const secrets = [];
34
+ for (const label of mailWebhookSecretLabels({ providerLabel, labelPrefix: required.labelPrefix })) {
35
+ const saved = await resolveByLabel(required.credentials, { workspaceId: required.workspaceId, label });
36
+ if (saved && saved.connection.token !== "")
37
+ secrets.push(saved.connection.token);
38
+ }
39
+ return secrets;
40
+ };
41
+ }
42
+ //# sourceMappingURL=feedback-sources.js.map
@@ -25,7 +25,7 @@ export type { SenderDomainVerificationDeps } from "./sender-domain-verification.
25
25
  export { createMailPolicyWrapper } from "./delivery-wrapper.js";
26
26
  export type { MailPolicyWrapperDeps, MailPolicyWrapperOptions, MailPolicyWrapperInput } from "./delivery-wrapper.js";
27
27
  export { createResolvedMailer } from "./resolve-mailer.js";
28
- export type { ResolveMailerDeps, ResolveMailerOptions, ResolvedMailer } from "./resolve-mailer.js";
28
+ export type { ResolveMailerDeps, ResolveMailerOptions, ResolvedMailer, CreatedResolvedMailer } from "./resolve-mailer.js";
29
29
  export { createTtlCache, MAIL_STATUS_TTL_MS } from "./mail-status-cache.js";
30
30
  export type { TtlCache } from "./mail-status-cache.js";
31
31
  export * from "./senders.js";
@@ -36,4 +36,13 @@ export * from "./activity/vocabulary.js";
36
36
  export type * from "./activity/ports.js";
37
37
  export * from "./activity/activity.js";
38
38
  export * from "./activity/suppressions.js";
39
+ export { createMailPurposeGateProbe } from "./purpose-gate-probe.js";
40
+ export type { MailPurposeGateProbe } from "./purpose-gate-probe.js";
41
+ export { wrapPositionalMailerWithPurposeGate } from "./positional-purpose-gate.js";
42
+ export type { WrapPositionalMailerWithPurposeGateOptions } from "./positional-purpose-gate.js";
43
+ export type { MailProviderControl } from "./mail-status.js";
44
+ export { createMailFeedbackRoute, flattenHeaders, MAIL_FEEDBACK_MAX_BODY_BYTES } from "./feedback-route.js";
45
+ export type { MailFeedbackRequest, MailFeedbackRoute, MailFeedbackRouteDeps } from "./feedback-route.js";
46
+ export { createPluginMailFeedbackSources, createVaultMailWebhookSecrets, mailWebhookSecretLabels } from "./feedback-sources.js";
47
+ export type { MailAdapterSource, MailWebhookSecretResolver } from "./feedback-sources.js";
39
48
  //# sourceMappingURL=index.d.ts.map
@@ -20,4 +20,8 @@ export * from "./provider-mailer.js";
20
20
  export * from "./activity/vocabulary.js";
21
21
  export * from "./activity/activity.js";
22
22
  export * from "./activity/suppressions.js";
23
+ export { createMailPurposeGateProbe } from "./purpose-gate-probe.js";
24
+ export { wrapPositionalMailerWithPurposeGate } from "./positional-purpose-gate.js";
25
+ export { createMailFeedbackRoute, flattenHeaders, MAIL_FEEDBACK_MAX_BODY_BYTES } from "./feedback-route.js";
26
+ export { createPluginMailFeedbackSources, createVaultMailWebhookSecrets, mailWebhookSecretLabels } from "./feedback-sources.js";
23
27
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,32 @@
1
+ /** Shared safe status/configuration contracts are owned by Jini; the host retains selection control.
2
+ * The provider verdict remains separate from credential presence and delivery evidence.
3
+ * Setup copy is plugin/host data, and credential summaries expose presence without values.
4
+ */
5
+ import type { MailProviderConfigurationReport } from "./ports.js";
6
+ /** Explicit provider selection: `check` validates without sending, `select` writes both lanes. */
7
+ export interface MailProviderControl {
8
+ check(required: {
9
+ id: string;
10
+ }): Promise<{
11
+ ok: true;
12
+ label: string;
13
+ } | {
14
+ ok: false;
15
+ reason: string;
16
+ }>;
17
+ select(required: {
18
+ id: string;
19
+ principalId: string;
20
+ expectedRevisionSeq?: number;
21
+ }): Promise<void>;
22
+ /** Exact addressed setting value and revision, read before an access approval. */
23
+ readSelection?(): Promise<{
24
+ setting: MailProviderConfigurationReport["setting"];
25
+ revisionSeq: number;
26
+ }>;
27
+ /** The safe configuration DTO for every installed provider. Absent in older roots. */
28
+ describe?(): Promise<MailProviderConfigurationReport>;
29
+ /** Drops cached provider mailers and status so the next send and status read start fresh. */
30
+ invalidate?(): void;
31
+ }
32
+ //# sourceMappingURL=mail-status.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=mail-status.js.map
@@ -0,0 +1,14 @@
1
+ import type { PositionalMailer as MailerPort } from "./plugin-abi.js";
2
+ import type { RuntimeMode } from "@jini-ai/core/contracts/site/core-runtime-mode";
3
+ export interface WrapPositionalMailerWithPurposeGateOptions {
4
+ inner: MailerPort;
5
+ mode: RuntimeMode;
6
+ durableOutboxReady: (required: {
7
+ capabilityName: string;
8
+ }) => boolean;
9
+ }
10
+ /** Injects the host's durable-outbox readiness into Jini's fail-closed purpose gate.
11
+ * @example wrapPositionalMailerWithPurposeGate({ inner, mode, durableOutboxReady })
12
+ */
13
+ export declare function wrapPositionalMailerWithPurposeGate({ inner, mode, durableOutboxReady }: WrapPositionalMailerWithPurposeGateOptions): MailerPort;
14
+ //# sourceMappingURL=positional-purpose-gate.d.ts.map
@@ -0,0 +1,18 @@
1
+ /** Host adapters for Jini mail and the SPEC-022 durable notification gate.
2
+ * Jini preserves U-001: only explicit interactive sends bypass production readiness;
3
+ * local mode proceeds, and the supplied mode is never re-read from the environment.
4
+ */
5
+ import { wrapMailerWithPurposeGate as wrapJiniMailerWithPurposeGate, } from "./purpose-scoped-mailer.js";
6
+ import { fromPositionalMailer as toJiniMailer, toPositionalMailer as toHostMailer } from "./plugin-abi.js";
7
+ /** Injects the host's durable-outbox readiness into Jini's fail-closed purpose gate.
8
+ * @example wrapPositionalMailerWithPurposeGate({ inner, mode, durableOutboxReady })
9
+ */
10
+ export function wrapPositionalMailerWithPurposeGate({ inner, mode, durableOutboxReady }) {
11
+ const mailer = wrapJiniMailerWithPurposeGate({
12
+ inner: toJiniMailer({ mailer: inner }),
13
+ mode,
14
+ readiness: { isReady: ({ capabilityName }) => durableOutboxReady({ capabilityName }) },
15
+ });
16
+ return toHostMailer({ mailer });
17
+ }
18
+ //# sourceMappingURL=positional-purpose-gate.js.map
@@ -0,0 +1,18 @@
1
+ import type { RuntimeMode } from "@jini-ai/core/contracts/site/core-runtime-mode";
2
+ export type MailPurposeGateProbe = (required: {
3
+ capabilityName: string;
4
+ lane: "interactive" | "notification";
5
+ }) => Promise<boolean>;
6
+ /**
7
+ * @returns `true` when the gate would pass a send for that capability and lane, `false` when it refuses.
8
+ * @throws Anything else the gate throws (an unexpected failure is the caller's `unknown`, not a refusal).
9
+ * @complexity O(1); no I/O.
10
+ * @example await createMailPurposeGateProbe({ mode: "production", durableOutboxReady: () => false })({ capabilityName: "forms", lane: "notification" })
11
+ */
12
+ export declare function createMailPurposeGateProbe(required: {
13
+ mode: RuntimeMode;
14
+ durableOutboxReady: (required: {
15
+ capabilityName: string;
16
+ }) => boolean;
17
+ }): MailPurposeGateProbe;
18
+ //# sourceMappingURL=purpose-gate-probe.d.ts.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @file Asks Jini's purpose gate (`wrapMailerWithPurposeGate`, SPEC-022 C-005 / U-001) whether it
3
+ * would let a send through, without sending: the probe calls the gate's own predicate. The Email
4
+ * page's use readiness reads the real gate instead of restating its rules, so the two cannot drift.
5
+ *
6
+ * It is given the same `mode` and `durableOutboxReady` the composition root hands the live mailer's
7
+ * gate (`server/runtime/composition/deps.ts`); this file never decides readiness itself.
8
+ */
9
+ import { isPurposeGateOpen, validateMode } from "./purpose-scoped-mailer.js";
10
+ /**
11
+ * @returns `true` when the gate would pass a send for that capability and lane, `false` when it refuses.
12
+ * @throws Anything else the gate throws (an unexpected failure is the caller's `unknown`, not a refusal).
13
+ * @complexity O(1); no I/O.
14
+ * @example await createMailPurposeGateProbe({ mode: "production", durableOutboxReady: () => false })({ capabilityName: "forms", lane: "notification" })
15
+ */
16
+ export function createMailPurposeGateProbe(required) {
17
+ // Validate at composition, as the previous gate wrapper did; no readiness read in local mode.
18
+ validateMode({ mode: required.mode });
19
+ return async ({ capabilityName, lane }) => isPurposeGateOpen({ mode: required.mode,
20
+ readiness: { isReady: ({ capabilityName }) => required.durableOutboxReady({ capabilityName }) }, options: { lane, sourceContext: { module: capabilityName } } });
21
+ }
22
+ //# sourceMappingURL=purpose-gate-probe.js.map
@@ -8,6 +8,10 @@ export interface WrapMailerWithPurposeGateOptions {
8
8
  mode: RuntimeMode;
9
9
  readiness: DeliveryReadinessPolicy;
10
10
  }
11
+ /** Validate composition mode without evaluating delivery readiness. */
12
+ export declare function validateMode({ mode }: {
13
+ mode: RuntimeMode;
14
+ }, _optional?: Record<string, never>): void;
11
15
  export interface PurposeGateRequired {
12
16
  mode: RuntimeMode;
13
17
  readiness: DeliveryReadinessPolicy;
@@ -9,7 +9,8 @@ function resolveLane(options) {
9
9
  function refusalError(capabilityName) {
10
10
  return new Error(`MAILER_SEND_REFUSED_NO_DURABLE_PATH: notification-lane mailer send refused for capability "${capabilityName}" — no durable outbox path registered`);
11
11
  }
12
- function validateMode(mode) {
12
+ /** Validate composition mode without evaluating delivery readiness. */
13
+ export function validateMode({ mode }, _optional = {}) {
13
14
  if (mode !== "production" && mode !== "local") {
14
15
  throw new TypeError('mailer mode must be "production" or "local"');
15
16
  }
@@ -21,7 +22,7 @@ function validateMode(mode) {
21
22
  */
22
23
  export function isPurposeGateOpen(required) {
23
24
  const { mode, readiness, options } = required;
24
- validateMode(mode);
25
+ validateMode({ mode });
25
26
  if (mode === "local")
26
27
  return true;
27
28
  if (resolveLane(options) !== "notification")
@@ -38,7 +39,7 @@ export function isPurposeGateOpen(required) {
38
39
  export function wrapMailerWithPurposeGate(options) {
39
40
  const { inner, mode, readiness } = options;
40
41
  // Validate at composition: typos must never silently disable durable delivery.
41
- validateMode(mode);
42
+ validateMode({ mode });
42
43
  function checkGate(sendOptions) {
43
44
  if (!isPurposeGateOpen({ mode, readiness, options: sendOptions })) {
44
45
  throw refusalError(sendOptions.sourceContext?.module ?? "unknown");
@@ -74,6 +74,16 @@ export interface ResolvedMailer {
74
74
  laneReady: (required: {
75
75
  lane: MailDeliveryLane;
76
76
  }) => Promise<boolean>;
77
+ /**
78
+ * The provider id the lane's policy-wrapped mailer is really built for, from the SAME resolution that
79
+ * routes a send: `"console"` when a chosen provider could not resolve and the local console fallback
80
+ * took over, the chosen id otherwise (production refusals keep it), `null` when nothing is chosen.
81
+ * A host planning a test-send approval reads this instead of re-reading settings, which could name a
82
+ * provider the send never used. Optional so hosts that implement this interface keep compiling.
83
+ */
84
+ readonly effectiveProviderId?: (required: {
85
+ lane: MailDeliveryLane;
86
+ }) => Promise<string | null>;
77
87
  senderDomainVerification: SenderDomainVerificationPort;
78
88
  /** Whether `id` may be selected: a registered hosted provider whose saved key resolves. Sends nothing. */
79
89
  checkProvider: (required: {
@@ -85,6 +95,8 @@ export interface ResolvedMailer {
85
95
  workspaceId: string;
86
96
  }) => Promise<DomainRequirement | null>;
87
97
  }
98
+ /** What `createResolvedMailer` returns: the resolver always supplies the optional `effectiveProviderId`. */
99
+ export type CreatedResolvedMailer = ResolvedMailer & Required<Pick<ResolvedMailer, "effectiveProviderId">>;
88
100
  /**
89
101
  * Build a lane router and its control surface. The host binds catalogs, secrets, safe copy and DTOs.
90
102
  * Each send reads selection and metadata; boot starts resolution synchronously. Selection faults
@@ -92,5 +104,5 @@ export interface ResolvedMailer {
92
104
  * @complexity O(providers) cached mailers/flights; status holds one report for its TTL.
93
105
  * @example const control = createResolvedMailer(hostPorts, { clock }); await control.ready;
94
106
  */
95
- export declare function createResolvedMailer<TRecord extends MailCredentialFact = MailCredentialFact>(required: ResolveMailerDeps<TRecord>, optional?: ResolveMailerOptions): ResolvedMailer;
107
+ export declare function createResolvedMailer<TRecord extends MailCredentialFact = MailCredentialFact>(required: ResolveMailerDeps<TRecord>, optional?: ResolveMailerOptions): CreatedResolvedMailer;
96
108
  //# sourceMappingURL=resolve-mailer.d.ts.map
@@ -84,6 +84,7 @@ async function consoleMailer({ state, catalog }) {
84
84
  const provider = catalog.registry.get({ id: "console" }).provider;
85
85
  const mailer = state.wrap({ providerId: "console", provider, mailer: state.deps.createProviderMailer({ provider, credential: { token: "" } }) });
86
86
  state.resolved.set("console", { mailer, fingerprint: "" });
87
+ state.consoleFallbacks.add(mailer);
87
88
  return mailer;
88
89
  }
89
90
  /** Local mode keeps working through console; production refuses and logs safe host copy once. */
@@ -173,19 +174,23 @@ async function currentMailer({ state, id }) {
173
174
  state.resolved.delete(id);
174
175
  return resolveOnce({ state, id });
175
176
  }
176
- /** Fresh lane selection precedes every resolution and updates the synchronous transactional projection. */
177
- async function mailerForLane({ state, lane }) {
177
+ /** Fresh lane selection precedes every resolution and updates the synchronous transactional projection.
178
+ * The reported id comes from this same pass, so a settings change mid-flight cannot split id from mailer. */
179
+ async function resolveLane({ state, lane }) {
178
180
  const id = (await currentSetting(state))[lane];
179
181
  const mailer = id === null
180
182
  ? await fallback({ state, catalog: await state.deps.loadCatalog({}), errorCode: "MAIL_UNCONFIGURED", message: state.deps.unconfiguredMessage({ lane }) })
181
183
  : await currentMailer({ state, id });
182
184
  if (lane === "transactional")
183
185
  state.lastTransactional = mailer;
184
- return mailer;
186
+ return { mailer, providerId: id !== null && state.consoleFallbacks.has(mailer) ? "console" : id };
185
187
  }
186
188
  /** Settings/catalog faults become a refusal rather than throwing across the routing boundary. */
189
+ function laneResolution(required) {
190
+ return resolveLane(required).catch(() => ({ mailer: refusingMailer({ errorCode: "MAIL_PROVIDER_UNAVAILABLE", message: "Mail provider selection failed; check configuration." }), providerId: null }));
191
+ }
187
192
  function forLane(required) {
188
- return mailerForLane(required).catch(() => refusingMailer({ errorCode: "MAIL_PROVIDER_UNAVAILABLE", message: "Mail provider selection failed; check configuration." }));
193
+ return laneResolution(required).then(resolution => resolution.mailer);
189
194
  }
190
195
  /** The public mailer preserves synchronous capability reporting and awaits the proper lane for sends. */
191
196
  function createRouter(state) {
@@ -330,7 +335,7 @@ function invalidate(state) {
330
335
  export function createResolvedMailer(required, optional = {}) {
331
336
  const state = { deps: required, options: optional, nowMs: () => (optional.clock ?? { nowMs: () => Date.now() }).nowMs(),
332
337
  warn: optional.warn ?? (message => createConsoleLogger({ prefix: '' }).warn({ message })),
333
- wrap: optional.wrapProviderMailer ?? (({ mailer }) => mailer), resolved: new Map(), inFlight: new Map(), warned: new Set(), generation: 0,
338
+ wrap: optional.wrapProviderMailer ?? (({ mailer }) => mailer), consoleFallbacks: new WeakSet(), resolved: new Map(), inFlight: new Map(), warned: new Set(), generation: 0,
334
339
  initialization: undefined, lastTransactional: undefined, lastError: undefined };
335
340
  const ready = forLane({ state, lane: "transactional" }).then(() => undefined);
336
341
  const mailer = createRouter(state);
@@ -344,6 +349,7 @@ export function createResolvedMailer(required, optional = {}) {
344
349
  describeProviders: () => describeProviders({ state, deps: required }),
345
350
  invalidate: () => { invalidate(state); statusCache.invalidate(); },
346
351
  laneReady: async ({ lane }) => (await forLane({ state, lane })).capabilities({}).driver !== "console",
352
+ effectiveProviderId: async ({ lane }) => (await laneResolution({ state, lane })).providerId,
347
353
  checkProvider: input => checkProvider({ state, ...input }),
348
354
  domainRequirements: input => domainRequirements({ state, ...input, resolveDomainReadCredential }),
349
355
  };
@@ -0,0 +1,20 @@
1
+ import type { MailActivityRepo } from "../activity/ports.js";
2
+ import type { MailActivityUse } from "../activity/vocabulary.js";
3
+ import type { MailRepoDeps } from "./ledger.repo.js";
4
+ /** Classify an observation once, before writing it; unknown keys stay explicitly unknown. */
5
+ export declare function mailActivityUse({ idempotencyKey }: {
6
+ idempotencyKey: string;
7
+ }, _optional?: Record<string, never>): MailActivityUse;
8
+ /**
9
+ * The activity reads. Newest first by creation, ties broken by the opaque activity id, so a page boundary
10
+ * inside one timestamp is resumed by its keyset position without exposing a key or address in the cursor.
11
+ * @complexity Ordinary lists merge at most two limit-sized indexed candidate pages, then probe
12
+ * feedback at most three times per candidate. The legacy branch can scan the recent 30-day window
13
+ * for purpose/duplicate exclusion. Outcome filters evaluate candidates in that window before LIMIT;
14
+ * they are not constant-time indexed reads. Detail uses indexed identity/recipient predicates.
15
+ * @example createMailActivityRepo({ db: kernel }).list({ workspaceId, limit: 26 }, { outcome: "bounced" })
16
+ */
17
+ export declare function createMailActivityRepo<DB>({ db }: MailRepoDeps<DB>, optional?: {
18
+ now?: () => number;
19
+ }): MailActivityRepo;
20
+ //# sourceMappingURL=activity.repo.d.ts.map
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @file Read projection over the send ledger joined with provider feedback (email phase 4): the
3
+ * Email page's **Recent sends and failures** and `mail_list_activity`/`mail_get_activity`. One SQL
4
+ * body for SQLite and Postgres; migrations 0029 and 0031 add the source and lookup indexes.
5
+ *
6
+ * Only body-free metadata leaves here: the ledger stores no subject, body or link, and this never
7
+ * reads `mail_capture`. Outcomes are derived, never stored:
8
+ *
9
+ * - `sent` rows are `accepted` until feedback says more; the most severe event wins
10
+ * (complained > bounced > delivered), joined by the provider's message id.
11
+ * - `failed` rows keep the policy's reason: `MAIL_RECIPIENT_SUPPRESSED` is `suppressed`,
12
+ * `MAIL_RATE_LIMITED` is `deferred`, anything else `failed`.
13
+ * - `reserved` (in flight, or a crash mid-send) and `unknown` are `unknown`: the provider may have
14
+ * taken it, which is exactly why there is no general Resend.
15
+ *
16
+ * The observer persists use (purpose) from the idempotency key prefix each owner already writes
17
+ * (`members:signin:`, `newsletter:confirm-email:`, `forms:notify:`, `newsletter:`, `mail:test:`).
18
+ * Historical ledgers derive it within the recent window; any other key is `unknown` rather than
19
+ * guessed.
20
+ */
21
+ import { sql } from "kysely";
22
+ import { MAIL_ACTIVITY_RETENTION_MS } from "./retention.js";
23
+ const USE_PREFIXES = [
24
+ ["members:signin:", "sign_in"], ["newsletter:confirm-email:", "newsletter_confirmation"],
25
+ ["forms:notify:", "form_notification"], ["mail:test:", "test"], ["newsletter:", "newsletter"],
26
+ ];
27
+ /** Classify an observation once, before writing it; unknown keys stay explicitly unknown. */
28
+ export function mailActivityUse({ idempotencyKey }, _optional = {}) {
29
+ return USE_PREFIXES.find(([prefix]) => idempotencyKey.startsWith(prefix))?.[1] ?? "unknown";
30
+ }
31
+ /** Historical ledgers predate the purpose column. Only their recent window is projected. */
32
+ function legacyUse(_required = {}, _optional = {}) {
33
+ const clauses = USE_PREFIXES.map(([prefix, use]) => {
34
+ const pattern = `${prefix}%`;
35
+ return sql `WHEN old.idempotency_key LIKE ${pattern} THEN ${use}`;
36
+ });
37
+ const joined = sql.join(clauses, sql ` `);
38
+ return sql `CASE ${joined} ELSE 'unknown' END`;
39
+ }
40
+ const feedbackExists = (kind) => sql `EXISTS (SELECT 1 FROM mail_feedback_inbox f
41
+ WHERE f.workspace_id = l.workspace_id AND f.provider_message_id = l.provider_message_id AND f.provider_id = l.provider_id AND f.recipient = l.effective_recipient AND f.kind = ${kind} AND f.processed_at IS NOT NULL)`;
42
+ /** Push non-derived predicates into each indexed source; outcome is resolved after feedback. */
43
+ function sourceConditions(required, _optional = {}) {
44
+ const { filter, legacy } = required;
45
+ const alias = legacy ? "old" : "a";
46
+ const col = ({ name }, _optional = {}) => sql.ref(`${alias}.${name}`);
47
+ const where = [sql `${col({ name: "workspace_id" })} = ${required.workspaceId}`, sql `${col({ name: "created_at" })} >= ${required.cutoff}`];
48
+ if (filter.use)
49
+ where.push(sql `${legacy ? legacyUse() : col({ name: "use_id" })} = ${filter.use}`);
50
+ if (required.idempotencyKey)
51
+ where.push(sql `${col({ name: "idempotency_key" })} = ${required.idempotencyKey}`);
52
+ if (filter.recipient)
53
+ where.push(recipientCondition({ ...required, recipient: filter.recipient }));
54
+ if (filter.before)
55
+ where.push(sql `(${col({ name: "created_at" })} < ${filter.before.createdAt} OR (${col({ name: "created_at" })} = ${filter.before.createdAt} AND ${col({ name: legacy ? "activity_id" : "id" })} < ${filter.before.key}))`);
56
+ return sql.join(where, sql ` AND `);
57
+ }
58
+ /** Exact effective-recipient lookup for details; list filters also match the original address. */
59
+ function recipientCondition(required, _optional = {}) {
60
+ const address = required.recipient.trim().toLowerCase();
61
+ const original = sql.ref(required.legacy ? "old.recipient" : "a.recipient");
62
+ const effective = sql.ref(required.legacy ? "old.recipient" : "a.effective_recipient");
63
+ return required.effectiveOnly ? sql `${effective} = ${address}` : sql `(${original} = ${address} OR ${effective} = ${address})`;
64
+ }
65
+ /** Limit each ordered source before the UNION/feedback work on ordinary page reads. */
66
+ function activitySources(required, _optional = {}) {
67
+ const limit = required.limit === undefined ? sql `` : sql `LIMIT ${required.limit}`;
68
+ return sql `SELECT * FROM (
69
+ SELECT a.id AS activity_id, a.workspace_id, a.idempotency_key, a.recipient, a.effective_recipient, a.delivery_mode,
70
+ a.lane, a.provider_id, a.outcome, a.provider_message_id, a.error_code, a.message, a.created_at, a.updated_at, a.use_id
71
+ FROM mail_activity_attempts a WHERE ${sourceConditions({ ...required, legacy: false })}
72
+ ORDER BY a.created_at DESC, a.id DESC ${limit}
73
+ ) attempts
74
+ UNION ALL SELECT * FROM (
75
+ SELECT old.activity_id, old.workspace_id, old.idempotency_key, old.recipient, old.recipient AS effective_recipient, 'off' AS delivery_mode,
76
+ old.lane, old.provider_id, old.outcome, old.provider_message_id, old.error_code, NULL AS message, old.created_at, old.updated_at, ${legacyUse()} AS use_id
77
+ FROM mail_send_ledger old WHERE ${sourceConditions({ ...required, legacy: true })}
78
+ AND old.activity_retained = 1 AND NOT EXISTS (SELECT 1 FROM mail_activity_attempts a
79
+ WHERE a.workspace_id = old.workspace_id AND a.idempotency_key = old.idempotency_key AND a.recipient = old.recipient)
80
+ ORDER BY old.created_at DESC, old.activity_id DESC ${limit}
81
+ ) legacy`;
82
+ }
83
+ /** Feedback is probed only for candidate rows; the attempts' stored purpose remains indexable. */
84
+ function projection(required, _optional = {}) {
85
+ return sql `SELECT l.*,
86
+ CASE WHEN l.outcome = 'captured' THEN 'captured' WHEN l.outcome = 'sent' THEN
87
+ CASE WHEN ${feedbackExists("complained")} THEN 'complained' WHEN ${feedbackExists("bounced")} THEN 'bounced'
88
+ WHEN ${feedbackExists("delivered")} THEN 'delivered' ELSE 'accepted' END
89
+ WHEN l.outcome = 'failed' THEN
90
+ CASE WHEN l.error_code = 'MAIL_RECIPIENT_SUPPRESSED' THEN 'suppressed' WHEN l.error_code = 'MAIL_RATE_LIMITED' THEN 'deferred' ELSE 'failed' END
91
+ ELSE 'unknown' END AS activity_outcome
92
+ FROM (${activitySources(required)}) l`;
93
+ }
94
+ function toRecord(row) {
95
+ return {
96
+ cursorKey: row.activity_id, idempotencyKey: row.idempotency_key, recipient: row.effective_recipient,
97
+ ...(row.delivery_mode === "off" ? {} : { originalRecipient: row.recipient, deliveryMode: row.delivery_mode }), lane: row.lane, providerId: row.provider_id, use: row.use_id,
98
+ outcome: row.activity_outcome, providerMessageId: row.provider_message_id, errorCode: row.error_code, message: row.message, createdAt: row.created_at, updatedAt: row.updated_at,
99
+ };
100
+ }
101
+ /**
102
+ * The activity reads. Newest first by creation, ties broken by the opaque activity id, so a page boundary
103
+ * inside one timestamp is resumed by its keyset position without exposing a key or address in the cursor.
104
+ * @complexity Ordinary lists merge at most two limit-sized indexed candidate pages, then probe
105
+ * feedback at most three times per candidate. The legacy branch can scan the recent 30-day window
106
+ * for purpose/duplicate exclusion. Outcome filters evaluate candidates in that window before LIMIT;
107
+ * they are not constant-time indexed reads. Detail uses indexed identity/recipient predicates.
108
+ * @example createMailActivityRepo({ db: kernel }).list({ workspaceId, limit: 26 }, { outcome: "bounced" })
109
+ */
110
+ export function createMailActivityRepo({ db }, optional = {}) {
111
+ const cutoff = () => new Date((optional.now ?? Date.now)() - MAIL_ACTIVITY_RETENTION_MS).toISOString();
112
+ return {
113
+ async list(required, optional = {}) {
114
+ const source = { workspaceId: required.workspaceId, cutoff: cutoff(), filter: optional, ...(optional.outcome ? {} : { limit: required.limit }) };
115
+ const outcome = optional.outcome ? sql `WHERE a.activity_outcome = ${optional.outcome}` : sql ``;
116
+ const rows = await db.query(sql `SELECT * FROM (${projection(source)}) a ${outcome}
117
+ ORDER BY a.created_at DESC, a.activity_id DESC LIMIT ${required.limit}`);
118
+ return rows.map(toRecord);
119
+ },
120
+ async get({ workspaceId, idempotencyKey, recipient }) {
121
+ const [row] = await db.query(sql `SELECT * FROM (${projection({ workspaceId, cutoff: cutoff(), filter: { recipient }, idempotencyKey, effectiveOnly: true, limit: 1 })}) a LIMIT 1`);
122
+ if (!row)
123
+ return null;
124
+ const feedback = row.provider_message_id === null ? [] : await db.query(sql `SELECT kind, hard_bounce, provider_id, occurred_at, received_at FROM mail_feedback_inbox
125
+ WHERE workspace_id = ${workspaceId} AND provider_message_id = ${row.provider_message_id} AND provider_id = ${row.provider_id} AND recipient = ${row.effective_recipient} AND processed_at IS NOT NULL ORDER BY occurred_at, event_id`);
126
+ return {
127
+ record: toRecord(row),
128
+ feedback: feedback.map((event) => ({ kind: event.kind, hardBounce: Number(event.hard_bounce) === 1, providerId: event.provider_id, occurredAt: event.occurred_at, receivedAt: event.received_at })),
129
+ };
130
+ },
131
+ };
132
+ }
133
+ //# sourceMappingURL=activity.repo.js.map
@@ -0,0 +1,17 @@
1
+ import type { MailRepoDeps, MailRepoOptions } from "./ledger.repo.js";
2
+ import type { MailTestModeSetting } from "@jini-ai/core/contracts/mail";
3
+ import type { MailerSendOptions, MailerSendResult, OutboundEmail } from "../ports.js";
4
+ /** The delivery policy's per-result observer. Declared here (not in server/) so features never import server code. */
5
+ export type MailAttemptObserver = (required: {
6
+ message: OutboundEmail;
7
+ options: MailerSendOptions;
8
+ providerId: string;
9
+ mode: MailTestModeSetting;
10
+ result: MailerSendResult;
11
+ }) => Promise<void>;
12
+ /** Upsert one request's latest result without changing its original position in activity history.
13
+ * @complexity One indexed write; no subject, body or authentication link is stored; only a scrubbed failure diagnostic. */
14
+ export declare function createMailAttemptObserver<DB>({ db }: MailRepoDeps<DB>, options?: MailRepoOptions & {
15
+ newId?: () => string;
16
+ }): MailAttemptObserver;
17
+ //# sourceMappingURL=attempts.repo.d.ts.map
@@ -0,0 +1,32 @@
1
+ /** Body-free observation of every policy result, including preflight refusals and captures. */
2
+ import { safeMailProviderText } from "../provider-error.js";
3
+ import { laneForPurpose } from "../policy.js";
4
+ import { mailActivityUse } from "./activity.repo.js";
5
+ import { randomUUID } from "node:crypto";
6
+ import { sql } from "kysely";
7
+ /** Upsert one request's latest result without changing its original position in activity history.
8
+ * @complexity One indexed write; no subject, body or authentication link is stored; only a scrubbed failure diagnostic. */
9
+ export function createMailAttemptObserver({ db }, options = {}) {
10
+ const nowIso = options.nowIso ?? (() => new Date().toISOString());
11
+ const newId = options.newId ?? randomUUID;
12
+ return async ({ message, options: send, providerId, mode, result }) => {
13
+ const at = nowIso();
14
+ const recipient = message.to.email.trim().toLowerCase();
15
+ const effective = mode.mode === "redirect" ? mode.to.trim().toLowerCase() : recipient;
16
+ let outcome;
17
+ if (result.ok) {
18
+ outcome = result.providerMessageId.startsWith("captured:") || providerId === "console" ? "captured" : "sent";
19
+ }
20
+ else {
21
+ outcome = result.unknown ? "unknown" : "failed";
22
+ }
23
+ await db.execute(sql `INSERT INTO mail_activity_attempts
24
+ (id, workspace_id, idempotency_key, recipient, effective_recipient, delivery_mode, use_id, lane, provider_id, outcome, provider_message_id, error_code, message, created_at, updated_at)
25
+ VALUES (${newId()}, ${send.workspaceId}, ${send.idempotencyKey}, ${recipient}, ${effective}, ${mode.mode}, ${mailActivityUse({ idempotencyKey: send.idempotencyKey })}, ${laneForPurpose({ purpose: send.purpose })}, ${providerId}, ${outcome}, ${result.ok ? result.providerMessageId : null}, ${result.ok ? null : safeMailProviderText({ text: result.errorCode })}, ${result.ok ? null : safeMailProviderText({ text: result.message })}, ${at}, ${at})
26
+ ON CONFLICT (workspace_id, idempotency_key, recipient) DO UPDATE SET
27
+ effective_recipient = excluded.effective_recipient, delivery_mode = excluded.delivery_mode, use_id = excluded.use_id,
28
+ provider_id = excluded.provider_id, outcome = excluded.outcome, provider_message_id = excluded.provider_message_id,
29
+ error_code = excluded.error_code, message = excluded.message, updated_at = excluded.updated_at`);
30
+ };
31
+ }
32
+ //# sourceMappingURL=attempts.repo.js.map
@@ -0,0 +1,69 @@
1
+ import { type OriginRegistryPort } from "@jini-ai/core/contracts/server/verified-origin";
2
+ import type { MailCaptureClearPlan } from "@jini-ai/core/contracts/mail";
3
+ import type { MailCapturePort, MailDeliveryLane, OutboundEmail } from "../ports.js";
4
+ import type { MailRepoDeps, MailRepoOptions } from "./ledger.repo.js";
5
+ export interface CapturedMail {
6
+ id: string;
7
+ lane: MailDeliveryLane;
8
+ idempotencyKey: string;
9
+ to: string;
10
+ subject: string;
11
+ message: OutboundEmail;
12
+ createdAt: string;
13
+ }
14
+ export interface MailCaptureRepo extends MailCapturePort {
15
+ /** Newest first. `limit` is clamped to 1..{@link MAX_CAPTURE_LIST}; default {@link DEFAULT_CAPTURE_LIST}. */
16
+ listCaptured(required: {
17
+ workspaceId: string;
18
+ }, optional?: {
19
+ limit?: number;
20
+ }): Promise<readonly CapturedMail[]>;
21
+ /**
22
+ * The owner's review of a clear: this workspace's stored captures plus the activity rows the Email
23
+ * Activity list shows as kept locally (`outcome = 'captured'`, which includes console-driver sends that
24
+ * never store a copy), their summary, and the revision naming exactly that set. `plan.count` counts
25
+ * distinct test emails (a test-mode capture and its activity row are one email).
26
+ */
27
+ reviewCaptured(required: {
28
+ workspaceId: string;
29
+ }): Promise<CapturedMailReview>;
30
+ /**
31
+ * Deletes, in one transaction, only the reviewed `captureIds` and still-captured `attemptIds` of this
32
+ * workspace, and retires the matching send-ledger rows from the activity projection so a cleared send
33
+ * cannot resurface there. A capture that arrived after the review, or another workspace's, is never
34
+ * deleted; the ledger rows themselves (duplicate protection) and real sends are untouched.
35
+ * @returns `deleted`: the distinct test emails removed, counted like `plan.count`.
36
+ */
37
+ clearReviewedCaptures(required: {
38
+ workspaceId: string;
39
+ captureIds: readonly string[];
40
+ attemptIds: readonly string[];
41
+ }): Promise<{
42
+ deleted: number;
43
+ }>;
44
+ }
45
+ /** A reviewed set of captured test emails; `revision` changes whenever the set does (not only its count or newest time). */
46
+ export interface CapturedMailReview {
47
+ plan: MailCaptureClearPlan;
48
+ captureIds: readonly string[];
49
+ attemptIds: readonly string[];
50
+ revision: string;
51
+ }
52
+ export declare const DEFAULT_CAPTURE_LIST = 50;
53
+ export declare const MAX_CAPTURE_LIST = 200;
54
+ /**
55
+ * Stores sign-in captures whole only for trusted loopback origins, so local/desktop operators
56
+ * can click their links. Public or missing origins retain routing metadata only: subject, body,
57
+ * headers, names and attachments may all contain credentials and must never reach storage.
58
+ * @complexity capture O(payload size); listCaptured O(returned payload size), with a bounded indexed row limit;
59
+ * reviewCaptured O(workspace captures + captured attempts), two workspace-scoped reads; clearReviewedCaptures
60
+ * O(reviewed ids) primary-key deletes in ceil(ids / 500) statements per table plus one indexed ledger
61
+ * update per deleted attempt, one transaction.
62
+ * @example createMailCaptureRepo({ db: kernel }).capture({ message, lane: "transactional", idempotencyKey })
63
+ */
64
+ export declare function createMailCaptureRepo<DB>({ db, origin }: MailRepoDeps<DB> & {
65
+ origin?: OriginRegistryPort;
66
+ }, optional?: MailRepoOptions & {
67
+ newId?: () => string;
68
+ }): MailCaptureRepo;
69
+ //# sourceMappingURL=capture.repo.d.ts.map