@businesskit/agent 1.0.0

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 (84) hide show
  1. package/.agents/skills/agents.md +56 -0
  2. package/.agents/skills/analytics.md +47 -0
  3. package/.agents/skills/brand.md +87 -0
  4. package/.agents/skills/schema.md +45 -0
  5. package/.agents/skills/store.md +46 -0
  6. package/.claude/commands/analytics.md +7 -0
  7. package/.claude/commands/blog-writer.md +9 -0
  8. package/.claude/commands/cbo.md +7 -0
  9. package/.claude/commands/ceo.md +10 -0
  10. package/.claude/commands/cmo.md +7 -0
  11. package/.claude/commands/compress.md +73 -0
  12. package/.claude/commands/coo.md +11 -0
  13. package/.claude/commands/copywriter.md +15 -0
  14. package/.claude/commands/course-creator.md +9 -0
  15. package/.claude/commands/crm.md +82 -0
  16. package/.claude/commands/deep.md +50 -0
  17. package/.claude/commands/docs-writer.md +8 -0
  18. package/.claude/commands/forms-builder.md +10 -0
  19. package/.claude/commands/jobs-manager.md +8 -0
  20. package/.claude/commands/kb.md +107 -0
  21. package/.claude/commands/newsletter-writer.md +9 -0
  22. package/.claude/commands/preserve.md +64 -0
  23. package/.claude/commands/resume.md +67 -0
  24. package/.claude/commands/scheduler.md +8 -0
  25. package/.claude/commands/seo.md +60 -0
  26. package/.claude/commands/social.md +51 -0
  27. package/.claude/commands/store-manager.md +11 -0
  28. package/.claude/skills/README.md +33 -0
  29. package/.claude/skills/agents.md +56 -0
  30. package/.claude/skills/analytics.md +7 -0
  31. package/.claude/skills/blog-writing.md +452 -0
  32. package/.claude/skills/brand.md +44 -0
  33. package/.claude/skills/content-seo.md +0 -0
  34. package/.claude/skills/humanizer.md +474 -0
  35. package/.claude/skills/schema.md +45 -0
  36. package/.claude/skills/social-content.md +278 -0
  37. package/.claude/skills/store-copywriting.md +519 -0
  38. package/.claude/skills/store.md +62 -0
  39. package/.claude-plugin/plugin.json +33 -0
  40. package/.cursorrules +0 -0
  41. package/.env.example +2 -0
  42. package/.mcp.json +3 -0
  43. package/AGENTS.md +63 -0
  44. package/CLAUDE.md +221 -0
  45. package/GEMINI.md +37 -0
  46. package/LICENSE +21 -0
  47. package/PLAN.md +253 -0
  48. package/PRD-Agent-Harness.md +316 -0
  49. package/README.md +237 -0
  50. package/SYSTEM.md +49 -0
  51. package/agents/_base.ts +63 -0
  52. package/agents/creators/blog-writer.ts +347 -0
  53. package/agents/creators/copywriter.ts +89 -0
  54. package/agents/creators/course-creator.ts +106 -0
  55. package/agents/creators/crm-agent.ts +479 -0
  56. package/agents/creators/docs-writer.ts +77 -0
  57. package/agents/creators/forms-builder.ts +90 -0
  58. package/agents/creators/jobs-manager.ts +82 -0
  59. package/agents/creators/newsletter-writer.ts +91 -0
  60. package/agents/creators/store-manager.ts +138 -0
  61. package/agents/csuite/cbo.ts +109 -0
  62. package/agents/csuite/ceo.ts +121 -0
  63. package/agents/csuite/cmo.ts +109 -0
  64. package/agents/csuite/coo.ts +115 -0
  65. package/agents/growth/analytics-agent.ts +52 -0
  66. package/agents/growth/scheduler.ts +68 -0
  67. package/agents/growth/seo-agent.ts +282 -0
  68. package/agents/growth/social-agent.ts +346 -0
  69. package/bin/businesskit.js +17 -0
  70. package/cli.ts +125 -0
  71. package/context/brand.md +80 -0
  72. package/context/business.md +66 -0
  73. package/lib/analytics.ts +81 -0
  74. package/lib/db.adapter.ts +30 -0
  75. package/lib/db.ts +16 -0
  76. package/lib/id.ts +15 -0
  77. package/lib/kb.ts +337 -0
  78. package/lib/memory.ts +219 -0
  79. package/lib/pattern-detector.ts +169 -0
  80. package/lib/profile.ts +119 -0
  81. package/lib/slug.ts +30 -0
  82. package/package.json +50 -0
  83. package/setup.ts +127 -0
  84. package/tsconfig.json +13 -0
