@businesskit/agent 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/.claude/settings.json +16 -0
  2. package/.claude/settings.local.json +11 -0
  3. package/.env.example +10 -0
  4. package/CLAUDE.md +32 -13
  5. package/PLAN.md +95 -134
  6. package/REFERENCE.md +60 -24
  7. package/agents/_base.ts +352 -44
  8. package/agents/analytics/SOUL.md +11 -0
  9. package/agents/analytics/analytics.ts +405 -0
  10. package/agents/business/SOUL.md +11 -0
  11. package/agents/{csuite/cbo.ts → business/business.ts} +2 -2
  12. package/agents/ceo/SOUL.md +15 -0
  13. package/agents/{csuite → ceo}/ceo.ts +33 -8
  14. package/agents/content/SOUL.md +11 -0
  15. package/agents/content/content.ts +379 -0
  16. package/agents/copywriting/SOUL.md +11 -0
  17. package/agents/courses/SOUL.md +11 -0
  18. package/agents/courses/courses.ts +451 -0
  19. package/agents/docs/SOUL.md +11 -0
  20. package/agents/forms/SOUL.md +11 -0
  21. package/agents/forms/forms.ts +364 -0
  22. package/agents/hiring/SOUL.md +11 -0
  23. package/agents/hiring/hiring.ts +314 -0
  24. package/agents/marketing/SOUL.md +15 -0
  25. package/agents/{csuite/cmo.ts → marketing/marketing.ts} +3 -3
  26. package/agents/newsletter/SOUL.md +11 -0
  27. package/agents/operations/SOUL.md +11 -0
  28. package/agents/operations/operations.ts +157 -0
  29. package/agents/sales/SOUL.md +44 -0
  30. package/agents/sales/sales.ts +883 -0
  31. package/agents/scheduler/SOUL.md +11 -0
  32. package/agents/{growth → scheduler}/scheduler.ts +2 -2
  33. package/agents/seo/SOUL.md +11 -0
  34. package/agents/{growth/seo-agent.ts → seo/seo.ts} +60 -54
  35. package/agents/social/SOUL.md +11 -0
  36. package/agents/social/social.ts +744 -0
  37. package/agents/store/SOUL.md +11 -0
  38. package/agents/store/store.ts +514 -0
  39. package/cli.ts +44 -25
  40. package/lib/cms.ts +88 -0
  41. package/lib/db.ts +58 -11
  42. package/lib/enums.ts +25 -0
  43. package/lib/groups.ts +122 -0
  44. package/lib/id.ts +38 -10
  45. package/lib/profile.ts +44 -8
  46. package/lib/schema.ts +2015 -0
  47. package/lib/validate.ts +33 -0
  48. package/package.json +1 -1
  49. package/scripts/generate-schema.ts +244 -0
  50. package/setup.ts +16 -2
  51. package/skills/schema/SKILL.md +57 -16
  52. package/tsconfig.json +2 -1
  53. package/agents/creators/blog-writer.ts +0 -347
  54. package/agents/creators/course-creator.ts +0 -106
  55. package/agents/creators/crm-agent.ts +0 -479
  56. package/agents/creators/forms-builder.ts +0 -90
  57. package/agents/creators/jobs-manager.ts +0 -82
  58. package/agents/creators/store-manager.ts +0 -138
  59. package/agents/csuite/coo.ts +0 -115
  60. package/agents/growth/analytics-agent.ts +0 -52
  61. package/agents/growth/social-agent.ts +0 -346
  62. /package/{ingest.md → .claude/commands/ingest.md} +0 -0
  63. /package/agents/{creators/copywriter.ts → copywriting/copywriting.ts} +0 -0
  64. /package/agents/{creators/docs-writer.ts → docs/docs.ts} +0 -0
  65. /package/agents/{creators/newsletter-writer.ts → newsletter/newsletter.ts} +0 -0
  66. /package/{ABOUT-ME.md → context/about-me.md} +0 -0
  67. /package/{brand-voice.md → context/brand-voice.md} +0 -0
  68. /package/{working-style.md → context/working-style.md} +0 -0
