@businesskit/agent 1.0.2 → 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.
- package/.claude/settings.json +16 -0
- package/.claude/settings.local.json +11 -0
- package/.claude-plugin/marketplace.json +36 -0
- package/.claude-plugin/plugin.json +7 -28
- package/.env.example +10 -0
- package/CLAUDE.md +56 -195
- package/HEARTBEAT.md +81 -57
- package/PLAN.md +211 -119
- package/PRD-Agent-Composition.md +149 -0
- package/README.md +25 -11
- package/REFERENCE.md +160 -0
- package/SOUL.md +31 -0
- package/SYSTEM.md +22 -0
- package/agents/_base.ts +352 -44
- package/agents/analytics/SOUL.md +11 -0
- package/agents/analytics/analytics.ts +405 -0
- package/agents/business/SOUL.md +11 -0
- package/agents/{csuite/cbo.ts → business/business.ts} +2 -2
- package/agents/ceo/SOUL.md +15 -0
- package/agents/{csuite → ceo}/ceo.ts +33 -8
- package/agents/content/SOUL.md +11 -0
- package/agents/content/content.ts +379 -0
- package/agents/copywriting/SOUL.md +11 -0
- package/agents/courses/SOUL.md +11 -0
- package/agents/courses/courses.ts +451 -0
- package/agents/docs/SOUL.md +11 -0
- package/agents/forms/SOUL.md +11 -0
- package/agents/forms/forms.ts +364 -0
- package/agents/hiring/SOUL.md +11 -0
- package/agents/hiring/hiring.ts +314 -0
- package/agents/marketing/SOUL.md +15 -0
- package/agents/{csuite/cmo.ts → marketing/marketing.ts} +3 -3
- package/agents/newsletter/SOUL.md +11 -0
- package/agents/operations/SOUL.md +11 -0
- package/agents/operations/operations.ts +157 -0
- package/agents/sales/SOUL.md +44 -0
- package/agents/sales/sales.ts +883 -0
- package/agents/scheduler/SOUL.md +11 -0
- package/agents/{growth → scheduler}/scheduler.ts +2 -2
- package/agents/seo/SOUL.md +11 -0
- package/agents/{growth/seo-agent.ts → seo/seo.ts} +60 -54
- package/agents/social/SOUL.md +11 -0
- package/agents/social/social.ts +744 -0
- package/agents/store/SOUL.md +11 -0
- package/agents/store/store.ts +514 -0
- package/cli.ts +44 -25
- package/lib/cms.ts +88 -0
- package/lib/db.ts +58 -11
- package/lib/enums.ts +25 -0
- package/lib/groups.ts +122 -0
- package/lib/id.ts +38 -10
- package/lib/profile.ts +44 -8
- package/lib/schema.ts +2015 -0
- package/lib/validate.ts +33 -0
- package/package.json +1 -1
- package/scripts/generate-schema.ts +244 -0
- package/setup.ts +16 -2
- package/{.agents/skills/analytics.md → skills/analytics/SKILL.md} +6 -1
- package/{.agents/skills/brand.md → skills/brand/SKILL.md} +14 -1
- package/skills/ceo/SKILL.md +25 -0
- package/skills/cmo/SKILL.md +8 -0
- package/skills/humanizer/SKILL.md +270 -0
- package/skills/schema/SKILL.md +86 -0
- package/tsconfig.json +2 -1
- package/.agents/skills/schema.md +0 -45
- package/.agents/skills/store.md +0 -46
- package/.claude/skills/agents.md +0 -56
- package/.claude/skills/analytics.md +0 -7
- package/.claude/skills/brand.md +0 -44
- package/.claude/skills/humanizer.md +0 -474
- package/.claude/skills/schema.md +0 -45
- package/agents/creators/blog-writer.ts +0 -347
- package/agents/creators/course-creator.ts +0 -106
- package/agents/creators/crm-agent.ts +0 -479
- package/agents/creators/forms-builder.ts +0 -90
- package/agents/creators/jobs-manager.ts +0 -82
- package/agents/creators/store-manager.ts +0 -138
- package/agents/csuite/coo.ts +0 -115
- package/agents/growth/analytics-agent.ts +0 -52
- package/agents/growth/social-agent.ts +0 -346
- /package/{ingest.md → .claude/commands/ingest.md} +0 -0
- /package/agents/{creators/copywriter.ts → copywriting/copywriting.ts} +0 -0
- /package/agents/{creators/docs-writer.ts → docs/docs.ts} +0 -0
- /package/agents/{creators/newsletter-writer.ts → newsletter/newsletter.ts} +0 -0
- /package/{ABOUT-ME.md → context/about-me.md} +0 -0
- /package/{brand-voice.md → context/brand-voice.md} +0 -0
- /package/{working-style.md → context/working-style.md} +0 -0
- /package/{.claude/skills → skills}/README.md +0 -0
- /package/{.agents/skills/agents.md → skills/agents/SKILL.md} +0 -0
- /package/{.claude/skills/blog-writing.md → skills/blog-writer/SKILL.md} +0 -0
- /package/{.claude/skills/store-copywriting.md → skills/copywriting/SKILL.md} +0 -0
- /package/{.claude/skills/social-content.md → skills/social/SKILL.md} +0 -0
- /package/{.claude/skills → skills/social}/content-seo.md +0 -0
- /package/{.claude/skills/store.md → skills/store/SKILL.md} +0 -0
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* LEO — Store Manager
|
|
3
|
-
* "Every product type lives here. Digital commerce is my domain."
|
|
4
|
-
*
|
|
5
|
-
* Handles: digital downloads, courses (SAGE delegates here), 1:1 meetings,
|
|
6
|
-
* webinars, events, listings, sponsorships, services
|
|
7
|
-
* Writes to: products table
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import { BaseAgent, db, ulid, now } from '../_base.ts'
|
|
11
|
-
import { uniqueSlug } from '../../lib/slug.ts'
|
|
12
|
-
|
|
13
|
-
export type ProductType =
|
|
14
|
-
| 'download' | 'course' | 'meeting' | 'webinar'
|
|
15
|
-
| 'event' | 'listing' | 'sponsorship' | 'service'
|
|
16
|
-
|
|
17
|
-
export interface ProductInput {
|
|
18
|
-
type: ProductType
|
|
19
|
-
title: string
|
|
20
|
-
description?: string
|
|
21
|
-
excerpt?: string
|
|
22
|
-
price_cents: number
|
|
23
|
-
sale_price_cents?: number
|
|
24
|
-
currency?: string
|
|
25
|
-
thumbnail_url?: string
|
|
26
|
-
// type-specific
|
|
27
|
-
file_url?: string // download
|
|
28
|
-
calendar_link?: string // meeting
|
|
29
|
-
scheduling_provider?: string
|
|
30
|
-
webinar_link?: string // webinar
|
|
31
|
-
webinar_platform?: string
|
|
32
|
-
webinar_schedule?: string // JSON schedule
|
|
33
|
-
webinar_settings?: string
|
|
34
|
-
event_settings?: string // event
|
|
35
|
-
meeting_settings?: string
|
|
36
|
-
billing_interval?: string // sponsorship: 'month'|'year'|'once'
|
|
37
|
-
features?: string[]
|
|
38
|
-
tags?: string[]
|
|
39
|
-
button_text?: string
|
|
40
|
-
platform_name?: string // listing
|
|
41
|
-
platform_url?: string
|
|
42
|
-
post_frequency?: string
|
|
43
|
-
cta_button?: Record<string, string>
|
|
44
|
-
publish?: boolean
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export class StoreManager extends BaseAgent {
|
|
48
|
-
readonly name = 'LEO'
|
|
49
|
-
readonly title = 'Store Manager'
|
|
50
|
-
|
|
51
|
-
async create(input: ProductInput) {
|
|
52
|
-
await this.init()
|
|
53
|
-
const id = ulid()
|
|
54
|
-
const slug = await uniqueSlug('products', input.title) // global unique
|
|
55
|
-
const ts = now()
|
|
56
|
-
|
|
57
|
-
await db.execute({
|
|
58
|
-
sql: `INSERT INTO products
|
|
59
|
-
(id,profile_id,user_id,type,title,excerpt,description,
|
|
60
|
-
price_cents,sale_price_cents,currency,slug,thumbnail_url,
|
|
61
|
-
file_url,calendar_link,scheduling_provider,
|
|
62
|
-
webinar_link,webinar_platform,webinar_schedule,webinar_settings,
|
|
63
|
-
event_settings,meeting_settings,billing_interval,
|
|
64
|
-
features,tags,button_text,platform_name,platform_url,post_frequency,
|
|
65
|
-
cta_button,is_active,published,hidden,created_at,updated_at)
|
|
66
|
-
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,0,?,?)`,
|
|
67
|
-
args: [
|
|
68
|
-
id, this.profileId, this.userId,
|
|
69
|
-
input.type, input.title, input.excerpt ?? null, input.description ?? null,
|
|
70
|
-
input.price_cents, input.sale_price_cents ?? null, input.currency ?? 'usd',
|
|
71
|
-
slug, input.thumbnail_url ?? null,
|
|
72
|
-
input.file_url ?? null, input.calendar_link ?? null, input.scheduling_provider ?? null,
|
|
73
|
-
input.webinar_link ?? null, input.webinar_platform ?? null,
|
|
74
|
-
input.webinar_schedule ?? null, input.webinar_settings ?? null,
|
|
75
|
-
input.event_settings ?? null, input.meeting_settings ?? null,
|
|
76
|
-
input.billing_interval ?? null,
|
|
77
|
-
input.features ? JSON.stringify(input.features) : null,
|
|
78
|
-
input.tags ? JSON.stringify(input.tags) : null,
|
|
79
|
-
input.button_text ?? null,
|
|
80
|
-
input.platform_name ?? null, input.platform_url ?? null, input.post_frequency ?? null,
|
|
81
|
-
input.cta_button ? JSON.stringify(input.cta_button) : '{}',
|
|
82
|
-
input.publish ? 1 : 0, ts, ts,
|
|
83
|
-
],
|
|
84
|
-
})
|
|
85
|
-
|
|
86
|
-
// Seed analytics row
|
|
87
|
-
await db.execute({
|
|
88
|
-
sql: `INSERT OR IGNORE INTO product_analytics (id,product_id,profile_id,created_at,updated_at)
|
|
89
|
-
VALUES (?,?,?,?,?)`,
|
|
90
|
-
args: [id, id, this.profileId, ts, ts],
|
|
91
|
-
})
|
|
92
|
-
|
|
93
|
-
return this.get(id)
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
async get(id: string) {
|
|
97
|
-
const { rows: [r] } = await db.execute({ sql: 'SELECT * FROM products WHERE id=?', args: [id] })
|
|
98
|
-
if (!r) throw new Error(`Product not found: ${id}`)
|
|
99
|
-
return r
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
async list(opts: { type?: ProductType; published?: boolean; limit?: number } = {}) {
|
|
103
|
-
await this.init()
|
|
104
|
-
const args: unknown[] = [this.profileId]
|
|
105
|
-
let where = 'WHERE profile_id=? AND hidden=0'
|
|
106
|
-
if (opts.type) { where += ' AND type=?'; args.push(opts.type) }
|
|
107
|
-
if (opts.published !== undefined) { where += ' AND published=?'; args.push(opts.published ? 1 : 0) }
|
|
108
|
-
const { rows } = await db.execute({
|
|
109
|
-
sql: `SELECT id,type,title,slug,price_cents,published FROM products
|
|
110
|
-
${where} ORDER BY created_at DESC LIMIT ?`,
|
|
111
|
-
args: [...args, opts.limit ?? 50],
|
|
112
|
-
})
|
|
113
|
-
return rows
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
async publish(id: string) {
|
|
117
|
-
const ts = now()
|
|
118
|
-
await db.execute({
|
|
119
|
-
sql: 'UPDATE products SET published=1,published_at=?,updated_at=? WHERE id=?',
|
|
120
|
-
args: [ts, ts, id],
|
|
121
|
-
})
|
|
122
|
-
return this.get(id)
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
async archive(id: string) { await super.archive('products', id) }
|
|
126
|
-
|
|
127
|
-
async storeOverview() {
|
|
128
|
-
await this.init()
|
|
129
|
-
const { rows } = await db.execute({
|
|
130
|
-
sql: `SELECT type, COUNT(*) n, SUM(CASE WHEN published=1 THEN 1 ELSE 0 END) live
|
|
131
|
-
FROM products WHERE profile_id=? AND hidden=0 GROUP BY type ORDER BY n DESC`,
|
|
132
|
-
args: [this.profileId],
|
|
133
|
-
})
|
|
134
|
-
return rows
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
export const storeManager = new StoreManager()
|
package/agents/csuite/coo.ts
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OTTO — Chief Operating Officer
|
|
3
|
-
* "Pipelines don't run themselves. I make sure they do."
|
|
4
|
-
* Manages: publish queue, draft pipeline, scheduling
|
|
5
|
-
* Phase 3: becomes the CF Durable Object that runs everything autonomously
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import { BaseAgent, db, now, iso } from '../_base.ts'
|
|
9
|
-
|
|
10
|
-
interface ScheduledItem {
|
|
11
|
-
table: string; id: string; title: string; scheduled_for: string | number
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export class COO extends BaseAgent {
|
|
15
|
-
readonly name = 'OTTO'
|
|
16
|
-
readonly title = 'Chief Operating Officer'
|
|
17
|
-
|
|
18
|
-
/** All drafts across every content type */
|
|
19
|
-
async draftPipeline() {
|
|
20
|
-
await this.init()
|
|
21
|
-
const tables = [
|
|
22
|
-
{ table: 'posts', label: 'Blog Posts', dateCol: 'date' },
|
|
23
|
-
{ table: 'products', label: 'Products', dateCol: null },
|
|
24
|
-
{ table: 'pages', label: 'Pages', dateCol: null },
|
|
25
|
-
{ table: 'job_listings', label: 'Jobs', dateCol: null },
|
|
26
|
-
{ table: 'forms', label: 'Forms', dateCol: null },
|
|
27
|
-
]
|
|
28
|
-
|
|
29
|
-
const results = await Promise.all(tables.map(async ({ table, label, dateCol }) => {
|
|
30
|
-
const { rows } = await db.execute({
|
|
31
|
-
sql: `SELECT id, title, ${dateCol ?? 'created_at'} AS scheduled_for
|
|
32
|
-
FROM ${table} WHERE profile_id=? AND published=0 AND hidden=0
|
|
33
|
-
ORDER BY created_at DESC`,
|
|
34
|
-
args: [this.profileId],
|
|
35
|
-
})
|
|
36
|
-
return { label, table, drafts: rows }
|
|
37
|
-
}))
|
|
38
|
-
|
|
39
|
-
return results.filter(r => r.drafts.length > 0)
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/** Content due for publish right now */
|
|
43
|
-
async publishQueue(): Promise<ScheduledItem[]> {
|
|
44
|
-
await this.init()
|
|
45
|
-
const nowUnix = now()
|
|
46
|
-
const nowISO = iso()
|
|
47
|
-
const queue: ScheduledItem[] = []
|
|
48
|
-
|
|
49
|
-
// ISO date tables: posts, job_listings
|
|
50
|
-
for (const table of ['posts', 'job_listings']) {
|
|
51
|
-
const { rows } = await db.execute({
|
|
52
|
-
sql: `SELECT id, title, date AS scheduled_for FROM ${table}
|
|
53
|
-
WHERE profile_id=? AND published=0 AND hidden=0
|
|
54
|
-
AND date IS NOT NULL AND date <= ? ORDER BY date ASC`,
|
|
55
|
-
args: [this.profileId, nowISO],
|
|
56
|
-
})
|
|
57
|
-
rows.forEach(r => queue.push({ table, id: r.id as string, title: r.title as string, scheduled_for: r.scheduled_for as string }))
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// Unix timestamp tables: products
|
|
61
|
-
const { rows: products } = await db.execute({
|
|
62
|
-
sql: `SELECT id, title, published_at AS scheduled_for FROM products
|
|
63
|
-
WHERE profile_id=? AND published=0 AND hidden=0
|
|
64
|
-
AND published_at IS NOT NULL AND published_at <= ? ORDER BY published_at ASC`,
|
|
65
|
-
args: [this.profileId, nowUnix],
|
|
66
|
-
})
|
|
67
|
-
products.forEach(r => queue.push({ table: 'products', id: r.id as string, title: r.title as string, scheduled_for: r.scheduled_for as number }))
|
|
68
|
-
|
|
69
|
-
return queue
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* Run the publish queue — flips published=1 on all due items.
|
|
74
|
-
* Phase 1: call manually. Phase 3: called by CF Durable Object on cron.
|
|
75
|
-
*/
|
|
76
|
-
async runPublishQueue(): Promise<ScheduledItem[]> {
|
|
77
|
-
await this.init()
|
|
78
|
-
const { n8n_webhook_url } = this.ctx.credentials
|
|
79
|
-
const queue = await this.publishQueue()
|
|
80
|
-
if (!queue.length) return []
|
|
81
|
-
|
|
82
|
-
const isoTables = new Set(['posts', 'job_listings'])
|
|
83
|
-
const statements = queue.map(item => ({
|
|
84
|
-
sql: `UPDATE ${item.table} SET published=1, updated_at=? WHERE id=?`,
|
|
85
|
-
args: [isoTables.has(item.table) ? iso() : now(), item.id],
|
|
86
|
-
}))
|
|
87
|
-
await db.batch(statements)
|
|
88
|
-
|
|
89
|
-
// Notify n8n once with the full batch
|
|
90
|
-
if (n8n_webhook_url) {
|
|
91
|
-
fetch(n8n_webhook_url, {
|
|
92
|
-
method: 'POST',
|
|
93
|
-
headers: { 'Content-Type': 'application/json' },
|
|
94
|
-
body: JSON.stringify({ event: 'content_published', business: this.ctx.profile.title, items: queue }),
|
|
95
|
-
}).catch(() => { /* non-blocking */ })
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
return queue
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** Schedule any content for future publish */
|
|
102
|
-
async schedule(table: 'posts' | 'products' | 'job_listings', id: string, at: Date) {
|
|
103
|
-
const isISO = table !== 'products'
|
|
104
|
-
const dateCol = table === 'products' ? 'published_at' : 'date'
|
|
105
|
-
const val = isISO ? at.toISOString().slice(0, 19) + 'Z' : Math.floor(at.getTime() / 1000)
|
|
106
|
-
const updCol = isISO ? `updated_at='${iso()}'` : `updated_at=${now()}`
|
|
107
|
-
|
|
108
|
-
await db.execute({
|
|
109
|
-
sql: `UPDATE ${table} SET published=0, ${dateCol}=?, ${updCol} WHERE id=?`,
|
|
110
|
-
args: [val, id],
|
|
111
|
-
})
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
export const coo = new COO()
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ATLAS — Analytics Agent
|
|
3
|
-
* "I see everything. I tell you what it means."
|
|
4
|
-
*
|
|
5
|
-
* Read-only. Never writes. Used by ARIA, REX, NOVA for intelligence.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import { BaseAgent } from '../_base.ts'
|
|
9
|
-
import { profileSummary, productSummary, linkSummary, formSummary } from '../../lib/analytics.ts'
|
|
10
|
-
|
|
11
|
-
export class AnalyticsAgent extends BaseAgent {
|
|
12
|
-
readonly name = 'ATLAS'
|
|
13
|
-
readonly title = 'Analytics Agent'
|
|
14
|
-
|
|
15
|
-
async snapshot() {
|
|
16
|
-
await this.init()
|
|
17
|
-
const [profile, products, links, forms] = await Promise.all([
|
|
18
|
-
profileSummary(this.profileId),
|
|
19
|
-
productSummary(this.profileId),
|
|
20
|
-
linkSummary(this.profileId),
|
|
21
|
-
formSummary(this.profileId),
|
|
22
|
-
])
|
|
23
|
-
return { profile, products, links, forms }
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
async revenueReport() {
|
|
27
|
-
await this.init()
|
|
28
|
-
const products = await productSummary(this.profileId)
|
|
29
|
-
const profile = await profileSummary(this.profileId)
|
|
30
|
-
return {
|
|
31
|
-
total_revenue: profile?.total_revenue ?? 0,
|
|
32
|
-
revenue_trend: profile?.revenue_trend ?? 'no data',
|
|
33
|
-
last_30d_revenue: profile?.revenue_30d.reduce((a, b) => a + b, 0) ?? 0,
|
|
34
|
-
top_products: products.slice(0, 5),
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
async trafficReport() {
|
|
39
|
-
await this.init()
|
|
40
|
-
const profile = await profileSummary(this.profileId)
|
|
41
|
-
const links = await linkSummary(this.profileId)
|
|
42
|
-
return {
|
|
43
|
-
total_clicks: profile?.total_clicks ?? 0,
|
|
44
|
-
clicks_30d: profile?.clicks_30d ?? [],
|
|
45
|
-
top_countries: profile?.top_countries ?? [],
|
|
46
|
-
top_referrers: profile?.top_referrers ?? [],
|
|
47
|
-
top_links: links,
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export const analyticsAgent = new AnalyticsAgent()
|
|
@@ -1,346 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Social Agent — Agent-First SMM
|
|
3
|
-
*
|
|
4
|
-
* All posting goes through Zernio API (https://zernio.com/api/v1).
|
|
5
|
-
* Reads from social_accounts, social_posts, social_post_platforms in Turso.
|
|
6
|
-
* Writes social_posts rows, then calls Zernio to schedule/publish.
|
|
7
|
-
*
|
|
8
|
-
* Three modes (from social.ts):
|
|
9
|
-
* zernio_byok → user's own Zernio key from connections table
|
|
10
|
-
* zernio_platform → BusinessKit platform key via POST /api/social/schedule
|
|
11
|
-
* direct → n8n webhook fallback
|
|
12
|
-
*
|
|
13
|
-
* Agent reads mode from social_accounts.connection_mode and routes accordingly.
|
|
14
|
-
* Platform key (ZERNIO_API_KEY) is NEVER used here — that's the Worker's job.
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
import { BaseAgent, db, ulid, now, iso } from '../_base.ts'
|
|
18
|
-
|
|
19
|
-
const ZERNIO_BASE = 'https://zernio.com/api/v1'
|
|
20
|
-
|
|
21
|
-
export type SocialPlatform =
|
|
22
|
-
| 'twitter' | 'instagram' | 'facebook' | 'linkedin' | 'tiktok'
|
|
23
|
-
| 'youtube' | 'pinterest' | 'reddit' | 'bluesky' | 'threads'
|
|
24
|
-
| 'googlebusiness' | 'telegram' | 'snapchat'
|
|
25
|
-
|
|
26
|
-
export interface PostInput {
|
|
27
|
-
content: string
|
|
28
|
-
platforms?: SocialPlatform[] // omit = all connected accounts
|
|
29
|
-
scheduledFor?: string // ISO: '2026-04-01T09:00:00'
|
|
30
|
-
timezone?: string // default: 'UTC'
|
|
31
|
-
publishNow?: boolean
|
|
32
|
-
useQueue?: boolean // use Zernio's recurring queue
|
|
33
|
-
mediaItems?: Array<{ url: string; type: 'image' | 'video' | 'document' }>
|
|
34
|
-
sourceId?: string // FK to posts.id / products.id for cross-post
|
|
35
|
-
sourceType?: 'blog_crosspost' | 'product_launch' | 'manual'
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export interface PostResult {
|
|
39
|
-
ok: boolean
|
|
40
|
-
post_id?: string // local social_posts.id
|
|
41
|
-
zernio_post_id?: string // Zernio's post ID
|
|
42
|
-
platforms: string[]
|
|
43
|
-
status: string
|
|
44
|
-
error?: string
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export class SocialAgent extends BaseAgent {
|
|
48
|
-
readonly name = 'Social Agent'
|
|
49
|
-
readonly title = 'Social Agent'
|
|
50
|
-
|
|
51
|
-
// ── Read state from DB ──────────────────────────────────────────────────────
|
|
52
|
-
|
|
53
|
-
async listAccounts(activeOnly = true) {
|
|
54
|
-
await this.init()
|
|
55
|
-
let sql = 'SELECT * FROM social_accounts WHERE profile_id=?'
|
|
56
|
-
const args: unknown[] = [this.profileId]
|
|
57
|
-
if (activeOnly) { sql += ' AND is_active=1 AND is_connected=1' }
|
|
58
|
-
const { rows } = await db.execute({ sql, args })
|
|
59
|
-
return rows
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
async listPosts(opts: { status?: string; limit?: number } = {}) {
|
|
63
|
-
await this.init()
|
|
64
|
-
let sql = 'SELECT * FROM social_posts WHERE profile_id=? AND hidden=0'
|
|
65
|
-
const args: unknown[] = [this.profileId]
|
|
66
|
-
if (opts.status) { sql += ' AND status=?'; args.push(opts.status) }
|
|
67
|
-
sql += ` ORDER BY created_at DESC LIMIT ${opts.limit ?? 20}`
|
|
68
|
-
const { rows } = await db.execute({ sql, args })
|
|
69
|
-
return rows
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
async getDrafts() { return this.listPosts({ status: 'draft' }) }
|
|
73
|
-
async getScheduled() { return this.listPosts({ status: 'scheduled' }) }
|
|
74
|
-
|
|
75
|
-
async getAnalytics(accountId: string) {
|
|
76
|
-
const { rows: [r] } = await db.execute({
|
|
77
|
-
sql: 'SELECT * FROM social_analytics WHERE account_id=? LIMIT 1',
|
|
78
|
-
args: [accountId],
|
|
79
|
-
})
|
|
80
|
-
return r ?? null
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
async getInbox(opts: { status?: string; type?: string; limit?: number } = {}) {
|
|
84
|
-
await this.init()
|
|
85
|
-
let sql = 'SELECT * FROM social_inbox WHERE profile_id=?'
|
|
86
|
-
const args: unknown[] = [this.profileId]
|
|
87
|
-
if (opts.status) { sql += ' AND status=?'; args.push(opts.status) }
|
|
88
|
-
if (opts.type) { sql += ' AND type=?'; args.push(opts.type) }
|
|
89
|
-
sql += ` ORDER BY received_at DESC LIMIT ${opts.limit ?? 50}`
|
|
90
|
-
const { rows } = await db.execute({ sql, args })
|
|
91
|
-
return rows
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
// ── Core: create + schedule a post ─────────────────────────────────────────
|
|
95
|
-
|
|
96
|
-
async post(input: PostInput): Promise<PostResult> {
|
|
97
|
-
await this.init()
|
|
98
|
-
|
|
99
|
-
// 1. Determine which accounts to post to
|
|
100
|
-
const accounts = await this.listAccounts()
|
|
101
|
-
if (!accounts.length) {
|
|
102
|
-
return { ok: false, platforms: [], status: 'no_accounts',
|
|
103
|
-
error: 'No connected social accounts. Connect platforms in BusinessKit → Settings → Social.' }
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
const targets = input.platforms
|
|
107
|
-
? accounts.filter(a => input.platforms!.includes(a.platform as SocialPlatform))
|
|
108
|
-
: accounts
|
|
109
|
-
|
|
110
|
-
if (!targets.length) {
|
|
111
|
-
return { ok: false, platforms: [], status: 'no_matching_accounts',
|
|
112
|
-
error: `No accounts connected for: ${input.platforms?.join(', ')}` }
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
// 2. Resolve Zernio key (BYOK only — platform key goes via /api/social/schedule)
|
|
116
|
-
const zernioKey = await this.resolveZernioKey()
|
|
117
|
-
|
|
118
|
-
// 3. Determine connection mode
|
|
119
|
-
const mode = targets[0].connection_mode as string
|
|
120
|
-
|
|
121
|
-
if (mode === 'zernio_byok' && zernioKey) {
|
|
122
|
-
return this.postViaZernio(input, targets, zernioKey, 'byok')
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
if (mode === 'zernio_platform') {
|
|
126
|
-
// Needs session token — only works in-app (Phase 2)
|
|
127
|
-
return {
|
|
128
|
-
ok: false, platforms: [], status: 'requires_session',
|
|
129
|
-
error: 'Platform key posting requires authentication. Use /api/social/schedule from the dashboard.',
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
if (mode === 'n8n' || this.ctx.credentials.n8n_webhook_url) {
|
|
134
|
-
return this.postViaN8n(input, targets)
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
return { ok: false, platforms: [], status: 'no_method',
|
|
138
|
-
error: 'No Zernio key or n8n webhook configured.' }
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
// ── Zernio posting (BYOK) ───────────────────────────────────────────────────
|
|
142
|
-
|
|
143
|
-
private async postViaZernio(
|
|
144
|
-
input: PostInput,
|
|
145
|
-
accounts: typeof Object[],
|
|
146
|
-
apiKey: string,
|
|
147
|
-
scheduledVia: 'byok' | 'platform'
|
|
148
|
-
): Promise<PostResult> {
|
|
149
|
-
const platforms = accounts.map((a: any) => ({
|
|
150
|
-
platform: a.platform,
|
|
151
|
-
accountId: a.zernio_account_id,
|
|
152
|
-
}))
|
|
153
|
-
|
|
154
|
-
const payload: Record<string, unknown> = {
|
|
155
|
-
content: input.content,
|
|
156
|
-
platforms,
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
if (input.publishNow) payload.publishNow = true
|
|
160
|
-
if (input.useQueue) payload.useQueue = true
|
|
161
|
-
if (input.scheduledFor) payload.scheduledFor = input.scheduledFor
|
|
162
|
-
if (input.timezone) payload.timezone = input.timezone ?? 'UTC'
|
|
163
|
-
if (input.mediaItems?.length) payload.mediaItems = input.mediaItems
|
|
164
|
-
|
|
165
|
-
let zernioRes: { id?: string; status?: string } = {}
|
|
166
|
-
let ok = false
|
|
167
|
-
let error: string | undefined
|
|
168
|
-
|
|
169
|
-
try {
|
|
170
|
-
const res = await fetch(`${ZERNIO_BASE}/posts`, {
|
|
171
|
-
method: 'POST',
|
|
172
|
-
headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
|
|
173
|
-
body: JSON.stringify(payload),
|
|
174
|
-
})
|
|
175
|
-
if (res.ok) {
|
|
176
|
-
zernioRes = await res.json() as typeof zernioRes
|
|
177
|
-
ok = true
|
|
178
|
-
} else {
|
|
179
|
-
const errBody = await res.text()
|
|
180
|
-
error = `Zernio ${res.status}: ${errBody}`
|
|
181
|
-
}
|
|
182
|
-
} catch (e) {
|
|
183
|
-
error = String(e)
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
// Write to social_posts regardless — draft if failed
|
|
187
|
-
const postId = ulid()
|
|
188
|
-
const ts = now()
|
|
189
|
-
const month = new Date().toISOString().slice(0, 7)
|
|
190
|
-
const status = ok
|
|
191
|
-
? (input.publishNow ? 'published' : input.scheduledFor ? 'scheduled' : 'queued')
|
|
192
|
-
: 'failed'
|
|
193
|
-
|
|
194
|
-
await db.execute({
|
|
195
|
-
sql: `INSERT INTO social_posts
|
|
196
|
-
(id,profile_id,content,status,scheduled_for,timezone,publish_now,use_queue,
|
|
197
|
-
source,source_id,zernio_post_id,scheduled_via,platform_schedule_month,
|
|
198
|
-
ai_generated,error,created_at,updated_at)
|
|
199
|
-
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0,?,?,?)`,
|
|
200
|
-
args: [
|
|
201
|
-
postId, this.profileId, input.content, status,
|
|
202
|
-
input.scheduledFor ?? null, input.timezone ?? 'UTC',
|
|
203
|
-
input.publishNow ? 1 : 0, input.useQueue ? 1 : 0,
|
|
204
|
-
input.sourceType ?? 'manual', input.sourceId ?? null,
|
|
205
|
-
zernioRes.id ?? null, scheduledVia, month,
|
|
206
|
-
error ?? null, ts, ts,
|
|
207
|
-
],
|
|
208
|
-
})
|
|
209
|
-
|
|
210
|
-
// Write per-platform rows
|
|
211
|
-
if (ok && zernioRes.id) {
|
|
212
|
-
const stmts = (accounts as any[]).map(a => ({
|
|
213
|
-
sql: `INSERT INTO social_post_platforms
|
|
214
|
-
(id,post_id,profile_id,account_id,platform,zernio_account_id,zernio_post_id,
|
|
215
|
-
status,created_at,updated_at)
|
|
216
|
-
VALUES (?,?,?,?,?,?,?,?,?,?)`,
|
|
217
|
-
args: [
|
|
218
|
-
ulid(), postId, this.profileId, a.id, a.platform,
|
|
219
|
-
a.zernio_account_id, zernioRes.id, status, ts, ts,
|
|
220
|
-
],
|
|
221
|
-
}))
|
|
222
|
-
await db.batch(stmts)
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
await this.logProgress(ok, input.content.slice(0, 60), (accounts as any[]).map(a => a.platform))
|
|
226
|
-
|
|
227
|
-
return {
|
|
228
|
-
ok,
|
|
229
|
-
post_id: postId,
|
|
230
|
-
zernio_post_id: zernioRes.id,
|
|
231
|
-
platforms: (accounts as any[]).map(a => a.platform),
|
|
232
|
-
status,
|
|
233
|
-
error,
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
// ── n8n fallback ────────────────────────────────────────────────────────────
|
|
238
|
-
|
|
239
|
-
private async postViaN8n(input: PostInput, accounts: typeof Object[]): Promise<PostResult> {
|
|
240
|
-
const { n8n_webhook_url } = this.ctx.credentials
|
|
241
|
-
if (!n8n_webhook_url) {
|
|
242
|
-
return { ok: false, platforms: [], status: 'no_n8n', error: 'No n8n webhook URL in credentials.' }
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
try {
|
|
246
|
-
const res = await fetch(n8n_webhook_url, {
|
|
247
|
-
method: 'POST',
|
|
248
|
-
headers: { 'Content-Type': 'application/json' },
|
|
249
|
-
body: JSON.stringify({
|
|
250
|
-
event: 'social_post',
|
|
251
|
-
profile_id: this.profileId,
|
|
252
|
-
business: this.ctx.profile.title,
|
|
253
|
-
content: input.content,
|
|
254
|
-
platforms: (accounts as any[]).map(a => a.platform),
|
|
255
|
-
scheduled_for: input.scheduledFor ?? null,
|
|
256
|
-
publish_now: input.publishNow ?? false,
|
|
257
|
-
source_id: input.sourceId ?? null,
|
|
258
|
-
timestamp: iso(),
|
|
259
|
-
}),
|
|
260
|
-
})
|
|
261
|
-
return {
|
|
262
|
-
ok: res.ok,
|
|
263
|
-
platforms: (accounts as any[]).map(a => a.platform),
|
|
264
|
-
status: res.ok ? 'sent_to_n8n' : 'n8n_error',
|
|
265
|
-
error: res.ok ? undefined : `n8n returned ${res.status}`,
|
|
266
|
-
}
|
|
267
|
-
} catch (e) {
|
|
268
|
-
return { ok: false, platforms: [], status: 'n8n_error', error: String(e) }
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
// ── Convenience: cross-post from content ────────────────────────────────────
|
|
273
|
-
|
|
274
|
-
async crossPostBlog(postId: string, title: string, slug: string, excerpt?: string) {
|
|
275
|
-
const url = `https://${this.ctx.profile.slug}.businesskit.io/blog/${slug}`
|
|
276
|
-
const content = excerpt ? `${title}\n\n${excerpt}\n\n${url}` : `${title}\n\n${url}`
|
|
277
|
-
return this.post({ content, sourceId: postId, sourceType: 'blog_crosspost' })
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
async announceProduct(productId: string, title: string, slug: string, priceCents: number) {
|
|
281
|
-
const url = `https://${this.ctx.profile.slug}.businesskit.io/store/${slug}`
|
|
282
|
-
const price = `$${(priceCents / 100).toFixed(2)}`
|
|
283
|
-
const content = `New: ${title} — ${price}\n\n${url}`
|
|
284
|
-
return this.post({ content, sourceId: productId, sourceType: 'product_launch' })
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
// ── Queue management ────────────────────────────────────────────────────────
|
|
288
|
-
|
|
289
|
-
async listQueueSlots(accountId?: string) {
|
|
290
|
-
await this.init()
|
|
291
|
-
let sql = 'SELECT * FROM social_queue WHERE profile_id=?'
|
|
292
|
-
const args: unknown[] = [this.profileId]
|
|
293
|
-
if (accountId) { sql += ' AND account_id=?'; args.push(accountId) }
|
|
294
|
-
sql += ' ORDER BY day_of_week ASC, time_of_day ASC'
|
|
295
|
-
const { rows } = await db.execute({ sql, args })
|
|
296
|
-
return rows
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
// ── Analytics summary ───────────────────────────────────────────────────────
|
|
300
|
-
|
|
301
|
-
async socialSummary() {
|
|
302
|
-
await this.init()
|
|
303
|
-
const accounts = await this.listAccounts()
|
|
304
|
-
const { rows: [counts] } = await db.execute({
|
|
305
|
-
sql: `SELECT
|
|
306
|
-
COUNT(*) total,
|
|
307
|
-
SUM(CASE WHEN status='published' THEN 1 ELSE 0 END) published,
|
|
308
|
-
SUM(CASE WHEN status='scheduled' THEN 1 ELSE 0 END) scheduled,
|
|
309
|
-
SUM(CASE WHEN status='draft' THEN 1 ELSE 0 END) drafts
|
|
310
|
-
FROM social_posts WHERE profile_id=? AND hidden=0`,
|
|
311
|
-
args: [this.profileId],
|
|
312
|
-
})
|
|
313
|
-
return { accounts: accounts.length, posts: counts }
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
// ── Helpers ─────────────────────────────────────────────────────────────────
|
|
317
|
-
|
|
318
|
-
private async resolveZernioKey(): Promise<string | null> {
|
|
319
|
-
try {
|
|
320
|
-
const { rows: [r] } = await db.execute({
|
|
321
|
-
sql: `SELECT client_id FROM connections
|
|
322
|
-
WHERE profile_id=? AND service='zernio' AND is_active=1 AND client_id IS NOT NULL
|
|
323
|
-
LIMIT 1`,
|
|
324
|
-
args: [this.profileId],
|
|
325
|
-
})
|
|
326
|
-
return (r?.client_id as string) ?? null
|
|
327
|
-
} catch {
|
|
328
|
-
return null
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
private async logProgress(ok: boolean, preview: string, platforms: string[]) {
|
|
333
|
-
try {
|
|
334
|
-
const { logMemory } = await import('../../lib/memory.ts')
|
|
335
|
-
await logMemory(
|
|
336
|
-
'social',
|
|
337
|
-
ok
|
|
338
|
-
? `Posted "${preview.slice(0, 80)}..." to ${platforms.join(', ')}`
|
|
339
|
-
: `Failed to post "${preview.slice(0, 80)}..."`,
|
|
340
|
-
{ platforms, ok }
|
|
341
|
-
)
|
|
342
|
-
} catch { /* memory_log optional until provisioned */ }
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
export const socialAgent = new SocialAgent()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|