package/lib/memory.ts ADDED
@@ -0,0 +1,219 @@
1
+ /**
2
+ * memory.ts — Dual-write agent memory
3
+ *
4
+ * Writes to BOTH:
5
+ * 1. agent_memory table in Turso — synced, loss-proof, queryable, Phase 2 ready
6
+ * 2. memory.md local file — works offline, instant read, Claude Code reads it
7
+ *
8
+ * If Turso write fails → local still written (never lose an action)
9
+ * If local write fails → Turso still written (CF Workers has no fs, that's fine)
10
+ *
11
+ * memory.md structure:
12
+ * ## Preferences ← user says "always/never do X" → agent adds here
13
+ * ## Recent Actions ← last 20 actions, newest first (agent appends)
14
+ *
15
+ * agent_memory table: rolling 20 rows per profile, auto-trimmed
16
+ * agent_skills table: live skill instructions, editable from dashboard
17
+ */
18
+
19
+ import { db } from './db.ts'
20
+ import { getProfile } from './profile.ts'
21
+
22
+ const MAX_MEMORY_ROWS = 20
23
+ const MEMORY_FILE = './memory.md'
24
+ const MEMORY_SEPARATOR = '\n## Recent Actions\n'
25
+
26
+ // ─────────────────────────────────────────────────────────────────────────────
27
+ // Agent Memory (dual-write: Turso + local file)
28
+ // ─────────────────────────────────────────────────────────────────────────────
29
+
30
+ export interface MemoryEntry {
31
+ id: number
32
+ profile_id: string
33
+ session_date: string // 'YYYY-MM-DD'
34
+ agent: string // 'ceo' | 'blog-writer' | 'crm' | 'social' etc
35
+ action: string // short summary of what happened
36
+ metadata: Record<string, unknown>
37
+ created_at: string
38
+ }
39
+
40
+ /**
41
+ * Log an agent action.
42
+ * Writes to Turso agent_memory table AND appends to memory.md.
43
+ * Either can fail independently without losing the write to the other.
44
+ */
45
+ export async function logMemory(
46
+ agent: string,
47
+ action: string,
48
+ metadata: Record<string, unknown> = {}
49
+ ): Promise<void> {
50
+ const today = new Date().toISOString().slice(0, 10)
51
+ const ts = new Date().toISOString().slice(0, 16).replace('T', ' ')
52
+ const line = `- [${ts}] [${agent}] ${action}`
53
+
54
+ // Write to Turso (primary — synced, loss-proof)
55
+ try {
56
+ const profile = await getProfile()
57
+ await db.execute({
58
+ sql: `INSERT INTO agent_memory (profile_id, session_date, agent, action, metadata)
59
+ VALUES (?,?,?,?,?)`,
60
+ args: [profile.id, today, agent, action, JSON.stringify(metadata)],
61
+ })
62
+ // Trim to MAX_MEMORY_ROWS
63
+ await db.execute({
64
+ sql: `DELETE FROM agent_memory WHERE profile_id=? AND id NOT IN (
65
+ SELECT id FROM agent_memory WHERE profile_id=?
66
+ ORDER BY id DESC LIMIT ?
67
+ )`,
68
+ args: [profile.id, profile.id, MAX_MEMORY_ROWS],
69
+ })
70
+ } catch {
71
+ // Turso unavailable — local write below still saves the action
72
+ }
73
+
74
+ // Write to memory.md (local — offline-safe, Claude Code reads automatically)
75
+ try {
76
+ const { appendFileSync, readFileSync, writeFileSync, existsSync } = await import('fs')
77
+
78
+ if (!existsSync(MEMORY_FILE)) {
79
+ writeFileSync(MEMORY_FILE, `# Agent Memory\n\n## Preferences\n<!-- Agent adds user preferences here -->\n${MEMORY_SEPARATOR}`, 'utf8')
80
+ }
81
+
82
+ const content = readFileSync(MEMORY_FILE, 'utf8')
83
+ const sepIdx = content.indexOf(MEMORY_SEPARATOR)
84
+
85
+ if (sepIdx === -1) {
86
+ // Separator missing — just append
87
+ appendFileSync(MEMORY_FILE, `\n${line}\n`, 'utf8')
88
+ } else {
89
+ // Insert new line right after separator header
90
+ const before = content.slice(0, sepIdx + MEMORY_SEPARATOR.length)
91
+ const after = content.slice(sepIdx + MEMORY_SEPARATOR.length)
92
+ // Keep only last MAX_MEMORY_ROWS lines in the actions section
93
+ const existing = after.split('\n').filter(l => l.startsWith('- ['))
94
+ const trimmed = [line, ...existing].slice(0, MAX_MEMORY_ROWS).join('\n')
95
+ writeFileSync(MEMORY_FILE, `${before}${trimmed}\n`, 'utf8')
96
+ }
97
+ } catch {
98
+ // No fs (CF Workers Phase 2) — Turso write above is sufficient
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Read memory from Turso (primary).
104
+ * Falls back to parsing memory.md if Turso is unreachable.
105
+ */
106
+ export async function readMemory(): Promise<MemoryEntry[]> {
107
+ // Try Turso first
108
+ try {
109
+ const profile = await getProfile()
110
+ const { rows } = await db.execute({
111
+ sql: `SELECT * FROM agent_memory WHERE profile_id=? ORDER BY id DESC LIMIT ?`,
112
+ args: [profile.id, MAX_MEMORY_ROWS],
113
+ })
114
+ if (rows.length) {
115
+ return rows.map(r => ({
116
+ ...r,
117
+ metadata: safeJSON(r.metadata, {}),
118
+ })) as unknown as MemoryEntry[]
119
+ }
120
+ } catch { /* fall through to local */ }
121
+
122
+ // Fallback: parse memory.md
123
+ try {
124
+ const { readFileSync, existsSync } = await import('fs')
125
+ if (!existsSync(MEMORY_FILE)) return []
126
+ const content = readFileSync(MEMORY_FILE, 'utf8')
127
+ const sepIdx = content.indexOf(MEMORY_SEPARATOR)
128
+ if (sepIdx === -1) return []
129
+ const lines = content
130
+ .slice(sepIdx + MEMORY_SEPARATOR.length)
131
+ .split('\n')
132
+ .filter(l => l.startsWith('- ['))
133
+ return lines.map((l, i) => ({
134
+ id: i,
135
+ profile_id: '',
136
+ session_date: l.match(/\[(\d{4}-\d{2}-\d{2})/)?.[1] ?? '',
137
+ agent: l.match(/\]\s*\[([^\]]+)\]/)?.[1] ?? '',
138
+ action: l.replace(/^- \[.*?\]\s*\[.*?\]\s*/, ''),
139
+ metadata: {},
140
+ created_at: '',
141
+ }))
142
+ } catch {
143
+ return []
144
+ }
145
+ }
146
+
147
+ /** Format memory as readable context string for session start */
148
+ export async function memoryContext(): Promise<string> {
149
+ const entries = await readMemory()
150
+ if (!entries.length) return '(No memory yet — this is the first session.)'
151
+ return [...entries].reverse()
152
+ .map(e => `[${e.session_date}] [${e.agent}] ${e.action}`)
153
+ .join('\n')
154
+ }
155
+
156
+ // ─────────────────────────────────────────────────────────────────────────────
157
+ // Agent Skills (Turso only — no local copy needed, editable from dashboard)
158
+ // ─────────────────────────────────────────────────────────────────────────────
159
+
160
+ export interface Skill {
161
+ id: number
162
+ profile_id: string
163
+ name: string // human label: 'Brand Voice', 'SEO Rules'
164
+ slug: string // 'brand-voice' | 'seo' | 'store' | 'analytics' | custom
165
+ content: string // markdown — the actual skill instructions
166
+ is_active: number
167
+ version: number
168
+ updated_at: string
169
+ }
170
+
171
+ export async function loadSkills(): Promise<Skill[]> {
172
+ const profile = await getProfile()
173
+ const { rows } = await db.execute({
174
+ sql: `SELECT * FROM agent_skills WHERE profile_id=? AND is_active=1 ORDER BY name ASC`,
175
+ args: [profile.id],
176
+ })
177
+ return rows as unknown as Skill[]
178
+ }
179
+
180
+ export async function loadSkill(slug: string): Promise<Skill | null> {
181
+ const profile = await getProfile()
182
+ const { rows: [r] } = await db.execute({
183
+ sql: `SELECT * FROM agent_skills WHERE profile_id=? AND slug=? AND is_active=1 LIMIT 1`,
184
+ args: [profile.id, slug],
185
+ })
186
+ return (r as unknown as Skill) ?? null
187
+ }
188
+
189
+ export async function upsertSkill(slug: string, name: string, content: string): Promise<void> {
190
+ const profile = await getProfile()
191
+ const now = new Date().toISOString().slice(0, 19) + 'Z'
192
+ await db.execute({
193
+ sql: `INSERT INTO agent_skills (profile_id, name, slug, content, is_active, version, updated_at)
194
+ VALUES (?,?,?,?,1,1,?)
195
+ ON CONFLICT(profile_id, slug) DO UPDATE SET
196
+ content=excluded.content, name=excluded.name,
197
+ version=version+1, updated_at=excluded.updated_at`,
198
+ args: [profile.id, name, slug, content, now],
199
+ })
200
+ }
201
+
202
+ export async function skillsContext(): Promise<string> {
203
+ const skills = await loadSkills()
204
+ if (!skills.length) return ''
205
+ return skills.map(s => `## Skill: ${s.name}\n${s.content}`).join('\n\n---\n\n')
206
+ }
207
+
208
+ // ─────────────────────────────────────────────────────────────────────────────
209
+ // Session bootstrap — call at start of every agent session
210
+ // ─────────────────────────────────────────────────────────────────────────────
211
+
212
+ export async function sessionContext(): Promise<{ memory: string; skills: string }> {
213
+ const [memory, skills] = await Promise.all([memoryContext(), skillsContext()])
214
+ return { memory, skills }
215
+ }
216
+
217
+ function safeJSON(v: unknown, fb: unknown) {
218
+ try { return JSON.parse(v as string) } catch { return fb }
219
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * pattern-detector.ts — Hermes-inspired periodic pattern detection
3
+ *
4
+ * NOT called on every agent run — called periodically by the Scheduler agent
5
+ * or when user explicitly runs /detect-patterns.
6
+ *
7
+ * What it does:
8
+ * 1. Reads last 20 agent_memory entries
9
+ * 2. Finds actions repeated 3+ times in 7 days by the same agent
10
+ * 3. Checks if a task already exists for that pattern
11
+ * 4. If not: creates a PENDING agent_tasks row + sets pending_skill_suggestion
12
+ * on the agents table → surfaces in dashboard for user to approve/reject
13
+ *
14
+ * User approves → task status='active', skill is_active=1
15
+ * User rejects → task status='cancelled'
16
+ *
17
+ * "Having them is better — not forced, not run every time."
18
+ */
19
+
20
+ import { db } from './db.ts'
21
+ import { getProfile } from './profile.ts'
22
+ import { ulid, now, iso } from './id.ts'
23
+
24
+ const PATTERN_THRESHOLD = 3 // times an action must repeat
25
+ const PATTERN_WINDOW_DAYS = 7 // within this many days
26
+
27
+ export interface DetectedPattern {
28
+ agent: string
29
+ action: string // action string that repeated
30
+ count: number
31
+ memory_ids: number[]
32
+ }
33
+
34
+ /**
35
+ * Scan agent_memory for repeated patterns.
36
+ * Returns patterns that don't already have an active/pending task.
37
+ */
38
+ export async function detectPatterns(): Promise<DetectedPattern[]> {
39
+ const profile = await getProfile()
40
+ const cutoff = new Date()
41
+ cutoff.setDate(cutoff.getDate() - PATTERN_WINDOW_DAYS)
42
+ const cutoffISO = cutoff.toISOString().slice(0, 10)
43
+
44
+ const { rows } = await db.execute({
45
+ sql: `SELECT id, agent, action, session_date FROM agent_memory
46
+ WHERE profile_id=? AND session_date >= ?
47
+ ORDER BY id DESC`,
48
+ args: [profile.id, cutoffISO],
49
+ })
50
+
51
+ // Count occurrences per agent+action_prefix
52
+ const counts = new Map<string, { agent: string; action: string; ids: number[] }>()
53
+
54
+ for (const row of rows) {
55
+ // Normalize action: strip IDs and numbers to find the pattern
56
+ // "Published 'Email Tips' (listicle, 2100 words)" → "published post"
57
+ const normalized = normalizeAction(row.action as string)
58
+ const key = `${row.agent}::${normalized}`
59
+
60
+ if (!counts.has(key)) {
61
+ counts.set(key, { agent: row.agent as string, action: normalized, ids: [] })
62
+ }
63
+ counts.get(key)!.ids.push(row.id as number)
64
+ }
65
+
66
+ const patterns: DetectedPattern[] = []
67
+ for (const [, v] of counts) {
68
+ if (v.ids.length >= PATTERN_THRESHOLD) {
69
+ patterns.push({ agent: v.agent, action: v.action, count: v.ids.length, memory_ids: v.ids })
70
+ }
71
+ }
72
+
73
+ // Filter out patterns that already have a task
74
+ if (!patterns.length) return []
75
+
76
+ const filtered: DetectedPattern[] = []
77
+ for (const p of patterns) {
78
+ const { rows: [existing] } = await db.execute({
79
+ sql: `SELECT id FROM agent_tasks WHERE profile_id=? AND agent=?
80
+ AND status NOT IN ('cancelled') AND command LIKE ?
81
+ LIMIT 1`,
82
+ args: [profile.id, p.agent, `%${p.action.split(' ')[0]}%`],
83
+ })
84
+ if (!existing) filtered.push(p)
85
+ }
86
+
87
+ return filtered
88
+ }
89
+
90
+ /**
91
+ * For each detected pattern: create a pending task + set skill suggestion.
92
+ * User sees these in dashboard and can approve or reject.
93
+ */
94
+ export async function suggestFromPatterns(patterns: DetectedPattern[]): Promise<void> {
95
+ if (!patterns.length) return
96
+ const profile = await getProfile()
97
+ const ts = now()
98
+
99
+ for (const p of patterns) {
100
+ const taskId = ulid()
101
+ const taskTitle = `Auto-detected: ${p.agent} — ${p.action} (${p.count}x in 7 days)`
102
+ const skillContent = `# Auto-detected skill: ${p.action}\n\nThis task was detected because the ${p.agent} agent performed "${p.action}" ${p.count} times in the last 7 days.\n\nApprove to schedule it automatically.`
103
+
104
+ // Create pending task
105
+ try {
106
+ await db.execute({
107
+ sql: `INSERT OR IGNORE INTO agent_tasks
108
+ (id,profile_id,agent,title,command,source,status,created_at,updated_at)
109
+ VALUES (?,?,?,?,'auto-detected','agent','pending',?,?)`,
110
+ args: [taskId, profile.id, p.agent, taskTitle, ts, ts],
111
+ })
112
+ } catch { /* already exists */ }
113
+
114
+ // Set pending skill suggestion on agents table
115
+ try {
116
+ const suggestion = JSON.stringify({
117
+ slug: `auto-${p.agent}-${p.action.replace(/\s+/g, '-').toLowerCase().slice(0, 30)}`,
118
+ name: `Auto: ${p.action}`,
119
+ content: skillContent,
120
+ detected_from: p.memory_ids,
121
+ task_id: taskId,
122
+ })
123
+ await db.execute({
124
+ sql: `UPDATE agents SET pending_skill_suggestion=?, skill_suggestion_at=?, updated_at=?
125
+ WHERE profile_id=? AND agent_type=?`,
126
+ args: [suggestion, ts, ts, profile.id, p.agent],
127
+ })
128
+ } catch { /* agents table may not exist */ }
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Run full detection + suggestion cycle.
134
+ * Called by Scheduler agent periodically (e.g. weekly).
135
+ * Not called on every agent run.
136
+ */
137
+ export async function runPatternDetection(): Promise<{
138
+ patterns_found: number
139
+ suggestions_created: number
140
+ }> {
141
+ const patterns = await detectPatterns()
142
+ if (!patterns.length) return { patterns_found: 0, suggestions_created: 0 }
143
+
144
+ await suggestFromPatterns(patterns)
145
+
146
+ return {
147
+ patterns_found: patterns.length,
148
+ suggestions_created: patterns.length,
149
+ }
150
+ }
151
+
152
+ // ─── helpers ─────────────────────────────────────────────────────────────────
153
+
154
+ function normalizeAction(action: string): string {
155
+ return action
156
+ .toLowerCase()
157
+ // Remove quoted strings (post titles, names)
158
+ .replace(/"[^"]*"/g, '')
159
+ .replace(/'[^']*'/g, '')
160
+ // Remove parenthetical details
161
+ .replace(/\([^)]*\)/g, '')
162
+ // Remove numbers
163
+ .replace(/\d+/g, '')
164
+ // Remove common filler
165
+ .replace(/\b(the|a|an|for|to|and|or|in|on|at|with)\b/g, '')
166
+ .replace(/\s+/g, ' ')
167
+ .trim()
168
+ .slice(0, 50)
169
+ }
package/lib/profile.ts ADDED
@@ -0,0 +1,119 @@
1
+ import { db as _defaultDB } from './db.ts'
2
+ import type { Client } from '@libsql/client'
3
+
4
+ export interface Profile {
5
+ id: string; user_id: string; slug: string; title: string
6
+ bio: string | null; tagline: string | null; avatar_url: string | null
7
+ social_links: Array<{ platform: string; url: string }>
8
+ enabled_categories: string[]
9
+ }
10
+
11
+ export interface Settings {
12
+ site_title: string | null; logo_url: string | null
13
+ theme: Record<string, unknown>
14
+ }
15
+
16
+ /**
17
+ * Credentials — read-only for agents. Never log these values.
18
+ *
19
+ * Columns are added to the `credentials` table via ALTER TABLE migrations
20
+ * in provision.ts MIGRATIONS_SQL. New columns = new entries there.
21
+ */
22
+ export interface Credentials {
23
+ // ── Email ──────────────────────────────────────────────────────────────────
24
+ resend_api_key: string | null
25
+ ses_access_key: string | null
26
+ ses_secret_key: string | null
27
+ ses_region: string | null
28
+ ses_from_email: string | null
29
+
30
+ // ── LLMs ───────────────────────────────────────────────────────────────────
31
+ anthropic_api_key: string | null
32
+ openai_api_key: string | null
33
+ gemini_api_key: string | null
34
+
35
+ // ── X / Twitter ────────────────────────────────────────────────────────────
36
+ twitter_api_key: string | null
37
+ twitter_api_secret: string | null
38
+ twitter_access_token: string | null
39
+ twitter_access_secret: string | null
40
+
41
+ // ── LinkedIn ───────────────────────────────────────────────────────────────
42
+ linkedin_access_token: string | null
43
+ linkedin_person_urn: string | null // urn:li:person:{id}
44
+
45
+ // ── Facebook ───────────────────────────────────────────────────────────────
46
+ facebook_page_id: string | null
47
+ facebook_page_token: string | null
48
+
49
+ // ── Instagram (Facebook Graph API) ─────────────────────────────────────────
50
+ instagram_account_id: string | null
51
+ instagram_access_token: string | null
52
+
53
+ // ── Automation (optional) ──────────────────────────────────────────────────
54
+ n8n_webhook_url: string | null
55
+ }
56
+
57
+ export interface BrandContext {
58
+ profile: Profile; settings: Settings; credentials: Credentials
59
+ }
60
+
61
+ let _ctx: BrandContext | null = null
62
+
63
+ export async function getBrandContext(client?: Client): Promise<BrandContext> {
64
+ if (!client && _ctx) return _ctx
65
+
66
+ const db = client ?? _defaultDB
67
+ const [[p], [s], [c]] = await Promise.all([
68
+ db.execute('SELECT * FROM profiles LIMIT 1').then(r => r.rows),
69
+ db.execute('SELECT * FROM settings LIMIT 1').then(r => r.rows),
70
+ db.execute('SELECT * FROM credentials LIMIT 1').then(r => r.rows),
71
+ ])
72
+
73
+ if (!p) throw new Error('No profile found — is your Turso DB provisioned?')
74
+
75
+ const parse = (v: unknown, fb: unknown) => { try { return JSON.parse(v as string) } catch { return fb } }
76
+ const str = (v: unknown) => (v as string | null) ?? null
77
+
78
+ const profile: Profile = {
79
+ id: p.id as string, user_id: p.user_id as string,
80
+ slug: p.slug as string, title: p.title as string,
81
+ bio: str(p.bio), tagline: str(p.tagline), avatar_url: str(p.avatar_url),
82
+ social_links: parse(p.social_links, []),
83
+ enabled_categories: parse(p.enabled_categories, []),
84
+ }
85
+
86
+ const settings: Settings = {
87
+ site_title: str(s?.site_title ?? p.site_title),
88
+ logo_url: str(s?.logo_url),
89
+ theme: parse(s?.theme, {}),
90
+ }
91
+
92
+ const credentials: Credentials = {
93
+ resend_api_key: str(c?.resend_api_key),
94
+ ses_access_key: str(c?.ses_access_key),
95
+ ses_secret_key: str(c?.ses_secret_key),
96
+ ses_region: str(c?.ses_region),
97
+ ses_from_email: str(c?.ses_from_email),
98
+ anthropic_api_key: str(c?.anthropic_api_key),
99
+ openai_api_key: str(c?.openai_api_key),
100
+ gemini_api_key: str(c?.gemini_api_key),
101
+ twitter_api_key: str(c?.twitter_api_key),
102
+ twitter_api_secret: str(c?.twitter_api_secret),
103
+ twitter_access_token: str(c?.twitter_access_token),
104
+ twitter_access_secret: str(c?.twitter_access_secret),
105
+ linkedin_access_token: str(c?.linkedin_access_token),
106
+ linkedin_person_urn: str(c?.linkedin_person_urn),
107
+ facebook_page_id: str(c?.facebook_page_id),
108
+ facebook_page_token: str(c?.facebook_page_token),
109
+ instagram_account_id: str(c?.instagram_account_id),
110
+ instagram_access_token: str(c?.instagram_access_token),
111
+ n8n_webhook_url: str(c?.n8n_webhook_url),
112
+ }
113
+
114
+ const result = { profile, settings, credentials }
115
+ if (!client) _ctx = result
116
+ return result
117
+ }
118
+
119
+ export const getProfile = async (client?: Client) => (await getBrandContext(client)).profile
package/lib/slug.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { db } from './db.ts'
2
+
3
+ export const toSlug = (s: string) =>
4
+ s.toLowerCase().trim()
5
+ .replace(/[^\w\s-]/g, '').replace(/[\s_]+/g, '-')
6
+ .replace(/-+/g, '-').replace(/^-|-$/g, '').slice(0, 100)
7
+
8
+ /**
9
+ * Generate a unique slug within a table.
10
+ * Products use global uniqueness (no profile scope).
11
+ * All other tables scope uniqueness to profile_id.
12
+ */
13
+ export async function uniqueSlug(
14
+ table: string,
15
+ title: string,
16
+ profileId?: string
17
+ ): Promise<string> {
18
+ const base = toSlug(title)
19
+ let slug = base, i = 0
20
+ while (true) {
21
+ const { rows } = await db.execute({
22
+ sql: profileId
23
+ ? `SELECT 1 FROM ${table} WHERE slug=? AND profile_id=? LIMIT 1`
24
+ : `SELECT 1 FROM ${table} WHERE slug=? LIMIT 1`,
25
+ args: profileId ? [slug, profileId] : [slug],
26
+ })
27
+ if (!rows.length) return slug
28
+ slug = `${base}-${++i}`
29
+ }
30
+ }
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@businesskit/agent",
3
+ "version": "1.0.0",
4
+ "description": "Autonomous business agent team — CEO, CRM, Social, SEO, Blog Writer and more. Powered by your own Turso database. Works with Claude Code, Claude Cowork, Gemini CLI, and Codex.",
5
+ "type": "module",
6
+ "bin": {
7
+ "bk": "./cli.ts",
8
+ "businesskit": "./cli.ts"
9
+ },
10
+ "scripts": {
11
+ "setup": "npx tsx setup.ts",
12
+ "cli": "npx tsx cli.ts",
13
+ "ceo": "npx tsx cli.ts ceo",
14
+ "cmo": "npx tsx cli.ts cmo",
15
+ "coo": "npx tsx cli.ts coo",
16
+ "cbo": "npx tsx cli.ts cbo",
17
+ "analytics": "npx tsx cli.ts analytics",
18
+ "seo": "npx tsx cli.ts seo",
19
+ "scheduler:hourly": "npx tsx cli.ts scheduler hourly",
20
+ "scheduler:daily": "npx tsx cli.ts scheduler daily",
21
+ "scheduler:weekly": "npx tsx cli.ts scheduler weekly"
22
+ },
23
+ "keywords": [
24
+ "claude-code",
25
+ "claude-cowork",
26
+ "ai-agent",
27
+ "business-agent",
28
+ "turso",
29
+ "crm",
30
+ "social-media",
31
+ "businesskit"
32
+ ],
33
+ "dependencies": {
34
+ "@libsql/client": "^0.15.15"
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "^22.0.0",
38
+ "tsx": "^4.19.0",
39
+ "typescript": "^5.4.5"
40
+ },
41
+ "engines": {
42
+ "node": ">=18.17.0"
43
+ },
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "https://github.com/businesskit-io/businesskit-agent"
47
+ },
48
+ "homepage": "https://github.com/businesskit-io/businesskit-agent",
49
+ "license": "MIT"
50
+ }