@happyvertical/garrula 0.1.5 → 0.1.7
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.
- package/dist/Garrula.d.ts +9 -2
- package/dist/index.js +46 -4
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/outbound/service.d.ts +7 -1
- package/dist/smrt-knowledge.json +3 -3
- package/dist/types.d.ts +2 -0
- package/package.json +1 -1
package/dist/Garrula.d.ts
CHANGED
|
@@ -213,6 +213,13 @@ export declare class Garrula extends Agent {
|
|
|
213
213
|
private resolveRequestTenantId;
|
|
214
214
|
private normalizeTenantId;
|
|
215
215
|
private getPostAccount;
|
|
216
|
+
/**
|
|
217
|
+
* Renew an account whose recorded expiry has passed, as publishing would:
|
|
218
|
+
* refresh the access token when it is due and save the new token set, which
|
|
219
|
+
* clears the lapsed expiry on a refreshable OAuth 2 account. Throws when the
|
|
220
|
+
* account has no credentials, cannot refresh, or the refresh fails.
|
|
221
|
+
*/
|
|
222
|
+
private renewLapsedAccount;
|
|
216
223
|
/**
|
|
217
224
|
* Build the account's adapter with a usable access token. A token that is
|
|
218
225
|
* expired or close to it (or of unknown age) is refreshed first and the new
|
|
@@ -232,8 +239,8 @@ export declare class Garrula extends Agent {
|
|
|
232
239
|
* Save a refreshed token set on the account (encrypted, tenant-scoped).
|
|
233
240
|
* `tokenExpiresAt` on the account means "the connection lapses then", so it
|
|
234
241
|
* is cleared for refreshable OAuth 2 tokens and moved forward for Threads.
|
|
235
|
-
* A failed save is logged
|
|
236
|
-
* publish.
|
|
242
|
+
* A failed save is logged, the account's in-memory state is restored, and
|
|
243
|
+
* the fresh token is still used for this publish.
|
|
237
244
|
*/
|
|
238
245
|
private saveRefreshedCredentials;
|
|
239
246
|
/**
|
package/dist/index.js
CHANGED
|
@@ -644,6 +644,10 @@ async function createOutboundStores(options) {
|
|
|
644
644
|
events: await GarrulaSourceEventCollection.create(opts)
|
|
645
645
|
};
|
|
646
646
|
}
|
|
647
|
+
/** Unready only because the access token's recorded expiry has passed. */
|
|
648
|
+
function isLapsedOnly(account) {
|
|
649
|
+
return account.isActive !== false && account.status === "connected" && account.hasCredentials && (account.missingPermissions?.length ?? 0) === 0 && (account.publishMode !== "public" || account.publicPublishingAllowed === true) && account.isTokenExpired;
|
|
650
|
+
}
|
|
647
651
|
var locks = /* @__PURE__ */ new Map();
|
|
648
652
|
function withLock(tenantId, fn) {
|
|
649
653
|
const run = (locks.get(tenantId) ?? Promise.resolve()).then(fn, fn);
|
|
@@ -675,7 +679,9 @@ var OutboundService = class {
|
|
|
675
679
|
configFn;
|
|
676
680
|
aiFn;
|
|
677
681
|
nowFn;
|
|
682
|
+
refreshAccount;
|
|
678
683
|
constructor(options) {
|
|
684
|
+
this.refreshAccount = options.refreshAccount;
|
|
679
685
|
this.stores = options.stores;
|
|
680
686
|
this.social = options.social;
|
|
681
687
|
this.configFn = options.config;
|
|
@@ -967,7 +973,22 @@ var OutboundService = class {
|
|
|
967
973
|
}));
|
|
968
974
|
}
|
|
969
975
|
async targetAccounts(tenantId, settings) {
|
|
970
|
-
|
|
976
|
+
const wanted = (account) => Boolean(account.id) && account.tenantId === tenantId && (settings.accountIds.length === 0 || settings.accountIds.includes(account.id));
|
|
977
|
+
const ready = (await this.social.socialAccounts.findReady()).filter(wanted);
|
|
978
|
+
const collection = this.social.socialAccounts;
|
|
979
|
+
if (!this.refreshAccount || typeof collection.findActive !== "function") return ready;
|
|
980
|
+
const readyIds = new Set(ready.map((account) => account.id));
|
|
981
|
+
const accounts = [...ready];
|
|
982
|
+
for (const account of (await collection.findActive()).filter(wanted)) {
|
|
983
|
+
if (readyIds.has(account.id) || !isLapsedOnly(account)) continue;
|
|
984
|
+
try {
|
|
985
|
+
await this.refreshAccount(account);
|
|
986
|
+
} catch {
|
|
987
|
+
continue;
|
|
988
|
+
}
|
|
989
|
+
if (account.isReady) accounts.push(account);
|
|
990
|
+
}
|
|
991
|
+
return accounts;
|
|
971
992
|
}
|
|
972
993
|
async requireRow(tenantId, id) {
|
|
973
994
|
const row = (await this.stores.posts.list({ where: {
|
|
@@ -1445,7 +1466,8 @@ var Garrula = class Garrula extends Agent {
|
|
|
1445
1466
|
},
|
|
1446
1467
|
config: () => this.garrulaConfig,
|
|
1447
1468
|
ai: () => this.draftingAI ?? this.ai,
|
|
1448
|
-
now: () => this.nowFn()
|
|
1469
|
+
now: () => this.nowFn(),
|
|
1470
|
+
refreshAccount: (account) => this.renewLapsedAccount(account)
|
|
1449
1471
|
});
|
|
1450
1472
|
}
|
|
1451
1473
|
if (!this.outbound && !this.unsafeDisableOutboundGate) throw new Error("Garrula has no outbound gate: pass `outboundStores` (or let it use its own database). `unsafeDisableOutboundGate: true` disables it and is for tests only.");
|
|
@@ -1995,6 +2017,18 @@ var Garrula = class Garrula extends Agent {
|
|
|
1995
2017
|
return account;
|
|
1996
2018
|
}
|
|
1997
2019
|
/**
|
|
2020
|
+
* Renew an account whose recorded expiry has passed, as publishing would:
|
|
2021
|
+
* refresh the access token when it is due and save the new token set, which
|
|
2022
|
+
* clears the lapsed expiry on a refreshable OAuth 2 account. Throws when the
|
|
2023
|
+
* account has no credentials, cannot refresh, or the refresh fails.
|
|
2024
|
+
*/
|
|
2025
|
+
async renewLapsedAccount(account) {
|
|
2026
|
+
const credentials = await account.getCredentials();
|
|
2027
|
+
if (!credentials || !refreshKind(account.platform, credentials)) throw new Error("Account cannot be refreshed");
|
|
2028
|
+
const { credentials: fresh } = await this.openAdapter(account, credentials);
|
|
2029
|
+
if (fresh === credentials && account.isTokenExpired && refreshKind(account.platform, fresh) === "oauth2") await this.saveRefreshedCredentials(account, fresh, null);
|
|
2030
|
+
}
|
|
2031
|
+
/**
|
|
1998
2032
|
* Build the account's adapter with a usable access token. A token that is
|
|
1999
2033
|
* expired or close to it (or of unknown age) is refreshed first and the new
|
|
2000
2034
|
* token set is saved on the account, so the next publish starts from it.
|
|
@@ -2067,10 +2101,15 @@ var Garrula = class Garrula extends Agent {
|
|
|
2067
2101
|
* Save a refreshed token set on the account (encrypted, tenant-scoped).
|
|
2068
2102
|
* `tokenExpiresAt` on the account means "the connection lapses then", so it
|
|
2069
2103
|
* is cleared for refreshable OAuth 2 tokens and moved forward for Threads.
|
|
2070
|
-
* A failed save is logged
|
|
2071
|
-
* publish.
|
|
2104
|
+
* A failed save is logged, the account's in-memory state is restored, and
|
|
2105
|
+
* the fresh token is still used for this publish.
|
|
2072
2106
|
*/
|
|
2073
2107
|
async saveRefreshedCredentials(account, credentials, connectionExpiresAt) {
|
|
2108
|
+
const previous = {
|
|
2109
|
+
tokenExpiresAt: account.tokenExpiresAt,
|
|
2110
|
+
status: account.status,
|
|
2111
|
+
errorMessage: account.errorMessage
|
|
2112
|
+
};
|
|
2074
2113
|
try {
|
|
2075
2114
|
account.tokenExpiresAt = connectionExpiresAt;
|
|
2076
2115
|
if (account.status !== "connected") {
|
|
@@ -2083,6 +2122,9 @@ var Garrula = class Garrula extends Agent {
|
|
|
2083
2122
|
platform: account.platform
|
|
2084
2123
|
});
|
|
2085
2124
|
} catch (error) {
|
|
2125
|
+
account.tokenExpiresAt = previous.tokenExpiresAt;
|
|
2126
|
+
account.status = previous.status;
|
|
2127
|
+
account.errorMessage = previous.errorMessage;
|
|
2086
2128
|
this.logger.error("Could not save a refreshed social account token", {
|
|
2087
2129
|
accountId: account.id,
|
|
2088
2130
|
platform: account.platform,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/credentials.ts","../src/outbound/rates.ts","../src/config.ts","../src/outbound/drafting.ts","../src/outbound/models.ts","../src/outbound/sources.ts","../src/outbound/state.ts","../src/ui/post-kinds.ts","../src/outbound/types.ts","../src/outbound/service.ts","../src/Garrula.ts"],"sourcesContent":["import { SocialError, type AuthResult } from \"@happyvertical/social\";\nimport type { SocialPlatformType } from \"@happyvertical/smrt-social\";\n\n/**\n * Social OAuth token upkeep for Garrula's publisher.\n *\n * TODO(happyvertical/sdk#1376): `@happyvertical/social` adapters should\n * refresh expired tokens themselves (expiry margin, retry after a 401) and\n * hand the refreshed token set to a callback for the caller to persist,\n * Threads included. Until then Garrula decides when to refresh, refreshes\n * Threads tokens itself, and persists every refreshed token set. Drop this\n * module's refresh logic when that ships.\n */\n\n/** Default for how long before expiry an access token is refreshed. */\nexport const ACCESS_TOKEN_REFRESH_MARGIN_MS = 5 * 60 * 1000;\n\n/**\n * Default window in which a Threads long-lived token (60 days) is refreshed:\n * once it is this close to lapsing. Meta refuses to refresh a token younger than 24 hours, so a\n * publish soon after connecting keeps the token it has.\n */\nexport const THREADS_REFRESH_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport const THREADS_REFRESH_URL = \"https://graph.threads.net/refresh_access_token\";\n\nconst PLATFORM_LABELS: Record<SocialPlatformType, string> = {\n youtube: \"YouTube\",\n x: \"X\",\n threads: \"Threads\",\n facebook: \"Facebook\",\n bluesky: \"Bluesky\",\n};\n\nexport function platformLabel(platform: SocialPlatformType): string {\n return PLATFORM_LABELS[platform] ?? platform;\n}\n\n/** Where a person reconnects an account, unless the host says otherwise. */\nexport const DEFAULT_SOCIAL_SETTINGS_LOCATION = \"Settings → Social\";\n\n/** What the poster sees when an account has to be connected again. */\nexport function reconnectMessage(\n platform: SocialPlatformType,\n settingsLocation: string = DEFAULT_SOCIAL_SETTINGS_LOCATION,\n): string {\n const label = platformLabel(platform);\n return `The ${label} account's sign-in has expired or was revoked, so nothing was posted. Reconnect ${label} in ${settingsLocation}, then try again.`;\n}\n\n/**\n * The account's sign-in can no longer be used or refreshed; a person has to\n * reconnect it. The message is safe to show and never carries provider text.\n */\nexport class GarrulaReconnectError extends Error {\n readonly code = \"RECONNECT_REQUIRED\";\n\n constructor(\n readonly platform: SocialPlatformType,\n settingsLocation?: string,\n ) {\n super(reconnectMessage(platform, settingsLocation));\n this.name = \"GarrulaReconnectError\";\n }\n}\n\n/** The provider rejected the sign-in (HTTP 401 or an auth error code). */\nexport function isAuthError(error: unknown): boolean {\n if (error instanceof GarrulaReconnectError) return false;\n if (!(error instanceof SocialError)) return false;\n return error.code === \"AUTH_ERROR\" || error.statusCode === 401;\n}\n\n/**\n * The provider refused the refresh grant itself (revoked consent,\n * `invalid_grant`, a rotated-away X refresh token), as opposed to a network\n * failure or an outage worth retrying later.\n */\nexport function isRefreshRejected(error: unknown): boolean {\n if (!(error instanceof SocialError)) return false;\n if (error.code === \"AUTH_ERROR\") {\n // The YouTube adapter reports every failed refresh (429 and 5xx too) as\n // an auth error carrying Google's response body, so only a refused grant\n // (RFC 6749 §5.2 error code) means the sign-in is gone.\n // TODO(happyvertical/sdk#1376): use the typed reauth error once it ships.\n if (error.platform === \"youtube\") return OAUTH_GRANT_REFUSED.test(error.message);\n return true;\n }\n const status = error.statusCode;\n return status === 400 || status === 401 || status === 403;\n}\n\nconst OAUTH_GRANT_REFUSED = /\\b(invalid_grant|invalid_client|unauthorized_client|invalid_scope)\\b/;\n\nexport function parseExpiry(value: unknown): Date | null {\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;\n if (typeof value === \"string\" || typeof value === \"number\") {\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n }\n return null;\n}\n\n/** Which refresh flow an account's stored credentials support. */\nexport type RefreshKind = \"oauth2\" | \"threads\" | null;\n\nexport function refreshKind(\n platform: SocialPlatformType,\n credentials: Record<string, unknown>,\n): RefreshKind {\n const has = (name: string) =>\n typeof credentials[name] === \"string\" && (credentials[name] as string).length > 0;\n switch (platform) {\n case \"youtube\":\n return has(\"refreshToken\") && has(\"clientId\") && has(\"clientSecret\") ? \"oauth2\" : null;\n case \"x\": {\n const oauth2 = credentials.authType === \"oauth2\" || !credentials.accessSecret;\n return oauth2 && has(\"refreshToken\") && has(\"clientId\") && has(\"clientSecret\")\n ? \"oauth2\"\n : null;\n }\n case \"threads\":\n return has(\"accessToken\") ? \"threads\" : null;\n default:\n return null;\n }\n}\n\n/**\n * The stored credentials with a refreshed token set merged in. Every other\n * stored field (client id/secret, user id, auth type, scopes) is kept.\n */\nexport function mergeRefreshedCredentials(\n credentials: Record<string, unknown>,\n auth: AuthResult,\n): Record<string, unknown> {\n const next: Record<string, unknown> = {\n ...credentials,\n accessToken: auth.accessToken,\n };\n if (auth.refreshToken) next.refreshToken = auth.refreshToken;\n if (auth.expiresAt) next.expiresAt = auth.expiresAt.toISOString();\n else delete next.expiresAt;\n if (auth.tokenType) next.tokenType = auth.tokenType;\n if (auth.scopes?.length) next.scopes = auth.scopes;\n return next;\n}\n\n/**\n * Refresh a Threads long-lived token. The upstream Threads adapter does not\n * implement `refreshToken()` (TODO(happyvertical/sdk#1376)).\n */\nexport async function refreshThreadsToken(\n accessToken: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<AuthResult> {\n const url = new URL(THREADS_REFRESH_URL);\n url.searchParams.set(\"grant_type\", \"th_refresh_token\");\n url.searchParams.set(\"access_token\", accessToken);\n const response = await fetchImpl(url);\n const body = (await response.json().catch(() => null)) as {\n access_token?: unknown;\n token_type?: unknown;\n expires_in?: unknown;\n error?: { message?: unknown; code?: unknown };\n } | null;\n if (!response.ok || typeof body?.access_token !== \"string\" || !body.access_token) {\n const code = body?.error?.code;\n const status = response.ok ? 400 : response.status;\n // Meta reports a dead token as code 190 (often with HTTP 400).\n throw new SocialError(\n \"Threads token refresh failed\",\n code === 190 ? \"AUTH_ERROR\" : \"REFRESH_FAILED\",\n \"threads\",\n code === 190 ? 401 : status,\n );\n }\n return {\n accessToken: body.access_token,\n tokenType: typeof body.token_type === \"string\" ? body.token_type : undefined,\n expiresAt:\n typeof body.expires_in === \"number\"\n ? new Date(Date.now() + body.expires_in * 1000)\n : undefined,\n };\n}\n","/**\n * Fallback publish prices, used only when the social adapter's publish result\n * carries no cost of its own.\n *\n * TEMPORARY: X's published API prices. Remove once happyvertical.com#518 lands\n * (the social SDK reports the real cost per publish); the host can override\n * these per platform with `GarrulaConfig.outboundRates`.\n */\nexport interface PlatformRates {\n /** A plain post, in USD. */\n post: number;\n /** A post that contains a URL, in USD. */\n postWithUrl: number;\n /** A reply to a mention, in USD (inbound is out of scope; kept for the table). */\n reply: number;\n}\n\nexport const FALLBACK_X_RATES: Readonly<PlatformRates> = Object.freeze({\n post: 0.015,\n postWithUrl: 0.2,\n reply: 0.01,\n});\n\nexport const DEFAULT_OUTBOUND_RATES: Readonly<Record<string, PlatformRates>> = Object.freeze({\n x: FALLBACK_X_RATES,\n});\n\nexport const MICROS_PER_USD = 1_000_000;\n\nexport function usdToMicros(usd: number): number {\n return Math.round(usd * MICROS_PER_USD);\n}\n\nexport type CostSource = \"adapter\" | \"rate-table\" | \"unpriced\";\n\nexport interface CostEstimate {\n micros: number;\n source: CostSource;\n}\n\n/** Estimate a publish from the rate table; unknown platforms are unpriced (0). */\nexport function estimateCost(\n rates: Readonly<Record<string, PlatformRates>>,\n platform: string,\n hasUrl: boolean,\n): CostEstimate {\n const table = rates[platform];\n if (!table) return { micros: 0, source: \"unpriced\" };\n return { micros: usdToMicros(hasUrl ? table.postWithUrl : table.post), source: \"rate-table\" };\n}\n\n/**\n * Read a cost the adapter reported on its publish result. The social SDK does\n * not report one yet (happyvertical.com#518); this accepts the shapes it is\n * expected to use: `cost` as USD number, or `{ usd }` / `{ amountUsd }`.\n */\nexport function adapterCostMicros(result: unknown): number | null {\n if (!result || typeof result !== \"object\") return null;\n const cost = (result as { cost?: unknown }).cost;\n let usd: unknown = cost;\n if (cost && typeof cost === \"object\") {\n const c = cost as { usd?: unknown; amountUsd?: unknown };\n usd = c.usd ?? c.amountUsd;\n }\n return typeof usd === \"number\" && Number.isFinite(usd) && usd >= 0 ? usdToMicros(usd) : null;\n}\n\n/** `YYYY-MM` in UTC. */\nexport function monthKey(date: Date): string {\n return date.toISOString().slice(0, 7);\n}\n","import { ACCESS_TOKEN_REFRESH_MARGIN_MS, THREADS_REFRESH_WINDOW_MS } from \"./credentials.js\";\nimport { DEFAULT_OUTBOUND_RATES, type PlatformRates } from \"./outbound/rates.js\";\nimport type { GarrulaTargetPlatform } from \"./types.js\";\n\n/**\n * Host-supplied configuration for Garrula. Everything here is a policy or\n * wording choice that belongs to the application using the agent, not to the\n * agent itself; the defaults are neutral and work for any tenant.\n */\nexport interface GarrulaConfig {\n /**\n * Platforms that receive a draft when a link post is created without\n * explicit `targets`.\n */\n storyLinkTargets: GarrulaTargetPlatform[];\n /**\n * Platforms that receive a draft when a video post is created without\n * explicit `targets`.\n */\n articleVideoTargets: GarrulaTargetPlatform[];\n /**\n * Publish mode used when an account records none. `dry_run` never reaches\n * the platform, so an unconfigured account cannot post by accident.\n */\n defaultPublishMode: string;\n /** What a tenant is called in messages shown to the person posting. */\n tenantLabel: string;\n /** Where a person reconnects a social account, as shown in messages. */\n socialSettingsLocation: string;\n /** Refresh an OAuth 2 access token this long before it expires. */\n accessTokenRefreshMarginMs: number;\n /** Refresh a Threads long-lived token once it is this close to lapsing. */\n threadsRefreshWindowMs: number;\n /**\n * Fallback publish prices per platform, in USD, used only when the adapter's\n * publish result reports no cost. Defaults to X's published prices; TEMPORARY\n * until the social SDK reports real costs (happyvertical.com#518).\n */\n outboundRates: Record<string, PlatformRates>;\n /** Monthly spend cap (USD) of a tenant that has not set its own. A cap always applies. */\n outboundDefaultMonthlyCapUsd: number;\n /** Longest post text a draft or edit may have. */\n outboundMaxLength: number;\n}\n\nexport const DEFAULT_GARRULA_CONFIG: Readonly<GarrulaConfig> = Object.freeze<GarrulaConfig>({\n storyLinkTargets: [\"facebook\", \"x\", \"threads\"],\n articleVideoTargets: [\"youtube\", \"x\", \"threads\", \"facebook\"],\n defaultPublishMode: \"dry_run\",\n tenantLabel: \"organization\",\n socialSettingsLocation: \"Settings → Social\",\n accessTokenRefreshMarginMs: ACCESS_TOKEN_REFRESH_MARGIN_MS,\n threadsRefreshWindowMs: THREADS_REFRESH_WINDOW_MS,\n outboundRates: DEFAULT_OUTBOUND_RATES as Record<string, PlatformRates>,\n outboundDefaultMonthlyCapUsd: 5,\n outboundMaxLength: 280,\n});\n\n/** Overlay the host's partial configuration on the neutral defaults. */\nexport function resolveGarrulaConfig(overrides: Partial<GarrulaConfig> = {}): GarrulaConfig {\n const config: GarrulaConfig = { ...DEFAULT_GARRULA_CONFIG };\n for (const key of Object.keys(overrides) as (keyof GarrulaConfig)[]) {\n const value = overrides[key];\n if (value !== undefined) (config as unknown as Record<string, unknown>)[key] = value;\n }\n config.storyLinkTargets = [...config.storyLinkTargets];\n config.articleVideoTargets = [...config.articleVideoTargets];\n config.outboundRates = { ...config.outboundRates };\n return config;\n}\n\n/** Why a post was not sent because its tenant may not publish. */\nexport function tenantBlockedMessage(config: GarrulaConfig): string {\n return `Posting is paused for this ${config.tenantLabel}, so nothing was posted.`;\n}\n\n/** What the caller is told when no tenant can be resolved. */\nexport function tenantRequiredMessage(config: GarrulaConfig): string {\n return `Social publishing requires an ${config.tenantLabel} (tenantId).`;\n}\n","import type {\n ClaimEvidence,\n DraftClaim,\n DraftingAI,\n OutboundPostKind,\n SourceEvent,\n} from \"./types.js\";\n\nexport interface DraftOutput {\n text: string;\n claims: DraftClaim[];\n}\n\nexport class DraftingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DraftingError\";\n }\n}\n\n/** Every reference the drafter may cite for an event, nothing else. */\nexport function allowedEvidence(event: SourceEvent): { urls: Set<string>; lines: Set<string> } {\n const urls = new Set<string>([event.url, ...(event.evidenceUrls ?? [])].filter(Boolean));\n const lines = new Set<string>(\n [event.changelogLine, ...(event.changelog ?? [])]\n .filter((line): line is string => typeof line === \"string\")\n .map((line) => line.trim())\n .filter(Boolean),\n );\n return { urls, lines };\n}\n\nexport function buildDraftPrompt(\n persona: string,\n kind: OutboundPostKind,\n event: SourceEvent,\n maxLength: number,\n): string {\n const { urls, lines } = allowedEvidence(event);\n return [\n \"You write one short social media post announcing a software change.\",\n `Write in this voice: ${persona.trim() || \"plain, factual, friendly\"}.`,\n `Post type: ${kind}. At most ${maxLength} characters. Do not include any URL in the text.`,\n \"State only facts supported by the event below. Do not invent features, numbers or dates.\",\n 'Reply with JSON only: {\"text\": string, \"claims\": [{\"text\": string, \"evidence\": string[]}]}.',\n \"Every factual statement in the post must appear in `claims`, and every claim must cite\",\n \"evidence copied exactly from the allowed evidence lists (a URL or a changelog line).\",\n \"\",\n `Event kind: ${event.kind}`,\n `Title: ${event.title}`,\n event.version ? `Version: ${event.version}` : \"\",\n event.repo ? `Repository: ${event.repo}` : \"\",\n event.summary ? `Summary: ${event.summary}` : \"\",\n `Allowed evidence URLs: ${JSON.stringify([...urls])}`,\n `Allowed evidence changelog lines: ${JSON.stringify([...lines])}`,\n ]\n .filter(Boolean)\n .join(\"\\n\");\n}\n\nfunction extractJson(raw: string): unknown {\n const fenced = raw.match(/```(?:json)?\\s*([\\s\\S]*?)```/i);\n const body = (fenced?.[1] ?? raw).trim();\n const start = body.indexOf(\"{\");\n const end = body.lastIndexOf(\"}\");\n if (start < 0 || end < start) throw new DraftingError(\"The drafter did not return JSON.\");\n try {\n return JSON.parse(body.slice(start, end + 1));\n } catch {\n throw new DraftingError(\"The drafter returned malformed JSON.\");\n }\n}\n\n/**\n * Parse a model reply into a draft. Evidence that is not one of the event's\n * own URLs or changelog lines is dropped, so a made-up citation leaves the\n * claim uncited (and the draft unpublishable) rather than looking supported.\n */\nexport function parseDraft(raw: string, event: SourceEvent): DraftOutput {\n const data = extractJson(raw) as { text?: unknown; claims?: unknown };\n const text = typeof data.text === \"string\" ? data.text.trim() : \"\";\n if (!text) throw new DraftingError(\"The drafter returned no post text.\");\n const { urls, lines } = allowedEvidence(event);\n\n const claims: DraftClaim[] = [];\n for (const entry of Array.isArray(data.claims) ? data.claims : []) {\n if (!entry || typeof entry !== \"object\") continue;\n const claimText = (entry as { text?: unknown }).text;\n if (typeof claimText !== \"string\" || !claimText.trim()) continue;\n const evidence: ClaimEvidence[] = [];\n const refs = (entry as { evidence?: unknown }).evidence;\n for (const ref of Array.isArray(refs) ? refs : []) {\n if (typeof ref !== \"string\") continue;\n const value = ref.trim();\n if (urls.has(value)) evidence.push({ type: \"url\", ref: value });\n else if (lines.has(value)) evidence.push({ type: \"changelog\", ref: value });\n }\n claims.push({ text: claimText.trim(), evidence });\n }\n return { text, claims };\n}\n\nexport async function draftPost(\n ai: DraftingAI,\n persona: string,\n kind: OutboundPostKind,\n event: SourceEvent,\n maxLength: number,\n): Promise<DraftOutput> {\n let raw: string;\n try {\n raw = await ai.message(buildDraftPrompt(persona, kind, event, maxLength));\n } catch (error) {\n throw new DraftingError(\n `Drafting failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const draft = parseDraft(raw, event);\n if (draft.text.length > maxLength) {\n throw new DraftingError(`The draft is longer than ${maxLength} characters.`);\n }\n return draft;\n}\n\n/** A post is publishable only with at least one claim, every claim with evidence. */\nexport function isFullyCited(claims: DraftClaim[] | null | undefined): boolean {\n if (!claims || claims.length === 0) return false;\n return claims.every(\n (claim) =>\n claim.text?.trim() &&\n Array.isArray(claim.evidence) &&\n claim.evidence.length > 0 &&\n claim.evidence.every((item) => typeof item.ref === \"string\" && item.ref.trim().length > 0),\n );\n}\n","import type { SmrtObjectOptions } from \"@happyvertical/smrt-core\";\nimport { SmrtCollection, SmrtObject, smrt } from \"@happyvertical/smrt-core\";\nimport { TenantScoped, tenantId } from \"@happyvertical/smrt-tenancy\";\nimport type {\n AutonomyMode,\n DraftClaim,\n LinkPolicy,\n OutboundPostKind,\n OutboundState,\n SourceEventKind,\n SourceRule,\n} from \"./types.js\";\n\n// Garrula-owned records of the outbound pipeline. Each is tenant scoped\n// (required mode) and has no REST/MCP surface: they are reached only through\n// the Garrula service methods, which re-check the tenant on every read.\n\nexport interface GarrulaOutboundSettingsOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n paused?: boolean;\n monthlyCapMicros?: number;\n persona?: string;\n sources?: SourceRule[];\n autonomy?: Record<OutboundPostKind, AutonomyMode>;\n linkPolicy?: Record<string, LinkPolicy>;\n defaultLinkPolicy?: LinkPolicy;\n accountIds?: string[];\n deferTopics?: string[];\n}\n\n/** One row per tenant: pause switch, cap, persona, source rules, autonomy, links. */\n@TenantScoped({ mode: \"required\" })\n@smrt({ tableStrategy: \"sti\", api: false, mcp: false, cli: false })\nexport class GarrulaOutboundSettings extends SmrtObject { static __smrtPackage__ = \"@happyvertical/garrula\";\n @tenantId({ nullable: false })\n tenantId: string | null = null;\n paused = false;\n monthlyCapMicros = 0;\n persona = \"\";\n sources: SourceRule[] = [];\n autonomy: Record<string, string> = {};\n linkPolicy: Record<string, string> = {};\n defaultLinkPolicy = \"none\";\n accountIds: string[] = [];\n deferTopics: string[] = [];\n\n constructor(options: GarrulaOutboundSettingsOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.paused !== undefined) this.paused = options.paused;\n if (options.monthlyCapMicros !== undefined) this.monthlyCapMicros = options.monthlyCapMicros;\n if (options.persona !== undefined) this.persona = options.persona;\n if (options.sources !== undefined) this.sources = options.sources;\n if (options.autonomy !== undefined) this.autonomy = options.autonomy;\n if (options.linkPolicy !== undefined) this.linkPolicy = options.linkPolicy;\n if (options.defaultLinkPolicy !== undefined) this.defaultLinkPolicy = options.defaultLinkPolicy;\n if (options.accountIds !== undefined) this.accountIds = options.accountIds;\n if (options.deferTopics !== undefined) this.deferTopics = options.deferTopics;\n }\n}\n\nexport class GarrulaOutboundSettingsCollection extends SmrtCollection<GarrulaOutboundSettings> {\n static readonly _itemClass = GarrulaOutboundSettings;\n}\n\nexport interface GarrulaOutboundPostOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n socialPostId?: string | null;\n state?: OutboundState;\n kind?: OutboundPostKind;\n sourceEventId?: string;\n sourceKind?: SourceEventKind;\n sourceUrl?: string | null;\n claims?: DraftClaim[];\n createdBy?: string | null;\n approvedBy?: string | null;\n rejectedReason?: string | null;\n}\n\n/**\n * The outbound lifecycle of one `smrt-social` SocialPost: state, kind, source\n * and cited claims. The text, account, schedule and publish result stay on the\n * SocialPost itself; `state` here is authoritative and mirrored onto it.\n * (smrt-social has no `rejected` status or claims field yet; see\n * docs/upstream-followups.md.)\n */\n@TenantScoped({ mode: \"required\" })\n@smrt({ tableStrategy: \"sti\", api: false, mcp: false, cli: false })\nexport class GarrulaOutboundPost extends SmrtObject { static __smrtPackage__ = \"@happyvertical/garrula\";\n @tenantId({ nullable: false })\n tenantId: string | null = null;\n socialPostId: string | null = null;\n state = \"draft\";\n kind = \"release\";\n sourceEventId = \"\";\n sourceKind = \"package-publish\";\n sourceUrl: string | null = null;\n claims: DraftClaim[] = [];\n /** Who supplied a manual draft (`createDraft`); null for ingested drafts. */\n createdBy: string | null = null;\n approvedBy: string | null = null;\n rejectedReason: string | null = null;\n\n constructor(options: GarrulaOutboundPostOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.socialPostId !== undefined) this.socialPostId = options.socialPostId;\n if (options.state !== undefined) this.state = options.state;\n if (options.kind !== undefined) this.kind = options.kind;\n if (options.sourceEventId !== undefined) this.sourceEventId = options.sourceEventId;\n if (options.sourceKind !== undefined) this.sourceKind = options.sourceKind;\n if (options.sourceUrl !== undefined) this.sourceUrl = options.sourceUrl;\n if (options.claims !== undefined) this.claims = options.claims;\n if (options.createdBy !== undefined) this.createdBy = options.createdBy;\n if (options.approvedBy !== undefined) this.approvedBy = options.approvedBy;\n if (options.rejectedReason !== undefined) this.rejectedReason = options.rejectedReason;\n }\n}\n\nexport class GarrulaOutboundPostCollection extends SmrtCollection<GarrulaOutboundPost> {\n static readonly _itemClass = GarrulaOutboundPost;\n}\n\nexport interface GarrulaSpendEntryOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n month?: string;\n socialPostId?: string | null;\n costMicros?: number;\n source?: string;\n status?: string;\n}\n\n/** Spend ledger: one entry per publish attempt, per tenant per month. */\n@TenantScoped({ mode: \"required\" })\n@smrt({ tableStrategy: \"sti\", api: false, mcp: false, cli: false })\nexport class GarrulaSpendEntry extends SmrtObject { static __smrtPackage__ = \"@happyvertical/garrula\";\n @tenantId({ nullable: false })\n tenantId: string | null = null;\n month = \"\";\n socialPostId: string | null = null;\n costMicros = 0;\n /** `adapter` | `rate-table` | `unpriced` */\n source = \"rate-table\";\n /** `reserved` | `recorded` | `released` */\n status = \"reserved\";\n\n constructor(options: GarrulaSpendEntryOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.month !== undefined) this.month = options.month;\n if (options.socialPostId !== undefined) this.socialPostId = options.socialPostId;\n if (options.costMicros !== undefined) this.costMicros = options.costMicros;\n if (options.source !== undefined) this.source = options.source;\n if (options.status !== undefined) this.status = options.status;\n }\n}\n\nexport class GarrulaSpendEntryCollection extends SmrtCollection<GarrulaSpendEntry> {\n static readonly _itemClass = GarrulaSpendEntry;\n}\n\nexport interface GarrulaSourceEventOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n eventKey?: string;\n outcome?: string;\n outboundPostIds?: string[];\n}\n\n/** Dedupe ledger: an event id seen once never yields a second candidate. */\n@TenantScoped({ mode: \"required\" })\n@smrt({ tableStrategy: \"sti\", api: false, mcp: false, cli: false })\nexport class GarrulaSourceEvent extends SmrtObject { static __smrtPackage__ = \"@happyvertical/garrula\";\n @tenantId({ nullable: false })\n tenantId: string | null = null;\n /** `<kind>:<id>` */\n eventKey = \"\";\n /** `drafted` | `ignored` */\n outcome = \"ignored\";\n outboundPostIds: string[] = [];\n\n constructor(options: GarrulaSourceEventOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.eventKey !== undefined) this.eventKey = options.eventKey;\n if (options.outcome !== undefined) this.outcome = options.outcome;\n if (options.outboundPostIds !== undefined) this.outboundPostIds = options.outboundPostIds;\n }\n}\n\nexport class GarrulaSourceEventCollection extends SmrtCollection<GarrulaSourceEvent> {\n static readonly _itemClass = GarrulaSourceEvent;\n}\n","import type {\n AutonomyMode,\n OutboundPostKind,\n OutboundSettings,\n SourceEvent,\n SourceRule,\n} from \"./types.js\";\n\n/**\n * Default source rules: package publishes always post, merged pull requests\n * only when they are a `feat`/`perf` change, docs changes are off. Chores,\n * dependency bumps and internal work never produce a candidate.\n */\nexport const DEFAULT_SOURCE_RULES: readonly SourceRule[] = Object.freeze([\n { kind: \"package-publish\", postKind: \"release\", excludeLabels: [\"internal\", \"skip-social\"] },\n {\n kind: \"merged-pr\",\n postKind: \"feature\",\n includeTitle: [\"^(feat|perf)(\\\\(|:|!)\"],\n excludeTitle: [\"\\\\b(deps?|dependenc(y|ies)|internal)\\\\b\"],\n excludeLabels: [\"internal\", \"dependencies\", \"skip-social\"],\n },\n {\n kind: \"docs-change\",\n postKind: \"docs\",\n enabled: false,\n excludeLabels: [\"internal\", \"skip-social\"],\n },\n]);\n\nexport const DEFAULT_AUTONOMY: Readonly<Record<OutboundPostKind, AutonomyMode>> = Object.freeze({\n release: \"require-approval\",\n feature: \"require-approval\",\n docs: \"require-approval\",\n});\n\nexport type RuleDecision =\n | { match: true; rule: SourceRule }\n | { match: false; reason: \"no-rule\" | \"rule-disabled\" | \"filtered\" };\n\nfunction anyMatches(patterns: string[] | undefined, value: string): boolean {\n return (patterns ?? []).some((pattern) => {\n try {\n return new RegExp(pattern, \"i\").test(value);\n } catch {\n return false;\n }\n });\n}\n\nfunction lower(values: string[] | undefined): string[] {\n return (values ?? []).map((value) => value.toLowerCase());\n}\n\n/** Decide whether an event produces a candidate under the tenant's rules. */\nexport function evaluateSourceEvent(\n settings: Pick<OutboundSettings, \"sources\">,\n event: SourceEvent,\n): RuleDecision {\n const rules = settings.sources.filter((candidate) => candidate.kind === event.kind);\n if (rules.length === 0) return { match: false, reason: \"no-rule\" };\n const enabled = rules.filter((candidate) => candidate.enabled !== false);\n if (enabled.length === 0) return { match: false, reason: \"rule-disabled\" };\n\n const labels = lower(event.labels);\n for (const rule of enabled) {\n if (rule.includeTitle?.length && !anyMatches(rule.includeTitle, event.title)) continue;\n if (anyMatches(rule.excludeTitle, event.title)) continue;\n const include = lower(rule.includeLabels);\n if (include.length > 0 && !include.some((label) => labels.includes(label))) continue;\n if (lower(rule.excludeLabels).some((label) => labels.includes(label))) continue;\n return { match: true, rule };\n }\n return { match: false, reason: \"filtered\" };\n}\n\nexport function eventKey(event: Pick<SourceEvent, \"kind\" | \"id\">): string {\n return `${event.kind}:${event.id}`;\n}\n\n/** True when the event mentions a topic the tenant leaves to a person. */\nexport function isDeferred(\n topics: readonly string[],\n event: Pick<SourceEvent, \"title\" | \"summary\" | \"labels\">,\n): boolean {\n const haystack = [event.title, event.summary ?? \"\", ...(event.labels ?? [])]\n .join(\"\\n\")\n .toLowerCase();\n return topics.some((topic) => topic.trim() !== \"\" && haystack.includes(topic.toLowerCase()));\n}\n","import type { OutboundState } from \"./types.js\";\n\n/** Legal outbound transitions. Anything else is refused. */\nexport const OUTBOUND_TRANSITIONS: Readonly<Record<OutboundState, readonly OutboundState[]>> = {\n draft: [\"approved\", \"rejected\"],\n // `draft` = approval withdrawn (an edit invalidates it).\n approved: [\"scheduled\", \"published\", \"failed\", \"rejected\", \"draft\"],\n scheduled: [\"approved\", \"published\", \"failed\", \"rejected\", \"draft\"],\n failed: [\"approved\", \"rejected\", \"draft\"],\n published: [],\n rejected: [],\n};\n\nexport function canTransition(from: OutboundState, to: OutboundState): boolean {\n return OUTBOUND_TRANSITIONS[from].includes(to);\n}\n\n/** The `smrt-social` post status that mirrors an outbound state. */\nexport function socialStatusFor(state: OutboundState): string {\n switch (state) {\n case \"draft\":\n return \"draft\";\n case \"approved\":\n return \"approved\";\n case \"scheduled\":\n return \"scheduled\";\n case \"published\":\n return \"published\";\n case \"failed\":\n return \"failed\";\n case \"rejected\":\n // smrt-social has no `rejected`; `cancelled` is never published.\n return \"cancelled\";\n }\n}\n","/**\n * Post kinds with their own autonomy setting. This module lives under `src/ui`\n * because the admin panels import it as a runtime value and `svelte-package`\n * emits only `src/ui` into `dist/ui`; `src/outbound/types.ts` re-exports it so\n * there is one source of truth.\n */\nexport type OutboundPostKind = \"release\" | \"feature\" | \"docs\";\n\nexport const OUTBOUND_POST_KINDS: readonly OutboundPostKind[] = [\"release\", \"feature\", \"docs\"];\n","/**\n * Outbound pipeline types: release/changelog source events become cited\n * drafts, which are approved, published under a spend cap, and recorded.\n * Outbound only: nothing here reads mentions, replies, or any inbound feed.\n */\n\n/** What kind of upstream event a host hands in. */\nexport type SourceEventKind = \"package-publish\" | \"merged-pr\" | \"docs-change\";\n\n/** Where an outbound post came from: an ingested event, or text supplied through `createDraft`. */\nexport type OutboundSourceKind = SourceEventKind | \"manual\";\n\nimport { OUTBOUND_POST_KINDS, type OutboundPostKind } from \"../ui/post-kinds.js\";\n\n/** Post types with their own autonomy setting (defined in `ui/post-kinds.ts`, which the admin panels load at runtime). */\nexport { OUTBOUND_POST_KINDS, type OutboundPostKind };\n\n/**\n * Plain data describing one upstream event. The host (a webhook, a job, a CLI)\n * builds it; Garrula never polls GitHub or any registry.\n */\nexport interface SourceEvent {\n kind: SourceEventKind;\n /** Stable id of the event (a PR URL, `pkg@version`, a commit sha). Dedupe key. */\n id: string;\n title: string;\n /** Canonical URL of the event (the PR, the release, the docs page). */\n url: string;\n summary?: string;\n /** The changelog line that describes this event, when there is one. */\n changelogLine?: string;\n /** Further changelog lines that may be cited. */\n changelog?: string[];\n /** Further URLs (pull requests) that may be cited as evidence. */\n evidenceUrls?: string[];\n labels?: string[];\n version?: string;\n repo?: string;\n}\n\n/** One per-tenant rule saying which events of a kind become candidates. */\nexport interface SourceRule {\n kind: SourceEventKind;\n postKind: OutboundPostKind;\n enabled?: boolean;\n /** Regular expressions (case-insensitive); when set, the title must match one. */\n includeTitle?: string[];\n /** Regular expressions; a title matching one is ignored. */\n excludeTitle?: string[];\n /** When set, the event needs one of these labels. */\n includeLabels?: string[];\n /** An event with one of these labels is ignored. */\n excludeLabels?: string[];\n}\n\nexport type AutonomyMode = \"require-approval\" | \"auto\";\n\n/** Whether the URL of the source is part of the published text. */\nexport type LinkPolicy = \"none\" | \"include\";\n\n/** Evidence behind one claim: a pull request / release URL or a changelog line. */\nexport interface ClaimEvidence {\n type: \"url\" | \"changelog\";\n ref: string;\n}\n\nexport interface DraftClaim {\n text: string;\n evidence: ClaimEvidence[];\n}\n\nexport type OutboundState =\n | \"draft\"\n | \"approved\"\n | \"scheduled\"\n | \"published\"\n | \"failed\"\n | \"rejected\";\n\nexport const OUTBOUND_STATES: readonly OutboundState[] = [\n \"draft\",\n \"approved\",\n \"scheduled\",\n \"published\",\n \"failed\",\n \"rejected\",\n];\n\n/** Per-tenant outbound settings (the stored row, with defaults applied). */\nexport interface OutboundSettings {\n tenantId: string;\n paused: boolean;\n /** Monthly spend cap in micro-dollars (1 USD = 1_000_000). Always set. */\n monthlyCapMicros: number;\n /** The tenant's voice; the drafter writes in it. */\n persona: string;\n sources: SourceRule[];\n autonomy: Record<OutboundPostKind, AutonomyMode>;\n /** Link policy per social account id; accounts not listed use `defaultLinkPolicy`. */\n linkPolicy: Record<string, LinkPolicy>;\n defaultLinkPolicy: LinkPolicy;\n /** Accounts that receive drafts; empty means every ready account of the tenant. */\n accountIds: string[];\n /**\n * Topics the agent leaves to a person: an event whose title, summary or labels\n * mention one (case-insensitive) is never auto-approved, whatever the\n * autonomy setting says.\n */\n deferTopics: string[];\n}\n\nexport type OutboundSettingsPatch = Partial<\n Omit<OutboundSettings, \"tenantId\" | \"autonomy\" | \"linkPolicy\">\n> & {\n autonomy?: Partial<Record<OutboundPostKind, AutonomyMode>>;\n linkPolicy?: Record<string, LinkPolicy>;\n};\n\n/** What the host and the UI see of one outbound post. */\nexport interface OutboundDraft {\n id: string;\n tenantId: string;\n socialPostId: string;\n accountId: string | null;\n state: OutboundState;\n kind: OutboundPostKind;\n text: string;\n hashtags: string[];\n claims: DraftClaim[];\n /** The URL that may be published, depending on the account's link policy. */\n linkUrl: string | null;\n sourceEventId: string;\n sourceKind: OutboundSourceKind;\n /** Who supplied the draft through `createDraft`; null for ingested drafts. */\n createdBy?: string | null;\n scheduledAt: Date | null;\n publishedUrl: string | null;\n error: string | null;\n rejectedReason: string | null;\n approvedBy: string | null;\n /** False when a claim lacks evidence, so the post cannot be published. */\n publishable: boolean;\n createdAt: Date | null;\n}\n\n/** Text and evidence supplied by a caller (a person or an agent) instead of an ingested event. */\nexport interface CreateDraftInput {\n /** The post text. Must fit `outboundMaxLength`. */\n text: string;\n /**\n * The factual claims in the text, each with evidence (a URL or a changelog\n * line). A post can only be approved and published when every claim has\n * evidence; a draft without it is created but `publishable` is false.\n */\n claims: DraftClaim[];\n /** Caller-chosen key, unique per tenant: the same key never creates a second draft. */\n idempotencyKey: string;\n /** Audit label for who supplied the draft (the host's verified identity). */\n createdBy: string;\n kind?: OutboundPostKind;\n /** URL to publish with the post; only used when the account's link policy is `include`. */\n linkUrl?: string | null;\n}\n\nexport type CreateDraftResult =\n | { outcome: \"drafted\"; drafts: OutboundDraft[] }\n | { outcome: \"duplicate\"; drafts: OutboundDraft[] }\n | { outcome: \"no-accounts\" };\n\nexport type IngestResult =\n | { outcome: \"drafted\"; drafts: OutboundDraft[] }\n | { outcome: \"ignored\"; reason: \"no-rule\" | \"rule-disabled\" | \"filtered\" | \"no-accounts\" }\n | { outcome: \"duplicate\" }\n | { outcome: \"draft-failed\"; error: string };\n\n/** Typed reasons the pipeline refuses to publish or change a post. */\nexport type OutboundRefusalCode =\n | \"paused\"\n | \"cap-reached\"\n | \"uncited\"\n | \"not-approved\"\n | \"illegal-transition\"\n | \"not-found\"\n | \"in-flight\"\n | \"invalid\";\n\nexport interface OutboundRefusal {\n code: OutboundRefusalCode;\n message: string;\n}\n\n/** Thrown by the public API for refused changes (never for a publish). */\nexport class OutboundError extends Error {\n readonly code: OutboundRefusalCode;\n constructor(code: OutboundRefusalCode, message: string) {\n super(message);\n this.name = \"OutboundError\";\n this.code = code;\n }\n}\n\nexport interface SpendEntryView {\n id: string;\n month: string;\n postId: string | null;\n costMicros: number;\n source: \"adapter\" | \"rate-table\" | \"unpriced\";\n status: \"reserved\" | \"recorded\" | \"released\";\n createdAt: Date | null;\n}\n\nexport interface SpendSummary {\n tenantId: string;\n /** `YYYY-MM` (UTC). */\n month: string;\n capMicros: number;\n /** Recorded plus currently reserved spend. */\n spentMicros: number;\n remainingMicros: number;\n paused: boolean;\n entries: SpendEntryView[];\n}\n\nexport interface PublishDueResult {\n postId: string;\n outboundId: string | null;\n success: boolean;\n skipped?: string;\n refusal?: OutboundRefusal;\n error?: string;\n}\n\n/** The model call the drafter needs; `Agent.ai` satisfies it. */\nexport interface DraftingAI {\n message(text: string, options?: Record<string, unknown>): Promise<string>;\n}\n","import { getTenantId, withTenant } from \"@happyvertical/smrt-tenancy\";\nimport type { GarrulaConfig } from \"../config.js\";\nimport type { GarrulaCollections, GarrulaSocialAccount, GarrulaSocialPost } from \"../types.js\";\nimport { DraftingError, draftPost, isFullyCited } from \"./drafting.js\";\nimport {\n type GarrulaOutboundPost,\n GarrulaOutboundPostCollection,\n type GarrulaOutboundSettings,\n GarrulaOutboundSettingsCollection,\n GarrulaSourceEventCollection,\n type GarrulaSpendEntry,\n GarrulaSpendEntryCollection,\n} from \"./models.js\";\nimport {\n adapterCostMicros,\n type CostSource,\n estimateCost,\n monthKey,\n usdToMicros,\n} from \"./rates.js\";\nimport {\n DEFAULT_AUTONOMY,\n DEFAULT_SOURCE_RULES,\n evaluateSourceEvent,\n eventKey,\n isDeferred,\n} from \"./sources.js\";\nimport { canTransition, socialStatusFor } from \"./state.js\";\nimport {\n type CreateDraftInput,\n type CreateDraftResult,\n type DraftClaim,\n type DraftingAI,\n type IngestResult,\n type LinkPolicy,\n OUTBOUND_POST_KINDS,\n OUTBOUND_STATES,\n type OutboundDraft,\n OutboundError,\n type OutboundPostKind,\n type OutboundRefusal,\n type OutboundSourceKind,\n type OutboundSettings,\n type OutboundSettingsPatch,\n type OutboundState,\n type SourceEvent,\n type SourceEventKind,\n type SpendSummary,\n} from \"./types.js\";\n\nexport interface OutboundStores {\n settings: GarrulaOutboundSettingsCollection;\n posts: GarrulaOutboundPostCollection;\n spend: GarrulaSpendEntryCollection;\n events: GarrulaSourceEventCollection;\n}\n\nexport async function createOutboundStores(options: {\n db?: unknown;\n ai?: unknown;\n}): Promise<OutboundStores> {\n const opts = options as ConstructorParameters<typeof GarrulaSpendEntryCollection>[0];\n return {\n settings: await GarrulaOutboundSettingsCollection.create(opts),\n posts: await GarrulaOutboundPostCollection.create(opts),\n spend: await GarrulaSpendEntryCollection.create(opts),\n events: await GarrulaSourceEventCollection.create(opts),\n };\n}\n\ntype SocialAccess = Pick<GarrulaCollections, \"socialAccounts\" | \"socialPosts\">;\n\nexport interface OutboundServiceOptions {\n stores: OutboundStores;\n social: SocialAccess;\n config: () => GarrulaConfig;\n /** The model client used to draft; resolved lazily so tests inject a fake. */\n ai: () => DraftingAI;\n now?: () => Date;\n}\n\n/** A reservation held between the gate and the publish outcome. */\nexport interface SpendReservation {\n tenantId: string;\n entryId: string;\n month: string;\n estimateMicros: number;\n estimateSource: CostSource;\n outboundId: string | null;\n}\n\nexport type GateDecision =\n | { ok: true; reservation: SpendReservation; linkUrl: string | null }\n | { ok: false; refusal: OutboundRefusal };\n\nexport interface SentOutcome {\n /** The adapter's publish result when the platform was reached. */\n result: { status?: string; cost?: unknown } | null;\n success: boolean;\n error?: string;\n}\n\n// In-process mutual exclusion per tenant, shared by every service instance in\n// the process. Reserve/record and ingest dedupe run inside it, so concurrent\n// publishes cannot both pass a cap check or both draft one event. It does NOT\n// span processes: with several worker processes a host must also serialise\n// publishing per tenant (see docs/outbound.md).\nconst locks = new Map<string, Promise<unknown>>();\n\nfunction withLock<T>(tenantId: string, fn: () => Promise<T>): Promise<T> {\n const previous = locks.get(tenantId) ?? Promise.resolve();\n const run = previous.then(fn, fn);\n const tail = run.catch(() => undefined);\n locks.set(tenantId, tail);\n void tail.then(() => {\n if (locks.get(tenantId) === tail) locks.delete(tenantId);\n });\n return run;\n}\n\ntype SaveablePost = GarrulaSocialPost;\n\n/**\n * Public entry points act for one tenant. When a tenant context is active it\n * must be that tenant: another tenant's records are reported as not found,\n * never touched.\n */\nfunction assertAmbientTenant(tenantId: string): void {\n const ambient = getTenantId()?.trim();\n if (ambient && ambient !== tenantId) {\n throw new OutboundError(\"not-found\", \"No such record for the current tenant.\");\n }\n}\n\n/** Title prefix on social posts created by outbound drafting. */\nexport const OUTBOUND_POST_MARKER = \"garrula-outbound:\";\n\n/** True for a social post that outbound drafting created. */\nexport function isOutboundMarked(post: GarrulaSocialPost): boolean {\n return typeof post.title === \"string\" && post.title.startsWith(OUTBOUND_POST_MARKER);\n}\n\nexport class OutboundService {\n private readonly stores: OutboundStores;\n private readonly social: SocialAccess;\n private readonly configFn: () => GarrulaConfig;\n private readonly aiFn: () => DraftingAI;\n private readonly nowFn: () => Date;\n\n constructor(options: OutboundServiceOptions) {\n this.stores = options.stores;\n this.social = options.social;\n this.configFn = options.config;\n this.aiFn = options.ai;\n this.nowFn = options.now ?? (() => new Date());\n }\n\n // ---- settings ---------------------------------------------------------\n\n /** The default cap; a non-finite or negative configured value falls back to the shipped default. */\n private defaultCapMicros(): number {\n const configured = this.configFn().outboundDefaultMonthlyCapUsd;\n const usd =\n typeof configured === \"number\" && Number.isFinite(configured) && configured >= 0\n ? configured\n : 5;\n return usdToMicros(usd);\n }\n\n private defaults(tenantId: string): OutboundSettings {\n return {\n tenantId,\n paused: false,\n monthlyCapMicros: this.defaultCapMicros(),\n persona: \"\",\n sources: DEFAULT_SOURCE_RULES.map((rule) => ({ ...rule })),\n autonomy: { ...DEFAULT_AUTONOMY },\n linkPolicy: {},\n defaultLinkPolicy: \"none\",\n accountIds: [],\n deferTopics: [],\n };\n }\n\n private async findSettingsRow(tenantId: string): Promise<GarrulaOutboundSettings | null> {\n const rows = await this.stores.settings.list({ where: { tenantId } });\n return rows.find((row) => row.tenantId === tenantId) ?? null;\n }\n\n private toSettings(tenantId: string, row: GarrulaOutboundSettings | null): OutboundSettings {\n const base = this.defaults(tenantId);\n if (!row) return base;\n const rule = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\";\n return {\n tenantId,\n paused: row.paused === true,\n monthlyCapMicros:\n Number.isFinite(row.monthlyCapMicros) && row.monthlyCapMicros >= 0\n ? row.monthlyCapMicros\n : base.monthlyCapMicros,\n persona: row.persona ?? \"\",\n sources: Array.isArray(row.sources) ? row.sources : base.sources,\n autonomy: {\n ...base.autonomy,\n ...(rule(row.autonomy) ? (row.autonomy as OutboundSettings[\"autonomy\"]) : {}),\n },\n linkPolicy: rule(row.linkPolicy) ? (row.linkPolicy as Record<string, LinkPolicy>) : {},\n defaultLinkPolicy: row.defaultLinkPolicy === \"include\" ? \"include\" : \"none\",\n accountIds: Array.isArray(row.accountIds) ? row.accountIds : [],\n deferTopics: Array.isArray(row.deferTopics) ? row.deferTopics.map(String) : [],\n };\n }\n\n /** Read fresh settings (never cached), defaults when the tenant has none. */\n getSettings(tenantId: string): Promise<OutboundSettings> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () =>\n this.toSettings(tenantId, await this.findSettingsRow(tenantId)),\n );\n }\n\n updateSettings(tenantId: string, patch: OutboundSettingsPatch): Promise<OutboundSettings> {\n assertAmbientTenant(tenantId);\n return withLock(tenantId, () =>\n withTenant({ tenantId }, async () => {\n const next = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n if (patch.paused !== undefined) next.paused = patch.paused === true;\n if (patch.monthlyCapMicros !== undefined) {\n const cap = patch.monthlyCapMicros;\n if (!Number.isFinite(cap) || cap < 0) {\n throw new OutboundError(\"invalid\", \"The monthly cap must be zero or more.\");\n }\n next.monthlyCapMicros = Math.round(cap);\n }\n if (patch.persona !== undefined) next.persona = String(patch.persona);\n if (patch.sources !== undefined) next.sources = patch.sources;\n if (patch.autonomy) {\n for (const [kind, mode] of Object.entries(patch.autonomy)) {\n if (!OUTBOUND_POST_KINDS.includes(kind as OutboundPostKind)) {\n throw new OutboundError(\"invalid\", `Unknown post type: ${kind}`);\n }\n if (mode !== \"auto\" && mode !== \"require-approval\") {\n throw new OutboundError(\"invalid\", `Unknown autonomy mode: ${String(mode)}`);\n }\n next.autonomy[kind as OutboundPostKind] = mode;\n }\n }\n if (patch.linkPolicy) next.linkPolicy = { ...next.linkPolicy, ...patch.linkPolicy };\n if (patch.defaultLinkPolicy !== undefined) next.defaultLinkPolicy = patch.defaultLinkPolicy;\n if (patch.accountIds !== undefined) next.accountIds = [...patch.accountIds];\n if (patch.deferTopics !== undefined) {\n next.deferTopics = [\n ...new Set(patch.deferTopics.map((topic) => String(topic).trim()).filter(Boolean)),\n ];\n }\n for (const policy of [next.defaultLinkPolicy, ...Object.values(next.linkPolicy)]) {\n if (policy !== \"none\" && policy !== \"include\") {\n throw new OutboundError(\"invalid\", `Unknown link policy: ${String(policy)}`);\n }\n }\n\n const row = await this.findSettingsRow(tenantId);\n const data = {\n paused: next.paused,\n monthlyCapMicros: next.monthlyCapMicros,\n persona: next.persona,\n sources: next.sources,\n autonomy: next.autonomy,\n linkPolicy: next.linkPolicy,\n defaultLinkPolicy: next.defaultLinkPolicy,\n accountIds: next.accountIds,\n deferTopics: next.deferTopics,\n };\n if (row) {\n Object.assign(row, data);\n await row.save();\n } else {\n await this.stores.settings.create({ tenantId, ...data });\n }\n return next;\n }),\n );\n }\n\n // ---- ingest -----------------------------------------------------------\n\n ingestSourceEvent(tenantId: string, event: SourceEvent): Promise<IngestResult> {\n assertAmbientTenant(tenantId);\n const kinds: SourceEventKind[] = [\"package-publish\", \"merged-pr\", \"docs-change\"];\n if (\n !event ||\n !kinds.includes(event.kind) ||\n !String(event.id ?? \"\").trim() ||\n !String(event.title ?? \"\").trim() ||\n !String(event.url ?? \"\").trim()\n ) {\n throw new OutboundError(\"invalid\", \"A source event needs a kind, id, title and url.\");\n }\n return withLock(tenantId, () =>\n withTenant({ tenantId }, async (): Promise<IngestResult> => {\n const key = eventKey(event);\n const seen = await this.stores.events.list({ where: { tenantId, eventKey: key } });\n if (seen.some((row) => row.tenantId === tenantId)) return { outcome: \"duplicate\" };\n\n const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n const decision = evaluateSourceEvent(settings, event);\n if (!decision.match) {\n await this.stores.events.create({ tenantId, eventKey: key, outcome: \"ignored\" });\n return { outcome: \"ignored\", reason: decision.reason };\n }\n\n const accounts = await this.targetAccounts(tenantId, settings);\n if (accounts.length === 0) return { outcome: \"ignored\", reason: \"no-accounts\" };\n\n const kind = decision.rule.postKind;\n let draft;\n try {\n draft = await draftPost(\n this.aiFn(),\n settings.persona,\n kind,\n event,\n this.configFn().outboundMaxLength,\n );\n } catch (error) {\n if (error instanceof DraftingError) {\n return { outcome: \"draft-failed\", error: error.message };\n }\n return {\n outcome: \"draft-failed\",\n error: error instanceof Error ? error.message : String(error),\n };\n }\n\n const drafts: OutboundDraft[] = [];\n const ids: string[] = [];\n for (const account of accounts) {\n const post = await this.social.socialPosts.createDraft({\n socialAccountId: account.id as string,\n postType: \"text\",\n title: `${OUTBOUND_POST_MARKER}${event.id}`,\n description: draft.text,\n linkUrl: event.url,\n tenantId,\n });\n let row;\n try {\n row = await this.stores.posts.create({\n tenantId,\n socialPostId: post.id as string,\n state: \"draft\",\n kind,\n sourceEventId: event.id,\n sourceKind: event.kind,\n sourceUrl: event.url,\n claims: draft.claims,\n });\n } catch (error) {\n // Compensate: never leave a social draft with no approval record.\n await this.discardSocialDraft(post);\n throw error;\n }\n ids.push(row.id as string);\n if (\n settings.autonomy[kind] === \"auto\" &&\n isFullyCited(draft.claims) &&\n !isDeferred(settings.deferTopics, event)\n ) {\n await this.transition(tenantId, row, \"approved\", { approvedBy: \"autonomy\" });\n }\n drafts.push(await this.view(tenantId, row, settings));\n }\n await this.stores.events.create({\n tenantId,\n eventKey: key,\n outcome: \"drafted\",\n outboundPostIds: ids,\n });\n return { outcome: \"drafted\", drafts };\n }),\n );\n }\n\n /**\n * Create a pending-approval draft from text and evidence supplied by the\n * host's caller. Tenant scoped and idempotent by `idempotencyKey`: a repeat\n * returns the original drafts. It never approves, schedules or publishes, and\n * ignores the autonomy settings; a person must still approve it.\n */\n createDraft(tenantId: string, input: CreateDraftInput): Promise<CreateDraftResult> {\n assertAmbientTenant(tenantId);\n if (!input || typeof input !== \"object\") {\n throw new OutboundError(\"invalid\", \"A draft needs text, claims, a key and a creator.\");\n }\n const key = String(input.idempotencyKey ?? \"\").trim();\n const createdBy = String(input?.createdBy ?? \"\").trim();\n const text = String(input?.text ?? \"\").trim();\n if (!key || key.length > 200) {\n throw new OutboundError(\n \"invalid\",\n \"A draft needs an idempotency key of at most 200 characters.\",\n );\n }\n if (!createdBy) throw new OutboundError(\"invalid\", \"A draft needs a creator.\");\n if (!text) throw new OutboundError(\"invalid\", \"The post text cannot be empty.\");\n const max = this.configFn().outboundMaxLength;\n if (text.length > max) {\n throw new OutboundError(\"invalid\", `The post text is longer than ${max} characters.`);\n }\n const kind = input.kind ?? \"release\";\n if (!OUTBOUND_POST_KINDS.includes(kind)) {\n throw new OutboundError(\"invalid\", \"Unknown post kind.\");\n }\n if (!Array.isArray(input.claims)) throw new OutboundError(\"invalid\", \"Claims must be a list.\");\n const claims: DraftClaim[] = input.claims.map((claim) => ({\n text: String(claim?.text ?? \"\").trim(),\n evidence: (Array.isArray(claim?.evidence) ? claim.evidence : []).map((item) => ({\n type: item?.type === \"changelog\" ? \"changelog\" : \"url\",\n ref: String(item?.ref ?? \"\").trim(),\n })),\n }));\n const linkUrl = input.linkUrl?.trim() || null;\n if (linkUrl && !/^https?:\\/\\/\\S+$/i.test(linkUrl)) {\n throw new OutboundError(\"invalid\", \"linkUrl must be an http(s) URL.\");\n }\n\n return withLock(tenantId, () =>\n withTenant({ tenantId }, async (): Promise<CreateDraftResult> => {\n const ledgerKey = `manual:${key}`;\n const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n const seen = (\n await this.stores.events.list({ where: { tenantId, eventKey: ledgerKey } })\n ).find((row) => row.tenantId === tenantId);\n if (seen) {\n const drafts: OutboundDraft[] = [];\n for (const id of seen.outboundPostIds ?? []) {\n drafts.push(await this.view(tenantId, await this.requireRow(tenantId, id), settings));\n }\n return { outcome: \"duplicate\", drafts };\n }\n\n const accounts = await this.targetAccounts(tenantId, settings);\n if (accounts.length === 0) return { outcome: \"no-accounts\" };\n\n // A retry after a partial failure (no ledger row yet) reuses the drafts\n // already created for this key instead of duplicating them.\n const drafts: OutboundDraft[] = [];\n const ids: string[] = [];\n const covered = new Set<string | null>();\n const earlier = (\n await this.stores.posts.list({\n where: { tenantId, sourceKind: \"manual\", sourceEventId: key },\n })\n ).filter((row) => row.tenantId === tenantId);\n for (const row of earlier) {\n const view = await this.view(tenantId, row, settings);\n covered.add(view.accountId);\n ids.push(row.id as string);\n drafts.push(view);\n }\n for (const account of accounts) {\n if (covered.has(account.id as string)) continue;\n const post = await this.social.socialPosts.createDraft({\n socialAccountId: account.id as string,\n postType: \"text\",\n title: `${OUTBOUND_POST_MARKER}manual:${key}`,\n description: text,\n linkUrl,\n tenantId,\n });\n let row;\n try {\n row = await this.stores.posts.create({\n tenantId,\n socialPostId: post.id as string,\n state: \"draft\",\n kind,\n sourceEventId: key,\n sourceKind: \"manual\",\n sourceUrl: linkUrl,\n claims,\n createdBy,\n });\n } catch (error) {\n await this.discardSocialDraft(post);\n throw error;\n }\n ids.push(row.id as string);\n drafts.push(await this.view(tenantId, row, settings));\n }\n await this.stores.events.create({\n tenantId,\n eventKey: ledgerKey,\n outcome: \"drafted\",\n outboundPostIds: ids,\n });\n return { outcome: \"drafted\", drafts };\n }),\n );\n }\n\n private async targetAccounts(\n tenantId: string,\n settings: OutboundSettings,\n ): Promise<GarrulaSocialAccount[]> {\n const ready = await this.social.socialAccounts.findReady();\n return ready.filter(\n (account) =>\n account.id &&\n account.tenantId === tenantId &&\n (settings.accountIds.length === 0 || settings.accountIds.includes(account.id)),\n );\n }\n\n // ---- drafts -----------------------------------------------------------\n\n private async requireRow(tenantId: string, id: string): Promise<GarrulaOutboundPost> {\n const rows = await this.stores.posts.list({ where: { id, tenantId } });\n const row = rows.find((item) => item.id === id && item.tenantId === tenantId);\n if (!row) throw new OutboundError(\"not-found\", \"No such outbound post for this tenant.\");\n return row;\n }\n\n private async loadPost(tenantId: string, row: GarrulaOutboundPost): Promise<SaveablePost | null> {\n if (!row.socialPostId) return null;\n const post = await this.social.socialPosts.get({ id: row.socialPostId }, { cache: false });\n return post && post.tenantId === tenantId ? post : null;\n }\n\n private async view(\n tenantId: string,\n row: GarrulaOutboundPost,\n settings: OutboundSettings,\n known?: SaveablePost | null,\n ): Promise<OutboundDraft> {\n const post = known === undefined ? await this.loadPost(tenantId, row) : known;\n const accountId = post?.socialAccountId ?? null;\n const policy = (accountId && settings.linkPolicy[accountId]) || settings.defaultLinkPolicy;\n return {\n id: row.id as string,\n tenantId,\n socialPostId: row.socialPostId as string,\n accountId,\n state: row.state as OutboundState,\n kind: row.kind as OutboundPostKind,\n text: post?.description ?? \"\",\n hashtags: post?.hashtags ?? [],\n claims: row.claims ?? [],\n linkUrl: policy === \"include\" ? (post?.linkUrl ?? row.sourceUrl ?? null) : null,\n sourceEventId: row.sourceEventId,\n sourceKind: row.sourceKind as OutboundSourceKind,\n createdBy: row.createdBy ?? null,\n scheduledAt: post?.scheduledAt ? new Date(post.scheduledAt) : null,\n publishedUrl: post?.platformUrl ?? null,\n error: post?.errorMessage ?? null,\n rejectedReason: row.rejectedReason ?? null,\n approvedBy: row.approvedBy ?? null,\n publishable: isFullyCited(row.claims),\n createdAt: row.created_at ?? null,\n };\n }\n\n listDrafts(\n tenantId: string,\n filter: { state?: OutboundState; kind?: OutboundPostKind; limit?: number } = {},\n ): Promise<OutboundDraft[]> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const where: Record<string, unknown> = { tenantId };\n if (filter.state) where.state = filter.state;\n if (filter.kind) where.kind = filter.kind;\n const rows = (\n await this.stores.posts.list({\n where,\n orderBy: \"created_at DESC\",\n limit: filter.limit,\n })\n ).filter((row) => row.tenantId === tenantId);\n const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n return Promise.all(rows.map((row) => this.view(tenantId, row, settings)));\n });\n }\n\n getDraft(tenantId: string, id: string): Promise<OutboundDraft> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.requireRow(tenantId, id);\n const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n return this.view(tenantId, row, settings);\n });\n }\n\n editDraft(\n tenantId: string,\n id: string,\n patch: { text?: string; claims?: DraftClaim[]; linkUrl?: string | null },\n ): Promise<OutboundDraft> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.requireRow(tenantId, id);\n const state = row.state as OutboundState;\n if (state === \"published\" || state === \"rejected\") {\n throw new OutboundError(\"illegal-transition\", `A ${state} post cannot be edited.`);\n }\n const social: Record<string, unknown> = {};\n if (patch.text !== undefined) {\n const text = String(patch.text).trim();\n const max = this.configFn().outboundMaxLength;\n if (!text) throw new OutboundError(\"invalid\", \"The post text cannot be empty.\");\n if (text.length > max) {\n throw new OutboundError(\"invalid\", `The post text is longer than ${max} characters.`);\n }\n social.description = text;\n }\n if (patch.linkUrl !== undefined) social.link_url = patch.linkUrl;\n if (patch.claims !== undefined) {\n if (!Array.isArray(patch.claims))\n throw new OutboundError(\"invalid\", \"Claims must be a list.\");\n row.claims = patch.claims.map((claim) => ({\n text: String(claim.text ?? \"\").trim(),\n evidence: (claim.evidence ?? []).map((item) => ({\n type: item.type === \"changelog\" ? \"changelog\" : \"url\",\n ref: String(item.ref ?? \"\").trim(),\n })),\n }));\n }\n // An edit withdraws any approval: the changed text must be approved again.\n // The social post is written first and conditionally, so an edit that\n // races an in-flight publish changes neither record.\n const back = state !== \"draft\";\n await this.updateSocialPost(tenantId, row, {\n ...social,\n ...(back ? { status: socialStatusFor(\"draft\"), scheduled_at: null } : {}),\n });\n if (back) row.state = \"draft\";\n await row.save();\n return this.getDraft(tenantId, id);\n });\n }\n\n approve(tenantId: string, id: string, approvedBy = \"user\"): Promise<OutboundDraft> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.requireRow(tenantId, id);\n if (!isFullyCited(row.claims)) {\n throw new OutboundError(\"uncited\", \"Every claim needs evidence before a post is approved.\");\n }\n await this.transition(tenantId, row, \"approved\", { approvedBy });\n return this.getDraft(tenantId, id);\n });\n }\n\n reject(tenantId: string, id: string, reason = \"\"): Promise<OutboundDraft> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.requireRow(tenantId, id);\n await this.transition(tenantId, row, \"rejected\", { rejectedReason: reason || null });\n return this.getDraft(tenantId, id);\n });\n }\n\n /** A failed post goes back to approved so the next run publishes it again. */\n retry(tenantId: string, id: string): Promise<OutboundDraft> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.requireRow(tenantId, id);\n if (row.state !== \"failed\") {\n throw new OutboundError(\"illegal-transition\", \"Only a failed post can be retried.\");\n }\n if (!isFullyCited(row.claims)) {\n throw new OutboundError(\"uncited\", \"Every claim needs evidence before a post is retried.\");\n }\n await this.transition(tenantId, row, \"approved\", {});\n return this.getDraft(tenantId, id);\n });\n }\n\n schedule(tenantId: string, id: string, at: Date): Promise<OutboundDraft> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n if (!(at instanceof Date) || Number.isNaN(at.getTime())) {\n throw new OutboundError(\"invalid\", \"A schedule needs a valid date.\");\n }\n const row = await this.requireRow(tenantId, id);\n if (!isFullyCited(row.claims)) {\n throw new OutboundError(\n \"uncited\",\n \"Every claim needs evidence before a post is scheduled.\",\n );\n }\n await this.transition(tenantId, row, \"scheduled\", {}, { scheduled_at: at });\n return this.getDraft(tenantId, id);\n });\n }\n\n /** Approved or scheduled posts of the tenant whose time has come. */\n async dueForPublish(tenantId: string, now: Date): Promise<GarrulaSocialPost[]> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const rows = (\n await this.stores.posts.list({ where: { tenantId }, orderBy: \"created_at ASC\" })\n ).filter(\n (row) =>\n row.tenantId === tenantId && (row.state === \"approved\" || row.state === \"scheduled\"),\n );\n const due: GarrulaSocialPost[] = [];\n for (const row of rows) {\n const post = await this.loadPost(tenantId, row);\n if (!post) continue;\n const at = post.scheduledAt ? new Date(post.scheduledAt) : null;\n if (!at || at.getTime() <= now.getTime()) due.push(post);\n }\n return due;\n });\n }\n\n /** The tenant's post to publish now: it must be approved or scheduled. */\n async postForPublish(tenantId: string, id: string): Promise<GarrulaSocialPost> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.requireRow(tenantId, id);\n if (row.state !== \"approved\" && row.state !== \"scheduled\") {\n throw new OutboundError(\n \"not-approved\",\n \"Only an approved or scheduled post can be published.\",\n );\n }\n const post = await this.loadPost(tenantId, row);\n if (!post) throw new OutboundError(\"not-found\", \"The social post is missing.\");\n return post;\n });\n }\n\n outboundIdForPost(tenantId: string, socialPostId: string): Promise<string | null> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.findRowForPost(tenantId, socialPostId);\n return row?.id ?? null;\n });\n }\n\n private async discardSocialDraft(post: GarrulaSocialPost): Promise<void> {\n try {\n await (post as unknown as { delete(): Promise<unknown> }).delete();\n } catch {\n // The marker keeps the gate refusing it if the delete also failed.\n }\n }\n\n private async findRowForPost(\n tenantId: string,\n socialPostId: string,\n ): Promise<GarrulaOutboundPost | null> {\n const rows = await this.stores.posts.list({ where: { tenantId, socialPostId } });\n return (\n rows.find((row) => row.tenantId === tenantId && row.socialPostId === socialPostId) ?? null\n );\n }\n\n private async transition(\n tenantId: string,\n row: GarrulaOutboundPost,\n to: OutboundState,\n extra: { approvedBy?: string; rejectedReason?: string | null },\n social: Record<string, unknown> = {},\n ): Promise<void> {\n const from = row.state as OutboundState;\n if (!OUTBOUND_STATES.includes(from) || !canTransition(from, to)) {\n throw new OutboundError(\"illegal-transition\", `A ${from} post cannot become ${to}.`);\n }\n // The social post is written first, conditionally on it not being claimed\n // for publishing; when that fails neither record has changed.\n await this.updateSocialPost(tenantId, row, { status: socialStatusFor(to), ...social });\n row.state = to;\n if (extra.approvedBy !== undefined) row.approvedBy = extra.approvedBy;\n if (extra.rejectedReason !== undefined) row.rejectedReason = extra.rejectedReason;\n try {\n await row.save();\n } catch (error) {\n row.state = from;\n await this.updateSocialPost(tenantId, row, { status: socialStatusFor(from) }).catch(\n () => undefined,\n );\n throw error;\n }\n }\n\n /**\n * Mirror onto the SocialPost with a conditional update: it never overwrites\n * a post a publisher has claimed (`publishing`). A refused write throws\n * `in-flight` (claimed) or `not-found` (missing) and changes nothing.\n */\n private async updateSocialPost(\n tenantId: string,\n row: GarrulaOutboundPost,\n data: Record<string, unknown>,\n ): Promise<void> {\n if (!row.socialPostId || Object.keys(data).length === 0) return;\n const { socialPosts } = this.social;\n const result = await socialPosts.db.update(\n socialPosts.tableName,\n { id: row.socialPostId, tenant_id: tenantId, \"status not in\": [\"publishing\"] },\n { ...data, updated_at: new Date() },\n );\n if (result.affected === 1) return;\n const current = await this.loadPost(tenantId, row);\n if (current && current.status === \"publishing\") {\n throw new OutboundError(\n \"in-flight\",\n \"This post is being published right now, so it was not changed.\",\n );\n }\n throw new OutboundError(\"not-found\", \"The social post for this draft is missing.\");\n }\n\n /**\n * Record a publish that failed before the gate (account, credentials, token\n * refresh, media) so no spend reservation exists to settle it: the approved\n * or scheduled post becomes `failed` and can be retried after repair.\n */\n failUnreserved(tenantId: string, socialPostId: string): Promise<void> {\n return withLock(tenantId, () =>\n withTenant({ tenantId }, async () => {\n const row = await this.findRowForPost(tenantId, socialPostId);\n if (row && (row.state === \"approved\" || row.state === \"scheduled\")) {\n row.state = \"failed\";\n await row.save();\n }\n }),\n );\n }\n\n // ---- spend ------------------------------------------------------------\n\n private async monthEntries(tenantId: string, month: string): Promise<GarrulaSpendEntry[]> {\n return (await this.stores.spend.list({ where: { tenantId, month } })).filter(\n (entry) => entry.tenantId === tenantId && entry.month === month,\n );\n }\n\n getSpend(tenantId: string, month?: string): Promise<SpendSummary> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const key = month ?? monthKey(this.nowFn());\n const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n const entries = await this.monthEntries(tenantId, key);\n const spent = entries\n .filter((entry) => entry.status !== \"released\")\n .reduce((sum, entry) => sum + entry.costMicros, 0);\n return {\n tenantId,\n month: key,\n capMicros: settings.monthlyCapMicros,\n spentMicros: spent,\n remainingMicros: Math.max(0, settings.monthlyCapMicros - spent),\n paused: settings.paused,\n entries: entries.map((entry) => ({\n id: entry.id as string,\n month: entry.month,\n postId: entry.socialPostId,\n costMicros: entry.costMicros,\n source: entry.source as CostSource,\n status: entry.status as \"reserved\" | \"recorded\" | \"released\",\n createdAt: entry.created_at ?? null,\n })),\n };\n });\n }\n\n // ---- publish gate -----------------------------------------------------\n\n /**\n * The server-side checks every publish passes immediately before the\n * adapter call: tenant, approval state, evidence, pause, link policy and\n * the monthly cap. On success a spend reservation is held (atomically with\n * the cap check) until {@link finish}.\n */\n beforeSend(post: GarrulaSocialPost, platform: string): Promise<GateDecision> {\n const tenantId = post.tenantId?.trim();\n const refuse = (code: OutboundRefusal[\"code\"], message: string): GateDecision => ({\n ok: false,\n refusal: { code, message },\n });\n if (!tenantId) return Promise.resolve(refuse(\"invalid\", \"The post has no tenant.\"));\n const ambient = getTenantId()?.trim();\n if (ambient && ambient !== tenantId) {\n return Promise.resolve(refuse(\"invalid\", \"The post belongs to another tenant.\"));\n }\n\n return withLock(tenantId, () =>\n withTenant({ tenantId }, async (): Promise<GateDecision> => {\n const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n if (settings.paused) {\n return refuse(\"paused\", \"Posting is paused for this tenant, so nothing was posted.\");\n }\n\n const row = post.id ? await this.findRowForPost(tenantId, post.id) : null;\n let linkUrl: string | null = post.linkUrl ?? null;\n if (row) {\n if (row.state !== \"approved\" && row.state !== \"scheduled\") {\n return refuse(\"not-approved\", `This post is ${row.state}, not approved.`);\n }\n if (!isFullyCited(row.claims)) {\n return refuse(\"uncited\", \"A claim in this post has no evidence, so it was not posted.\");\n }\n const accountId = post.socialAccountId ?? \"\";\n const policy = settings.linkPolicy[accountId] ?? settings.defaultLinkPolicy;\n linkUrl = policy === \"include\" ? (post.linkUrl ?? row.sourceUrl ?? null) : null;\n } else if (isOutboundMarked(post)) {\n // Outbound drafting created this post but its approval record is\n // missing: never skip approval and evidence.\n return refuse(\n \"not-approved\",\n \"This post was drafted by the outbound pipeline but has no approval record, so it was not posted.\",\n );\n }\n\n const config = this.configFn();\n const estimate = estimateCost(config.outboundRates, platform, linkUrl !== null);\n const month = monthKey(this.nowFn());\n const entries = await this.monthEntries(tenantId, month);\n const spent = entries\n .filter((entry) => entry.status !== \"released\")\n .reduce((sum, entry) => sum + entry.costMicros, 0);\n const valid = (n: number) => Number.isFinite(n) && n >= 0;\n if (!valid(estimate.micros) || !valid(settings.monthlyCapMicros) || !valid(spent)) {\n return refuse(\n \"invalid\",\n \"The cost estimate or spend cap is not a valid amount, so nothing was posted.\",\n );\n }\n if (\n spent >= settings.monthlyCapMicros ||\n spent + estimate.micros > settings.monthlyCapMicros\n ) {\n return refuse(\n \"cap-reached\",\n \"The monthly posting spend cap is reached, so nothing was posted.\",\n );\n }\n\n const entry = await this.stores.spend.create({\n tenantId,\n month,\n socialPostId: post.id ?? null,\n costMicros: estimate.micros,\n source: estimate.source,\n status: \"reserved\",\n });\n return {\n ok: true,\n linkUrl,\n reservation: {\n tenantId,\n entryId: entry.id as string,\n month,\n estimateMicros: estimate.micros,\n estimateSource: estimate.source,\n outboundId: row?.id ?? null,\n },\n };\n }),\n );\n }\n\n /**\n * Settle a reservation after the publish. Spend is recorded whenever the\n * platform was reached (adapter cost, else the rate table; a dry run costs\n * nothing) and released otherwise; the outbound state follows the outcome.\n */\n finish(reservation: SpendReservation, outcome: SentOutcome): Promise<void> {\n const { tenantId } = reservation;\n assertAmbientTenant(tenantId);\n return withLock(tenantId, () =>\n withTenant({ tenantId }, async () => {\n const entries = await this.monthEntries(tenantId, reservation.month);\n const entry = entries.find((item) => item.id === reservation.entryId);\n if (entry) {\n const result = outcome.result;\n if (!result) {\n entry.status = \"released\";\n entry.costMicros = 0;\n } else if (result.status === \"dry_run\" || result.status === \"staged\") {\n entry.status = \"recorded\";\n entry.costMicros = 0;\n entry.source = \"unpriced\";\n } else {\n const reported = adapterCostMicros(result);\n entry.status = \"recorded\";\n entry.costMicros = reported ?? reservation.estimateMicros;\n entry.source = reported !== null ? \"adapter\" : reservation.estimateSource;\n }\n await entry.save();\n }\n\n if (reservation.outboundId) {\n const row = await this.requireRow(tenantId, reservation.outboundId).catch(() => null);\n if (row && (row.state === \"approved\" || row.state === \"scheduled\")) {\n row.state = outcome.result || outcome.success ? \"published\" : \"failed\";\n await row.save();\n }\n }\n }),\n );\n }\n}\n","import {\n Agent,\n type AgentAdminRoute,\n type AgentOptions,\n type AgentUISlots,\n} from \"@happyvertical/smrt-agents\";\nimport { smrt } from \"@happyvertical/smrt-core\";\nimport {\n type PostStatus,\n type RawAnalyticsPayload,\n SocialAccountCollection,\n type SocialPlatformType,\n SocialPostAnalyticsSnapshotCollection,\n SocialPostCollection,\n} from \"@happyvertical/smrt-social\";\nimport { getTenantId, withTenant } from \"@happyvertical/smrt-tenancy\";\nimport { getSocial, SocialError } from \"@happyvertical/social\";\nimport {\n DEFAULT_GARRULA_CONFIG,\n type GarrulaConfig,\n resolveGarrulaConfig,\n tenantBlockedMessage,\n tenantRequiredMessage,\n} from \"./config.js\";\nimport {\n GarrulaReconnectError,\n isAuthError,\n isRefreshRejected,\n mergeRefreshedCredentials,\n parseExpiry,\n platformLabel,\n refreshKind,\n refreshThreadsToken,\n} from \"./credentials.js\";\nimport {\n createOutboundStores,\n isOutboundMarked,\n OutboundService,\n type OutboundStores,\n type SpendReservation,\n} from \"./outbound/service.js\";\nimport type {\n CreateDraftInput,\n CreateDraftResult,\n DraftClaim,\n DraftingAI,\n IngestResult,\n OutboundDraft,\n OutboundPostKind,\n OutboundSettings,\n OutboundSettingsPatch,\n OutboundState,\n PublishDueResult,\n SourceEvent,\n SpendSummary,\n} from \"./outbound/types.js\";\nimport type {\n AnalyticsSyncResult,\n ArticleVideoPostRequest,\n GarrulaCollections,\n GarrulaHost,\n GarrulaSocialAccount,\n GarrulaSocialAdapter,\n GarrulaSocialConfig,\n GarrulaSocialPost,\n GarrulaTargetPlatform,\n PublishPostOptions,\n PublishPostResult,\n SocialFactory,\n StoryLinkPostRequest,\n} from \"./types.js\";\n\nexport interface GarrulaOptions extends AgentOptions {\n collections?: GarrulaCollections;\n socialFactory?: SocialFactory;\n /** Overrides the host hooks registered with {@link setGarrulaHost}. */\n host?: GarrulaHost;\n /** Overrides the configuration registered with {@link setGarrulaConfig}. */\n garrula?: Partial<GarrulaConfig>;\n /**\n * Model client for drafting release posts (default: the agent's own `ai`).\n * Tests pass a fake.\n */\n draftingAI?: DraftingAI;\n /** Outbound persistence; created from the agent's database on initialize. */\n outboundStores?: OutboundStores;\n /**\n * TEST ONLY. Skips the outbound gate (pause switch, spend cap, approval,\n * evidence) when no outbound stores are available. Without it, `initialize()`\n * throws if the gate cannot be built, so a host never publishes ungated by\n * accident.\n */\n unsafeDisableOutboundGate?: boolean;\n /** Clock for spend months and due times (tests). */\n now?: () => Date;\n}\n\n/** Per-publish state shared between the publish path and its outbound gate. */\ninterface SendContext {\n reservation?: SpendReservation;\n sent?: { status?: string; cost?: unknown };\n}\n\n/**\n * Host hooks shared by every Garrula instance in this process, including the\n * ones the job runner constructs for scheduled posts. The host application\n * registers them once at startup with {@link setGarrulaHost}.\n */\nlet registeredHost: GarrulaHost = {};\n\nexport function setGarrulaHost(host: GarrulaHost): void {\n registeredHost = host;\n}\n\n/**\n * Configuration shared by every Garrula instance in this process, registered\n * once at startup like the host hooks. Unset keys keep the neutral defaults.\n */\nlet registeredConfig: Partial<GarrulaConfig> = {};\n\nexport function setGarrulaConfig(config: Partial<GarrulaConfig>): void {\n registeredConfig = config;\n}\n\n/** Why a post was not sent because its tenant may not publish (default wording). */\nexport const GARRULA_TENANT_BLOCKED_MESSAGE = tenantBlockedMessage(DEFAULT_GARRULA_CONFIG);\n\n/** Why a post was not sent because another publish already has it. */\nexport const GARRULA_POST_BUSY_MESSAGE =\n \"This post is already being posted or is no longer waiting to be posted.\";\n\n/** Why a post was not sent because its account is switched off. */\nexport const GARRULA_ACCOUNT_INACTIVE_MESSAGE =\n \"This social account is switched off, so nothing was posted.\";\n\n/** Every status a post may be published from. */\nconst PUBLISHABLE_STATUSES: PostStatus[] = [\"draft\", \"approved\", \"scheduled\", \"failed\"];\n\n/** Statuses of posts that {@link Garrula.run} publishes when due. */\nconst DUE_STATUSES: PostStatus[] = [\"approved\", \"scheduled\"];\n\n@smrt({\n agent: {\n icon: \"share-2\",\n tier: \"standard\",\n description: \"Social media publishing, account health, and post analytics\",\n },\n // Garrula sets no REST surface, so since smrt 0.57 it inherits the Agent\n // base's closed api. Both CLI commands run in process (agent runtime and\n // background worker), so they are acknowledged rather than opened over REST.\n cli: { include: [\"run\", \"syncAnalytics\"], skipApiCheck: [\"run\", \"syncAnalytics\"] },\n mcp: { include: [\"createStoryLinkPosts\", \"createArticleVideoPosts\"] },\n})\nexport class Garrula extends Agent { static __smrtPackage__ = \"@happyvertical/garrula\";\n static override uiSlots: AgentUISlots = {\n queue: {\n id: \"queue\",\n label: \"Dashboard\",\n description: \"Review social posts, status, and latest stats\",\n icon: \"list-checks\",\n order: 1,\n },\n settings: {\n id: \"settings\",\n label: \"Settings\",\n description: \"Connect and manage social accounts\",\n icon: \"settings\",\n order: 2,\n },\n };\n\n static override adminRoutes: AgentAdminRoute[] = [\n { path: \"queue\", component: \"QueuePanel\" },\n { path: \"settings\", component: \"SettingsPanel\" },\n ];\n\n private socialAccounts!: GarrulaCollections[\"socialAccounts\"];\n private socialPosts!: GarrulaCollections[\"socialPosts\"];\n private analyticsSnapshots!: GarrulaCollections[\"analyticsSnapshots\"];\n private socialFactory?: SocialFactory;\n private hostOverride?: GarrulaHost;\n private configOverride?: Partial<GarrulaConfig>;\n private draftingAI?: DraftingAI;\n private outboundStores?: OutboundStores;\n private unsafeDisableOutboundGate = false;\n private outbound?: OutboundService;\n private nowFn: () => Date = () => new Date();\n /** The Agent base's persisted config; Garrula's own settings are {@link garrulaConfig}. */\n protected config: Record<string, never> = {};\n\n constructor(options: GarrulaOptions = {}) {\n super(options);\n this.socialFactory = options.socialFactory;\n this.hostOverride = options.host;\n this.configOverride = options.garrula;\n this.draftingAI = options.draftingAI;\n this.outboundStores = options.outboundStores;\n this.unsafeDisableOutboundGate = options.unsafeDisableOutboundGate === true;\n if (options.now) this.nowFn = options.now;\n\n if (options.collections) {\n this.socialAccounts = options.collections.socialAccounts;\n this.socialPosts = options.collections.socialPosts;\n this.analyticsSnapshots = options.collections.analyticsSnapshots;\n }\n }\n\n async initialize(): Promise<this> {\n await super.initialize();\n\n let ownCollections = false;\n if (!this.socialAccounts || !this.socialPosts || !this.analyticsSnapshots) {\n const opts = { db: this.options.db, ai: this.options.ai };\n this.socialAccounts = await SocialAccountCollection.create(opts);\n this.socialPosts = await SocialPostCollection.create(opts);\n this.analyticsSnapshots = await SocialPostAnalyticsSnapshotCollection.create(opts);\n ownCollections = true;\n }\n\n // The outbound pipeline (pause switch, spend cap, cited drafts) runs on\n // the agent's own database, or on injected `outboundStores`. A host that\n // injects only collections must also inject `outboundStores` (or opt out,\n // for tests, with `unsafeDisableOutboundGate`); otherwise publishing would\n // silently run without the gate.\n if (!this.outbound && (ownCollections || this.outboundStores)) {\n this.outboundStores ??= await createOutboundStores({\n db: this.options.db,\n ai: this.options.ai,\n });\n this.outbound = new OutboundService({\n stores: this.outboundStores,\n social: { socialAccounts: this.socialAccounts, socialPosts: this.socialPosts },\n config: () => this.garrulaConfig,\n ai: () => this.draftingAI ?? (this.ai as unknown as DraftingAI),\n now: () => this.nowFn(),\n });\n }\n if (!this.outbound && !this.unsafeDisableOutboundGate) {\n throw new Error(\n \"Garrula has no outbound gate: pass `outboundStores` (or let it use its own database). \" +\n \"`unsafeDisableOutboundGate: true` disables it and is for tests only.\",\n );\n }\n\n return this;\n }\n\n private get hostHooks(): GarrulaHost {\n return this.hostOverride ?? registeredHost;\n }\n\n /** The host's configuration over the neutral defaults. */\n get garrulaConfig(): GarrulaConfig {\n return resolveGarrulaConfig({ ...registeredConfig, ...this.configOverride });\n }\n\n /**\n * Publish every post that is due (scheduled time reached, or approved).\n * Posts of an organization that may not publish right now are left as they\n * are and picked up by a later run.\n */\n async run(): Promise<void> {\n const duePosts = await this.socialPosts.findDueForPublish(new Date());\n let published = 0;\n let failed = 0;\n let skipped = 0;\n for (const post of duePosts) {\n const result = await this.publishClaimed(post, { claimFrom: DUE_STATUSES });\n if (result.success) published++;\n else if (result.skipped) skipped++;\n else failed++;\n }\n if (duePosts.length > 0) {\n this.logger.info(\"Published due social posts\", {\n due: duePosts.length,\n published,\n failed,\n skipped,\n });\n }\n }\n\n async createStoryLinkPosts(request: StoryLinkPostRequest): Promise<GarrulaSocialPost[]> {\n const tenantId = this.resolveRequestTenantId(request.tenantId);\n\n return withTenant({ tenantId }, async () => {\n const accounts = await this.resolveTargetAccounts(\n request.targets ?? this.garrulaConfig.storyLinkTargets,\n tenantId,\n );\n\n return Promise.all(\n accounts.map((account) =>\n this.socialPosts.createDraft({\n socialAccountId: this.requireAccountId(account),\n contentId: request.contentId,\n postType: \"link\",\n title: request.title,\n description: request.excerpt ?? request.title,\n hashtags: this.mergeHashtags(account, request.hashtags),\n linkUrl: request.url,\n scheduledAt: request.scheduledAt ?? null,\n createdByUserId: request.createdByUserId ?? null,\n tenantId,\n }),\n ),\n );\n });\n }\n\n async createArticleVideoPosts(request: ArticleVideoPostRequest): Promise<GarrulaSocialPost[]> {\n const tenantId = this.resolveRequestTenantId(request.tenantId);\n\n return withTenant({ tenantId }, async () => {\n const readyAccounts = await this.resolveTargetAccounts(\n request.targets ?? this.garrulaConfig.articleVideoTargets,\n tenantId,\n );\n const accounts = this.selectAccounts(readyAccounts, request.accountIds);\n\n return Promise.all(\n accounts.map((account) =>\n this.socialPosts.createDraft({\n socialAccountId: this.requireAccountId(account),\n contentId: request.contentId,\n videoContentId: request.videoContentId ?? null,\n postType: \"video\",\n title: request.title,\n description: request.description ?? request.title,\n hashtags: this.mergeHashtags(account, request.hashtags),\n linkUrl: request.url ?? null,\n mediaUrl: request.mediaUrl,\n scheduledAt: request.scheduledAt ?? null,\n createdByUserId: request.createdByUserId ?? null,\n tenantId,\n }),\n ),\n );\n });\n }\n\n // ---- Outbound release pipeline -------------------------------------------\n //\n // Every method acts for one tenant: `options.tenantId`, else the tenant of\n // the current `withTenant` context (a different explicit tenant is refused).\n // Records of another tenant are reported as not found.\n\n private outboundFor(options?: { tenantId?: string }): {\n service: OutboundService;\n tenantId: string;\n } {\n if (!this.outbound) {\n throw new Error(\"The outbound pipeline is not initialized; call initialize() first.\");\n }\n return { service: this.outbound, tenantId: this.resolveRequestTenantId(options?.tenantId) };\n }\n\n /**\n * Offer a release/changelog event as a post candidate. Events that match no\n * enabled source rule, or were seen before, produce nothing; a match is\n * drafted in the tenant's persona with a cited claim list.\n */\n async ingestSourceEvent(\n event: SourceEvent,\n options?: { tenantId?: string },\n ): Promise<IngestResult> {\n const { service, tenantId } = this.outboundFor(options);\n return service.ingestSourceEvent(tenantId, event);\n }\n\n /**\n * Create a pending-approval draft from supplied text and evidence. Tenant\n * scoped, idempotent by `idempotencyKey`, records `createdBy`, and never\n * approves or publishes: a person must approve it and its claims need\n * evidence before it can publish. The host authorizes the caller.\n */\n async createDraft(\n input: CreateDraftInput,\n options?: { tenantId?: string },\n ): Promise<CreateDraftResult> {\n const { service, tenantId } = this.outboundFor(options);\n return service.createDraft(tenantId, input);\n }\n\n async listDrafts(\n filter: { state?: OutboundState; kind?: OutboundPostKind; limit?: number } = {},\n options?: { tenantId?: string },\n ): Promise<OutboundDraft[]> {\n const { service, tenantId } = this.outboundFor(options);\n return service.listDrafts(tenantId, filter);\n }\n\n /** Edit text, claims or link. An edit withdraws approval (back to draft). */\n async editDraft(\n id: string,\n patch: { text?: string; claims?: DraftClaim[]; linkUrl?: string | null },\n options?: { tenantId?: string },\n ): Promise<OutboundDraft> {\n const { service, tenantId } = this.outboundFor(options);\n return service.editDraft(tenantId, id, patch);\n }\n\n async approve(\n id: string,\n options?: { tenantId?: string; approvedBy?: string },\n ): Promise<OutboundDraft> {\n const { service, tenantId } = this.outboundFor(options);\n return service.approve(tenantId, id, options?.approvedBy);\n }\n\n async reject(\n id: string,\n reason?: string,\n options?: { tenantId?: string },\n ): Promise<OutboundDraft> {\n const { service, tenantId } = this.outboundFor(options);\n return service.reject(tenantId, id, reason);\n }\n\n /** Send a failed post back to approved so the next run publishes it again. */\n async retry(id: string, options?: { tenantId?: string }): Promise<OutboundDraft> {\n const { service, tenantId } = this.outboundFor(options);\n return service.retry(tenantId, id);\n }\n\n async schedule(id: string, at: Date, options?: { tenantId?: string }): Promise<OutboundDraft> {\n const { service, tenantId } = this.outboundFor(options);\n return service.schedule(tenantId, id, at);\n }\n\n /**\n * Publish the tenant's approved posts whose time has come (scheduled time\n * reached, or approved without one). Each goes through the same gate as any\n * publish: a pause or spend cap refuses it without calling the platform.\n */\n async publishDue(options?: { tenantId?: string; now?: Date }): Promise<PublishDueResult[]> {\n const { service, tenantId } = this.outboundFor(options);\n const due = await service.dueForPublish(tenantId, options?.now ?? this.nowFn());\n const results: PublishDueResult[] = [];\n for (const post of due) {\n results.push(await this.publishOutboundPost(service, tenantId, post));\n }\n return results;\n }\n\n /** Publish one approved or scheduled draft now. */\n async publishNow(id: string, options?: { tenantId?: string }): Promise<PublishDueResult> {\n const { service, tenantId } = this.outboundFor(options);\n const post = await service.postForPublish(tenantId, id);\n return this.publishOutboundPost(service, tenantId, post);\n }\n\n private async publishOutboundPost(\n service: OutboundService,\n tenantId: string,\n post: GarrulaSocialPost,\n ): Promise<PublishDueResult> {\n const outboundId = await service.outboundIdForPost(tenantId, post.id ?? \"\");\n const result = await this.publishClaimed(post, { claimFrom: DUE_STATUSES });\n return {\n postId: result.postId,\n outboundId,\n success: result.success,\n skipped: result.skipped,\n refusal: result.refusal as PublishDueResult[\"refusal\"],\n error: result.error,\n };\n }\n\n async getSettings(options?: { tenantId?: string }): Promise<OutboundSettings> {\n const { service, tenantId } = this.outboundFor(options);\n return service.getSettings(tenantId);\n }\n\n async updateSettings(\n patch: OutboundSettingsPatch,\n options?: { tenantId?: string },\n ): Promise<OutboundSettings> {\n const { service, tenantId } = this.outboundFor(options);\n return service.updateSettings(tenantId, patch);\n }\n\n /** Stop all publishing for the tenant, effective on the very next publish. */\n async pause(options?: { tenantId?: string }): Promise<OutboundSettings> {\n return this.updateSettings({ paused: true }, options);\n }\n\n async resume(options?: { tenantId?: string }): Promise<OutboundSettings> {\n return this.updateSettings({ paused: false }, options);\n }\n\n /** Spend ledger and cap for a month (`YYYY-MM`, default: this month, UTC). */\n async getSpend(options?: { tenantId?: string; month?: string }): Promise<SpendSummary> {\n const { service, tenantId } = this.outboundFor(options);\n return service.getSpend(tenantId, options?.month);\n }\n\n /** Record the failure on the post, then let the host tell the poster. */\n private async recordFailure(post: GarrulaSocialPost, error: Error | string): Promise<void> {\n await this.socialPosts.recordPublishFailure(post, error);\n const onPublishFailed = this.hostHooks.onPublishFailed;\n if (!onPublishFailed) return;\n try {\n await onPublishFailed(post, error instanceof Error ? error.message : error);\n } catch (hookError) {\n this.logger.warn(\"Social publish failure hook failed\", {\n postId: post.id,\n error: hookError,\n });\n }\n }\n\n /**\n * Publish one post. The post is first claimed with a single conditional\n * update (`status` → `publishing`, only from `options.claimFrom`), so\n * overlapping runs or a double-clicked retry never send it twice. A post\n * of an organization that may not publish is left as it is; after the\n * claim, every failure is recorded on the post (never left `publishing`).\n */\n async publishPost(\n post: GarrulaSocialPost,\n options: PublishPostOptions = {},\n ): Promise<PublishPostResult> {\n // A request-facing call acts for the ambient tenant: another tenant's post\n // is refused before anything is claimed. Only `run()` (the background job)\n // publishes across tenants, through {@link publishClaimed}.\n const postTenant = this.normalizeTenantId(post.tenantId);\n if (postTenant) this.resolveRequestTenantId(postTenant);\n return this.publishClaimed(post, options);\n }\n\n /** The trusted publish path: enters the post's own tenant (see {@link publishPost}). */\n private async publishClaimed(\n post: GarrulaSocialPost,\n options: PublishPostOptions = {},\n ): Promise<PublishPostResult> {\n const tenantId = this.normalizeTenantId(post.tenantId);\n const postId = post.id ?? \"\";\n const previousStatus = post.status;\n if (!tenantId) {\n const error = new Error(\"Cannot publish social post without tenant context\");\n await this.recordFailure(post, error);\n return {\n postId,\n platform: \"unknown\",\n success: false,\n error: error.message,\n };\n }\n\n if (this.hostHooks.canPublish && !(await this.hostHooks.canPublish(tenantId))) {\n return {\n postId,\n platform: \"unknown\",\n success: false,\n error: tenantBlockedMessage(this.garrulaConfig),\n skipped: \"tenant-blocked\",\n };\n }\n\n const claimed = await this.claimForPublish(\n post,\n tenantId,\n options.claimFrom ?? PUBLISHABLE_STATUSES,\n );\n if (!claimed) {\n return {\n postId,\n platform: \"unknown\",\n success: false,\n error: GARRULA_POST_BUSY_MESSAGE,\n skipped: \"post-busy\",\n };\n }\n\n const context: SendContext = {};\n let result: PublishPostResult;\n try {\n result = await withTenant({ tenantId }, () =>\n this.publishPostInTenant(post, context, previousStatus),\n );\n } catch (error) {\n await this.settleOutbound(tenantId, postId, context, false, errorMessage(error));\n throw error;\n }\n await this.settleOutbound(\n tenantId,\n postId,\n context,\n result.success,\n result.error,\n result.skipped !== undefined,\n );\n return result;\n }\n\n /** Record spend and the outbound state once a publish attempt is over. */\n private async settleOutbound(\n tenantId: string,\n postId: string,\n context: SendContext,\n success: boolean,\n error?: string,\n skipped = false,\n ): Promise<void> {\n if (!this.outbound) return;\n try {\n // Settle inside the post's own tenant (run() publishes across tenants).\n await withTenant({ tenantId }, async () => {\n if (context.reservation) {\n await this.outbound?.finish(context.reservation, {\n result: context.sent ?? null,\n success,\n error,\n });\n } else if (!success && !skipped && postId) {\n // Failed before the gate, so no reservation exists to settle it.\n await this.outbound?.failUnreserved(tenantId, postId);\n }\n });\n } catch (settleError) {\n // The reservation stays counted against the cap, which errs on the side\n // of not overspending; say so loudly.\n this.logger.error(\"Could not settle the outcome of a publish\", {\n entryId: context.reservation?.entryId,\n postId,\n error: errorMessage(settleError),\n });\n }\n }\n\n /** Put a refused post back where it was, so a later run can try again. */\n private async releaseClaim(post: GarrulaSocialPost, status: PostStatus | undefined) {\n if (!post.id || !status) return;\n await this.socialPosts.db.update(\n this.socialPosts.tableName,\n { id: post.id, tenant_id: post.tenantId, status: \"publishing\" },\n { status, updated_at: new Date() },\n );\n }\n\n /**\n * Atomically move the post to `publishing` if it is still in one of\n * `from`. Returns false when another publisher got there first.\n *\n * The claim writes the row directly, so the caller's copy of the post keeps\n * the old revision; {@link loadClaimedPost} re-reads it before anything is\n * saved.\n *\n * TODO(happyvertical/smrt#3300): a `SocialPostCollection.claimForPublish`\n * that returns the claimed post belongs next to\n * `recordPublishSuccess`/`recordPublishFailure`; adopt it and drop the\n * re-read.\n */\n private async claimForPublish(\n post: GarrulaSocialPost,\n tenantId: string,\n from: PostStatus[],\n ): Promise<boolean> {\n if (!post.id || from.length === 0) return false;\n const result = await this.socialPosts.db.update(\n this.socialPosts.tableName,\n { id: post.id, tenant_id: tenantId, \"status in\": from },\n { status: \"publishing\", error_message: null, updated_at: new Date() },\n );\n if (result.affected !== 1) return false;\n post.status = \"publishing\";\n post.errorMessage = null;\n return true;\n }\n\n /**\n * Re-read a post the claim just moved to `publishing`, so the revision the\n * outcome is saved against is the one the claim wrote. Saving the caller's\n * copy instead always fails with `RUNTIME_REVISION_CONFLICT`.\n */\n private async loadClaimedPost(post: GarrulaSocialPost): Promise<GarrulaSocialPost> {\n const claimed = post.id ? await this.socialPosts.get({ id: post.id }, { cache: false }) : null;\n if (!claimed) {\n throw new Error(\"This post could not be read back after it was claimed.\");\n }\n return claimed;\n }\n\n /**\n * Runs after the claim: every outcome is recorded on the post, and a\n * failure to record never hides why the publish itself failed.\n */\n private async publishPostInTenant(\n claimedPost: GarrulaSocialPost,\n context: SendContext,\n previousStatus: PostStatus | undefined,\n ): Promise<PublishPostResult> {\n const postId = claimedPost.id ?? \"\";\n let post: GarrulaSocialPost | null = null;\n let platform: PublishPostResult[\"platform\"] = \"unknown\";\n let accountPlatform: SocialPlatformType;\n let adapter: GarrulaSocialAdapter;\n let result: Awaited<ReturnType<GarrulaSocialAdapter[\"publishLink\"]>>;\n try {\n post = await this.loadClaimedPost(claimedPost);\n const account = await this.getPostAccount(post);\n if (!account) {\n throw new Error(\"Social account not found\");\n }\n platform = accountPlatform = account.platform;\n if (account.isActive === false) {\n throw new Error(GARRULA_ACCOUNT_INACTIVE_MESSAGE);\n }\n\n const credentials = await account.getCredentials();\n if (!credentials) {\n throw new Error(`No credentials configured for ${account.name}`);\n }\n\n let session = await this.openAdapter(account, credentials);\n const mediaUrl =\n post.postType === \"video\"\n ? (await this.hostHooks.resolveMediaUrl?.(post)) || post.mediaUrl\n : post.mediaUrl;\n\n // Server-side gate, immediately before the platform call: pause switch,\n // approval, evidence, link policy and the monthly spend cap. A refusal\n // leaves the post exactly as it was.\n let sendPost = post;\n if (this.outbound) {\n const gate = await this.outbound.beforeSend(post, account.platform);\n if (!gate.ok) {\n await this.releaseClaim(post, previousStatus);\n return {\n postId,\n platform,\n success: false,\n error: gate.refusal.message,\n skipped: \"refused\",\n refusal: gate.refusal,\n };\n }\n context.reservation = gate.reservation;\n sendPost = {\n ...post,\n linkUrl: gate.linkUrl,\n ...(isOutboundMarked(post) ? { title: null } : {}),\n } as GarrulaSocialPost;\n }\n try {\n result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null);\n } catch (publishError) {\n if (!isAuthError(publishError)) throw publishError;\n // The platform rejected a token we believed was valid: refresh once\n // and retry, or ask for a reconnect when the token cannot refresh.\n session = await this.openAdapter(account, session.credentials, { force: true });\n try {\n result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null);\n } catch (retryError) {\n if (!isAuthError(retryError)) throw retryError;\n throw await this.requireReconnect(account, \"publish rejected after refresh\");\n }\n }\n adapter = session.adapter;\n context.sent = result;\n } catch (error) {\n return this.failClaimedPost(post ?? claimedPost, post !== null, platform, error);\n }\n\n let publishedPost: GarrulaSocialPost;\n try {\n publishedPost = await this.socialPosts.recordPublishSuccess(post, {\n platformPostId: result.id,\n platformUrl: result.url,\n publishedAt: result.publishedAt,\n status:\n result.status === \"dry_run\" || result.status === \"staged\" ? result.status : \"published\",\n });\n } catch (recordError) {\n // A dry run never reached the platform, so retrying it is harmless:\n // record it as failed like any other error, on a fresh read (the failed\n // save left the dry-run outcome on this copy).\n if (result.status === \"dry_run\") {\n return this.failClaimedPost(post, false, platform, recordError);\n }\n // The platform has the post. Leave it `publishing` so nothing retries it\n // into a duplicate, and say so loudly.\n this.logger.error(\"Social post was sent but its result could not be saved\", {\n postId,\n platform,\n platformPostId: result.id,\n platformUrl: result.url,\n error: errorMessage(recordError),\n });\n return {\n postId,\n platform,\n success: false,\n platformPostId: result.id,\n platformUrl: result.url,\n error: `Posted (${result.url || result.id}), but the result could not be saved. Do not post it again.`,\n };\n }\n\n if (result.status === \"published\" || result.status === \"processing\") {\n try {\n await this.syncAnalyticsForPost(publishedPost, adapter, accountPlatform);\n } catch (analyticsError) {\n this.logger.warn(\"Unable to sync analytics after social publish\", {\n postId,\n platform,\n error: errorMessage(analyticsError),\n });\n }\n }\n\n return {\n postId,\n platform,\n success: true,\n platformPostId: result.id,\n platformUrl: result.url,\n };\n }\n\n /**\n * Record why a claimed post was not published and return that reason. The\n * reason is logged first, so it survives even when recording it fails.\n */\n private async failClaimedPost(\n post: GarrulaSocialPost,\n isFresh: boolean,\n platform: PublishPostResult[\"platform\"],\n error: unknown,\n ): Promise<PublishPostResult> {\n const postId = post.id ?? \"\";\n const reason = errorMessage(error);\n this.logger.error(\"Social publish failed\", { postId, platform, error: reason });\n try {\n const current = isFresh ? post : await this.loadClaimedPost(post);\n await this.recordFailure(current, error instanceof Error ? error : reason);\n } catch (recordError) {\n this.logger.error(\n \"Could not record a failed social publish; the post is still marked publishing\",\n {\n postId,\n platform,\n publishError: reason,\n error: errorMessage(recordError),\n },\n );\n }\n return { postId, platform, success: false, error: reason };\n }\n\n /**\n * Refresh the stats of published posts. With `options.tenantId`, only that\n * organization's posts are read; organizations that may not publish right\n * now (see {@link GarrulaHost.canPublish}) are skipped.\n */\n async syncAnalytics(\n postIds?: string[],\n options: { tenantId?: string | null } = {},\n ): Promise<AnalyticsSyncResult> {\n const where: Record<string, unknown> = { status: \"published\" };\n // An explicit tenant goes through the same check as every entry point (a\n // mismatch with the ambient context throws); a surrounding context scopes\n // the sync. Only a call with neither (the background job) spans tenants.\n const scopeTenantId =\n this.normalizeTenantId(options.tenantId) || this.normalizeTenantId(getTenantId())\n ? this.resolveRequestTenantId(options.tenantId)\n : null;\n if (scopeTenantId) where.tenantId = scopeTenantId;\n if (postIds?.length) where[\"id in\"] = postIds;\n const posts = await this.socialPosts.list({\n where,\n orderBy: \"publishedAt DESC\",\n });\n const selected = posts.filter(\n (post) =>\n (!postIds?.length || (post.id && postIds.includes(post.id))) &&\n (!scopeTenantId || this.normalizeTenantId(post.tenantId) === scopeTenantId),\n );\n const mayPublish = new Map<string, boolean>();\n const tenantMayPublish = async (tenantId: string): Promise<boolean> => {\n const canPublish = this.hostHooks.canPublish;\n if (!canPublish) return true;\n if (!mayPublish.has(tenantId)) mayPublish.set(tenantId, await canPublish(tenantId));\n return mayPublish.get(tenantId)!;\n };\n\n const result: AnalyticsSyncResult = {\n checked: selected.length,\n updated: 0,\n failed: 0,\n skipped: 0,\n errors: [],\n };\n\n for (const post of selected) {\n const tenantId = this.normalizeTenantId(post.tenantId);\n if (!tenantId || !(await tenantMayPublish(tenantId))) {\n result.skipped++;\n continue;\n }\n\n try {\n await withTenant({ tenantId }, async () => {\n const account = await this.getPostAccount(post);\n // A disconnected (inactive) account is never used again, not even\n // to read stats for posts it already published (privacy policy).\n if (!account || account.isActive === false || !post.platformPostId) {\n result.skipped++;\n return;\n }\n const credentials = await account.getCredentials();\n if (!credentials) {\n result.skipped++;\n return;\n }\n const { adapter } = await this.openAdapter(account, credentials);\n await this.syncAnalyticsForPost(post, adapter, account.platform);\n result.updated++;\n });\n } catch (error) {\n result.failed++;\n result.errors.push(error instanceof Error ? error.message : String(error));\n }\n }\n\n return result;\n }\n\n private async resolveTargetAccounts(\n targets: GarrulaTargetPlatform[],\n tenantId: string,\n ): Promise<GarrulaSocialAccount[]> {\n const groups = await Promise.all(\n targets.map((platform) => this.socialAccounts.findReady(platform)),\n );\n const accounts = groups.flat();\n\n return accounts.filter((account) => account.tenantId === tenantId);\n }\n\n /**\n * Narrow ready accounts to the requested ids. Every requested id must be one\n * of the ready accounts, so a stale or foreign id is refused, not skipped.\n */\n private selectAccounts(\n readyAccounts: GarrulaSocialAccount[],\n accountIds?: string[],\n ): GarrulaSocialAccount[] {\n if (!accountIds) return readyAccounts;\n const requested = new Set(accountIds.map((id) => id.trim()).filter(Boolean));\n const selected = readyAccounts.filter((account) => account.id && requested.has(account.id));\n if (requested.size === 0 || selected.length !== requested.size) {\n throw new Error(\"One or more selected social accounts are not ready to post.\");\n }\n return selected;\n }\n\n private mergeHashtags(account: GarrulaSocialAccount, requested?: string[]): string[] {\n return Array.from(new Set([...(account.defaultHashtags ?? []), ...(requested ?? [])]));\n }\n\n private requireAccountId(account: GarrulaSocialAccount): string {\n if (!account.id) {\n throw new Error(`Ready social account is missing an id: ${account.name}`);\n }\n return account.id;\n }\n\n /**\n * The tenant a request acts for: its own `tenantId`, else the tenant of the\n * current context. A request naming a different tenant than the active\n * context is refused rather than silently crossing tenants.\n */\n private resolveRequestTenantId(value?: string | null): string {\n const requested = this.normalizeTenantId(value);\n const ambient = this.normalizeTenantId(getTenantId());\n if (requested && ambient && requested !== ambient) {\n throw new Error(\"The request names a different tenant than the current tenant context.\");\n }\n const tenantId = requested ?? ambient;\n if (!tenantId) {\n throw new Error(tenantRequiredMessage(this.garrulaConfig));\n }\n return tenantId;\n }\n\n private normalizeTenantId(value?: string | null): string | null {\n const tenantId = value?.trim();\n return tenantId ? tenantId : null;\n }\n\n private async getPostAccount(post: GarrulaSocialPost): Promise<GarrulaSocialAccount | null> {\n if (!post.socialAccountId) return null;\n const account = await this.socialAccounts.get({ id: post.socialAccountId });\n if (\n account &&\n this.normalizeTenantId(account.tenantId) !== this.normalizeTenantId(post.tenantId)\n ) {\n return null;\n }\n return account;\n }\n\n /**\n * Build the account's adapter with a usable access token. A token that is\n * expired or close to it (or of unknown age) is refreshed first and the new\n * token set is saved on the account, so the next publish starts from it.\n * With `force`, the token is refreshed even if it looks valid (the platform\n * just rejected it); a token that cannot be refreshed then needs a\n * reconnect.\n */\n private async openAdapter(\n account: GarrulaSocialAccount,\n credentials: Record<string, unknown>,\n options: { force?: boolean } = {},\n ): Promise<{ adapter: GarrulaSocialAdapter; credentials: Record<string, unknown> }> {\n const adapter = await this.createAdapter(account, credentials);\n const fresh = await this.ensureFreshCredentials(account, credentials, adapter, options);\n if (fresh === credentials) return { adapter, credentials };\n return { adapter: await this.createAdapter(account, fresh), credentials: fresh };\n }\n\n /**\n * Return credentials whose access token can be used now: the stored ones,\n * or a refreshed set that has been saved on the account.\n */\n private async ensureFreshCredentials(\n account: GarrulaSocialAccount,\n credentials: Record<string, unknown>,\n adapter: GarrulaSocialAdapter,\n options: { force?: boolean },\n ): Promise<Record<string, unknown>> {\n const kind = refreshKind(account.platform, credentials);\n const force = options.force === true;\n if (!kind) {\n if (force) throw await this.requireReconnect(account, \"token rejected and not refreshable\");\n return credentials;\n }\n\n const { accessTokenRefreshMarginMs, threadsRefreshWindowMs } = this.garrulaConfig;\n const now = Date.now();\n if (kind === \"threads\") {\n const expiresAt = parseExpiry(credentials.expiresAt) ?? parseExpiry(account.tokenExpiresAt);\n if (expiresAt && expiresAt.getTime() <= now) {\n // A lapsed long-lived Threads token cannot be refreshed.\n throw await this.requireReconnect(account, \"long-lived token expired\");\n }\n if (!force && (!expiresAt || expiresAt.getTime() - now > threadsRefreshWindowMs)) {\n return credentials;\n }\n return this.refreshCredentials(account, credentials, adapter, kind, { force });\n }\n\n // OAuth 2 (YouTube, X): the stored expiry decides; with no stored expiry\n // (accounts connected before it was recorded) refresh once, which records\n // it. A refresh is one token call, the same cost as checking the token.\n const expiresAt = parseExpiry(credentials.expiresAt);\n if (!force && expiresAt && expiresAt.getTime() - now > accessTokenRefreshMarginMs) {\n return credentials;\n }\n return this.refreshCredentials(account, credentials, adapter, kind, { force: true });\n }\n\n private async refreshCredentials(\n account: GarrulaSocialAccount,\n credentials: Record<string, unknown>,\n adapter: GarrulaSocialAdapter,\n kind: \"oauth2\" | \"threads\",\n options: { force: boolean },\n ): Promise<Record<string, unknown>> {\n let auth;\n try {\n auth =\n kind === \"threads\"\n ? await refreshThreadsToken(String(credentials.accessToken))\n : await adapter.refreshToken(String(credentials.refreshToken));\n } catch (error) {\n // Another publish may have refreshed (and, on X, rotated) the token\n // first: use what is stored now if it changed.\n const stored = await account.getCredentials().catch(() => null);\n if (stored && stored.accessToken !== credentials.accessToken) {\n return stored;\n }\n if (isRefreshRejected(error)) {\n throw await this.requireReconnect(account, \"refresh rejected\");\n }\n if (!options.force && kind === \"threads\") {\n // An early Threads refresh is best effort: the token still works.\n this.logger.warn(\"Could not refresh a Threads token early; using the current one\", {\n accountId: account.id,\n error: errorMessage(error),\n });\n return credentials;\n }\n this.logger.warn(\"Social token refresh failed\", {\n accountId: account.id,\n platform: account.platform,\n error: errorMessage(error),\n });\n throw new Error(\n `Could not renew the ${platformLabel(account.platform)} sign-in right now. Try again in a few minutes.`,\n );\n }\n\n const next = mergeRefreshedCredentials(credentials, auth);\n await this.saveRefreshedCredentials(\n account,\n next,\n kind === \"threads\" ? (auth.expiresAt ?? null) : null,\n );\n return next;\n }\n\n /**\n * Save a refreshed token set on the account (encrypted, tenant-scoped).\n * `tokenExpiresAt` on the account means \"the connection lapses then\", so it\n * is cleared for refreshable OAuth 2 tokens and moved forward for Threads.\n * A failed save is logged and the fresh token is still used for this\n * publish.\n */\n private async saveRefreshedCredentials(\n account: GarrulaSocialAccount,\n credentials: Record<string, unknown>,\n connectionExpiresAt: Date | null,\n ): Promise<void> {\n try {\n account.tokenExpiresAt = connectionExpiresAt;\n if (account.status !== \"connected\") {\n account.status = \"connected\";\n account.errorMessage = null;\n }\n await account.setCredentials(credentials);\n this.logger.info(\"Refreshed social account token\", {\n accountId: account.id,\n platform: account.platform,\n });\n } catch (error) {\n this.logger.error(\"Could not save a refreshed social account token\", {\n accountId: account.id,\n platform: account.platform,\n error: errorMessage(error),\n });\n }\n }\n\n /**\n * Mark the account as needing a reconnect and return the error to throw.\n * Provider error text is never shown: it can be cryptic, and the message\n * says what to do.\n */\n private async requireReconnect(\n account: GarrulaSocialAccount,\n reason: string,\n ): Promise<GarrulaReconnectError> {\n const error = new GarrulaReconnectError(\n account.platform,\n this.garrulaConfig.socialSettingsLocation,\n );\n this.logger.warn(\"Social account needs to be reconnected\", {\n accountId: account.id,\n platform: account.platform,\n reason,\n });\n try {\n account.status = \"expired\";\n account.errorMessage = error.message;\n await account.save();\n } catch (saveError) {\n this.logger.error(\"Could not mark a social account as needing reconnection\", {\n accountId: account.id,\n platform: account.platform,\n error: errorMessage(saveError),\n });\n }\n return error;\n }\n\n private async createAdapter(\n account: GarrulaSocialAccount,\n credentials: Record<string, unknown>,\n ): Promise<GarrulaSocialAdapter> {\n if (this.socialFactory) {\n return this.socialFactory(account, credentials);\n }\n const adapter = await getSocial(this.buildSocialConfig(account, credentials));\n return adapter as GarrulaSocialAdapter;\n }\n\n private buildSocialConfig(\n account: GarrulaSocialAccount,\n credentials: Record<string, unknown>,\n ): GarrulaSocialConfig {\n const required = (name: string): string => {\n const value = credentials[name];\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(`Missing ${name} for ${account.platform}`);\n }\n return value;\n };\n const optional = (name: string): string | undefined => {\n const value = credentials[name];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n };\n const publishMode =\n account.effectivePublishMode ?? account.publishMode ?? this.garrulaConfig.defaultPublishMode;\n\n switch (account.platform) {\n case \"youtube\":\n return {\n type: \"youtube\",\n clientId: required(\"clientId\"),\n clientSecret: required(\"clientSecret\"),\n accessToken: required(\"accessToken\"),\n refreshToken: optional(\"refreshToken\"),\n publishMode,\n };\n case \"facebook\":\n return {\n type: \"facebook\",\n accessToken: required(\"accessToken\"),\n pageId:\n typeof credentials.pageId === \"string\"\n ? credentials.pageId\n : (account.platformUserId ?? required(\"pageId\")),\n publishMode,\n };\n case \"threads\":\n return {\n type: \"threads\",\n accessToken: required(\"accessToken\"),\n userId:\n typeof credentials.userId === \"string\"\n ? credentials.userId\n : (account.platformUserId ?? required(\"userId\")),\n publishMode,\n };\n case \"x\": {\n const linkBehavior =\n account.linkBehavior === \"reply\" || account.linkBehavior === \"none\"\n ? account.linkBehavior\n : \"inline\";\n const authType =\n credentials.authType === \"oauth2\" || !credentials.accessSecret ? \"oauth2\" : \"oauth1\";\n if (authType === \"oauth2\") {\n return {\n type: \"x\",\n authType: \"oauth2\",\n clientId: optional(\"clientId\"),\n clientSecret: optional(\"clientSecret\"),\n accessToken: required(\"accessToken\"),\n refreshToken: optional(\"refreshToken\"),\n linkBehavior,\n publishMode,\n };\n }\n return {\n type: \"x\",\n apiKey: required(\"apiKey\"),\n apiSecret: required(\"apiSecret\"),\n accessToken: required(\"accessToken\"),\n accessSecret: required(\"accessSecret\"),\n linkBehavior,\n publishMode,\n };\n }\n case \"bluesky\":\n // TODO(garrula-v2): Re-enable Bluesky once the platform is back in scope.\n throw new SocialError(\n \"Posting to Bluesky is not available yet.\",\n \"UNSUPPORTED_PLATFORM\",\n \"bluesky\",\n );\n }\n }\n\n private publishWithAdapter(\n adapter: GarrulaSocialAdapter,\n post: GarrulaSocialPost,\n mediaUrl: string | null,\n ) {\n if (post.postType === \"link\") {\n if (!post.linkUrl) {\n throw new SocialError(\"Link URL is required\", \"MISSING_LINK_URL\");\n }\n return adapter.publishLink({\n url: post.linkUrl,\n text: post.description,\n title: post.title ?? undefined,\n tags: post.hashtags,\n });\n }\n\n if (post.postType === \"video\") {\n if (!mediaUrl) {\n throw new SocialError(\"Media URL is required\", \"MISSING_MEDIA_URL\");\n }\n return adapter.publishVideo({\n file: mediaUrl,\n title: post.title ?? undefined,\n description: post.description,\n tags: post.hashtags,\n linkUrl: post.linkUrl ?? undefined,\n isShort: adapter.platform === \"youtube\",\n });\n }\n\n if (post.postType === \"image\") {\n // Picture posts carry their picture; never fall back to text-only.\n if (!mediaUrl) {\n throw new SocialError(\"A picture is required for a picture post\", \"MISSING_MEDIA_URL\");\n }\n return adapter.publishImage({\n file: mediaUrl,\n description: post.description,\n altText: post.title ?? undefined,\n tags: post.hashtags,\n linkUrl: post.linkUrl ?? undefined,\n });\n }\n\n return adapter.publishText({\n text: post.description,\n tags: post.hashtags,\n linkUrl: post.linkUrl ?? undefined,\n });\n }\n\n private async syncAnalyticsForPost(\n post: GarrulaSocialPost,\n adapter: GarrulaSocialAdapter,\n platform: SocialPlatformType,\n ): Promise<void> {\n if (!post.platformPostId) return;\n const analytics = await adapter.getAnalytics(post.platformPostId);\n const capturedAt = analytics.lastUpdated ?? new Date();\n\n await this.socialPosts.updateLatestAnalytics(post, analytics, capturedAt);\n await this.analyticsSnapshots.recordSnapshot({\n socialPostId: post.id ?? \"\",\n platform,\n metrics: analytics,\n raw: toRawAnalyticsPayload(analytics.raw),\n capturedAt,\n tenantId: post.tenantId ?? null,\n });\n }\n}\n\nfunction toRawAnalyticsPayload(value: unknown): RawAnalyticsPayload | undefined {\n if (value === null || Array.isArray(value)) return value;\n return typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAeA,IAAa,iCAAiC,MAAS;;;;;;AAOvD,IAAa,4BAA4B,QAAc,KAA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AI,KAAK;EAErD,MAAM,KAAK,YAAY,sBAAsB,MAAM,WAAW,UAAU;EACxE,MAAM,KAAK,mBAAmB,eAAe;GAC3C,cAAc,KAAK,MAAM;GACzB;GACA,SAAS;GACT,KAAK,sBAAsB,UAAU,GAAG;GACxC;GACA,UAAU,KAAK,YAAY;EAC7B,CAAC;CACH;AACF;sBAtrCC,KAAK;CACJ,OAAO;EACL,MAAM;EACN,MAAM;EACN,aAAa;CACf;CAIA,KAAK;EAAE,SAAS,CAAC,OAAO,eAAe;EAAG,cAAc,CAAC,OAAO,eAAe;CAAE;CACjF,KAAK,EAAE,SAAS,CAAC,wBAAwB,yBAAyB,EAAE;AACtE,CAAC,GAAA,mBAAA,qBAAA,CAAA,MAAA,CAAA,CAAA,GAAA,OAAA;AA6qCD,SAAS,sBAAsB,OAAiD;CAC9E,IAAI,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO;CACnD,OAAO,OAAO,UAAU,WAAY,QAAoC,KAAA;AAC1E;AAEA,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/credentials.ts","../src/outbound/rates.ts","../src/config.ts","../src/outbound/drafting.ts","../src/outbound/models.ts","../src/outbound/sources.ts","../src/outbound/state.ts","../src/ui/post-kinds.ts","../src/outbound/types.ts","../src/outbound/service.ts","../src/Garrula.ts"],"sourcesContent":["import { SocialError, type AuthResult } from \"@happyvertical/social\";\nimport type { SocialPlatformType } from \"@happyvertical/smrt-social\";\n\n/**\n * Social OAuth token upkeep for Garrula's publisher.\n *\n * TODO(happyvertical/sdk#1376): `@happyvertical/social` adapters should\n * refresh expired tokens themselves (expiry margin, retry after a 401) and\n * hand the refreshed token set to a callback for the caller to persist,\n * Threads included. Until then Garrula decides when to refresh, refreshes\n * Threads tokens itself, and persists every refreshed token set. Drop this\n * module's refresh logic when that ships.\n */\n\n/** Default for how long before expiry an access token is refreshed. */\nexport const ACCESS_TOKEN_REFRESH_MARGIN_MS = 5 * 60 * 1000;\n\n/**\n * Default window in which a Threads long-lived token (60 days) is refreshed:\n * once it is this close to lapsing. Meta refuses to refresh a token younger than 24 hours, so a\n * publish soon after connecting keeps the token it has.\n */\nexport const THREADS_REFRESH_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport const THREADS_REFRESH_URL = \"https://graph.threads.net/refresh_access_token\";\n\nconst PLATFORM_LABELS: Record<SocialPlatformType, string> = {\n youtube: \"YouTube\",\n x: \"X\",\n threads: \"Threads\",\n facebook: \"Facebook\",\n bluesky: \"Bluesky\",\n};\n\nexport function platformLabel(platform: SocialPlatformType): string {\n return PLATFORM_LABELS[platform] ?? platform;\n}\n\n/** Where a person reconnects an account, unless the host says otherwise. */\nexport const DEFAULT_SOCIAL_SETTINGS_LOCATION = \"Settings → Social\";\n\n/** What the poster sees when an account has to be connected again. */\nexport function reconnectMessage(\n platform: SocialPlatformType,\n settingsLocation: string = DEFAULT_SOCIAL_SETTINGS_LOCATION,\n): string {\n const label = platformLabel(platform);\n return `The ${label} account's sign-in has expired or was revoked, so nothing was posted. Reconnect ${label} in ${settingsLocation}, then try again.`;\n}\n\n/**\n * The account's sign-in can no longer be used or refreshed; a person has to\n * reconnect it. The message is safe to show and never carries provider text.\n */\nexport class GarrulaReconnectError extends Error {\n readonly code = \"RECONNECT_REQUIRED\";\n\n constructor(\n readonly platform: SocialPlatformType,\n settingsLocation?: string,\n ) {\n super(reconnectMessage(platform, settingsLocation));\n this.name = \"GarrulaReconnectError\";\n }\n}\n\n/** The provider rejected the sign-in (HTTP 401 or an auth error code). */\nexport function isAuthError(error: unknown): boolean {\n if (error instanceof GarrulaReconnectError) return false;\n if (!(error instanceof SocialError)) return false;\n return error.code === \"AUTH_ERROR\" || error.statusCode === 401;\n}\n\n/**\n * The provider refused the refresh grant itself (revoked consent,\n * `invalid_grant`, a rotated-away X refresh token), as opposed to a network\n * failure or an outage worth retrying later.\n */\nexport function isRefreshRejected(error: unknown): boolean {\n if (!(error instanceof SocialError)) return false;\n if (error.code === \"AUTH_ERROR\") {\n // The YouTube adapter reports every failed refresh (429 and 5xx too) as\n // an auth error carrying Google's response body, so only a refused grant\n // (RFC 6749 §5.2 error code) means the sign-in is gone.\n // TODO(happyvertical/sdk#1376): use the typed reauth error once it ships.\n if (error.platform === \"youtube\") return OAUTH_GRANT_REFUSED.test(error.message);\n return true;\n }\n const status = error.statusCode;\n return status === 400 || status === 401 || status === 403;\n}\n\nconst OAUTH_GRANT_REFUSED = /\\b(invalid_grant|invalid_client|unauthorized_client|invalid_scope)\\b/;\n\nexport function parseExpiry(value: unknown): Date | null {\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;\n if (typeof value === \"string\" || typeof value === \"number\") {\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n }\n return null;\n}\n\n/** Which refresh flow an account's stored credentials support. */\nexport type RefreshKind = \"oauth2\" | \"threads\" | null;\n\nexport function refreshKind(\n platform: SocialPlatformType,\n credentials: Record<string, unknown>,\n): RefreshKind {\n const has = (name: string) =>\n typeof credentials[name] === \"string\" && (credentials[name] as string).length > 0;\n switch (platform) {\n case \"youtube\":\n return has(\"refreshToken\") && has(\"clientId\") && has(\"clientSecret\") ? \"oauth2\" : null;\n case \"x\": {\n const oauth2 = credentials.authType === \"oauth2\" || !credentials.accessSecret;\n return oauth2 && has(\"refreshToken\") && has(\"clientId\") && has(\"clientSecret\")\n ? \"oauth2\"\n : null;\n }\n case \"threads\":\n return has(\"accessToken\") ? \"threads\" : null;\n default:\n return null;\n }\n}\n\n/**\n * The stored credentials with a refreshed token set merged in. Every other\n * stored field (client id/secret, user id, auth type, scopes) is kept.\n */\nexport function mergeRefreshedCredentials(\n credentials: Record<string, unknown>,\n auth: AuthResult,\n): Record<string, unknown> {\n const next: Record<string, unknown> = {\n ...credentials,\n accessToken: auth.accessToken,\n };\n if (auth.refreshToken) next.refreshToken = auth.refreshToken;\n if (auth.expiresAt) next.expiresAt = auth.expiresAt.toISOString();\n else delete next.expiresAt;\n if (auth.tokenType) next.tokenType = auth.tokenType;\n if (auth.scopes?.length) next.scopes = auth.scopes;\n return next;\n}\n\n/**\n * Refresh a Threads long-lived token. The upstream Threads adapter does not\n * implement `refreshToken()` (TODO(happyvertical/sdk#1376)).\n */\nexport async function refreshThreadsToken(\n accessToken: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<AuthResult> {\n const url = new URL(THREADS_REFRESH_URL);\n url.searchParams.set(\"grant_type\", \"th_refresh_token\");\n url.searchParams.set(\"access_token\", accessToken);\n const response = await fetchImpl(url);\n const body = (await response.json().catch(() => null)) as {\n access_token?: unknown;\n token_type?: unknown;\n expires_in?: unknown;\n error?: { message?: unknown; code?: unknown };\n } | null;\n if (!response.ok || typeof body?.access_token !== \"string\" || !body.access_token) {\n const code = body?.error?.code;\n const status = response.ok ? 400 : response.status;\n // Meta reports a dead token as code 190 (often with HTTP 400).\n throw new SocialError(\n \"Threads token refresh failed\",\n code === 190 ? \"AUTH_ERROR\" : \"REFRESH_FAILED\",\n \"threads\",\n code === 190 ? 401 : status,\n );\n }\n return {\n accessToken: body.access_token,\n tokenType: typeof body.token_type === \"string\" ? body.token_type : undefined,\n expiresAt:\n typeof body.expires_in === \"number\"\n ? new Date(Date.now() + body.expires_in * 1000)\n : undefined,\n };\n}\n","/**\n * Fallback publish prices, used only when the social adapter's publish result\n * carries no cost of its own.\n *\n * TEMPORARY: X's published API prices. Remove once happyvertical.com#518 lands\n * (the social SDK reports the real cost per publish); the host can override\n * these per platform with `GarrulaConfig.outboundRates`.\n */\nexport interface PlatformRates {\n /** A plain post, in USD. */\n post: number;\n /** A post that contains a URL, in USD. */\n postWithUrl: number;\n /** A reply to a mention, in USD (inbound is out of scope; kept for the table). */\n reply: number;\n}\n\nexport const FALLBACK_X_RATES: Readonly<PlatformRates> = Object.freeze({\n post: 0.015,\n postWithUrl: 0.2,\n reply: 0.01,\n});\n\nexport const DEFAULT_OUTBOUND_RATES: Readonly<Record<string, PlatformRates>> = Object.freeze({\n x: FALLBACK_X_RATES,\n});\n\nexport const MICROS_PER_USD = 1_000_000;\n\nexport function usdToMicros(usd: number): number {\n return Math.round(usd * MICROS_PER_USD);\n}\n\nexport type CostSource = \"adapter\" | \"rate-table\" | \"unpriced\";\n\nexport interface CostEstimate {\n micros: number;\n source: CostSource;\n}\n\n/** Estimate a publish from the rate table; unknown platforms are unpriced (0). */\nexport function estimateCost(\n rates: Readonly<Record<string, PlatformRates>>,\n platform: string,\n hasUrl: boolean,\n): CostEstimate {\n const table = rates[platform];\n if (!table) return { micros: 0, source: \"unpriced\" };\n return { micros: usdToMicros(hasUrl ? table.postWithUrl : table.post), source: \"rate-table\" };\n}\n\n/**\n * Read a cost the adapter reported on its publish result. The social SDK does\n * not report one yet (happyvertical.com#518); this accepts the shapes it is\n * expected to use: `cost` as USD number, or `{ usd }` / `{ amountUsd }`.\n */\nexport function adapterCostMicros(result: unknown): number | null {\n if (!result || typeof result !== \"object\") return null;\n const cost = (result as { cost?: unknown }).cost;\n let usd: unknown = cost;\n if (cost && typeof cost === \"object\") {\n const c = cost as { usd?: unknown; amountUsd?: unknown };\n usd = c.usd ?? c.amountUsd;\n }\n return typeof usd === \"number\" && Number.isFinite(usd) && usd >= 0 ? usdToMicros(usd) : null;\n}\n\n/** `YYYY-MM` in UTC. */\nexport function monthKey(date: Date): string {\n return date.toISOString().slice(0, 7);\n}\n","import { ACCESS_TOKEN_REFRESH_MARGIN_MS, THREADS_REFRESH_WINDOW_MS } from \"./credentials.js\";\nimport { DEFAULT_OUTBOUND_RATES, type PlatformRates } from \"./outbound/rates.js\";\nimport type { GarrulaTargetPlatform } from \"./types.js\";\n\n/**\n * Host-supplied configuration for Garrula. Everything here is a policy or\n * wording choice that belongs to the application using the agent, not to the\n * agent itself; the defaults are neutral and work for any tenant.\n */\nexport interface GarrulaConfig {\n /**\n * Platforms that receive a draft when a link post is created without\n * explicit `targets`.\n */\n storyLinkTargets: GarrulaTargetPlatform[];\n /**\n * Platforms that receive a draft when a video post is created without\n * explicit `targets`.\n */\n articleVideoTargets: GarrulaTargetPlatform[];\n /**\n * Publish mode used when an account records none. `dry_run` never reaches\n * the platform, so an unconfigured account cannot post by accident.\n */\n defaultPublishMode: string;\n /** What a tenant is called in messages shown to the person posting. */\n tenantLabel: string;\n /** Where a person reconnects a social account, as shown in messages. */\n socialSettingsLocation: string;\n /** Refresh an OAuth 2 access token this long before it expires. */\n accessTokenRefreshMarginMs: number;\n /** Refresh a Threads long-lived token once it is this close to lapsing. */\n threadsRefreshWindowMs: number;\n /**\n * Fallback publish prices per platform, in USD, used only when the adapter's\n * publish result reports no cost. Defaults to X's published prices; TEMPORARY\n * until the social SDK reports real costs (happyvertical.com#518).\n */\n outboundRates: Record<string, PlatformRates>;\n /** Monthly spend cap (USD) of a tenant that has not set its own. A cap always applies. */\n outboundDefaultMonthlyCapUsd: number;\n /** Longest post text a draft or edit may have. */\n outboundMaxLength: number;\n}\n\nexport const DEFAULT_GARRULA_CONFIG: Readonly<GarrulaConfig> = Object.freeze<GarrulaConfig>({\n storyLinkTargets: [\"facebook\", \"x\", \"threads\"],\n articleVideoTargets: [\"youtube\", \"x\", \"threads\", \"facebook\"],\n defaultPublishMode: \"dry_run\",\n tenantLabel: \"organization\",\n socialSettingsLocation: \"Settings → Social\",\n accessTokenRefreshMarginMs: ACCESS_TOKEN_REFRESH_MARGIN_MS,\n threadsRefreshWindowMs: THREADS_REFRESH_WINDOW_MS,\n outboundRates: DEFAULT_OUTBOUND_RATES as Record<string, PlatformRates>,\n outboundDefaultMonthlyCapUsd: 5,\n outboundMaxLength: 280,\n});\n\n/** Overlay the host's partial configuration on the neutral defaults. */\nexport function resolveGarrulaConfig(overrides: Partial<GarrulaConfig> = {}): GarrulaConfig {\n const config: GarrulaConfig = { ...DEFAULT_GARRULA_CONFIG };\n for (const key of Object.keys(overrides) as (keyof GarrulaConfig)[]) {\n const value = overrides[key];\n if (value !== undefined) (config as unknown as Record<string, unknown>)[key] = value;\n }\n config.storyLinkTargets = [...config.storyLinkTargets];\n config.articleVideoTargets = [...config.articleVideoTargets];\n config.outboundRates = { ...config.outboundRates };\n return config;\n}\n\n/** Why a post was not sent because its tenant may not publish. */\nexport function tenantBlockedMessage(config: GarrulaConfig): string {\n return `Posting is paused for this ${config.tenantLabel}, so nothing was posted.`;\n}\n\n/** What the caller is told when no tenant can be resolved. */\nexport function tenantRequiredMessage(config: GarrulaConfig): string {\n return `Social publishing requires an ${config.tenantLabel} (tenantId).`;\n}\n","import type {\n ClaimEvidence,\n DraftClaim,\n DraftingAI,\n OutboundPostKind,\n SourceEvent,\n} from \"./types.js\";\n\nexport interface DraftOutput {\n text: string;\n claims: DraftClaim[];\n}\n\nexport class DraftingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DraftingError\";\n }\n}\n\n/** Every reference the drafter may cite for an event, nothing else. */\nexport function allowedEvidence(event: SourceEvent): { urls: Set<string>; lines: Set<string> } {\n const urls = new Set<string>([event.url, ...(event.evidenceUrls ?? [])].filter(Boolean));\n const lines = new Set<string>(\n [event.changelogLine, ...(event.changelog ?? [])]\n .filter((line): line is string => typeof line === \"string\")\n .map((line) => line.trim())\n .filter(Boolean),\n );\n return { urls, lines };\n}\n\nexport function buildDraftPrompt(\n persona: string,\n kind: OutboundPostKind,\n event: SourceEvent,\n maxLength: number,\n): string {\n const { urls, lines } = allowedEvidence(event);\n return [\n \"You write one short social media post announcing a software change.\",\n `Write in this voice: ${persona.trim() || \"plain, factual, friendly\"}.`,\n `Post type: ${kind}. At most ${maxLength} characters. Do not include any URL in the text.`,\n \"State only facts supported by the event below. Do not invent features, numbers or dates.\",\n 'Reply with JSON only: {\"text\": string, \"claims\": [{\"text\": string, \"evidence\": string[]}]}.',\n \"Every factual statement in the post must appear in `claims`, and every claim must cite\",\n \"evidence copied exactly from the allowed evidence lists (a URL or a changelog line).\",\n \"\",\n `Event kind: ${event.kind}`,\n `Title: ${event.title}`,\n event.version ? `Version: ${event.version}` : \"\",\n event.repo ? `Repository: ${event.repo}` : \"\",\n event.summary ? `Summary: ${event.summary}` : \"\",\n `Allowed evidence URLs: ${JSON.stringify([...urls])}`,\n `Allowed evidence changelog lines: ${JSON.stringify([...lines])}`,\n ]\n .filter(Boolean)\n .join(\"\\n\");\n}\n\nfunction extractJson(raw: string): unknown {\n const fenced = raw.match(/```(?:json)?\\s*([\\s\\S]*?)```/i);\n const body = (fenced?.[1] ?? raw).trim();\n const start = body.indexOf(\"{\");\n const end = body.lastIndexOf(\"}\");\n if (start < 0 || end < start) throw new DraftingError(\"The drafter did not return JSON.\");\n try {\n return JSON.parse(body.slice(start, end + 1));\n } catch {\n throw new DraftingError(\"The drafter returned malformed JSON.\");\n }\n}\n\n/**\n * Parse a model reply into a draft. Evidence that is not one of the event's\n * own URLs or changelog lines is dropped, so a made-up citation leaves the\n * claim uncited (and the draft unpublishable) rather than looking supported.\n */\nexport function parseDraft(raw: string, event: SourceEvent): DraftOutput {\n const data = extractJson(raw) as { text?: unknown; claims?: unknown };\n const text = typeof data.text === \"string\" ? data.text.trim() : \"\";\n if (!text) throw new DraftingError(\"The drafter returned no post text.\");\n const { urls, lines } = allowedEvidence(event);\n\n const claims: DraftClaim[] = [];\n for (const entry of Array.isArray(data.claims) ? data.claims : []) {\n if (!entry || typeof entry !== \"object\") continue;\n const claimText = (entry as { text?: unknown }).text;\n if (typeof claimText !== \"string\" || !claimText.trim()) continue;\n const evidence: ClaimEvidence[] = [];\n const refs = (entry as { evidence?: unknown }).evidence;\n for (const ref of Array.isArray(refs) ? refs : []) {\n if (typeof ref !== \"string\") continue;\n const value = ref.trim();\n if (urls.has(value)) evidence.push({ type: \"url\", ref: value });\n else if (lines.has(value)) evidence.push({ type: \"changelog\", ref: value });\n }\n claims.push({ text: claimText.trim(), evidence });\n }\n return { text, claims };\n}\n\nexport async function draftPost(\n ai: DraftingAI,\n persona: string,\n kind: OutboundPostKind,\n event: SourceEvent,\n maxLength: number,\n): Promise<DraftOutput> {\n let raw: string;\n try {\n raw = await ai.message(buildDraftPrompt(persona, kind, event, maxLength));\n } catch (error) {\n throw new DraftingError(\n `Drafting failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const draft = parseDraft(raw, event);\n if (draft.text.length > maxLength) {\n throw new DraftingError(`The draft is longer than ${maxLength} characters.`);\n }\n return draft;\n}\n\n/** A post is publishable only with at least one claim, every claim with evidence. */\nexport function isFullyCited(claims: DraftClaim[] | null | undefined): boolean {\n if (!claims || claims.length === 0) return false;\n return claims.every(\n (claim) =>\n claim.text?.trim() &&\n Array.isArray(claim.evidence) &&\n claim.evidence.length > 0 &&\n claim.evidence.every((item) => typeof item.ref === \"string\" && item.ref.trim().length > 0),\n );\n}\n","import type { SmrtObjectOptions } from \"@happyvertical/smrt-core\";\nimport { SmrtCollection, SmrtObject, smrt } from \"@happyvertical/smrt-core\";\nimport { TenantScoped, tenantId } from \"@happyvertical/smrt-tenancy\";\nimport type {\n AutonomyMode,\n DraftClaim,\n LinkPolicy,\n OutboundPostKind,\n OutboundState,\n SourceEventKind,\n SourceRule,\n} from \"./types.js\";\n\n// Garrula-owned records of the outbound pipeline. Each is tenant scoped\n// (required mode) and has no REST/MCP surface: they are reached only through\n// the Garrula service methods, which re-check the tenant on every read.\n\nexport interface GarrulaOutboundSettingsOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n paused?: boolean;\n monthlyCapMicros?: number;\n persona?: string;\n sources?: SourceRule[];\n autonomy?: Record<OutboundPostKind, AutonomyMode>;\n linkPolicy?: Record<string, LinkPolicy>;\n defaultLinkPolicy?: LinkPolicy;\n accountIds?: string[];\n deferTopics?: string[];\n}\n\n/** One row per tenant: pause switch, cap, persona, source rules, autonomy, links. */\n@TenantScoped({ mode: \"required\" })\n@smrt({ tableStrategy: \"sti\", api: false, mcp: false, cli: false })\nexport class GarrulaOutboundSettings extends SmrtObject { static __smrtPackage__ = \"@happyvertical/garrula\";\n @tenantId({ nullable: false })\n tenantId: string | null = null;\n paused = false;\n monthlyCapMicros = 0;\n persona = \"\";\n sources: SourceRule[] = [];\n autonomy: Record<string, string> = {};\n linkPolicy: Record<string, string> = {};\n defaultLinkPolicy = \"none\";\n accountIds: string[] = [];\n deferTopics: string[] = [];\n\n constructor(options: GarrulaOutboundSettingsOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.paused !== undefined) this.paused = options.paused;\n if (options.monthlyCapMicros !== undefined) this.monthlyCapMicros = options.monthlyCapMicros;\n if (options.persona !== undefined) this.persona = options.persona;\n if (options.sources !== undefined) this.sources = options.sources;\n if (options.autonomy !== undefined) this.autonomy = options.autonomy;\n if (options.linkPolicy !== undefined) this.linkPolicy = options.linkPolicy;\n if (options.defaultLinkPolicy !== undefined) this.defaultLinkPolicy = options.defaultLinkPolicy;\n if (options.accountIds !== undefined) this.accountIds = options.accountIds;\n if (options.deferTopics !== undefined) this.deferTopics = options.deferTopics;\n }\n}\n\nexport class GarrulaOutboundSettingsCollection extends SmrtCollection<GarrulaOutboundSettings> {\n static readonly _itemClass = GarrulaOutboundSettings;\n}\n\nexport interface GarrulaOutboundPostOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n socialPostId?: string | null;\n state?: OutboundState;\n kind?: OutboundPostKind;\n sourceEventId?: string;\n sourceKind?: SourceEventKind;\n sourceUrl?: string | null;\n claims?: DraftClaim[];\n createdBy?: string | null;\n approvedBy?: string | null;\n rejectedReason?: string | null;\n}\n\n/**\n * The outbound lifecycle of one `smrt-social` SocialPost: state, kind, source\n * and cited claims. The text, account, schedule and publish result stay on the\n * SocialPost itself; `state` here is authoritative and mirrored onto it.\n * (smrt-social has no `rejected` status or claims field yet; see\n * docs/upstream-followups.md.)\n */\n@TenantScoped({ mode: \"required\" })\n@smrt({ tableStrategy: \"sti\", api: false, mcp: false, cli: false })\nexport class GarrulaOutboundPost extends SmrtObject { static __smrtPackage__ = \"@happyvertical/garrula\";\n @tenantId({ nullable: false })\n tenantId: string | null = null;\n socialPostId: string | null = null;\n state = \"draft\";\n kind = \"release\";\n sourceEventId = \"\";\n sourceKind = \"package-publish\";\n sourceUrl: string | null = null;\n claims: DraftClaim[] = [];\n /** Who supplied a manual draft (`createDraft`); null for ingested drafts. */\n createdBy: string | null = null;\n approvedBy: string | null = null;\n rejectedReason: string | null = null;\n\n constructor(options: GarrulaOutboundPostOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.socialPostId !== undefined) this.socialPostId = options.socialPostId;\n if (options.state !== undefined) this.state = options.state;\n if (options.kind !== undefined) this.kind = options.kind;\n if (options.sourceEventId !== undefined) this.sourceEventId = options.sourceEventId;\n if (options.sourceKind !== undefined) this.sourceKind = options.sourceKind;\n if (options.sourceUrl !== undefined) this.sourceUrl = options.sourceUrl;\n if (options.claims !== undefined) this.claims = options.claims;\n if (options.createdBy !== undefined) this.createdBy = options.createdBy;\n if (options.approvedBy !== undefined) this.approvedBy = options.approvedBy;\n if (options.rejectedReason !== undefined) this.rejectedReason = options.rejectedReason;\n }\n}\n\nexport class GarrulaOutboundPostCollection extends SmrtCollection<GarrulaOutboundPost> {\n static readonly _itemClass = GarrulaOutboundPost;\n}\n\nexport interface GarrulaSpendEntryOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n month?: string;\n socialPostId?: string | null;\n costMicros?: number;\n source?: string;\n status?: string;\n}\n\n/** Spend ledger: one entry per publish attempt, per tenant per month. */\n@TenantScoped({ mode: \"required\" })\n@smrt({ tableStrategy: \"sti\", api: false, mcp: false, cli: false })\nexport class GarrulaSpendEntry extends SmrtObject { static __smrtPackage__ = \"@happyvertical/garrula\";\n @tenantId({ nullable: false })\n tenantId: string | null = null;\n month = \"\";\n socialPostId: string | null = null;\n costMicros = 0;\n /** `adapter` | `rate-table` | `unpriced` */\n source = \"rate-table\";\n /** `reserved` | `recorded` | `released` */\n status = \"reserved\";\n\n constructor(options: GarrulaSpendEntryOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.month !== undefined) this.month = options.month;\n if (options.socialPostId !== undefined) this.socialPostId = options.socialPostId;\n if (options.costMicros !== undefined) this.costMicros = options.costMicros;\n if (options.source !== undefined) this.source = options.source;\n if (options.status !== undefined) this.status = options.status;\n }\n}\n\nexport class GarrulaSpendEntryCollection extends SmrtCollection<GarrulaSpendEntry> {\n static readonly _itemClass = GarrulaSpendEntry;\n}\n\nexport interface GarrulaSourceEventOptions extends SmrtObjectOptions {\n tenantId?: string | null;\n eventKey?: string;\n outcome?: string;\n outboundPostIds?: string[];\n}\n\n/** Dedupe ledger: an event id seen once never yields a second candidate. */\n@TenantScoped({ mode: \"required\" })\n@smrt({ tableStrategy: \"sti\", api: false, mcp: false, cli: false })\nexport class GarrulaSourceEvent extends SmrtObject { static __smrtPackage__ = \"@happyvertical/garrula\";\n @tenantId({ nullable: false })\n tenantId: string | null = null;\n /** `<kind>:<id>` */\n eventKey = \"\";\n /** `drafted` | `ignored` */\n outcome = \"ignored\";\n outboundPostIds: string[] = [];\n\n constructor(options: GarrulaSourceEventOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.eventKey !== undefined) this.eventKey = options.eventKey;\n if (options.outcome !== undefined) this.outcome = options.outcome;\n if (options.outboundPostIds !== undefined) this.outboundPostIds = options.outboundPostIds;\n }\n}\n\nexport class GarrulaSourceEventCollection extends SmrtCollection<GarrulaSourceEvent> {\n static readonly _itemClass = GarrulaSourceEvent;\n}\n","import type {\n AutonomyMode,\n OutboundPostKind,\n OutboundSettings,\n SourceEvent,\n SourceRule,\n} from \"./types.js\";\n\n/**\n * Default source rules: package publishes always post, merged pull requests\n * only when they are a `feat`/`perf` change, docs changes are off. Chores,\n * dependency bumps and internal work never produce a candidate.\n */\nexport const DEFAULT_SOURCE_RULES: readonly SourceRule[] = Object.freeze([\n { kind: \"package-publish\", postKind: \"release\", excludeLabels: [\"internal\", \"skip-social\"] },\n {\n kind: \"merged-pr\",\n postKind: \"feature\",\n includeTitle: [\"^(feat|perf)(\\\\(|:|!)\"],\n excludeTitle: [\"\\\\b(deps?|dependenc(y|ies)|internal)\\\\b\"],\n excludeLabels: [\"internal\", \"dependencies\", \"skip-social\"],\n },\n {\n kind: \"docs-change\",\n postKind: \"docs\",\n enabled: false,\n excludeLabels: [\"internal\", \"skip-social\"],\n },\n]);\n\nexport const DEFAULT_AUTONOMY: Readonly<Record<OutboundPostKind, AutonomyMode>> = Object.freeze({\n release: \"require-approval\",\n feature: \"require-approval\",\n docs: \"require-approval\",\n});\n\nexport type RuleDecision =\n | { match: true; rule: SourceRule }\n | { match: false; reason: \"no-rule\" | \"rule-disabled\" | \"filtered\" };\n\nfunction anyMatches(patterns: string[] | undefined, value: string): boolean {\n return (patterns ?? []).some((pattern) => {\n try {\n return new RegExp(pattern, \"i\").test(value);\n } catch {\n return false;\n }\n });\n}\n\nfunction lower(values: string[] | undefined): string[] {\n return (values ?? []).map((value) => value.toLowerCase());\n}\n\n/** Decide whether an event produces a candidate under the tenant's rules. */\nexport function evaluateSourceEvent(\n settings: Pick<OutboundSettings, \"sources\">,\n event: SourceEvent,\n): RuleDecision {\n const rules = settings.sources.filter((candidate) => candidate.kind === event.kind);\n if (rules.length === 0) return { match: false, reason: \"no-rule\" };\n const enabled = rules.filter((candidate) => candidate.enabled !== false);\n if (enabled.length === 0) return { match: false, reason: \"rule-disabled\" };\n\n const labels = lower(event.labels);\n for (const rule of enabled) {\n if (rule.includeTitle?.length && !anyMatches(rule.includeTitle, event.title)) continue;\n if (anyMatches(rule.excludeTitle, event.title)) continue;\n const include = lower(rule.includeLabels);\n if (include.length > 0 && !include.some((label) => labels.includes(label))) continue;\n if (lower(rule.excludeLabels).some((label) => labels.includes(label))) continue;\n return { match: true, rule };\n }\n return { match: false, reason: \"filtered\" };\n}\n\nexport function eventKey(event: Pick<SourceEvent, \"kind\" | \"id\">): string {\n return `${event.kind}:${event.id}`;\n}\n\n/** True when the event mentions a topic the tenant leaves to a person. */\nexport function isDeferred(\n topics: readonly string[],\n event: Pick<SourceEvent, \"title\" | \"summary\" | \"labels\">,\n): boolean {\n const haystack = [event.title, event.summary ?? \"\", ...(event.labels ?? [])]\n .join(\"\\n\")\n .toLowerCase();\n return topics.some((topic) => topic.trim() !== \"\" && haystack.includes(topic.toLowerCase()));\n}\n","import type { OutboundState } from \"./types.js\";\n\n/** Legal outbound transitions. Anything else is refused. */\nexport const OUTBOUND_TRANSITIONS: Readonly<Record<OutboundState, readonly OutboundState[]>> = {\n draft: [\"approved\", \"rejected\"],\n // `draft` = approval withdrawn (an edit invalidates it).\n approved: [\"scheduled\", \"published\", \"failed\", \"rejected\", \"draft\"],\n scheduled: [\"approved\", \"published\", \"failed\", \"rejected\", \"draft\"],\n failed: [\"approved\", \"rejected\", \"draft\"],\n published: [],\n rejected: [],\n};\n\nexport function canTransition(from: OutboundState, to: OutboundState): boolean {\n return OUTBOUND_TRANSITIONS[from].includes(to);\n}\n\n/** The `smrt-social` post status that mirrors an outbound state. */\nexport function socialStatusFor(state: OutboundState): string {\n switch (state) {\n case \"draft\":\n return \"draft\";\n case \"approved\":\n return \"approved\";\n case \"scheduled\":\n return \"scheduled\";\n case \"published\":\n return \"published\";\n case \"failed\":\n return \"failed\";\n case \"rejected\":\n // smrt-social has no `rejected`; `cancelled` is never published.\n return \"cancelled\";\n }\n}\n","/**\n * Post kinds with their own autonomy setting. This module lives under `src/ui`\n * because the admin panels import it as a runtime value and `svelte-package`\n * emits only `src/ui` into `dist/ui`; `src/outbound/types.ts` re-exports it so\n * there is one source of truth.\n */\nexport type OutboundPostKind = \"release\" | \"feature\" | \"docs\";\n\nexport const OUTBOUND_POST_KINDS: readonly OutboundPostKind[] = [\"release\", \"feature\", \"docs\"];\n","/**\n * Outbound pipeline types: release/changelog source events become cited\n * drafts, which are approved, published under a spend cap, and recorded.\n * Outbound only: nothing here reads mentions, replies, or any inbound feed.\n */\n\n/** What kind of upstream event a host hands in. */\nexport type SourceEventKind = \"package-publish\" | \"merged-pr\" | \"docs-change\";\n\n/** Where an outbound post came from: an ingested event, or text supplied through `createDraft`. */\nexport type OutboundSourceKind = SourceEventKind | \"manual\";\n\nimport { OUTBOUND_POST_KINDS, type OutboundPostKind } from \"../ui/post-kinds.js\";\n\n/** Post types with their own autonomy setting (defined in `ui/post-kinds.ts`, which the admin panels load at runtime). */\nexport { OUTBOUND_POST_KINDS, type OutboundPostKind };\n\n/**\n * Plain data describing one upstream event. The host (a webhook, a job, a CLI)\n * builds it; Garrula never polls GitHub or any registry.\n */\nexport interface SourceEvent {\n kind: SourceEventKind;\n /** Stable id of the event (a PR URL, `pkg@version`, a commit sha). Dedupe key. */\n id: string;\n title: string;\n /** Canonical URL of the event (the PR, the release, the docs page). */\n url: string;\n summary?: string;\n /** The changelog line that describes this event, when there is one. */\n changelogLine?: string;\n /** Further changelog lines that may be cited. */\n changelog?: string[];\n /** Further URLs (pull requests) that may be cited as evidence. */\n evidenceUrls?: string[];\n labels?: string[];\n version?: string;\n repo?: string;\n}\n\n/** One per-tenant rule saying which events of a kind become candidates. */\nexport interface SourceRule {\n kind: SourceEventKind;\n postKind: OutboundPostKind;\n enabled?: boolean;\n /** Regular expressions (case-insensitive); when set, the title must match one. */\n includeTitle?: string[];\n /** Regular expressions; a title matching one is ignored. */\n excludeTitle?: string[];\n /** When set, the event needs one of these labels. */\n includeLabels?: string[];\n /** An event with one of these labels is ignored. */\n excludeLabels?: string[];\n}\n\nexport type AutonomyMode = \"require-approval\" | \"auto\";\n\n/** Whether the URL of the source is part of the published text. */\nexport type LinkPolicy = \"none\" | \"include\";\n\n/** Evidence behind one claim: a pull request / release URL or a changelog line. */\nexport interface ClaimEvidence {\n type: \"url\" | \"changelog\";\n ref: string;\n}\n\nexport interface DraftClaim {\n text: string;\n evidence: ClaimEvidence[];\n}\n\nexport type OutboundState =\n | \"draft\"\n | \"approved\"\n | \"scheduled\"\n | \"published\"\n | \"failed\"\n | \"rejected\";\n\nexport const OUTBOUND_STATES: readonly OutboundState[] = [\n \"draft\",\n \"approved\",\n \"scheduled\",\n \"published\",\n \"failed\",\n \"rejected\",\n];\n\n/** Per-tenant outbound settings (the stored row, with defaults applied). */\nexport interface OutboundSettings {\n tenantId: string;\n paused: boolean;\n /** Monthly spend cap in micro-dollars (1 USD = 1_000_000). Always set. */\n monthlyCapMicros: number;\n /** The tenant's voice; the drafter writes in it. */\n persona: string;\n sources: SourceRule[];\n autonomy: Record<OutboundPostKind, AutonomyMode>;\n /** Link policy per social account id; accounts not listed use `defaultLinkPolicy`. */\n linkPolicy: Record<string, LinkPolicy>;\n defaultLinkPolicy: LinkPolicy;\n /** Accounts that receive drafts; empty means every ready account of the tenant. */\n accountIds: string[];\n /**\n * Topics the agent leaves to a person: an event whose title, summary or labels\n * mention one (case-insensitive) is never auto-approved, whatever the\n * autonomy setting says.\n */\n deferTopics: string[];\n}\n\nexport type OutboundSettingsPatch = Partial<\n Omit<OutboundSettings, \"tenantId\" | \"autonomy\" | \"linkPolicy\">\n> & {\n autonomy?: Partial<Record<OutboundPostKind, AutonomyMode>>;\n linkPolicy?: Record<string, LinkPolicy>;\n};\n\n/** What the host and the UI see of one outbound post. */\nexport interface OutboundDraft {\n id: string;\n tenantId: string;\n socialPostId: string;\n accountId: string | null;\n state: OutboundState;\n kind: OutboundPostKind;\n text: string;\n hashtags: string[];\n claims: DraftClaim[];\n /** The URL that may be published, depending on the account's link policy. */\n linkUrl: string | null;\n sourceEventId: string;\n sourceKind: OutboundSourceKind;\n /** Who supplied the draft through `createDraft`; null for ingested drafts. */\n createdBy?: string | null;\n scheduledAt: Date | null;\n publishedUrl: string | null;\n error: string | null;\n rejectedReason: string | null;\n approvedBy: string | null;\n /** False when a claim lacks evidence, so the post cannot be published. */\n publishable: boolean;\n createdAt: Date | null;\n}\n\n/** Text and evidence supplied by a caller (a person or an agent) instead of an ingested event. */\nexport interface CreateDraftInput {\n /** The post text. Must fit `outboundMaxLength`. */\n text: string;\n /**\n * The factual claims in the text, each with evidence (a URL or a changelog\n * line). A post can only be approved and published when every claim has\n * evidence; a draft without it is created but `publishable` is false.\n */\n claims: DraftClaim[];\n /** Caller-chosen key, unique per tenant: the same key never creates a second draft. */\n idempotencyKey: string;\n /** Audit label for who supplied the draft (the host's verified identity). */\n createdBy: string;\n kind?: OutboundPostKind;\n /** URL to publish with the post; only used when the account's link policy is `include`. */\n linkUrl?: string | null;\n}\n\nexport type CreateDraftResult =\n | { outcome: \"drafted\"; drafts: OutboundDraft[] }\n | { outcome: \"duplicate\"; drafts: OutboundDraft[] }\n | { outcome: \"no-accounts\" };\n\nexport type IngestResult =\n | { outcome: \"drafted\"; drafts: OutboundDraft[] }\n | { outcome: \"ignored\"; reason: \"no-rule\" | \"rule-disabled\" | \"filtered\" | \"no-accounts\" }\n | { outcome: \"duplicate\" }\n | { outcome: \"draft-failed\"; error: string };\n\n/** Typed reasons the pipeline refuses to publish or change a post. */\nexport type OutboundRefusalCode =\n | \"paused\"\n | \"cap-reached\"\n | \"uncited\"\n | \"not-approved\"\n | \"illegal-transition\"\n | \"not-found\"\n | \"in-flight\"\n | \"invalid\";\n\nexport interface OutboundRefusal {\n code: OutboundRefusalCode;\n message: string;\n}\n\n/** Thrown by the public API for refused changes (never for a publish). */\nexport class OutboundError extends Error {\n readonly code: OutboundRefusalCode;\n constructor(code: OutboundRefusalCode, message: string) {\n super(message);\n this.name = \"OutboundError\";\n this.code = code;\n }\n}\n\nexport interface SpendEntryView {\n id: string;\n month: string;\n postId: string | null;\n costMicros: number;\n source: \"adapter\" | \"rate-table\" | \"unpriced\";\n status: \"reserved\" | \"recorded\" | \"released\";\n createdAt: Date | null;\n}\n\nexport interface SpendSummary {\n tenantId: string;\n /** `YYYY-MM` (UTC). */\n month: string;\n capMicros: number;\n /** Recorded plus currently reserved spend. */\n spentMicros: number;\n remainingMicros: number;\n paused: boolean;\n entries: SpendEntryView[];\n}\n\nexport interface PublishDueResult {\n postId: string;\n outboundId: string | null;\n success: boolean;\n skipped?: string;\n refusal?: OutboundRefusal;\n error?: string;\n}\n\n/** The model call the drafter needs; `Agent.ai` satisfies it. */\nexport interface DraftingAI {\n message(text: string, options?: Record<string, unknown>): Promise<string>;\n}\n","import { getTenantId, withTenant } from \"@happyvertical/smrt-tenancy\";\nimport type { GarrulaConfig } from \"../config.js\";\nimport type { GarrulaCollections, GarrulaSocialAccount, GarrulaSocialPost } from \"../types.js\";\nimport { DraftingError, draftPost, isFullyCited } from \"./drafting.js\";\nimport {\n type GarrulaOutboundPost,\n GarrulaOutboundPostCollection,\n type GarrulaOutboundSettings,\n GarrulaOutboundSettingsCollection,\n GarrulaSourceEventCollection,\n type GarrulaSpendEntry,\n GarrulaSpendEntryCollection,\n} from \"./models.js\";\nimport {\n adapterCostMicros,\n type CostSource,\n estimateCost,\n monthKey,\n usdToMicros,\n} from \"./rates.js\";\nimport {\n DEFAULT_AUTONOMY,\n DEFAULT_SOURCE_RULES,\n evaluateSourceEvent,\n eventKey,\n isDeferred,\n} from \"./sources.js\";\nimport { canTransition, socialStatusFor } from \"./state.js\";\nimport {\n type CreateDraftInput,\n type CreateDraftResult,\n type DraftClaim,\n type DraftingAI,\n type IngestResult,\n type LinkPolicy,\n OUTBOUND_POST_KINDS,\n OUTBOUND_STATES,\n type OutboundDraft,\n OutboundError,\n type OutboundPostKind,\n type OutboundRefusal,\n type OutboundSourceKind,\n type OutboundSettings,\n type OutboundSettingsPatch,\n type OutboundState,\n type SourceEvent,\n type SourceEventKind,\n type SpendSummary,\n} from \"./types.js\";\n\nexport interface OutboundStores {\n settings: GarrulaOutboundSettingsCollection;\n posts: GarrulaOutboundPostCollection;\n spend: GarrulaSpendEntryCollection;\n events: GarrulaSourceEventCollection;\n}\n\nexport async function createOutboundStores(options: {\n db?: unknown;\n ai?: unknown;\n}): Promise<OutboundStores> {\n const opts = options as ConstructorParameters<typeof GarrulaSpendEntryCollection>[0];\n return {\n settings: await GarrulaOutboundSettingsCollection.create(opts),\n posts: await GarrulaOutboundPostCollection.create(opts),\n spend: await GarrulaSpendEntryCollection.create(opts),\n events: await GarrulaSourceEventCollection.create(opts),\n };\n}\n\n/** Unready only because the access token's recorded expiry has passed. */\nfunction isLapsedOnly(account: GarrulaSocialAccount): boolean {\n return (\n account.isActive !== false &&\n account.status === \"connected\" &&\n account.hasCredentials &&\n (account.missingPermissions?.length ?? 0) === 0 &&\n (account.publishMode !== \"public\" || account.publicPublishingAllowed === true) &&\n account.isTokenExpired\n );\n}\n\ntype SocialAccess = Pick<GarrulaCollections, \"socialAccounts\" | \"socialPosts\">;\n\nexport interface OutboundServiceOptions {\n stores: OutboundStores;\n social: SocialAccess;\n config: () => GarrulaConfig;\n /** The model client used to draft; resolved lazily so tests inject a fake. */\n ai: () => DraftingAI;\n now?: () => Date;\n /**\n * Renew a lapsed but refreshable access token and save it on the account\n * (clearing the lapsed expiry). Throws when the account cannot be renewed.\n */\n refreshAccount?: (account: GarrulaSocialAccount) => Promise<void>;\n}\n\n/** A reservation held between the gate and the publish outcome. */\nexport interface SpendReservation {\n tenantId: string;\n entryId: string;\n month: string;\n estimateMicros: number;\n estimateSource: CostSource;\n outboundId: string | null;\n}\n\nexport type GateDecision =\n | { ok: true; reservation: SpendReservation; linkUrl: string | null }\n | { ok: false; refusal: OutboundRefusal };\n\nexport interface SentOutcome {\n /** The adapter's publish result when the platform was reached. */\n result: { status?: string; cost?: unknown } | null;\n success: boolean;\n error?: string;\n}\n\n// In-process mutual exclusion per tenant, shared by every service instance in\n// the process. Reserve/record and ingest dedupe run inside it, so concurrent\n// publishes cannot both pass a cap check or both draft one event. It does NOT\n// span processes: with several worker processes a host must also serialise\n// publishing per tenant (see docs/outbound.md).\nconst locks = new Map<string, Promise<unknown>>();\n\nfunction withLock<T>(tenantId: string, fn: () => Promise<T>): Promise<T> {\n const previous = locks.get(tenantId) ?? Promise.resolve();\n const run = previous.then(fn, fn);\n const tail = run.catch(() => undefined);\n locks.set(tenantId, tail);\n void tail.then(() => {\n if (locks.get(tenantId) === tail) locks.delete(tenantId);\n });\n return run;\n}\n\ntype SaveablePost = GarrulaSocialPost;\n\n/**\n * Public entry points act for one tenant. When a tenant context is active it\n * must be that tenant: another tenant's records are reported as not found,\n * never touched.\n */\nfunction assertAmbientTenant(tenantId: string): void {\n const ambient = getTenantId()?.trim();\n if (ambient && ambient !== tenantId) {\n throw new OutboundError(\"not-found\", \"No such record for the current tenant.\");\n }\n}\n\n/** Title prefix on social posts created by outbound drafting. */\nexport const OUTBOUND_POST_MARKER = \"garrula-outbound:\";\n\n/** True for a social post that outbound drafting created. */\nexport function isOutboundMarked(post: GarrulaSocialPost): boolean {\n return typeof post.title === \"string\" && post.title.startsWith(OUTBOUND_POST_MARKER);\n}\n\nexport class OutboundService {\n private readonly stores: OutboundStores;\n private readonly social: SocialAccess;\n private readonly configFn: () => GarrulaConfig;\n private readonly aiFn: () => DraftingAI;\n private readonly nowFn: () => Date;\n private readonly refreshAccount?: (account: GarrulaSocialAccount) => Promise<void>;\n\n constructor(options: OutboundServiceOptions) {\n this.refreshAccount = options.refreshAccount;\n this.stores = options.stores;\n this.social = options.social;\n this.configFn = options.config;\n this.aiFn = options.ai;\n this.nowFn = options.now ?? (() => new Date());\n }\n\n // ---- settings ---------------------------------------------------------\n\n /** The default cap; a non-finite or negative configured value falls back to the shipped default. */\n private defaultCapMicros(): number {\n const configured = this.configFn().outboundDefaultMonthlyCapUsd;\n const usd =\n typeof configured === \"number\" && Number.isFinite(configured) && configured >= 0\n ? configured\n : 5;\n return usdToMicros(usd);\n }\n\n private defaults(tenantId: string): OutboundSettings {\n return {\n tenantId,\n paused: false,\n monthlyCapMicros: this.defaultCapMicros(),\n persona: \"\",\n sources: DEFAULT_SOURCE_RULES.map((rule) => ({ ...rule })),\n autonomy: { ...DEFAULT_AUTONOMY },\n linkPolicy: {},\n defaultLinkPolicy: \"none\",\n accountIds: [],\n deferTopics: [],\n };\n }\n\n private async findSettingsRow(tenantId: string): Promise<GarrulaOutboundSettings | null> {\n const rows = await this.stores.settings.list({ where: { tenantId } });\n return rows.find((row) => row.tenantId === tenantId) ?? null;\n }\n\n private toSettings(tenantId: string, row: GarrulaOutboundSettings | null): OutboundSettings {\n const base = this.defaults(tenantId);\n if (!row) return base;\n const rule = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\";\n return {\n tenantId,\n paused: row.paused === true,\n monthlyCapMicros:\n Number.isFinite(row.monthlyCapMicros) && row.monthlyCapMicros >= 0\n ? row.monthlyCapMicros\n : base.monthlyCapMicros,\n persona: row.persona ?? \"\",\n sources: Array.isArray(row.sources) ? row.sources : base.sources,\n autonomy: {\n ...base.autonomy,\n ...(rule(row.autonomy) ? (row.autonomy as OutboundSettings[\"autonomy\"]) : {}),\n },\n linkPolicy: rule(row.linkPolicy) ? (row.linkPolicy as Record<string, LinkPolicy>) : {},\n defaultLinkPolicy: row.defaultLinkPolicy === \"include\" ? \"include\" : \"none\",\n accountIds: Array.isArray(row.accountIds) ? row.accountIds : [],\n deferTopics: Array.isArray(row.deferTopics) ? row.deferTopics.map(String) : [],\n };\n }\n\n /** Read fresh settings (never cached), defaults when the tenant has none. */\n getSettings(tenantId: string): Promise<OutboundSettings> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () =>\n this.toSettings(tenantId, await this.findSettingsRow(tenantId)),\n );\n }\n\n updateSettings(tenantId: string, patch: OutboundSettingsPatch): Promise<OutboundSettings> {\n assertAmbientTenant(tenantId);\n return withLock(tenantId, () =>\n withTenant({ tenantId }, async () => {\n const next = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n if (patch.paused !== undefined) next.paused = patch.paused === true;\n if (patch.monthlyCapMicros !== undefined) {\n const cap = patch.monthlyCapMicros;\n if (!Number.isFinite(cap) || cap < 0) {\n throw new OutboundError(\"invalid\", \"The monthly cap must be zero or more.\");\n }\n next.monthlyCapMicros = Math.round(cap);\n }\n if (patch.persona !== undefined) next.persona = String(patch.persona);\n if (patch.sources !== undefined) next.sources = patch.sources;\n if (patch.autonomy) {\n for (const [kind, mode] of Object.entries(patch.autonomy)) {\n if (!OUTBOUND_POST_KINDS.includes(kind as OutboundPostKind)) {\n throw new OutboundError(\"invalid\", `Unknown post type: ${kind}`);\n }\n if (mode !== \"auto\" && mode !== \"require-approval\") {\n throw new OutboundError(\"invalid\", `Unknown autonomy mode: ${String(mode)}`);\n }\n next.autonomy[kind as OutboundPostKind] = mode;\n }\n }\n if (patch.linkPolicy) next.linkPolicy = { ...next.linkPolicy, ...patch.linkPolicy };\n if (patch.defaultLinkPolicy !== undefined) next.defaultLinkPolicy = patch.defaultLinkPolicy;\n if (patch.accountIds !== undefined) next.accountIds = [...patch.accountIds];\n if (patch.deferTopics !== undefined) {\n next.deferTopics = [\n ...new Set(patch.deferTopics.map((topic) => String(topic).trim()).filter(Boolean)),\n ];\n }\n for (const policy of [next.defaultLinkPolicy, ...Object.values(next.linkPolicy)]) {\n if (policy !== \"none\" && policy !== \"include\") {\n throw new OutboundError(\"invalid\", `Unknown link policy: ${String(policy)}`);\n }\n }\n\n const row = await this.findSettingsRow(tenantId);\n const data = {\n paused: next.paused,\n monthlyCapMicros: next.monthlyCapMicros,\n persona: next.persona,\n sources: next.sources,\n autonomy: next.autonomy,\n linkPolicy: next.linkPolicy,\n defaultLinkPolicy: next.defaultLinkPolicy,\n accountIds: next.accountIds,\n deferTopics: next.deferTopics,\n };\n if (row) {\n Object.assign(row, data);\n await row.save();\n } else {\n await this.stores.settings.create({ tenantId, ...data });\n }\n return next;\n }),\n );\n }\n\n // ---- ingest -----------------------------------------------------------\n\n ingestSourceEvent(tenantId: string, event: SourceEvent): Promise<IngestResult> {\n assertAmbientTenant(tenantId);\n const kinds: SourceEventKind[] = [\"package-publish\", \"merged-pr\", \"docs-change\"];\n if (\n !event ||\n !kinds.includes(event.kind) ||\n !String(event.id ?? \"\").trim() ||\n !String(event.title ?? \"\").trim() ||\n !String(event.url ?? \"\").trim()\n ) {\n throw new OutboundError(\"invalid\", \"A source event needs a kind, id, title and url.\");\n }\n return withLock(tenantId, () =>\n withTenant({ tenantId }, async (): Promise<IngestResult> => {\n const key = eventKey(event);\n const seen = await this.stores.events.list({ where: { tenantId, eventKey: key } });\n if (seen.some((row) => row.tenantId === tenantId)) return { outcome: \"duplicate\" };\n\n const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n const decision = evaluateSourceEvent(settings, event);\n if (!decision.match) {\n await this.stores.events.create({ tenantId, eventKey: key, outcome: \"ignored\" });\n return { outcome: \"ignored\", reason: decision.reason };\n }\n\n const accounts = await this.targetAccounts(tenantId, settings);\n if (accounts.length === 0) return { outcome: \"ignored\", reason: \"no-accounts\" };\n\n const kind = decision.rule.postKind;\n let draft;\n try {\n draft = await draftPost(\n this.aiFn(),\n settings.persona,\n kind,\n event,\n this.configFn().outboundMaxLength,\n );\n } catch (error) {\n if (error instanceof DraftingError) {\n return { outcome: \"draft-failed\", error: error.message };\n }\n return {\n outcome: \"draft-failed\",\n error: error instanceof Error ? error.message : String(error),\n };\n }\n\n const drafts: OutboundDraft[] = [];\n const ids: string[] = [];\n for (const account of accounts) {\n const post = await this.social.socialPosts.createDraft({\n socialAccountId: account.id as string,\n postType: \"text\",\n title: `${OUTBOUND_POST_MARKER}${event.id}`,\n description: draft.text,\n linkUrl: event.url,\n tenantId,\n });\n let row;\n try {\n row = await this.stores.posts.create({\n tenantId,\n socialPostId: post.id as string,\n state: \"draft\",\n kind,\n sourceEventId: event.id,\n sourceKind: event.kind,\n sourceUrl: event.url,\n claims: draft.claims,\n });\n } catch (error) {\n // Compensate: never leave a social draft with no approval record.\n await this.discardSocialDraft(post);\n throw error;\n }\n ids.push(row.id as string);\n if (\n settings.autonomy[kind] === \"auto\" &&\n isFullyCited(draft.claims) &&\n !isDeferred(settings.deferTopics, event)\n ) {\n await this.transition(tenantId, row, \"approved\", { approvedBy: \"autonomy\" });\n }\n drafts.push(await this.view(tenantId, row, settings));\n }\n await this.stores.events.create({\n tenantId,\n eventKey: key,\n outcome: \"drafted\",\n outboundPostIds: ids,\n });\n return { outcome: \"drafted\", drafts };\n }),\n );\n }\n\n /**\n * Create a pending-approval draft from text and evidence supplied by the\n * host's caller. Tenant scoped and idempotent by `idempotencyKey`: a repeat\n * returns the original drafts. It never approves, schedules or publishes, and\n * ignores the autonomy settings; a person must still approve it.\n */\n createDraft(tenantId: string, input: CreateDraftInput): Promise<CreateDraftResult> {\n assertAmbientTenant(tenantId);\n if (!input || typeof input !== \"object\") {\n throw new OutboundError(\"invalid\", \"A draft needs text, claims, a key and a creator.\");\n }\n const key = String(input.idempotencyKey ?? \"\").trim();\n const createdBy = String(input?.createdBy ?? \"\").trim();\n const text = String(input?.text ?? \"\").trim();\n if (!key || key.length > 200) {\n throw new OutboundError(\n \"invalid\",\n \"A draft needs an idempotency key of at most 200 characters.\",\n );\n }\n if (!createdBy) throw new OutboundError(\"invalid\", \"A draft needs a creator.\");\n if (!text) throw new OutboundError(\"invalid\", \"The post text cannot be empty.\");\n const max = this.configFn().outboundMaxLength;\n if (text.length > max) {\n throw new OutboundError(\"invalid\", `The post text is longer than ${max} characters.`);\n }\n const kind = input.kind ?? \"release\";\n if (!OUTBOUND_POST_KINDS.includes(kind)) {\n throw new OutboundError(\"invalid\", \"Unknown post kind.\");\n }\n if (!Array.isArray(input.claims)) throw new OutboundError(\"invalid\", \"Claims must be a list.\");\n const claims: DraftClaim[] = input.claims.map((claim) => ({\n text: String(claim?.text ?? \"\").trim(),\n evidence: (Array.isArray(claim?.evidence) ? claim.evidence : []).map((item) => ({\n type: item?.type === \"changelog\" ? \"changelog\" : \"url\",\n ref: String(item?.ref ?? \"\").trim(),\n })),\n }));\n const linkUrl = input.linkUrl?.trim() || null;\n if (linkUrl && !/^https?:\\/\\/\\S+$/i.test(linkUrl)) {\n throw new OutboundError(\"invalid\", \"linkUrl must be an http(s) URL.\");\n }\n\n return withLock(tenantId, () =>\n withTenant({ tenantId }, async (): Promise<CreateDraftResult> => {\n const ledgerKey = `manual:${key}`;\n const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n const seen = (\n await this.stores.events.list({ where: { tenantId, eventKey: ledgerKey } })\n ).find((row) => row.tenantId === tenantId);\n if (seen) {\n const drafts: OutboundDraft[] = [];\n for (const id of seen.outboundPostIds ?? []) {\n drafts.push(await this.view(tenantId, await this.requireRow(tenantId, id), settings));\n }\n return { outcome: \"duplicate\", drafts };\n }\n\n const accounts = await this.targetAccounts(tenantId, settings);\n if (accounts.length === 0) return { outcome: \"no-accounts\" };\n\n // A retry after a partial failure (no ledger row yet) reuses the drafts\n // already created for this key instead of duplicating them.\n const drafts: OutboundDraft[] = [];\n const ids: string[] = [];\n const covered = new Set<string | null>();\n const earlier = (\n await this.stores.posts.list({\n where: { tenantId, sourceKind: \"manual\", sourceEventId: key },\n })\n ).filter((row) => row.tenantId === tenantId);\n for (const row of earlier) {\n const view = await this.view(tenantId, row, settings);\n covered.add(view.accountId);\n ids.push(row.id as string);\n drafts.push(view);\n }\n for (const account of accounts) {\n if (covered.has(account.id as string)) continue;\n const post = await this.social.socialPosts.createDraft({\n socialAccountId: account.id as string,\n postType: \"text\",\n title: `${OUTBOUND_POST_MARKER}manual:${key}`,\n description: text,\n linkUrl,\n tenantId,\n });\n let row;\n try {\n row = await this.stores.posts.create({\n tenantId,\n socialPostId: post.id as string,\n state: \"draft\",\n kind,\n sourceEventId: key,\n sourceKind: \"manual\",\n sourceUrl: linkUrl,\n claims,\n createdBy,\n });\n } catch (error) {\n await this.discardSocialDraft(post);\n throw error;\n }\n ids.push(row.id as string);\n drafts.push(await this.view(tenantId, row, settings));\n }\n await this.stores.events.create({\n tenantId,\n eventKey: ledgerKey,\n outcome: \"drafted\",\n outboundPostIds: ids,\n });\n return { outcome: \"drafted\", drafts };\n }),\n );\n }\n\n private async targetAccounts(\n tenantId: string,\n settings: OutboundSettings,\n ): Promise<GarrulaSocialAccount[]> {\n const wanted = (account: GarrulaSocialAccount): boolean =>\n Boolean(account.id) &&\n account.tenantId === tenantId &&\n (settings.accountIds.length === 0 || settings.accountIds.includes(account.id as string));\n const ready = (await this.social.socialAccounts.findReady()).filter(wanted);\n const collection = this.social.socialAccounts;\n if (!this.refreshAccount || typeof collection.findActive !== \"function\") return ready;\n\n // An OAuth 2 access token lapses every few hours, but an idle account is\n // only refreshed when something publishes, and nothing publishes without a\n // draft. Renew accounts that are unready for that reason alone.\n const readyIds = new Set(ready.map((account) => account.id));\n const accounts = [...ready];\n for (const account of (await collection.findActive()).filter(wanted)) {\n if (readyIds.has(account.id) || !isLapsedOnly(account)) continue;\n try {\n await this.refreshAccount(account);\n } catch {\n continue; // A failed renewal excludes only this account.\n }\n if (account.isReady) accounts.push(account);\n }\n return accounts;\n }\n\n // ---- drafts -----------------------------------------------------------\n\n private async requireRow(tenantId: string, id: string): Promise<GarrulaOutboundPost> {\n const rows = await this.stores.posts.list({ where: { id, tenantId } });\n const row = rows.find((item) => item.id === id && item.tenantId === tenantId);\n if (!row) throw new OutboundError(\"not-found\", \"No such outbound post for this tenant.\");\n return row;\n }\n\n private async loadPost(tenantId: string, row: GarrulaOutboundPost): Promise<SaveablePost | null> {\n if (!row.socialPostId) return null;\n const post = await this.social.socialPosts.get({ id: row.socialPostId }, { cache: false });\n return post && post.tenantId === tenantId ? post : null;\n }\n\n private async view(\n tenantId: string,\n row: GarrulaOutboundPost,\n settings: OutboundSettings,\n known?: SaveablePost | null,\n ): Promise<OutboundDraft> {\n const post = known === undefined ? await this.loadPost(tenantId, row) : known;\n const accountId = post?.socialAccountId ?? null;\n const policy = (accountId && settings.linkPolicy[accountId]) || settings.defaultLinkPolicy;\n return {\n id: row.id as string,\n tenantId,\n socialPostId: row.socialPostId as string,\n accountId,\n state: row.state as OutboundState,\n kind: row.kind as OutboundPostKind,\n text: post?.description ?? \"\",\n hashtags: post?.hashtags ?? [],\n claims: row.claims ?? [],\n linkUrl: policy === \"include\" ? (post?.linkUrl ?? row.sourceUrl ?? null) : null,\n sourceEventId: row.sourceEventId,\n sourceKind: row.sourceKind as OutboundSourceKind,\n createdBy: row.createdBy ?? null,\n scheduledAt: post?.scheduledAt ? new Date(post.scheduledAt) : null,\n publishedUrl: post?.platformUrl ?? null,\n error: post?.errorMessage ?? null,\n rejectedReason: row.rejectedReason ?? null,\n approvedBy: row.approvedBy ?? null,\n publishable: isFullyCited(row.claims),\n createdAt: row.created_at ?? null,\n };\n }\n\n listDrafts(\n tenantId: string,\n filter: { state?: OutboundState; kind?: OutboundPostKind; limit?: number } = {},\n ): Promise<OutboundDraft[]> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const where: Record<string, unknown> = { tenantId };\n if (filter.state) where.state = filter.state;\n if (filter.kind) where.kind = filter.kind;\n const rows = (\n await this.stores.posts.list({\n where,\n orderBy: \"created_at DESC\",\n limit: filter.limit,\n })\n ).filter((row) => row.tenantId === tenantId);\n const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n return Promise.all(rows.map((row) => this.view(tenantId, row, settings)));\n });\n }\n\n getDraft(tenantId: string, id: string): Promise<OutboundDraft> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.requireRow(tenantId, id);\n const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n return this.view(tenantId, row, settings);\n });\n }\n\n editDraft(\n tenantId: string,\n id: string,\n patch: { text?: string; claims?: DraftClaim[]; linkUrl?: string | null },\n ): Promise<OutboundDraft> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.requireRow(tenantId, id);\n const state = row.state as OutboundState;\n if (state === \"published\" || state === \"rejected\") {\n throw new OutboundError(\"illegal-transition\", `A ${state} post cannot be edited.`);\n }\n const social: Record<string, unknown> = {};\n if (patch.text !== undefined) {\n const text = String(patch.text).trim();\n const max = this.configFn().outboundMaxLength;\n if (!text) throw new OutboundError(\"invalid\", \"The post text cannot be empty.\");\n if (text.length > max) {\n throw new OutboundError(\"invalid\", `The post text is longer than ${max} characters.`);\n }\n social.description = text;\n }\n if (patch.linkUrl !== undefined) social.link_url = patch.linkUrl;\n if (patch.claims !== undefined) {\n if (!Array.isArray(patch.claims))\n throw new OutboundError(\"invalid\", \"Claims must be a list.\");\n row.claims = patch.claims.map((claim) => ({\n text: String(claim.text ?? \"\").trim(),\n evidence: (claim.evidence ?? []).map((item) => ({\n type: item.type === \"changelog\" ? \"changelog\" : \"url\",\n ref: String(item.ref ?? \"\").trim(),\n })),\n }));\n }\n // An edit withdraws any approval: the changed text must be approved again.\n // The social post is written first and conditionally, so an edit that\n // races an in-flight publish changes neither record.\n const back = state !== \"draft\";\n await this.updateSocialPost(tenantId, row, {\n ...social,\n ...(back ? { status: socialStatusFor(\"draft\"), scheduled_at: null } : {}),\n });\n if (back) row.state = \"draft\";\n await row.save();\n return this.getDraft(tenantId, id);\n });\n }\n\n approve(tenantId: string, id: string, approvedBy = \"user\"): Promise<OutboundDraft> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.requireRow(tenantId, id);\n if (!isFullyCited(row.claims)) {\n throw new OutboundError(\"uncited\", \"Every claim needs evidence before a post is approved.\");\n }\n await this.transition(tenantId, row, \"approved\", { approvedBy });\n return this.getDraft(tenantId, id);\n });\n }\n\n reject(tenantId: string, id: string, reason = \"\"): Promise<OutboundDraft> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.requireRow(tenantId, id);\n await this.transition(tenantId, row, \"rejected\", { rejectedReason: reason || null });\n return this.getDraft(tenantId, id);\n });\n }\n\n /** A failed post goes back to approved so the next run publishes it again. */\n retry(tenantId: string, id: string): Promise<OutboundDraft> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.requireRow(tenantId, id);\n if (row.state !== \"failed\") {\n throw new OutboundError(\"illegal-transition\", \"Only a failed post can be retried.\");\n }\n if (!isFullyCited(row.claims)) {\n throw new OutboundError(\"uncited\", \"Every claim needs evidence before a post is retried.\");\n }\n await this.transition(tenantId, row, \"approved\", {});\n return this.getDraft(tenantId, id);\n });\n }\n\n schedule(tenantId: string, id: string, at: Date): Promise<OutboundDraft> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n if (!(at instanceof Date) || Number.isNaN(at.getTime())) {\n throw new OutboundError(\"invalid\", \"A schedule needs a valid date.\");\n }\n const row = await this.requireRow(tenantId, id);\n if (!isFullyCited(row.claims)) {\n throw new OutboundError(\n \"uncited\",\n \"Every claim needs evidence before a post is scheduled.\",\n );\n }\n await this.transition(tenantId, row, \"scheduled\", {}, { scheduled_at: at });\n return this.getDraft(tenantId, id);\n });\n }\n\n /** Approved or scheduled posts of the tenant whose time has come. */\n async dueForPublish(tenantId: string, now: Date): Promise<GarrulaSocialPost[]> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const rows = (\n await this.stores.posts.list({ where: { tenantId }, orderBy: \"created_at ASC\" })\n ).filter(\n (row) =>\n row.tenantId === tenantId && (row.state === \"approved\" || row.state === \"scheduled\"),\n );\n const due: GarrulaSocialPost[] = [];\n for (const row of rows) {\n const post = await this.loadPost(tenantId, row);\n if (!post) continue;\n const at = post.scheduledAt ? new Date(post.scheduledAt) : null;\n if (!at || at.getTime() <= now.getTime()) due.push(post);\n }\n return due;\n });\n }\n\n /** The tenant's post to publish now: it must be approved or scheduled. */\n async postForPublish(tenantId: string, id: string): Promise<GarrulaSocialPost> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.requireRow(tenantId, id);\n if (row.state !== \"approved\" && row.state !== \"scheduled\") {\n throw new OutboundError(\n \"not-approved\",\n \"Only an approved or scheduled post can be published.\",\n );\n }\n const post = await this.loadPost(tenantId, row);\n if (!post) throw new OutboundError(\"not-found\", \"The social post is missing.\");\n return post;\n });\n }\n\n outboundIdForPost(tenantId: string, socialPostId: string): Promise<string | null> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const row = await this.findRowForPost(tenantId, socialPostId);\n return row?.id ?? null;\n });\n }\n\n private async discardSocialDraft(post: GarrulaSocialPost): Promise<void> {\n try {\n await (post as unknown as { delete(): Promise<unknown> }).delete();\n } catch {\n // The marker keeps the gate refusing it if the delete also failed.\n }\n }\n\n private async findRowForPost(\n tenantId: string,\n socialPostId: string,\n ): Promise<GarrulaOutboundPost | null> {\n const rows = await this.stores.posts.list({ where: { tenantId, socialPostId } });\n return (\n rows.find((row) => row.tenantId === tenantId && row.socialPostId === socialPostId) ?? null\n );\n }\n\n private async transition(\n tenantId: string,\n row: GarrulaOutboundPost,\n to: OutboundState,\n extra: { approvedBy?: string; rejectedReason?: string | null },\n social: Record<string, unknown> = {},\n ): Promise<void> {\n const from = row.state as OutboundState;\n if (!OUTBOUND_STATES.includes(from) || !canTransition(from, to)) {\n throw new OutboundError(\"illegal-transition\", `A ${from} post cannot become ${to}.`);\n }\n // The social post is written first, conditionally on it not being claimed\n // for publishing; when that fails neither record has changed.\n await this.updateSocialPost(tenantId, row, { status: socialStatusFor(to), ...social });\n row.state = to;\n if (extra.approvedBy !== undefined) row.approvedBy = extra.approvedBy;\n if (extra.rejectedReason !== undefined) row.rejectedReason = extra.rejectedReason;\n try {\n await row.save();\n } catch (error) {\n row.state = from;\n await this.updateSocialPost(tenantId, row, { status: socialStatusFor(from) }).catch(\n () => undefined,\n );\n throw error;\n }\n }\n\n /**\n * Mirror onto the SocialPost with a conditional update: it never overwrites\n * a post a publisher has claimed (`publishing`). A refused write throws\n * `in-flight` (claimed) or `not-found` (missing) and changes nothing.\n */\n private async updateSocialPost(\n tenantId: string,\n row: GarrulaOutboundPost,\n data: Record<string, unknown>,\n ): Promise<void> {\n if (!row.socialPostId || Object.keys(data).length === 0) return;\n const { socialPosts } = this.social;\n const result = await socialPosts.db.update(\n socialPosts.tableName,\n { id: row.socialPostId, tenant_id: tenantId, \"status not in\": [\"publishing\"] },\n { ...data, updated_at: new Date() },\n );\n if (result.affected === 1) return;\n const current = await this.loadPost(tenantId, row);\n if (current && current.status === \"publishing\") {\n throw new OutboundError(\n \"in-flight\",\n \"This post is being published right now, so it was not changed.\",\n );\n }\n throw new OutboundError(\"not-found\", \"The social post for this draft is missing.\");\n }\n\n /**\n * Record a publish that failed before the gate (account, credentials, token\n * refresh, media) so no spend reservation exists to settle it: the approved\n * or scheduled post becomes `failed` and can be retried after repair.\n */\n failUnreserved(tenantId: string, socialPostId: string): Promise<void> {\n return withLock(tenantId, () =>\n withTenant({ tenantId }, async () => {\n const row = await this.findRowForPost(tenantId, socialPostId);\n if (row && (row.state === \"approved\" || row.state === \"scheduled\")) {\n row.state = \"failed\";\n await row.save();\n }\n }),\n );\n }\n\n // ---- spend ------------------------------------------------------------\n\n private async monthEntries(tenantId: string, month: string): Promise<GarrulaSpendEntry[]> {\n return (await this.stores.spend.list({ where: { tenantId, month } })).filter(\n (entry) => entry.tenantId === tenantId && entry.month === month,\n );\n }\n\n getSpend(tenantId: string, month?: string): Promise<SpendSummary> {\n assertAmbientTenant(tenantId);\n return withTenant({ tenantId }, async () => {\n const key = month ?? monthKey(this.nowFn());\n const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n const entries = await this.monthEntries(tenantId, key);\n const spent = entries\n .filter((entry) => entry.status !== \"released\")\n .reduce((sum, entry) => sum + entry.costMicros, 0);\n return {\n tenantId,\n month: key,\n capMicros: settings.monthlyCapMicros,\n spentMicros: spent,\n remainingMicros: Math.max(0, settings.monthlyCapMicros - spent),\n paused: settings.paused,\n entries: entries.map((entry) => ({\n id: entry.id as string,\n month: entry.month,\n postId: entry.socialPostId,\n costMicros: entry.costMicros,\n source: entry.source as CostSource,\n status: entry.status as \"reserved\" | \"recorded\" | \"released\",\n createdAt: entry.created_at ?? null,\n })),\n };\n });\n }\n\n // ---- publish gate -----------------------------------------------------\n\n /**\n * The server-side checks every publish passes immediately before the\n * adapter call: tenant, approval state, evidence, pause, link policy and\n * the monthly cap. On success a spend reservation is held (atomically with\n * the cap check) until {@link finish}.\n */\n beforeSend(post: GarrulaSocialPost, platform: string): Promise<GateDecision> {\n const tenantId = post.tenantId?.trim();\n const refuse = (code: OutboundRefusal[\"code\"], message: string): GateDecision => ({\n ok: false,\n refusal: { code, message },\n });\n if (!tenantId) return Promise.resolve(refuse(\"invalid\", \"The post has no tenant.\"));\n const ambient = getTenantId()?.trim();\n if (ambient && ambient !== tenantId) {\n return Promise.resolve(refuse(\"invalid\", \"The post belongs to another tenant.\"));\n }\n\n return withLock(tenantId, () =>\n withTenant({ tenantId }, async (): Promise<GateDecision> => {\n const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));\n if (settings.paused) {\n return refuse(\"paused\", \"Posting is paused for this tenant, so nothing was posted.\");\n }\n\n const row = post.id ? await this.findRowForPost(tenantId, post.id) : null;\n let linkUrl: string | null = post.linkUrl ?? null;\n if (row) {\n if (row.state !== \"approved\" && row.state !== \"scheduled\") {\n return refuse(\"not-approved\", `This post is ${row.state}, not approved.`);\n }\n if (!isFullyCited(row.claims)) {\n return refuse(\"uncited\", \"A claim in this post has no evidence, so it was not posted.\");\n }\n const accountId = post.socialAccountId ?? \"\";\n const policy = settings.linkPolicy[accountId] ?? settings.defaultLinkPolicy;\n linkUrl = policy === \"include\" ? (post.linkUrl ?? row.sourceUrl ?? null) : null;\n } else if (isOutboundMarked(post)) {\n // Outbound drafting created this post but its approval record is\n // missing: never skip approval and evidence.\n return refuse(\n \"not-approved\",\n \"This post was drafted by the outbound pipeline but has no approval record, so it was not posted.\",\n );\n }\n\n const config = this.configFn();\n const estimate = estimateCost(config.outboundRates, platform, linkUrl !== null);\n const month = monthKey(this.nowFn());\n const entries = await this.monthEntries(tenantId, month);\n const spent = entries\n .filter((entry) => entry.status !== \"released\")\n .reduce((sum, entry) => sum + entry.costMicros, 0);\n const valid = (n: number) => Number.isFinite(n) && n >= 0;\n if (!valid(estimate.micros) || !valid(settings.monthlyCapMicros) || !valid(spent)) {\n return refuse(\n \"invalid\",\n \"The cost estimate or spend cap is not a valid amount, so nothing was posted.\",\n );\n }\n if (\n spent >= settings.monthlyCapMicros ||\n spent + estimate.micros > settings.monthlyCapMicros\n ) {\n return refuse(\n \"cap-reached\",\n \"The monthly posting spend cap is reached, so nothing was posted.\",\n );\n }\n\n const entry = await this.stores.spend.create({\n tenantId,\n month,\n socialPostId: post.id ?? null,\n costMicros: estimate.micros,\n source: estimate.source,\n status: \"reserved\",\n });\n return {\n ok: true,\n linkUrl,\n reservation: {\n tenantId,\n entryId: entry.id as string,\n month,\n estimateMicros: estimate.micros,\n estimateSource: estimate.source,\n outboundId: row?.id ?? null,\n },\n };\n }),\n );\n }\n\n /**\n * Settle a reservation after the publish. Spend is recorded whenever the\n * platform was reached (adapter cost, else the rate table; a dry run costs\n * nothing) and released otherwise; the outbound state follows the outcome.\n */\n finish(reservation: SpendReservation, outcome: SentOutcome): Promise<void> {\n const { tenantId } = reservation;\n assertAmbientTenant(tenantId);\n return withLock(tenantId, () =>\n withTenant({ tenantId }, async () => {\n const entries = await this.monthEntries(tenantId, reservation.month);\n const entry = entries.find((item) => item.id === reservation.entryId);\n if (entry) {\n const result = outcome.result;\n if (!result) {\n entry.status = \"released\";\n entry.costMicros = 0;\n } else if (result.status === \"dry_run\" || result.status === \"staged\") {\n entry.status = \"recorded\";\n entry.costMicros = 0;\n entry.source = \"unpriced\";\n } else {\n const reported = adapterCostMicros(result);\n entry.status = \"recorded\";\n entry.costMicros = reported ?? reservation.estimateMicros;\n entry.source = reported !== null ? \"adapter\" : reservation.estimateSource;\n }\n await entry.save();\n }\n\n if (reservation.outboundId) {\n const row = await this.requireRow(tenantId, reservation.outboundId).catch(() => null);\n if (row && (row.state === \"approved\" || row.state === \"scheduled\")) {\n row.state = outcome.result || outcome.success ? \"published\" : \"failed\";\n await row.save();\n }\n }\n }),\n );\n }\n}\n","import {\n Agent,\n type AgentAdminRoute,\n type AgentOptions,\n type AgentUISlots,\n} from \"@happyvertical/smrt-agents\";\nimport { smrt } from \"@happyvertical/smrt-core\";\nimport {\n type PostStatus,\n type RawAnalyticsPayload,\n SocialAccountCollection,\n type SocialPlatformType,\n SocialPostAnalyticsSnapshotCollection,\n SocialPostCollection,\n} from \"@happyvertical/smrt-social\";\nimport { getTenantId, withTenant } from \"@happyvertical/smrt-tenancy\";\nimport { getSocial, SocialError } from \"@happyvertical/social\";\nimport {\n DEFAULT_GARRULA_CONFIG,\n type GarrulaConfig,\n resolveGarrulaConfig,\n tenantBlockedMessage,\n tenantRequiredMessage,\n} from \"./config.js\";\nimport {\n GarrulaReconnectError,\n isAuthError,\n isRefreshRejected,\n mergeRefreshedCredentials,\n parseExpiry,\n platformLabel,\n refreshKind,\n refreshThreadsToken,\n} from \"./credentials.js\";\nimport {\n createOutboundStores,\n isOutboundMarked,\n OutboundService,\n type OutboundStores,\n type SpendReservation,\n} from \"./outbound/service.js\";\nimport type {\n CreateDraftInput,\n CreateDraftResult,\n DraftClaim,\n DraftingAI,\n IngestResult,\n OutboundDraft,\n OutboundPostKind,\n OutboundSettings,\n OutboundSettingsPatch,\n OutboundState,\n PublishDueResult,\n SourceEvent,\n SpendSummary,\n} from \"./outbound/types.js\";\nimport type {\n AnalyticsSyncResult,\n ArticleVideoPostRequest,\n GarrulaCollections,\n GarrulaHost,\n GarrulaSocialAccount,\n GarrulaSocialAdapter,\n GarrulaSocialConfig,\n GarrulaSocialPost,\n GarrulaTargetPlatform,\n PublishPostOptions,\n PublishPostResult,\n SocialFactory,\n StoryLinkPostRequest,\n} from \"./types.js\";\n\nexport interface GarrulaOptions extends AgentOptions {\n collections?: GarrulaCollections;\n socialFactory?: SocialFactory;\n /** Overrides the host hooks registered with {@link setGarrulaHost}. */\n host?: GarrulaHost;\n /** Overrides the configuration registered with {@link setGarrulaConfig}. */\n garrula?: Partial<GarrulaConfig>;\n /**\n * Model client for drafting release posts (default: the agent's own `ai`).\n * Tests pass a fake.\n */\n draftingAI?: DraftingAI;\n /** Outbound persistence; created from the agent's database on initialize. */\n outboundStores?: OutboundStores;\n /**\n * TEST ONLY. Skips the outbound gate (pause switch, spend cap, approval,\n * evidence) when no outbound stores are available. Without it, `initialize()`\n * throws if the gate cannot be built, so a host never publishes ungated by\n * accident.\n */\n unsafeDisableOutboundGate?: boolean;\n /** Clock for spend months and due times (tests). */\n now?: () => Date;\n}\n\n/** Per-publish state shared between the publish path and its outbound gate. */\ninterface SendContext {\n reservation?: SpendReservation;\n sent?: { status?: string; cost?: unknown };\n}\n\n/**\n * Host hooks shared by every Garrula instance in this process, including the\n * ones the job runner constructs for scheduled posts. The host application\n * registers them once at startup with {@link setGarrulaHost}.\n */\nlet registeredHost: GarrulaHost = {};\n\nexport function setGarrulaHost(host: GarrulaHost): void {\n registeredHost = host;\n}\n\n/**\n * Configuration shared by every Garrula instance in this process, registered\n * once at startup like the host hooks. Unset keys keep the neutral defaults.\n */\nlet registeredConfig: Partial<GarrulaConfig> = {};\n\nexport function setGarrulaConfig(config: Partial<GarrulaConfig>): void {\n registeredConfig = config;\n}\n\n/** Why a post was not sent because its tenant may not publish (default wording). */\nexport const GARRULA_TENANT_BLOCKED_MESSAGE = tenantBlockedMessage(DEFAULT_GARRULA_CONFIG);\n\n/** Why a post was not sent because another publish already has it. */\nexport const GARRULA_POST_BUSY_MESSAGE =\n \"This post is already being posted or is no longer waiting to be posted.\";\n\n/** Why a post was not sent because its account is switched off. */\nexport const GARRULA_ACCOUNT_INACTIVE_MESSAGE =\n \"This social account is switched off, so nothing was posted.\";\n\n/** Every status a post may be published from. */\nconst PUBLISHABLE_STATUSES: PostStatus[] = [\"draft\", \"approved\", \"scheduled\", \"failed\"];\n\n/** Statuses of posts that {@link Garrula.run} publishes when due. */\nconst DUE_STATUSES: PostStatus[] = [\"approved\", \"scheduled\"];\n\n@smrt({\n agent: {\n icon: \"share-2\",\n tier: \"standard\",\n description: \"Social media publishing, account health, and post analytics\",\n },\n // Garrula sets no REST surface, so since smrt 0.57 it inherits the Agent\n // base's closed api. Both CLI commands run in process (agent runtime and\n // background worker), so they are acknowledged rather than opened over REST.\n cli: { include: [\"run\", \"syncAnalytics\"], skipApiCheck: [\"run\", \"syncAnalytics\"] },\n mcp: { include: [\"createStoryLinkPosts\", \"createArticleVideoPosts\"] },\n})\nexport class Garrula extends Agent { static __smrtPackage__ = \"@happyvertical/garrula\";\n static override uiSlots: AgentUISlots = {\n queue: {\n id: \"queue\",\n label: \"Dashboard\",\n description: \"Review social posts, status, and latest stats\",\n icon: \"list-checks\",\n order: 1,\n },\n settings: {\n id: \"settings\",\n label: \"Settings\",\n description: \"Connect and manage social accounts\",\n icon: \"settings\",\n order: 2,\n },\n };\n\n static override adminRoutes: AgentAdminRoute[] = [\n { path: \"queue\", component: \"QueuePanel\" },\n { path: \"settings\", component: \"SettingsPanel\" },\n ];\n\n private socialAccounts!: GarrulaCollections[\"socialAccounts\"];\n private socialPosts!: GarrulaCollections[\"socialPosts\"];\n private analyticsSnapshots!: GarrulaCollections[\"analyticsSnapshots\"];\n private socialFactory?: SocialFactory;\n private hostOverride?: GarrulaHost;\n private configOverride?: Partial<GarrulaConfig>;\n private draftingAI?: DraftingAI;\n private outboundStores?: OutboundStores;\n private unsafeDisableOutboundGate = false;\n private outbound?: OutboundService;\n private nowFn: () => Date = () => new Date();\n /** The Agent base's persisted config; Garrula's own settings are {@link garrulaConfig}. */\n protected config: Record<string, never> = {};\n\n constructor(options: GarrulaOptions = {}) {\n super(options);\n this.socialFactory = options.socialFactory;\n this.hostOverride = options.host;\n this.configOverride = options.garrula;\n this.draftingAI = options.draftingAI;\n this.outboundStores = options.outboundStores;\n this.unsafeDisableOutboundGate = options.unsafeDisableOutboundGate === true;\n if (options.now) this.nowFn = options.now;\n\n if (options.collections) {\n this.socialAccounts = options.collections.socialAccounts;\n this.socialPosts = options.collections.socialPosts;\n this.analyticsSnapshots = options.collections.analyticsSnapshots;\n }\n }\n\n async initialize(): Promise<this> {\n await super.initialize();\n\n let ownCollections = false;\n if (!this.socialAccounts || !this.socialPosts || !this.analyticsSnapshots) {\n const opts = { db: this.options.db, ai: this.options.ai };\n this.socialAccounts = await SocialAccountCollection.create(opts);\n this.socialPosts = await SocialPostCollection.create(opts);\n this.analyticsSnapshots = await SocialPostAnalyticsSnapshotCollection.create(opts);\n ownCollections = true;\n }\n\n // The outbound pipeline (pause switch, spend cap, cited drafts) runs on\n // the agent's own database, or on injected `outboundStores`. A host that\n // injects only collections must also inject `outboundStores` (or opt out,\n // for tests, with `unsafeDisableOutboundGate`); otherwise publishing would\n // silently run without the gate.\n if (!this.outbound && (ownCollections || this.outboundStores)) {\n this.outboundStores ??= await createOutboundStores({\n db: this.options.db,\n ai: this.options.ai,\n });\n this.outbound = new OutboundService({\n stores: this.outboundStores,\n social: { socialAccounts: this.socialAccounts, socialPosts: this.socialPosts },\n config: () => this.garrulaConfig,\n ai: () => this.draftingAI ?? (this.ai as unknown as DraftingAI),\n now: () => this.nowFn(),\n refreshAccount: (account) => this.renewLapsedAccount(account),\n });\n }\n if (!this.outbound && !this.unsafeDisableOutboundGate) {\n throw new Error(\n \"Garrula has no outbound gate: pass `outboundStores` (or let it use its own database). \" +\n \"`unsafeDisableOutboundGate: true` disables it and is for tests only.\",\n );\n }\n\n return this;\n }\n\n private get hostHooks(): GarrulaHost {\n return this.hostOverride ?? registeredHost;\n }\n\n /** The host's configuration over the neutral defaults. */\n get garrulaConfig(): GarrulaConfig {\n return resolveGarrulaConfig({ ...registeredConfig, ...this.configOverride });\n }\n\n /**\n * Publish every post that is due (scheduled time reached, or approved).\n * Posts of an organization that may not publish right now are left as they\n * are and picked up by a later run.\n */\n async run(): Promise<void> {\n const duePosts = await this.socialPosts.findDueForPublish(new Date());\n let published = 0;\n let failed = 0;\n let skipped = 0;\n for (const post of duePosts) {\n const result = await this.publishClaimed(post, { claimFrom: DUE_STATUSES });\n if (result.success) published++;\n else if (result.skipped) skipped++;\n else failed++;\n }\n if (duePosts.length > 0) {\n this.logger.info(\"Published due social posts\", {\n due: duePosts.length,\n published,\n failed,\n skipped,\n });\n }\n }\n\n async createStoryLinkPosts(request: StoryLinkPostRequest): Promise<GarrulaSocialPost[]> {\n const tenantId = this.resolveRequestTenantId(request.tenantId);\n\n return withTenant({ tenantId }, async () => {\n const accounts = await this.resolveTargetAccounts(\n request.targets ?? this.garrulaConfig.storyLinkTargets,\n tenantId,\n );\n\n return Promise.all(\n accounts.map((account) =>\n this.socialPosts.createDraft({\n socialAccountId: this.requireAccountId(account),\n contentId: request.contentId,\n postType: \"link\",\n title: request.title,\n description: request.excerpt ?? request.title,\n hashtags: this.mergeHashtags(account, request.hashtags),\n linkUrl: request.url,\n scheduledAt: request.scheduledAt ?? null,\n createdByUserId: request.createdByUserId ?? null,\n tenantId,\n }),\n ),\n );\n });\n }\n\n async createArticleVideoPosts(request: ArticleVideoPostRequest): Promise<GarrulaSocialPost[]> {\n const tenantId = this.resolveRequestTenantId(request.tenantId);\n\n return withTenant({ tenantId }, async () => {\n const readyAccounts = await this.resolveTargetAccounts(\n request.targets ?? this.garrulaConfig.articleVideoTargets,\n tenantId,\n );\n const accounts = this.selectAccounts(readyAccounts, request.accountIds);\n\n return Promise.all(\n accounts.map((account) =>\n this.socialPosts.createDraft({\n socialAccountId: this.requireAccountId(account),\n contentId: request.contentId,\n videoContentId: request.videoContentId ?? null,\n postType: \"video\",\n title: request.title,\n description: request.description ?? request.title,\n hashtags: this.mergeHashtags(account, request.hashtags),\n linkUrl: request.url ?? null,\n mediaUrl: request.mediaUrl,\n scheduledAt: request.scheduledAt ?? null,\n createdByUserId: request.createdByUserId ?? null,\n tenantId,\n }),\n ),\n );\n });\n }\n\n // ---- Outbound release pipeline -------------------------------------------\n //\n // Every method acts for one tenant: `options.tenantId`, else the tenant of\n // the current `withTenant` context (a different explicit tenant is refused).\n // Records of another tenant are reported as not found.\n\n private outboundFor(options?: { tenantId?: string }): {\n service: OutboundService;\n tenantId: string;\n } {\n if (!this.outbound) {\n throw new Error(\"The outbound pipeline is not initialized; call initialize() first.\");\n }\n return { service: this.outbound, tenantId: this.resolveRequestTenantId(options?.tenantId) };\n }\n\n /**\n * Offer a release/changelog event as a post candidate. Events that match no\n * enabled source rule, or were seen before, produce nothing; a match is\n * drafted in the tenant's persona with a cited claim list.\n */\n async ingestSourceEvent(\n event: SourceEvent,\n options?: { tenantId?: string },\n ): Promise<IngestResult> {\n const { service, tenantId } = this.outboundFor(options);\n return service.ingestSourceEvent(tenantId, event);\n }\n\n /**\n * Create a pending-approval draft from supplied text and evidence. Tenant\n * scoped, idempotent by `idempotencyKey`, records `createdBy`, and never\n * approves or publishes: a person must approve it and its claims need\n * evidence before it can publish. The host authorizes the caller.\n */\n async createDraft(\n input: CreateDraftInput,\n options?: { tenantId?: string },\n ): Promise<CreateDraftResult> {\n const { service, tenantId } = this.outboundFor(options);\n return service.createDraft(tenantId, input);\n }\n\n async listDrafts(\n filter: { state?: OutboundState; kind?: OutboundPostKind; limit?: number } = {},\n options?: { tenantId?: string },\n ): Promise<OutboundDraft[]> {\n const { service, tenantId } = this.outboundFor(options);\n return service.listDrafts(tenantId, filter);\n }\n\n /** Edit text, claims or link. An edit withdraws approval (back to draft). */\n async editDraft(\n id: string,\n patch: { text?: string; claims?: DraftClaim[]; linkUrl?: string | null },\n options?: { tenantId?: string },\n ): Promise<OutboundDraft> {\n const { service, tenantId } = this.outboundFor(options);\n return service.editDraft(tenantId, id, patch);\n }\n\n async approve(\n id: string,\n options?: { tenantId?: string; approvedBy?: string },\n ): Promise<OutboundDraft> {\n const { service, tenantId } = this.outboundFor(options);\n return service.approve(tenantId, id, options?.approvedBy);\n }\n\n async reject(\n id: string,\n reason?: string,\n options?: { tenantId?: string },\n ): Promise<OutboundDraft> {\n const { service, tenantId } = this.outboundFor(options);\n return service.reject(tenantId, id, reason);\n }\n\n /** Send a failed post back to approved so the next run publishes it again. */\n async retry(id: string, options?: { tenantId?: string }): Promise<OutboundDraft> {\n const { service, tenantId } = this.outboundFor(options);\n return service.retry(tenantId, id);\n }\n\n async schedule(id: string, at: Date, options?: { tenantId?: string }): Promise<OutboundDraft> {\n const { service, tenantId } = this.outboundFor(options);\n return service.schedule(tenantId, id, at);\n }\n\n /**\n * Publish the tenant's approved posts whose time has come (scheduled time\n * reached, or approved without one). Each goes through the same gate as any\n * publish: a pause or spend cap refuses it without calling the platform.\n */\n async publishDue(options?: { tenantId?: string; now?: Date }): Promise<PublishDueResult[]> {\n const { service, tenantId } = this.outboundFor(options);\n const due = await service.dueForPublish(tenantId, options?.now ?? this.nowFn());\n const results: PublishDueResult[] = [];\n for (const post of due) {\n results.push(await this.publishOutboundPost(service, tenantId, post));\n }\n return results;\n }\n\n /** Publish one approved or scheduled draft now. */\n async publishNow(id: string, options?: { tenantId?: string }): Promise<PublishDueResult> {\n const { service, tenantId } = this.outboundFor(options);\n const post = await service.postForPublish(tenantId, id);\n return this.publishOutboundPost(service, tenantId, post);\n }\n\n private async publishOutboundPost(\n service: OutboundService,\n tenantId: string,\n post: GarrulaSocialPost,\n ): Promise<PublishDueResult> {\n const outboundId = await service.outboundIdForPost(tenantId, post.id ?? \"\");\n const result = await this.publishClaimed(post, { claimFrom: DUE_STATUSES });\n return {\n postId: result.postId,\n outboundId,\n success: result.success,\n skipped: result.skipped,\n refusal: result.refusal as PublishDueResult[\"refusal\"],\n error: result.error,\n };\n }\n\n async getSettings(options?: { tenantId?: string }): Promise<OutboundSettings> {\n const { service, tenantId } = this.outboundFor(options);\n return service.getSettings(tenantId);\n }\n\n async updateSettings(\n patch: OutboundSettingsPatch,\n options?: { tenantId?: string },\n ): Promise<OutboundSettings> {\n const { service, tenantId } = this.outboundFor(options);\n return service.updateSettings(tenantId, patch);\n }\n\n /** Stop all publishing for the tenant, effective on the very next publish. */\n async pause(options?: { tenantId?: string }): Promise<OutboundSettings> {\n return this.updateSettings({ paused: true }, options);\n }\n\n async resume(options?: { tenantId?: string }): Promise<OutboundSettings> {\n return this.updateSettings({ paused: false }, options);\n }\n\n /** Spend ledger and cap for a month (`YYYY-MM`, default: this month, UTC). */\n async getSpend(options?: { tenantId?: string; month?: string }): Promise<SpendSummary> {\n const { service, tenantId } = this.outboundFor(options);\n return service.getSpend(tenantId, options?.month);\n }\n\n /** Record the failure on the post, then let the host tell the poster. */\n private async recordFailure(post: GarrulaSocialPost, error: Error | string): Promise<void> {\n await this.socialPosts.recordPublishFailure(post, error);\n const onPublishFailed = this.hostHooks.onPublishFailed;\n if (!onPublishFailed) return;\n try {\n await onPublishFailed(post, error instanceof Error ? error.message : error);\n } catch (hookError) {\n this.logger.warn(\"Social publish failure hook failed\", {\n postId: post.id,\n error: hookError,\n });\n }\n }\n\n /**\n * Publish one post. The post is first claimed with a single conditional\n * update (`status` → `publishing`, only from `options.claimFrom`), so\n * overlapping runs or a double-clicked retry never send it twice. A post\n * of an organization that may not publish is left as it is; after the\n * claim, every failure is recorded on the post (never left `publishing`).\n */\n async publishPost(\n post: GarrulaSocialPost,\n options: PublishPostOptions = {},\n ): Promise<PublishPostResult> {\n // A request-facing call acts for the ambient tenant: another tenant's post\n // is refused before anything is claimed. Only `run()` (the background job)\n // publishes across tenants, through {@link publishClaimed}.\n const postTenant = this.normalizeTenantId(post.tenantId);\n if (postTenant) this.resolveRequestTenantId(postTenant);\n return this.publishClaimed(post, options);\n }\n\n /** The trusted publish path: enters the post's own tenant (see {@link publishPost}). */\n private async publishClaimed(\n post: GarrulaSocialPost,\n options: PublishPostOptions = {},\n ): Promise<PublishPostResult> {\n const tenantId = this.normalizeTenantId(post.tenantId);\n const postId = post.id ?? \"\";\n const previousStatus = post.status;\n if (!tenantId) {\n const error = new Error(\"Cannot publish social post without tenant context\");\n await this.recordFailure(post, error);\n return {\n postId,\n platform: \"unknown\",\n success: false,\n error: error.message,\n };\n }\n\n if (this.hostHooks.canPublish && !(await this.hostHooks.canPublish(tenantId))) {\n return {\n postId,\n platform: \"unknown\",\n success: false,\n error: tenantBlockedMessage(this.garrulaConfig),\n skipped: \"tenant-blocked\",\n };\n }\n\n const claimed = await this.claimForPublish(\n post,\n tenantId,\n options.claimFrom ?? PUBLISHABLE_STATUSES,\n );\n if (!claimed) {\n return {\n postId,\n platform: \"unknown\",\n success: false,\n error: GARRULA_POST_BUSY_MESSAGE,\n skipped: \"post-busy\",\n };\n }\n\n const context: SendContext = {};\n let result: PublishPostResult;\n try {\n result = await withTenant({ tenantId }, () =>\n this.publishPostInTenant(post, context, previousStatus),\n );\n } catch (error) {\n await this.settleOutbound(tenantId, postId, context, false, errorMessage(error));\n throw error;\n }\n await this.settleOutbound(\n tenantId,\n postId,\n context,\n result.success,\n result.error,\n result.skipped !== undefined,\n );\n return result;\n }\n\n /** Record spend and the outbound state once a publish attempt is over. */\n private async settleOutbound(\n tenantId: string,\n postId: string,\n context: SendContext,\n success: boolean,\n error?: string,\n skipped = false,\n ): Promise<void> {\n if (!this.outbound) return;\n try {\n // Settle inside the post's own tenant (run() publishes across tenants).\n await withTenant({ tenantId }, async () => {\n if (context.reservation) {\n await this.outbound?.finish(context.reservation, {\n result: context.sent ?? null,\n success,\n error,\n });\n } else if (!success && !skipped && postId) {\n // Failed before the gate, so no reservation exists to settle it.\n await this.outbound?.failUnreserved(tenantId, postId);\n }\n });\n } catch (settleError) {\n // The reservation stays counted against the cap, which errs on the side\n // of not overspending; say so loudly.\n this.logger.error(\"Could not settle the outcome of a publish\", {\n entryId: context.reservation?.entryId,\n postId,\n error: errorMessage(settleError),\n });\n }\n }\n\n /** Put a refused post back where it was, so a later run can try again. */\n private async releaseClaim(post: GarrulaSocialPost, status: PostStatus | undefined) {\n if (!post.id || !status) return;\n await this.socialPosts.db.update(\n this.socialPosts.tableName,\n { id: post.id, tenant_id: post.tenantId, status: \"publishing\" },\n { status, updated_at: new Date() },\n );\n }\n\n /**\n * Atomically move the post to `publishing` if it is still in one of\n * `from`. Returns false when another publisher got there first.\n *\n * The claim writes the row directly, so the caller's copy of the post keeps\n * the old revision; {@link loadClaimedPost} re-reads it before anything is\n * saved.\n *\n * TODO(happyvertical/smrt#3300): a `SocialPostCollection.claimForPublish`\n * that returns the claimed post belongs next to\n * `recordPublishSuccess`/`recordPublishFailure`; adopt it and drop the\n * re-read.\n */\n private async claimForPublish(\n post: GarrulaSocialPost,\n tenantId: string,\n from: PostStatus[],\n ): Promise<boolean> {\n if (!post.id || from.length === 0) return false;\n const result = await this.socialPosts.db.update(\n this.socialPosts.tableName,\n { id: post.id, tenant_id: tenantId, \"status in\": from },\n { status: \"publishing\", error_message: null, updated_at: new Date() },\n );\n if (result.affected !== 1) return false;\n post.status = \"publishing\";\n post.errorMessage = null;\n return true;\n }\n\n /**\n * Re-read a post the claim just moved to `publishing`, so the revision the\n * outcome is saved against is the one the claim wrote. Saving the caller's\n * copy instead always fails with `RUNTIME_REVISION_CONFLICT`.\n */\n private async loadClaimedPost(post: GarrulaSocialPost): Promise<GarrulaSocialPost> {\n const claimed = post.id ? await this.socialPosts.get({ id: post.id }, { cache: false }) : null;\n if (!claimed) {\n throw new Error(\"This post could not be read back after it was claimed.\");\n }\n return claimed;\n }\n\n /**\n * Runs after the claim: every outcome is recorded on the post, and a\n * failure to record never hides why the publish itself failed.\n */\n private async publishPostInTenant(\n claimedPost: GarrulaSocialPost,\n context: SendContext,\n previousStatus: PostStatus | undefined,\n ): Promise<PublishPostResult> {\n const postId = claimedPost.id ?? \"\";\n let post: GarrulaSocialPost | null = null;\n let platform: PublishPostResult[\"platform\"] = \"unknown\";\n let accountPlatform: SocialPlatformType;\n let adapter: GarrulaSocialAdapter;\n let result: Awaited<ReturnType<GarrulaSocialAdapter[\"publishLink\"]>>;\n try {\n post = await this.loadClaimedPost(claimedPost);\n const account = await this.getPostAccount(post);\n if (!account) {\n throw new Error(\"Social account not found\");\n }\n platform = accountPlatform = account.platform;\n if (account.isActive === false) {\n throw new Error(GARRULA_ACCOUNT_INACTIVE_MESSAGE);\n }\n\n const credentials = await account.getCredentials();\n if (!credentials) {\n throw new Error(`No credentials configured for ${account.name}`);\n }\n\n let session = await this.openAdapter(account, credentials);\n const mediaUrl =\n post.postType === \"video\"\n ? (await this.hostHooks.resolveMediaUrl?.(post)) || post.mediaUrl\n : post.mediaUrl;\n\n // Server-side gate, immediately before the platform call: pause switch,\n // approval, evidence, link policy and the monthly spend cap. A refusal\n // leaves the post exactly as it was.\n let sendPost = post;\n if (this.outbound) {\n const gate = await this.outbound.beforeSend(post, account.platform);\n if (!gate.ok) {\n await this.releaseClaim(post, previousStatus);\n return {\n postId,\n platform,\n success: false,\n error: gate.refusal.message,\n skipped: \"refused\",\n refusal: gate.refusal,\n };\n }\n context.reservation = gate.reservation;\n sendPost = {\n ...post,\n linkUrl: gate.linkUrl,\n ...(isOutboundMarked(post) ? { title: null } : {}),\n } as GarrulaSocialPost;\n }\n try {\n result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null);\n } catch (publishError) {\n if (!isAuthError(publishError)) throw publishError;\n // The platform rejected a token we believed was valid: refresh once\n // and retry, or ask for a reconnect when the token cannot refresh.\n session = await this.openAdapter(account, session.credentials, { force: true });\n try {\n result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null);\n } catch (retryError) {\n if (!isAuthError(retryError)) throw retryError;\n throw await this.requireReconnect(account, \"publish rejected after refresh\");\n }\n }\n adapter = session.adapter;\n context.sent = result;\n } catch (error) {\n return this.failClaimedPost(post ?? claimedPost, post !== null, platform, error);\n }\n\n let publishedPost: GarrulaSocialPost;\n try {\n publishedPost = await this.socialPosts.recordPublishSuccess(post, {\n platformPostId: result.id,\n platformUrl: result.url,\n publishedAt: result.publishedAt,\n status:\n result.status === \"dry_run\" || result.status === \"staged\" ? result.status : \"published\",\n });\n } catch (recordError) {\n // A dry run never reached the platform, so retrying it is harmless:\n // record it as failed like any other error, on a fresh read (the failed\n // save left the dry-run outcome on this copy).\n if (result.status === \"dry_run\") {\n return this.failClaimedPost(post, false, platform, recordError);\n }\n // The platform has the post. Leave it `publishing` so nothing retries it\n // into a duplicate, and say so loudly.\n this.logger.error(\"Social post was sent but its result could not be saved\", {\n postId,\n platform,\n platformPostId: result.id,\n platformUrl: result.url,\n error: errorMessage(recordError),\n });\n return {\n postId,\n platform,\n success: false,\n platformPostId: result.id,\n platformUrl: result.url,\n error: `Posted (${result.url || result.id}), but the result could not be saved. Do not post it again.`,\n };\n }\n\n if (result.status === \"published\" || result.status === \"processing\") {\n try {\n await this.syncAnalyticsForPost(publishedPost, adapter, accountPlatform);\n } catch (analyticsError) {\n this.logger.warn(\"Unable to sync analytics after social publish\", {\n postId,\n platform,\n error: errorMessage(analyticsError),\n });\n }\n }\n\n return {\n postId,\n platform,\n success: true,\n platformPostId: result.id,\n platformUrl: result.url,\n };\n }\n\n /**\n * Record why a claimed post was not published and return that reason. The\n * reason is logged first, so it survives even when recording it fails.\n */\n private async failClaimedPost(\n post: GarrulaSocialPost,\n isFresh: boolean,\n platform: PublishPostResult[\"platform\"],\n error: unknown,\n ): Promise<PublishPostResult> {\n const postId = post.id ?? \"\";\n const reason = errorMessage(error);\n this.logger.error(\"Social publish failed\", { postId, platform, error: reason });\n try {\n const current = isFresh ? post : await this.loadClaimedPost(post);\n await this.recordFailure(current, error instanceof Error ? error : reason);\n } catch (recordError) {\n this.logger.error(\n \"Could not record a failed social publish; the post is still marked publishing\",\n {\n postId,\n platform,\n publishError: reason,\n error: errorMessage(recordError),\n },\n );\n }\n return { postId, platform, success: false, error: reason };\n }\n\n /**\n * Refresh the stats of published posts. With `options.tenantId`, only that\n * organization's posts are read; organizations that may not publish right\n * now (see {@link GarrulaHost.canPublish}) are skipped.\n */\n async syncAnalytics(\n postIds?: string[],\n options: { tenantId?: string | null } = {},\n ): Promise<AnalyticsSyncResult> {\n const where: Record<string, unknown> = { status: \"published\" };\n // An explicit tenant goes through the same check as every entry point (a\n // mismatch with the ambient context throws); a surrounding context scopes\n // the sync. Only a call with neither (the background job) spans tenants.\n const scopeTenantId =\n this.normalizeTenantId(options.tenantId) || this.normalizeTenantId(getTenantId())\n ? this.resolveRequestTenantId(options.tenantId)\n : null;\n if (scopeTenantId) where.tenantId = scopeTenantId;\n if (postIds?.length) where[\"id in\"] = postIds;\n const posts = await this.socialPosts.list({\n where,\n orderBy: \"publishedAt DESC\",\n });\n const selected = posts.filter(\n (post) =>\n (!postIds?.length || (post.id && postIds.includes(post.id))) &&\n (!scopeTenantId || this.normalizeTenantId(post.tenantId) === scopeTenantId),\n );\n const mayPublish = new Map<string, boolean>();\n const tenantMayPublish = async (tenantId: string): Promise<boolean> => {\n const canPublish = this.hostHooks.canPublish;\n if (!canPublish) return true;\n if (!mayPublish.has(tenantId)) mayPublish.set(tenantId, await canPublish(tenantId));\n return mayPublish.get(tenantId)!;\n };\n\n const result: AnalyticsSyncResult = {\n checked: selected.length,\n updated: 0,\n failed: 0,\n skipped: 0,\n errors: [],\n };\n\n for (const post of selected) {\n const tenantId = this.normalizeTenantId(post.tenantId);\n if (!tenantId || !(await tenantMayPublish(tenantId))) {\n result.skipped++;\n continue;\n }\n\n try {\n await withTenant({ tenantId }, async () => {\n const account = await this.getPostAccount(post);\n // A disconnected (inactive) account is never used again, not even\n // to read stats for posts it already published (privacy policy).\n if (!account || account.isActive === false || !post.platformPostId) {\n result.skipped++;\n return;\n }\n const credentials = await account.getCredentials();\n if (!credentials) {\n result.skipped++;\n return;\n }\n const { adapter } = await this.openAdapter(account, credentials);\n await this.syncAnalyticsForPost(post, adapter, account.platform);\n result.updated++;\n });\n } catch (error) {\n result.failed++;\n result.errors.push(error instanceof Error ? error.message : String(error));\n }\n }\n\n return result;\n }\n\n private async resolveTargetAccounts(\n targets: GarrulaTargetPlatform[],\n tenantId: string,\n ): Promise<GarrulaSocialAccount[]> {\n const groups = await Promise.all(\n targets.map((platform) => this.socialAccounts.findReady(platform)),\n );\n const accounts = groups.flat();\n\n return accounts.filter((account) => account.tenantId === tenantId);\n }\n\n /**\n * Narrow ready accounts to the requested ids. Every requested id must be one\n * of the ready accounts, so a stale or foreign id is refused, not skipped.\n */\n private selectAccounts(\n readyAccounts: GarrulaSocialAccount[],\n accountIds?: string[],\n ): GarrulaSocialAccount[] {\n if (!accountIds) return readyAccounts;\n const requested = new Set(accountIds.map((id) => id.trim()).filter(Boolean));\n const selected = readyAccounts.filter((account) => account.id && requested.has(account.id));\n if (requested.size === 0 || selected.length !== requested.size) {\n throw new Error(\"One or more selected social accounts are not ready to post.\");\n }\n return selected;\n }\n\n private mergeHashtags(account: GarrulaSocialAccount, requested?: string[]): string[] {\n return Array.from(new Set([...(account.defaultHashtags ?? []), ...(requested ?? [])]));\n }\n\n private requireAccountId(account: GarrulaSocialAccount): string {\n if (!account.id) {\n throw new Error(`Ready social account is missing an id: ${account.name}`);\n }\n return account.id;\n }\n\n /**\n * The tenant a request acts for: its own `tenantId`, else the tenant of the\n * current context. A request naming a different tenant than the active\n * context is refused rather than silently crossing tenants.\n */\n private resolveRequestTenantId(value?: string | null): string {\n const requested = this.normalizeTenantId(value);\n const ambient = this.normalizeTenantId(getTenantId());\n if (requested && ambient && requested !== ambient) {\n throw new Error(\"The request names a different tenant than the current tenant context.\");\n }\n const tenantId = requested ?? ambient;\n if (!tenantId) {\n throw new Error(tenantRequiredMessage(this.garrulaConfig));\n }\n return tenantId;\n }\n\n private normalizeTenantId(value?: string | null): string | null {\n const tenantId = value?.trim();\n return tenantId ? tenantId : null;\n }\n\n private async getPostAccount(post: GarrulaSocialPost): Promise<GarrulaSocialAccount | null> {\n if (!post.socialAccountId) return null;\n const account = await this.socialAccounts.get({ id: post.socialAccountId });\n if (\n account &&\n this.normalizeTenantId(account.tenantId) !== this.normalizeTenantId(post.tenantId)\n ) {\n return null;\n }\n return account;\n }\n\n /**\n * Renew an account whose recorded expiry has passed, as publishing would:\n * refresh the access token when it is due and save the new token set, which\n * clears the lapsed expiry on a refreshable OAuth 2 account. Throws when the\n * account has no credentials, cannot refresh, or the refresh fails.\n */\n private async renewLapsedAccount(account: GarrulaSocialAccount): Promise<void> {\n const credentials = await account.getCredentials();\n if (!credentials || !refreshKind(account.platform, credentials)) {\n throw new Error(\"Account cannot be refreshed\");\n }\n const { credentials: fresh } = await this.openAdapter(account, credentials);\n // The stored token was still valid (the account's expiry was stale): clear it.\n if (\n fresh === credentials &&\n account.isTokenExpired &&\n refreshKind(account.platform, fresh) === \"oauth2\"\n ) {\n await this.saveRefreshedCredentials(account, fresh, null);\n }\n }\n\n /**\n * Build the account's adapter with a usable access token. A token that is\n * expired or close to it (or of unknown age) is refreshed first and the new\n * token set is saved on the account, so the next publish starts from it.\n * With `force`, the token is refreshed even if it looks valid (the platform\n * just rejected it); a token that cannot be refreshed then needs a\n * reconnect.\n */\n private async openAdapter(\n account: GarrulaSocialAccount,\n credentials: Record<string, unknown>,\n options: { force?: boolean } = {},\n ): Promise<{ adapter: GarrulaSocialAdapter; credentials: Record<string, unknown> }> {\n const adapter = await this.createAdapter(account, credentials);\n const fresh = await this.ensureFreshCredentials(account, credentials, adapter, options);\n if (fresh === credentials) return { adapter, credentials };\n return { adapter: await this.createAdapter(account, fresh), credentials: fresh };\n }\n\n /**\n * Return credentials whose access token can be used now: the stored ones,\n * or a refreshed set that has been saved on the account.\n */\n private async ensureFreshCredentials(\n account: GarrulaSocialAccount,\n credentials: Record<string, unknown>,\n adapter: GarrulaSocialAdapter,\n options: { force?: boolean },\n ): Promise<Record<string, unknown>> {\n const kind = refreshKind(account.platform, credentials);\n const force = options.force === true;\n if (!kind) {\n if (force) throw await this.requireReconnect(account, \"token rejected and not refreshable\");\n return credentials;\n }\n\n const { accessTokenRefreshMarginMs, threadsRefreshWindowMs } = this.garrulaConfig;\n const now = Date.now();\n if (kind === \"threads\") {\n const expiresAt = parseExpiry(credentials.expiresAt) ?? parseExpiry(account.tokenExpiresAt);\n if (expiresAt && expiresAt.getTime() <= now) {\n // A lapsed long-lived Threads token cannot be refreshed.\n throw await this.requireReconnect(account, \"long-lived token expired\");\n }\n if (!force && (!expiresAt || expiresAt.getTime() - now > threadsRefreshWindowMs)) {\n return credentials;\n }\n return this.refreshCredentials(account, credentials, adapter, kind, { force });\n }\n\n // OAuth 2 (YouTube, X): the stored expiry decides; with no stored expiry\n // (accounts connected before it was recorded) refresh once, which records\n // it. A refresh is one token call, the same cost as checking the token.\n const expiresAt = parseExpiry(credentials.expiresAt);\n if (!force && expiresAt && expiresAt.getTime() - now > accessTokenRefreshMarginMs) {\n return credentials;\n }\n return this.refreshCredentials(account, credentials, adapter, kind, { force: true });\n }\n\n private async refreshCredentials(\n account: GarrulaSocialAccount,\n credentials: Record<string, unknown>,\n adapter: GarrulaSocialAdapter,\n kind: \"oauth2\" | \"threads\",\n options: { force: boolean },\n ): Promise<Record<string, unknown>> {\n let auth;\n try {\n auth =\n kind === \"threads\"\n ? await refreshThreadsToken(String(credentials.accessToken))\n : await adapter.refreshToken(String(credentials.refreshToken));\n } catch (error) {\n // Another publish may have refreshed (and, on X, rotated) the token\n // first: use what is stored now if it changed.\n const stored = await account.getCredentials().catch(() => null);\n if (stored && stored.accessToken !== credentials.accessToken) {\n return stored;\n }\n if (isRefreshRejected(error)) {\n throw await this.requireReconnect(account, \"refresh rejected\");\n }\n if (!options.force && kind === \"threads\") {\n // An early Threads refresh is best effort: the token still works.\n this.logger.warn(\"Could not refresh a Threads token early; using the current one\", {\n accountId: account.id,\n error: errorMessage(error),\n });\n return credentials;\n }\n this.logger.warn(\"Social token refresh failed\", {\n accountId: account.id,\n platform: account.platform,\n error: errorMessage(error),\n });\n throw new Error(\n `Could not renew the ${platformLabel(account.platform)} sign-in right now. Try again in a few minutes.`,\n );\n }\n\n const next = mergeRefreshedCredentials(credentials, auth);\n await this.saveRefreshedCredentials(\n account,\n next,\n kind === \"threads\" ? (auth.expiresAt ?? null) : null,\n );\n return next;\n }\n\n /**\n * Save a refreshed token set on the account (encrypted, tenant-scoped).\n * `tokenExpiresAt` on the account means \"the connection lapses then\", so it\n * is cleared for refreshable OAuth 2 tokens and moved forward for Threads.\n * A failed save is logged, the account's in-memory state is restored, and\n * the fresh token is still used for this publish.\n */\n private async saveRefreshedCredentials(\n account: GarrulaSocialAccount,\n credentials: Record<string, unknown>,\n connectionExpiresAt: Date | null,\n ): Promise<void> {\n const previous = {\n tokenExpiresAt: account.tokenExpiresAt,\n status: account.status,\n errorMessage: account.errorMessage,\n };\n try {\n account.tokenExpiresAt = connectionExpiresAt;\n if (account.status !== \"connected\") {\n account.status = \"connected\";\n account.errorMessage = null;\n }\n await account.setCredentials(credentials);\n this.logger.info(\"Refreshed social account token\", {\n accountId: account.id,\n platform: account.platform,\n });\n } catch (error) {\n // Not persisted: leave the account as it was (a lapsed one stays unready\n // for drafting) rather than treat a token that may be lost as durable.\n account.tokenExpiresAt = previous.tokenExpiresAt;\n account.status = previous.status;\n account.errorMessage = previous.errorMessage;\n this.logger.error(\"Could not save a refreshed social account token\", {\n accountId: account.id,\n platform: account.platform,\n error: errorMessage(error),\n });\n }\n }\n\n /**\n * Mark the account as needing a reconnect and return the error to throw.\n * Provider error text is never shown: it can be cryptic, and the message\n * says what to do.\n */\n private async requireReconnect(\n account: GarrulaSocialAccount,\n reason: string,\n ): Promise<GarrulaReconnectError> {\n const error = new GarrulaReconnectError(\n account.platform,\n this.garrulaConfig.socialSettingsLocation,\n );\n this.logger.warn(\"Social account needs to be reconnected\", {\n accountId: account.id,\n platform: account.platform,\n reason,\n });\n try {\n account.status = \"expired\";\n account.errorMessage = error.message;\n await account.save();\n } catch (saveError) {\n this.logger.error(\"Could not mark a social account as needing reconnection\", {\n accountId: account.id,\n platform: account.platform,\n error: errorMessage(saveError),\n });\n }\n return error;\n }\n\n private async createAdapter(\n account: GarrulaSocialAccount,\n credentials: Record<string, unknown>,\n ): Promise<GarrulaSocialAdapter> {\n if (this.socialFactory) {\n return this.socialFactory(account, credentials);\n }\n const adapter = await getSocial(this.buildSocialConfig(account, credentials));\n return adapter as GarrulaSocialAdapter;\n }\n\n private buildSocialConfig(\n account: GarrulaSocialAccount,\n credentials: Record<string, unknown>,\n ): GarrulaSocialConfig {\n const required = (name: string): string => {\n const value = credentials[name];\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(`Missing ${name} for ${account.platform}`);\n }\n return value;\n };\n const optional = (name: string): string | undefined => {\n const value = credentials[name];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n };\n const publishMode =\n account.effectivePublishMode ?? account.publishMode ?? this.garrulaConfig.defaultPublishMode;\n\n switch (account.platform) {\n case \"youtube\":\n return {\n type: \"youtube\",\n clientId: required(\"clientId\"),\n clientSecret: required(\"clientSecret\"),\n accessToken: required(\"accessToken\"),\n refreshToken: optional(\"refreshToken\"),\n publishMode,\n };\n case \"facebook\":\n return {\n type: \"facebook\",\n accessToken: required(\"accessToken\"),\n pageId:\n typeof credentials.pageId === \"string\"\n ? credentials.pageId\n : (account.platformUserId ?? required(\"pageId\")),\n publishMode,\n };\n case \"threads\":\n return {\n type: \"threads\",\n accessToken: required(\"accessToken\"),\n userId:\n typeof credentials.userId === \"string\"\n ? credentials.userId\n : (account.platformUserId ?? required(\"userId\")),\n publishMode,\n };\n case \"x\": {\n const linkBehavior =\n account.linkBehavior === \"reply\" || account.linkBehavior === \"none\"\n ? account.linkBehavior\n : \"inline\";\n const authType =\n credentials.authType === \"oauth2\" || !credentials.accessSecret ? \"oauth2\" : \"oauth1\";\n if (authType === \"oauth2\") {\n return {\n type: \"x\",\n authType: \"oauth2\",\n clientId: optional(\"clientId\"),\n clientSecret: optional(\"clientSecret\"),\n accessToken: required(\"accessToken\"),\n refreshToken: optional(\"refreshToken\"),\n linkBehavior,\n publishMode,\n };\n }\n return {\n type: \"x\",\n apiKey: required(\"apiKey\"),\n apiSecret: required(\"apiSecret\"),\n accessToken: required(\"accessToken\"),\n accessSecret: required(\"accessSecret\"),\n linkBehavior,\n publishMode,\n };\n }\n case \"bluesky\":\n // TODO(garrula-v2): Re-enable Bluesky once the platform is back in scope.\n throw new SocialError(\n \"Posting to Bluesky is not available yet.\",\n \"UNSUPPORTED_PLATFORM\",\n \"bluesky\",\n );\n }\n }\n\n private publishWithAdapter(\n adapter: GarrulaSocialAdapter,\n post: GarrulaSocialPost,\n mediaUrl: string | null,\n ) {\n if (post.postType === \"link\") {\n if (!post.linkUrl) {\n throw new SocialError(\"Link URL is required\", \"MISSING_LINK_URL\");\n }\n return adapter.publishLink({\n url: post.linkUrl,\n text: post.description,\n title: post.title ?? undefined,\n tags: post.hashtags,\n });\n }\n\n if (post.postType === \"video\") {\n if (!mediaUrl) {\n throw new SocialError(\"Media URL is required\", \"MISSING_MEDIA_URL\");\n }\n return adapter.publishVideo({\n file: mediaUrl,\n title: post.title ?? undefined,\n description: post.description,\n tags: post.hashtags,\n linkUrl: post.linkUrl ?? undefined,\n isShort: adapter.platform === \"youtube\",\n });\n }\n\n if (post.postType === \"image\") {\n // Picture posts carry their picture; never fall back to text-only.\n if (!mediaUrl) {\n throw new SocialError(\"A picture is required for a picture post\", \"MISSING_MEDIA_URL\");\n }\n return adapter.publishImage({\n file: mediaUrl,\n description: post.description,\n altText: post.title ?? undefined,\n tags: post.hashtags,\n linkUrl: post.linkUrl ?? undefined,\n });\n }\n\n return adapter.publishText({\n text: post.description,\n tags: post.hashtags,\n linkUrl: post.linkUrl ?? undefined,\n });\n }\n\n private async syncAnalyticsForPost(\n post: GarrulaSocialPost,\n adapter: GarrulaSocialAdapter,\n platform: SocialPlatformType,\n ): Promise<void> {\n if (!post.platformPostId) return;\n const analytics = await adapter.getAnalytics(post.platformPostId);\n const capturedAt = analytics.lastUpdated ?? new Date();\n\n await this.socialPosts.updateLatestAnalytics(post, analytics, capturedAt);\n await this.analyticsSnapshots.recordSnapshot({\n socialPostId: post.id ?? \"\",\n platform,\n metrics: analytics,\n raw: toRawAnalyticsPayload(analytics.raw),\n capturedAt,\n tenantId: post.tenantId ?? null,\n });\n }\n}\n\nfunction toRawAnalyticsPayload(value: unknown): RawAnalyticsPayload | undefined {\n if (value === null || Array.isArray(value)) return value;\n return typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAeA,IAAa,iCAAiC,MAAS;;;;;;AAOvD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AAM,QAAQ,aAAa,KAAK,cAAc;EAChE,MAAM,aAAa,UAAU,+BAAe,IAAI,KAAK;EAErD,MAAM,KAAK,YAAY,sBAAsB,MAAM,WAAW,UAAU;EACxE,MAAM,KAAK,mBAAmB,eAAe;GAC3C,cAAc,KAAK,MAAM;GACzB;GACA,SAAS;GACT,KAAK,sBAAsB,UAAU,GAAG;GACxC;GACA,UAAU,KAAK,YAAY;EAC7B,CAAC;CACH;AACF;sBAvtCC,KAAK;CACJ,OAAO;EACL,MAAM;EACN,MAAM;EACN,aAAa;CACf;CAIA,KAAK;EAAE,SAAS,CAAC,OAAO,eAAe;EAAG,cAAc,CAAC,OAAO,eAAe;CAAE;CACjF,KAAK,EAAE,SAAS,CAAC,wBAAwB,yBAAyB,EAAE;AACtE,CAAC,GAAA,mBAAA,qBAAA,CAAA,MAAA,CAAA,CAAA,GAAA,OAAA;AA8sCD,SAAS,sBAAsB,OAAiD;CAC9E,IAAI,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO;CACnD,OAAO,OAAO,UAAU,WAAY,QAAoC,KAAA;AAC1E;AAEA,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D"}
|
package/dist/manifest.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { GarrulaConfig } from '../config.js';
|
|
2
|
-
import { GarrulaCollections, GarrulaSocialPost } from '../types.js';
|
|
2
|
+
import { GarrulaCollections, GarrulaSocialAccount, GarrulaSocialPost } from '../types.js';
|
|
3
3
|
import { GarrulaOutboundPostCollection, GarrulaOutboundSettingsCollection, GarrulaSourceEventCollection, GarrulaSpendEntryCollection } from './models.js';
|
|
4
4
|
import { CostSource } from './rates.js';
|
|
5
5
|
import { CreateDraftInput, CreateDraftResult, DraftClaim, DraftingAI, IngestResult, OutboundDraft, OutboundPostKind, OutboundRefusal, OutboundSettings, OutboundSettingsPatch, OutboundState, SourceEvent, SpendSummary } from './types.js';
|
|
@@ -21,6 +21,11 @@ export interface OutboundServiceOptions {
|
|
|
21
21
|
/** The model client used to draft; resolved lazily so tests inject a fake. */
|
|
22
22
|
ai: () => DraftingAI;
|
|
23
23
|
now?: () => Date;
|
|
24
|
+
/**
|
|
25
|
+
* Renew a lapsed but refreshable access token and save it on the account
|
|
26
|
+
* (clearing the lapsed expiry). Throws when the account cannot be renewed.
|
|
27
|
+
*/
|
|
28
|
+
refreshAccount?: (account: GarrulaSocialAccount) => Promise<void>;
|
|
24
29
|
}
|
|
25
30
|
/** A reservation held between the gate and the publish outcome. */
|
|
26
31
|
export interface SpendReservation {
|
|
@@ -58,6 +63,7 @@ export declare class OutboundService {
|
|
|
58
63
|
private readonly configFn;
|
|
59
64
|
private readonly aiFn;
|
|
60
65
|
private readonly nowFn;
|
|
66
|
+
private readonly refreshAccount?;
|
|
61
67
|
constructor(options: OutboundServiceOptions);
|
|
62
68
|
/** The default cap; a non-finite or negative configured value falls back to the shipped default. */
|
|
63
69
|
private defaultCapMicros;
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,12 +3,12 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/garrula",
|
|
6
|
-
"packageVersion": "0.1.
|
|
6
|
+
"packageVersion": "0.1.7",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
10
|
+
"manifest": "59a45b290b8b47022ca8344df74bfe79f2e3420e6a143aa2edc2a15b4353a761",
|
|
11
|
+
"packageJson": "97faec35c811c7d378a7eb1d76a81c2cd6a2e76e3f2ba9a6a58012c1fe4aa845",
|
|
12
12
|
"agents": "37df674b62c16b50b91bda6e6057f1da0c0e2169b9d13f31ac0cdabb88f0f3f5"
|
|
13
13
|
},
|
|
14
14
|
"exports": [
|
package/dist/types.d.ts
CHANGED
|
@@ -133,6 +133,8 @@ export interface GarrulaClaimDatabase {
|
|
|
133
133
|
export interface GarrulaCollections {
|
|
134
134
|
socialAccounts: {
|
|
135
135
|
findReady(platform?: GarrulaTargetPlatform): Promise<GarrulaSocialAccount[]>;
|
|
136
|
+
/** Active accounts; optional, used to renew lapsed tokens before drafting. */
|
|
137
|
+
findActive?(platform?: GarrulaTargetPlatform): Promise<GarrulaSocialAccount[]>;
|
|
136
138
|
get(criteria: {
|
|
137
139
|
id: string;
|
|
138
140
|
}): Promise<GarrulaSocialAccount | null>;
|