@@ -0,0 +1,744 @@
1
+ /**
2
+ * Social Agent — one post per (post, platform). Zernio primary, direct
3
+ * platform APIs secondary, n8n fallback.
4
+ *
5
+ * DB contract (businesskit-files/social.ts):
6
+ * - connections : encrypted API creds. service='zernio' for BYOK,
7
+ * service='{platform}_direct' for direct mode.
8
+ * - social_accounts : one row per connected account. Owns connection_mode:
9
+ * 'zernio_platform' | 'zernio_byok' | 'direct' | 'n8n'
10
+ * - social_posts : ★ ONE ROW PER POST PER PLATFORM. Same content to
11
+ * N platforms → N rows + one shared group_id.
12
+ * platform_post_id is first-class indexed column,
13
+ * written by Zernio webhook / direct API response.
14
+ * UNIQUE (idempotency_key) WHERE NOT NULL.
15
+ * - social_post_groups: 1 row per cross-post. trg_social_post_group_count
16
+ * auto-bumps platform_count on each child insert.
17
+ * - social_post_analytics: auto-seeded by trg_social_post_analytics_insert
18
+ * on every social_posts INSERT. Never INSERT here.
19
+ * - social_analytics : per-account aggregate. total_posts/published/
20
+ * scheduled/failed trigger-maintained. Rest written
21
+ * by aggregator job.
22
+ * - social_queue : recurring slots (day_of_week + time_of_day).
23
+ * Zernio mirrors slots via zernio_slot_id.
24
+ * - social_inbox : DMs/comments/reviews. CRM bridge via crm_contact_id.
25
+ *
26
+ * Triggers that fire on our writes (all auto):
27
+ * - trg_social_post_analytics_insert → seeds social_post_analytics
28
+ * - trg_social_post_group_count → +1 social_post_groups.platform_count
29
+ * - trg_social_post_published_insert → bumps social_analytics when
30
+ * status='published' at INSERT time
31
+ * - trg_social_post_scheduled_insert → bumps social_analytics when
32
+ * status='scheduled' at INSERT time
33
+ *
34
+ * Posting modes (Mode A platform key is Phase 2 — session-required, skipped):
35
+ * Mode B (primary) — Zernio BYOK. connections WHERE service='zernio'
36
+ * → POST {ZERNIO_BASE}/posts with Bearer key.
37
+ * Mode C (secondary)— Direct platform API. connections WHERE
38
+ * service='{platform}_direct'. Agent writes the row
39
+ * with status='scheduled'; the app-side dispatcher
40
+ * cron calls the platform API. Agent does NOT call
41
+ * the platform APIs itself (wildly divergent shapes).
42
+ * Mode D (fallback) — n8n. POST credentials.n8n_webhook_url with payload,
43
+ * n8n callback sets platform_post_id + status.
44
+ *
45
+ * Timestamps on social_posts are INTEGER unix seconds except `scheduled_for`
46
+ * (ISO TEXT) and `published_at` (INTEGER).
47
+ */
48
+
49
+ import { BaseAgent, db, ulid, now } from '../_base.ts'
50
+
51
+ const ZERNIO_BASE = 'https://zernio.com/api/v1'
52
+ const FREE_TIER_CAP = 20 // posts/month via platform key (matches social.ts)
53
+ const MAX_CONTENT_DEF = 2200 // fallback when platform unknown
54
+
55
+ export type SocialPlatform =
56
+ | 'twitter' | 'instagram' | 'facebook' | 'linkedin' | 'tiktok'
57
+ | 'youtube' | 'pinterest' | 'reddit' | 'bluesky' | 'threads'
58
+ | 'googlebusiness' | 'telegram' | 'snapchat'
59
+
60
+ export type ConnectionMode = 'zernio_platform' | 'zernio_byok' | 'direct' | 'n8n'
61
+
62
+ export type PostStatus =
63
+ | 'draft' | 'scheduled' | 'queued' | 'publishing' | 'published'
64
+ | 'partial' | 'failed' | 'cancelled'
65
+
66
+ export type InboxStatus = 'unread' | 'read' | 'replied' | 'archived' | 'spam'
67
+ export type InboxType = 'dm' | 'comment' | 'review'
68
+
69
+ export interface MediaItem {
70
+ url: string
71
+ type: 'image' | 'video' | 'document'
72
+ thumbnail_url?: string
73
+ alt_text?: string
74
+ }
75
+
76
+ export interface PostInput {
77
+ content: string
78
+ platforms?: SocialPlatform[] // omit = all connected active accounts
79
+ account_ids?: string[] // or target specific social_accounts.id
80
+ scheduled_for?: string // ISO e.g. '2026-04-01T09:00:00'
81
+ timezone?: string // default 'UTC'
82
+ publish_now?: boolean
83
+ use_queue?: boolean
84
+ media_items?: MediaItem[]
85
+ link_url?: string
86
+ platform_specific_data?: Record<string, unknown>
87
+ source?: string // 'manual' | 'agent' | 'blog_crosspost' | …
88
+ source_id?: string // FK → posts.id / products.id
89
+ ai_generated?: boolean
90
+ ai_prompt?: string
91
+ approval_status?: 'pending' | 'approved' | 'auto_sent'
92
+ group_name?: string // optional label for the cross-post
93
+ idempotency_prefix?: string // customise retry dedup scope
94
+ }
95
+
96
+ export interface PerPlatformResult {
97
+ account_id: string
98
+ platform: SocialPlatform
99
+ social_post_id: string
100
+ status: PostStatus
101
+ zernio_post_id?: string | null
102
+ platform_post_id?: string | null
103
+ error?: string
104
+ scheduled_via: 'byok' | 'platform' | 'direct' | 'n8n'
105
+ }
106
+
107
+ export interface PostResult {
108
+ ok: boolean
109
+ group_id?: string
110
+ results: PerPlatformResult[]
111
+ error?: string
112
+ }
113
+
114
+ export class SocialAgent extends BaseAgent {
115
+ readonly name = 'Social'
116
+ readonly title = 'Social Agent'
117
+
118
+ // ── Reads ────────────────────────────────────────────────────────────────
119
+
120
+ async listAccounts(opts: {
121
+ platform?: SocialPlatform
122
+ active_only?: boolean
123
+ } = {}) {
124
+ await this.init()
125
+ let where = 'WHERE profile_id=?'
126
+ const args: unknown[] = [this.profileId]
127
+ if (opts.active_only !== false) where += ' AND is_active=1 AND is_connected=1'
128
+ if (opts.platform) { where += ' AND platform=?'; args.push(opts.platform) }
129
+ const { rows } = await db.execute({
130
+ sql: `SELECT id, connection_id, connection_mode, platform,
131
+ platform_username, platform_display_name, platform_avatar_url,
132
+ zernio_account_id, follower_count,
133
+ token_status, is_connected, is_active, last_health_check_at,
134
+ default_timezone
135
+ FROM social_accounts ${where}
136
+ ORDER BY platform ASC`,
137
+ args,
138
+ })
139
+ return rows
140
+ }
141
+
142
+ async listPosts(opts: {
143
+ status?: PostStatus
144
+ platform?: SocialPlatform
145
+ account_id?: string
146
+ group_id?: string
147
+ limit?: number
148
+ } = {}) {
149
+ await this.init()
150
+ let where = 'WHERE profile_id=? AND hidden=0'
151
+ const args: unknown[] = [this.profileId]
152
+ if (opts.status) { where += ' AND status=?'; args.push(opts.status) }
153
+ if (opts.platform) { where += ' AND platform=?'; args.push(opts.platform) }
154
+ if (opts.account_id) { where += ' AND account_id=?'; args.push(opts.account_id) }
155
+ if (opts.group_id) { where += ' AND group_id=?'; args.push(opts.group_id) }
156
+ const { rows } = await db.execute({
157
+ sql: `SELECT id, account_id, group_id, platform, status, scheduled_for,
158
+ published_at, platform_post_id, platform_post_url,
159
+ zernio_post_id, content, approval_status, scheduled_via,
160
+ error, created_at
161
+ FROM social_posts ${where}
162
+ ORDER BY created_at DESC LIMIT ?`,
163
+ args: [...args, opts.limit ?? 50],
164
+ })
165
+ return rows
166
+ }
167
+
168
+ getDrafts() { return this.listPosts({ status: 'draft' }) }
169
+ getScheduled() { return this.listPosts({ status: 'scheduled' }) }
170
+ getPublished() { return this.listPosts({ status: 'published' }) }
171
+
172
+ async getPost(id: string) {
173
+ await this.init()
174
+ const { rows: [r] } = await db.execute({
175
+ sql: `SELECT * FROM social_posts WHERE id=? AND profile_id=? LIMIT 1`,
176
+ args: [id, this.profileId],
177
+ })
178
+ if (!r) throw new Error(`Social post not found: ${id}`)
179
+ return r
180
+ }
181
+
182
+ async getGroup(groupId: string) {
183
+ await this.init()
184
+ const [{ rows: [group] }, { rows: posts }] = await Promise.all([
185
+ db.execute({
186
+ sql: `SELECT * FROM social_post_groups WHERE id=? AND profile_id=? LIMIT 1`,
187
+ args: [groupId, this.profileId],
188
+ }),
189
+ db.execute({
190
+ sql: `SELECT id, account_id, platform, status, platform_post_id,
191
+ platform_post_url, zernio_post_id, scheduled_via, error
192
+ FROM social_posts
193
+ WHERE group_id=? AND profile_id=?
194
+ ORDER BY platform ASC`,
195
+ args: [groupId, this.profileId],
196
+ }),
197
+ ])
198
+ if (!group) throw new Error(`Group not found: ${groupId}`)
199
+ return { ...group, posts }
200
+ }
201
+
202
+ // ── Core: create + dispatch ──────────────────────────────────────────────
203
+
204
+ async post(input: PostInput): Promise<PostResult> {
205
+ await this.init()
206
+
207
+ if (!input.content?.trim()) {
208
+ return { ok: false, results: [], error: 'content is required' }
209
+ }
210
+
211
+ // 1. Resolve target accounts
212
+ const allAccounts = await this.listAccounts({ active_only: true })
213
+ if (!allAccounts.length) {
214
+ return {
215
+ ok: false, results: [],
216
+ error: 'No connected social accounts. Connect platforms in BusinessKit → Settings → Social.',
217
+ }
218
+ }
219
+
220
+ let targets = allAccounts as Array<Record<string, unknown>>
221
+ if (input.account_ids?.length) {
222
+ const ids = new Set(input.account_ids)
223
+ targets = targets.filter(a => ids.has(a.id as string))
224
+ } else if (input.platforms?.length) {
225
+ const ps = new Set(input.platforms)
226
+ targets = targets.filter(a => ps.has(a.platform as SocialPlatform))
227
+ }
228
+ if (!targets.length) {
229
+ return {
230
+ ok: false, results: [],
231
+ error: `No matching accounts for: ${
232
+ input.account_ids?.join(', ') ?? input.platforms?.join(', ') ?? '(all)'
233
+ }`,
234
+ }
235
+ }
236
+
237
+ // 2. Per-platform content length check (truncate upstream; we just warn).
238
+ for (const a of targets) {
239
+ const max = getMaxContentLength(a.platform as SocialPlatform)
240
+ if (input.content.length > max) {
241
+ return {
242
+ ok: false, results: [],
243
+ error: `Content exceeds ${a.platform} max length (${max}). Shorten or target platforms separately.`,
244
+ }
245
+ }
246
+ }
247
+
248
+ // 3. Create cross-post group if >1 target.
249
+ const ts = now()
250
+ let groupId: string | null = null
251
+ if (targets.length > 1) {
252
+ groupId = ulid()
253
+ await db.write({
254
+ sql: `INSERT INTO social_post_groups (id, profile_id, name, source_content, platform_count)
255
+ VALUES (?,?,?,?,0)`,
256
+ args: [groupId, this.profileId, input.group_name ?? null, input.content],
257
+ })
258
+ }
259
+
260
+ // 4. Resolve a Zernio BYOK key once — reused for every zernio_byok account.
261
+ const zernioByokKey = await this.resolveZernioByokKey()
262
+
263
+ // 5. Dispatch per account. One social_posts row per account/platform.
264
+ const results: PerPlatformResult[] = []
265
+ for (const acc of targets) {
266
+ const mode = (acc.connection_mode as ConnectionMode) ?? 'zernio_byok'
267
+ const r = await this.dispatchOne({
268
+ account: acc, mode, input, ts, groupId,
269
+ zernioByokKey,
270
+ })
271
+ results.push(r)
272
+ }
273
+
274
+ const ok = results.every(r => r.status !== 'failed')
275
+ await this.logMemory(
276
+ ok
277
+ ? `Posted "${input.content.slice(0, 60)}..." to ${results.map(r => r.platform).join(', ')}`
278
+ : `Post partially failed: ${results.filter(r => r.error).map(r => r.platform).join(', ')}`,
279
+ { group_id: groupId, count: results.length, ok },
280
+ )
281
+
282
+ return { ok, group_id: groupId ?? undefined, results }
283
+ }
284
+
285
+ // ── Convenience wrappers ─────────────────────────────────────────────────
286
+
287
+ async crossPostBlog(postId: string, title: string, slug: string, excerpt?: string) {
288
+ const url = `https://${this.ctx.profile.slug}.businesskit.io/blog/${slug}`
289
+ const content = excerpt ? `${title}\n\n${excerpt}\n\n${url}` : `${title}\n\n${url}`
290
+ return this.post({
291
+ content,
292
+ source: 'blog_crosspost',
293
+ source_id: postId,
294
+ })
295
+ }
296
+
297
+ async announceProduct(productId: string, title: string, slug: string, priceCents: number) {
298
+ const url = `https://${this.ctx.profile.slug}.businesskit.io/store/${slug}`
299
+ const price = `$${(priceCents / 100).toFixed(2)}`
300
+ return this.post({
301
+ content: `New: ${title} — ${price}\n\n${url}`,
302
+ source: 'product_launch',
303
+ source_id: productId,
304
+ })
305
+ }
306
+
307
+ // ── Queue ────────────────────────────────────────────────────────────────
308
+
309
+ async listQueueSlots(accountId?: string) {
310
+ await this.init()
311
+ let where = 'WHERE profile_id=?'
312
+ const args: unknown[] = [this.profileId]
313
+ if (accountId) { where += ' AND account_id=?'; args.push(accountId) }
314
+ const { rows } = await db.execute({
315
+ sql: `SELECT id, account_id, day_of_week, time_of_day, timezone,
316
+ is_active, next_scheduled_at, last_used_at, zernio_slot_id
317
+ FROM social_queue ${where}
318
+ ORDER BY day_of_week ASC, time_of_day ASC`,
319
+ args,
320
+ })
321
+ return rows
322
+ }
323
+
324
+ async addQueueSlot(input: {
325
+ account_id: string
326
+ day_of_week: number // 0=Sun … 6=Sat
327
+ time_of_day: string // 'HH:MM'
328
+ timezone?: string
329
+ }) {
330
+ await this.init()
331
+ if (input.day_of_week < 0 || input.day_of_week > 6) {
332
+ throw new Error(`day_of_week must be 0..6, got ${input.day_of_week}`)
333
+ }
334
+ if (!/^\d{2}:\d{2}$/.test(input.time_of_day)) {
335
+ throw new Error(`time_of_day must be 'HH:MM', got ${input.time_of_day}`)
336
+ }
337
+ const id = ulid()
338
+ const ikey = `queue:${input.account_id}:${input.day_of_week}:${input.time_of_day}`
339
+ await db.write({
340
+ sql: `INSERT OR IGNORE INTO social_queue
341
+ (id, profile_id, account_id, day_of_week, time_of_day, timezone,
342
+ is_active, idempotency_key)
343
+ VALUES (?,?,?,?,?,?,1,?)`,
344
+ args: [
345
+ id, this.profileId, input.account_id, input.day_of_week,
346
+ input.time_of_day, input.timezone ?? 'UTC', ikey,
347
+ ],
348
+ })
349
+ return id
350
+ }
351
+
352
+ async removeQueueSlot(slotId: string) {
353
+ await this.init()
354
+ await db.write({
355
+ sql: `DELETE FROM social_queue WHERE id=? AND profile_id=?`,
356
+ args: [slotId, this.profileId],
357
+ })
358
+ }
359
+
360
+ // ── Inbox ────────────────────────────────────────────────────────────────
361
+
362
+ async inbox(opts: {
363
+ status?: InboxStatus
364
+ type?: InboxType
365
+ platform?: SocialPlatform
366
+ limit?: number
367
+ } = {}) {
368
+ await this.init()
369
+ let where = 'WHERE profile_id=?'
370
+ const args: unknown[] = [this.profileId]
371
+ if (opts.status) { where += ' AND status=?'; args.push(opts.status) }
372
+ if (opts.type) { where += ' AND type=?'; args.push(opts.type) }
373
+ if (opts.platform) { where += ' AND platform=?'; args.push(opts.platform) }
374
+ const { rows } = await db.execute({
375
+ sql: `SELECT id, account_id, type, platform, status, sender_username,
376
+ sender_display_name, crm_contact_id, post_id,
377
+ content, rating, sentiment, is_starred,
378
+ agent_draft, agent_suggested_action, approval_status,
379
+ received_at
380
+ FROM social_inbox ${where}
381
+ ORDER BY received_at DESC LIMIT ?`,
382
+ args: [...args, opts.limit ?? 50],
383
+ })
384
+ return rows
385
+ }
386
+
387
+ async markInbox(id: string, status: InboxStatus) {
388
+ await this.init()
389
+ await db.write({
390
+ sql: `UPDATE social_inbox SET status=?, updated_at=?
391
+ WHERE id=? AND profile_id=?`,
392
+ args: [status, now(), id, this.profileId],
393
+ })
394
+ }
395
+
396
+ // ── Analytics summary ────────────────────────────────────────────────────
397
+
398
+ /** Per-profile cross-platform overview using social_analytics_view (1 row
399
+ * per profile, auto-joined across accounts). Falls back to ad-hoc query
400
+ * if the view isn't provisioned yet. */
401
+ async socialSummary() {
402
+ await this.init()
403
+ try {
404
+ const { rows: [r] } = await db.execute({
405
+ sql: `SELECT * FROM social_analytics_view WHERE profile_id=? LIMIT 1`,
406
+ args: [this.profileId],
407
+ })
408
+ if (r) return r
409
+ } catch { /* view missing — fall through */ }
410
+
411
+ const { rows: accountRows } = await db.execute({
412
+ sql: `SELECT COUNT(*) AS accounts
413
+ FROM social_accounts
414
+ WHERE profile_id=? AND is_active=1 AND is_connected=1`,
415
+ args: [this.profileId],
416
+ })
417
+ const { rows: [counts] } = await db.execute({
418
+ sql: `SELECT
419
+ COUNT(*) AS total,
420
+ SUM(CASE WHEN status='published' THEN 1 ELSE 0 END) AS published,
421
+ SUM(CASE WHEN status='scheduled' THEN 1 ELSE 0 END) AS scheduled,
422
+ SUM(CASE WHEN status='draft' THEN 1 ELSE 0 END) AS drafts,
423
+ SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END) AS failed
424
+ FROM social_posts
425
+ WHERE profile_id=? AND hidden=0`,
426
+ args: [this.profileId],
427
+ })
428
+ return {
429
+ accounts: Number(accountRows[0]?.accounts ?? 0),
430
+ total: Number(counts?.total ?? 0),
431
+ published: Number(counts?.published ?? 0),
432
+ scheduled: Number(counts?.scheduled ?? 0),
433
+ drafts: Number(counts?.drafts ?? 0),
434
+ failed: Number(counts?.failed ?? 0),
435
+ }
436
+ }
437
+
438
+ async accountAnalytics(accountId: string) {
439
+ await this.init()
440
+ const { rows: [r] } = await db.execute({
441
+ sql: `SELECT * FROM social_analytics WHERE account_id=? AND profile_id=? LIMIT 1`,
442
+ args: [accountId, this.profileId],
443
+ })
444
+ return r ?? null
445
+ }
446
+
447
+ // ── Dispatch (private) ───────────────────────────────────────────────────
448
+
449
+ /** Write one social_posts row + dispatch per its mode. Never throws —
450
+ * catches and stuffs error into the row so you still get a record. */
451
+ private async dispatchOne(args: {
452
+ account: Record<string, unknown>
453
+ mode: ConnectionMode
454
+ input: PostInput
455
+ ts: number
456
+ groupId: string | null
457
+ zernioByokKey: string | null
458
+ }): Promise<PerPlatformResult> {
459
+ const { account, mode, input, ts, groupId, zernioByokKey } = args
460
+ const accountId = account.id as string
461
+ const platform = account.platform as SocialPlatform
462
+ const postId = ulid()
463
+ const month = new Date(ts * 1000).toISOString().slice(0, 7)
464
+ const scheduledVia: PerPlatformResult['scheduled_via'] =
465
+ mode === 'zernio_byok' ? 'byok'
466
+ : mode === 'zernio_platform' ? 'platform'
467
+ : mode === 'direct' ? 'direct'
468
+ : 'n8n'
469
+
470
+ const base: PerPlatformResult = {
471
+ account_id: accountId, platform, social_post_id: postId,
472
+ status: 'draft', scheduled_via: scheduledVia,
473
+ }
474
+
475
+ // Initial status from mode + options
476
+ let status: PostStatus =
477
+ input.publish_now ? 'queued' :
478
+ input.scheduled_for ? 'scheduled' :
479
+ input.use_queue ? 'queued' :
480
+ 'draft'
481
+ let zernioPostId: string | null = null
482
+ let platformPostId: string | null = null
483
+ let errorText: string | null = null
484
+
485
+ // ── Zernio BYOK — actually call the API ────────────────────────────────
486
+ if (mode === 'zernio_byok') {
487
+ if (!zernioByokKey) {
488
+ errorText = 'No Zernio BYOK key in connections (service=zernio)'
489
+ status = 'failed'
490
+ } else if (!account.zernio_account_id) {
491
+ errorText = `Account missing zernio_account_id — reconnect via Zernio`
492
+ status = 'failed'
493
+ } else {
494
+ const resp = await callZernio({
495
+ apiKey: zernioByokKey,
496
+ content: input.content,
497
+ platforms: [{ platform, accountId: account.zernio_account_id as string }],
498
+ publishNow: input.publish_now,
499
+ useQueue: input.use_queue,
500
+ scheduledFor: input.scheduled_for,
501
+ timezone: input.timezone ?? (account.default_timezone as string) ?? 'UTC',
502
+ mediaItems: input.media_items,
503
+ platformSpecific: input.platform_specific_data,
504
+ })
505
+ if (resp.ok) {
506
+ zernioPostId = resp.zernio_post_id ?? null
507
+ platformPostId = resp.platform_post_id ?? null
508
+ status = input.publish_now
509
+ ? (platformPostId ? 'published' : 'publishing')
510
+ : input.scheduled_for ? 'scheduled' : 'queued'
511
+ } else {
512
+ errorText = resp.error ?? 'Zernio API error'
513
+ status = 'failed'
514
+ }
515
+ }
516
+ }
517
+
518
+ // ── Zernio platform key — requires session; refuse from agent ──────────
519
+ if (mode === 'zernio_platform') {
520
+ errorText = 'Platform-key posting requires dashboard session. Use /api/social/schedule.'
521
+ status = 'failed'
522
+ }
523
+
524
+ // ── Direct mode — write row, let app-side dispatcher call the API ──────
525
+ if (mode === 'direct') {
526
+ // Leave status so the cron picks it up:
527
+ // publish_now → 'queued' (dispatcher promotes to 'publishing' → 'published')
528
+ // scheduled_for→ 'scheduled' (dispatcher picks up when scheduled_for<=now)
529
+ // use_queue → 'queued' (dispatcher picks next queue slot)
530
+ // otherwise → 'draft'
531
+ // Nothing to do here — writing the row is the action.
532
+ }
533
+
534
+ // ── n8n mode — forward payload, treat as fire-and-forget ──────────────
535
+ if (mode === 'n8n') {
536
+ const webhook = this.ctx.credentials?.n8n_webhook_url as string | undefined
537
+ if (!webhook) {
538
+ errorText = 'No n8n_webhook_url in credentials'
539
+ status = 'failed'
540
+ } else {
541
+ try {
542
+ const r = await fetch(webhook, {
543
+ method: 'POST',
544
+ headers: { 'Content-Type': 'application/json' },
545
+ body: JSON.stringify({
546
+ event: 'social_post',
547
+ profile_id: this.profileId,
548
+ account_id: accountId,
549
+ platform,
550
+ content: input.content,
551
+ media_items: input.media_items ?? [],
552
+ scheduled_for: input.scheduled_for ?? null,
553
+ publish_now: input.publish_now ?? false,
554
+ timezone: input.timezone ?? 'UTC',
555
+ source: input.source ?? 'agent',
556
+ source_id: input.source_id ?? null,
557
+ post_id: postId,
558
+ }),
559
+ })
560
+ if (!r.ok) {
561
+ errorText = `n8n returned ${r.status}`
562
+ status = 'failed'
563
+ } else {
564
+ // n8n callback sets platform_post_id + final status async
565
+ status = input.publish_now ? 'queued' : status
566
+ }
567
+ } catch (e) {
568
+ errorText = `n8n error: ${(e as Error).message}`
569
+ status = 'failed'
570
+ }
571
+ }
572
+ }
573
+
574
+ // ── Write the social_posts row ────────────────────────────────────────
575
+ // idempotency_key dedupes retries of the same logical send.
576
+ const ikey = (input.idempotency_prefix ?? 'sp')
577
+ + `:${accountId}:${input.source_id ?? 'none'}:${sha(input.content).slice(0, 16)}`
578
+
579
+ await db.write({
580
+ sql: `INSERT OR IGNORE INTO social_posts (
581
+ id, profile_id, account_id, group_id, platform,
582
+ platform_post_id, platform_post_url,
583
+ zernio_post_id, zernio_account_id,
584
+ content, media_items, link_url,
585
+ platform_specific_data,
586
+ status, scheduled_for, timezone, publish_now, use_queue,
587
+ published_at,
588
+ approval_status,
589
+ source, source_id,
590
+ ai_generated, ai_prompt,
591
+ scheduled_via, platform_schedule_count, platform_schedule_month,
592
+ error,
593
+ idempotency_key,
594
+ created_at, updated_at
595
+ ) VALUES (
596
+ ?,?,?,?,?,
597
+ ?,?,
598
+ ?,?,
599
+ ?,?,?,
600
+ ?,
601
+ ?,?,?,?,?,
602
+ ?,
603
+ ?,
604
+ ?,?,
605
+ ?,?,
606
+ ?,?,?,
607
+ ?,
608
+ ?,
609
+ ?,?
610
+ )`,
611
+ args: [
612
+ postId, this.profileId, accountId, groupId, platform,
613
+ platformPostId, null,
614
+ zernioPostId, (account.zernio_account_id as string) ?? null,
615
+ input.content,
616
+ JSON.stringify(input.media_items ?? []),
617
+ input.link_url ?? null,
618
+ JSON.stringify(input.platform_specific_data ?? {}),
619
+ status, input.scheduled_for ?? null, input.timezone ?? 'UTC',
620
+ input.publish_now ? 1 : 0, input.use_queue ? 1 : 0,
621
+ status === 'published' ? ts : null,
622
+ input.approval_status ?? 'auto_sent',
623
+ input.source ?? 'agent', input.source_id ?? null,
624
+ input.ai_generated ? 1 : 0, input.ai_prompt ?? null,
625
+ scheduledVia, 0, month,
626
+ errorText,
627
+ ikey,
628
+ ts, ts,
629
+ ],
630
+ })
631
+
632
+ return {
633
+ ...base,
634
+ status,
635
+ zernio_post_id: zernioPostId,
636
+ platform_post_id: platformPostId,
637
+ error: errorText ?? undefined,
638
+ }
639
+ }
640
+
641
+ // ── Zernio BYOK resolver ─────────────────────────────────────────────────
642
+ // Priority matches app-side resolveZernioKey(): BYOK first. We do NOT
643
+ // fall through to a platform key — that path requires session auth.
644
+ private async resolveZernioByokKey(): Promise<string | null> {
645
+ try {
646
+ const { rows: [r] } = await db.execute({
647
+ sql: `SELECT client_id FROM connections
648
+ WHERE profile_id=? AND service='zernio'
649
+ AND is_active=1 AND client_id IS NOT NULL
650
+ LIMIT 1`,
651
+ args: [this.profileId],
652
+ })
653
+ return (r?.client_id as string) ?? null
654
+ } catch {
655
+ return null
656
+ }
657
+ }
658
+ }
659
+
660
+ // ── Zernio API client ──────────────────────────────────────────────────────
661
+
662
+ interface ZernioCallArgs {
663
+ apiKey: string
664
+ content: string
665
+ platforms: Array<{ platform: string; accountId: string }>
666
+ publishNow?: boolean
667
+ useQueue?: boolean
668
+ scheduledFor?: string
669
+ timezone?: string
670
+ mediaItems?: MediaItem[]
671
+ platformSpecific?: Record<string, unknown>
672
+ }
673
+
674
+ interface ZernioCallResult {
675
+ ok: boolean
676
+ zernio_post_id?: string | null
677
+ platform_post_id?: string | null
678
+ error?: string
679
+ }
680
+
681
+ async function callZernio(args: ZernioCallArgs): Promise<ZernioCallResult> {
682
+ const payload: Record<string, unknown> = {
683
+ content: args.content,
684
+ platforms: args.platforms,
685
+ }
686
+ if (args.publishNow) payload.publishNow = true
687
+ if (args.useQueue) payload.useQueue = true
688
+ if (args.scheduledFor) payload.scheduledFor = args.scheduledFor
689
+ if (args.timezone) payload.timezone = args.timezone
690
+ if (args.mediaItems?.length) payload.mediaItems = args.mediaItems
691
+ if (args.platformSpecific &&
692
+ Object.keys(args.platformSpecific).length)
693
+ payload.platformSpecific = args.platformSpecific
694
+
695
+ try {
696
+ const res = await fetch(`${ZERNIO_BASE}/posts`, {
697
+ method: 'POST',
698
+ headers: {
699
+ Authorization: `Bearer ${args.apiKey}`,
700
+ 'Content-Type': 'application/json',
701
+ },
702
+ body: JSON.stringify(payload),
703
+ })
704
+ const text = await res.text()
705
+ if (!res.ok) return { ok: false, error: `Zernio ${res.status}: ${text.slice(0, 300)}` }
706
+ const body = safeJson(text) as Record<string, unknown> | null
707
+ // Zernio shape can vary; grab the first result we recognise.
708
+ const first = Array.isArray(body?.results) ? (body.results as Record<string, unknown>[])[0]
709
+ : Array.isArray(body?.posts) ? (body.posts as Record<string, unknown>[])[0]
710
+ : body
711
+ return {
712
+ ok: true,
713
+ zernio_post_id: (first?.id ?? first?.post_id ?? first?.zernio_post_id ?? null) as string | null,
714
+ platform_post_id: (first?.platform_post_id ?? first?.platformPostId ?? null) as string | null,
715
+ }
716
+ } catch (e) {
717
+ return { ok: false, error: `Zernio fetch failed: ${(e as Error).message}` }
718
+ }
719
+ }
720
+
721
+ // ── helpers ────────────────────────────────────────────────────────────────
722
+
723
+ function getMaxContentLength(platform: SocialPlatform): number {
724
+ // Matches businesskit-files/social.ts SOCIAL_PLATFORMS.
725
+ const m: Record<SocialPlatform, number> = {
726
+ twitter: 280, instagram: 2200, facebook: 63206, linkedin: 3000, tiktok: 2200,
727
+ youtube: 5000, pinterest: 500, reddit: 40000, bluesky: 300, threads: 500,
728
+ googlebusiness: 1500, telegram: 4096, snapchat: 0,
729
+ }
730
+ return m[platform] ?? MAX_CONTENT_DEF
731
+ }
732
+
733
+ function safeJson(s: string): unknown {
734
+ try { return JSON.parse(s) } catch { return null }
735
+ }
736
+
737
+ /** Small non-crypto hash for idempotency_key disambiguation. */
738
+ function sha(s: string): string {
739
+ let h = 0
740
+ for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0
741
+ return (h >>> 0).toString(36).padStart(8, '0')
742
+ }
743
+
744
+ export const socialAgent = new SocialAgent()