@businesskit/agent 1.0.4 → 1.0.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.
Files changed (190) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.cursor-plugin/plugin.json +25 -0
  3. package/.cursorrules +10 -0
  4. package/.superconsole-plugin/plugin.json +62 -0
  5. package/AGENTS.md +105 -63
  6. package/CLAUDE.md +11 -84
  7. package/GEMINI.md +11 -34
  8. package/README.md +95 -154
  9. package/assets/logo.svg +3 -0
  10. package/bin/businesskit.js +45 -18
  11. package/commands/add-contact.md +47 -0
  12. package/commands/add-inventory-from-invoice.md +80 -0
  13. package/commands/adjust-stock.md +46 -0
  14. package/commands/brief.md +12 -0
  15. package/commands/capabilities.md +33 -0
  16. package/commands/chase.md +12 -0
  17. package/commands/check-stock.md +43 -0
  18. package/commands/create-component.md +109 -0
  19. package/commands/create-invoice.md +69 -0
  20. package/commands/create-new-bill.md +65 -0
  21. package/commands/create-page.md +124 -0
  22. package/commands/crm.md +13 -0
  23. package/commands/followups.md +13 -0
  24. package/commands/list-components.md +41 -0
  25. package/commands/list-content.md +46 -0
  26. package/commands/list-pages.md +45 -0
  27. package/commands/pipeline.md +13 -0
  28. package/commands/publish-page.md +64 -0
  29. package/commands/send-invoice.md +42 -0
  30. package/commands/seo-audit.md +36 -0
  31. package/commands/update-agent.md +33 -0
  32. package/commands/update-contact.md +46 -0
  33. package/commands/update-content.md +48 -0
  34. package/commands/update-page.md +56 -0
  35. package/commands/update-price.md +47 -0
  36. package/commands/write-blog.md +56 -0
  37. package/commands/write-docs.md +90 -0
  38. package/commands/write-guide.md +51 -0
  39. package/commands/write-newsletter.md +50 -0
  40. package/dist/server.js +4099 -0
  41. package/mcp_config.json +12 -0
  42. package/package.json +54 -25
  43. package/plugin.json +32 -0
  44. package/scripts/setup.sh +169 -0
  45. package/scripts/setup.ts +129 -0
  46. package/scripts/update.sh +56 -0
  47. package/server.json +21 -0
  48. package/skills/README.md +20 -27
  49. package/skills/billing/SKILL.md +64 -0
  50. package/skills/brand/SKILL.md +30 -86
  51. package/skills/cms/SKILL.md +111 -0
  52. package/skills/cms/references/cms-hubs.md +84 -0
  53. package/skills/cms/references/html-blocks.md +177 -0
  54. package/skills/copywriting/SKILL.md +1 -1
  55. package/skills/crm/SKILL.md +24 -0
  56. package/skills/docs/SKILL.md +65 -0
  57. package/skills/docs/references/how-to.md +155 -0
  58. package/skills/inbox/SKILL.md +49 -0
  59. package/skills/inventory/SKILL.md +69 -0
  60. package/skills/pages/SKILL.md +214 -0
  61. package/skills/pages/references/sections-catalog.json +1183 -0
  62. package/skills/social/SKILL.md +84 -211
  63. package/skills/social/evals/evals.json +66 -0
  64. package/skills/social/evals/rubric.md +26 -0
  65. package/skills/social/examples/repurposing-blog-to-social.md +93 -0
  66. package/skills/social/examples/weekly-content-calendar.md +30 -0
  67. package/skills/social/linkedin/SKILL.md +107 -0
  68. package/skills/social/linkedin/evals/evals.json +106 -0
  69. package/skills/social/linkedin/evals/rubric.md +28 -0
  70. package/skills/social/linkedin/examples/gasp-weekly-sprint.md +24 -0
  71. package/skills/social/linkedin/examples/growth-posts-by-format.md +140 -0
  72. package/skills/social/linkedin/references/gasp-funnel-and-calibration.md +90 -0
  73. package/skills/social/linkedin/references/six-growth-formats.md +114 -0
  74. package/skills/social/references/platforms.md +76 -0
  75. package/skills/social/references/post-templates.md +105 -0
  76. package/skills/social/references/reverse-engineering.md +62 -0
  77. package/src/data/sections-catalog.json +950 -0
  78. package/src/db.ts +170 -0
  79. package/src/server.ts +75 -0
  80. package/src/tools/content.ts +326 -0
  81. package/src/tools/crm.ts +1416 -0
  82. package/src/tools/domains.ts +89 -0
  83. package/src/tools/inbox.ts +270 -0
  84. package/src/tools/index.ts +116 -0
  85. package/src/tools/pages.ts +1217 -0
  86. package/src/tools/shop.ts +771 -0
  87. package/src/tools/system.ts +94 -0
  88. package/src/tools/types.ts +17 -0
  89. package/templates/antigravity.json +8 -0
  90. package/templates/claude-code.mcp.json +8 -0
  91. package/templates/cursor.mcp.json +8 -0
  92. package/templates/vscode.mcp.json +9 -0
  93. package/.claude/commands/analytics.md +0 -7
  94. package/.claude/commands/blog-writer.md +0 -9
  95. package/.claude/commands/cbo.md +0 -7
  96. package/.claude/commands/ceo.md +0 -10
  97. package/.claude/commands/cmo.md +0 -7
  98. package/.claude/commands/compress.md +0 -73
  99. package/.claude/commands/coo.md +0 -11
  100. package/.claude/commands/copywriter.md +0 -15
  101. package/.claude/commands/course-creator.md +0 -9
  102. package/.claude/commands/crm.md +0 -591
  103. package/.claude/commands/deep.md +0 -50
  104. package/.claude/commands/docs-writer.md +0 -8
  105. package/.claude/commands/forms-builder.md +0 -10
  106. package/.claude/commands/ingest.md +0 -110
  107. package/.claude/commands/jobs-manager.md +0 -8
  108. package/.claude/commands/kb.md +0 -107
  109. package/.claude/commands/newsletter-writer.md +0 -9
  110. package/.claude/commands/preserve.md +0 -64
  111. package/.claude/commands/resume.md +0 -67
  112. package/.claude/commands/scheduler.md +0 -8
  113. package/.claude/commands/seo.md +0 -60
  114. package/.claude/commands/social.md +0 -51
  115. package/.claude/commands/store-manager.md +0 -11
  116. package/.claude/settings.json +0 -16
  117. package/.claude/settings.local.json +0 -11
  118. package/.env.example +0 -12
  119. package/.mcp.json +0 -3
  120. package/HEARTBEAT.md +0 -105
  121. package/PLAN.md +0 -345
  122. package/PRD-Agent-Composition.md +0 -149
  123. package/PRD-Agent-Harness.md +0 -316
  124. package/REFERENCE.md +0 -160
  125. package/SOUL.md +0 -148
  126. package/SYSTEM.md +0 -71
  127. package/agents/_base.ts +0 -371
  128. package/agents/analytics/SOUL.md +0 -11
  129. package/agents/analytics/analytics.ts +0 -405
  130. package/agents/business/SOUL.md +0 -11
  131. package/agents/business/business.ts +0 -109
  132. package/agents/ceo/SOUL.md +0 -15
  133. package/agents/ceo/ceo.ts +0 -146
  134. package/agents/content/SOUL.md +0 -11
  135. package/agents/content/content.ts +0 -379
  136. package/agents/copywriting/SOUL.md +0 -11
  137. package/agents/copywriting/copywriting.ts +0 -89
  138. package/agents/courses/SOUL.md +0 -11
  139. package/agents/courses/courses.ts +0 -451
  140. package/agents/docs/SOUL.md +0 -11
  141. package/agents/docs/docs.ts +0 -77
  142. package/agents/forms/SOUL.md +0 -11
  143. package/agents/forms/forms.ts +0 -364
  144. package/agents/hiring/SOUL.md +0 -11
  145. package/agents/hiring/hiring.ts +0 -314
  146. package/agents/marketing/SOUL.md +0 -15
  147. package/agents/marketing/marketing.ts +0 -109
  148. package/agents/newsletter/SOUL.md +0 -11
  149. package/agents/newsletter/newsletter.ts +0 -91
  150. package/agents/operations/SOUL.md +0 -11
  151. package/agents/operations/operations.ts +0 -157
  152. package/agents/sales/SOUL.md +0 -44
  153. package/agents/sales/sales.ts +0 -883
  154. package/agents/scheduler/SOUL.md +0 -11
  155. package/agents/scheduler/scheduler.ts +0 -68
  156. package/agents/seo/SOUL.md +0 -11
  157. package/agents/seo/seo.ts +0 -288
  158. package/agents/social/SOUL.md +0 -11
  159. package/agents/social/social.ts +0 -744
  160. package/agents/store/SOUL.md +0 -11
  161. package/agents/store/store.ts +0 -514
  162. package/cli.ts +0 -144
  163. package/context/about-me.md +0 -96
  164. package/context/brand-voice.md +0 -127
  165. package/context/brand.md +0 -80
  166. package/context/business.md +0 -66
  167. package/context/working-style.md +0 -87
  168. package/lib/analytics.ts +0 -81
  169. package/lib/cms.ts +0 -88
  170. package/lib/db.adapter.ts +0 -30
  171. package/lib/db.ts +0 -63
  172. package/lib/enums.ts +0 -25
  173. package/lib/groups.ts +0 -122
  174. package/lib/id.ts +0 -43
  175. package/lib/kb.ts +0 -337
  176. package/lib/memory.ts +0 -219
  177. package/lib/pattern-detector.ts +0 -169
  178. package/lib/profile.ts +0 -155
  179. package/lib/schema.ts +0 -2015
  180. package/lib/slug.ts +0 -30
  181. package/lib/validate.ts +0 -33
  182. package/setup.ts +0 -141
  183. package/skills/agents/SKILL.md +0 -56
  184. package/skills/analytics/SKILL.md +0 -52
  185. package/skills/blog-writer/SKILL.md +0 -452
  186. package/skills/ceo/SKILL.md +0 -25
  187. package/skills/cmo/SKILL.md +0 -8
  188. package/skills/schema/SKILL.md +0 -86
  189. package/skills/store/SKILL.md +0 -62
  190. package/tsconfig.json +0 -14
package/lib/memory.ts DELETED
@@ -1,219 +0,0 @@
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
- }
@@ -1,169 +0,0 @@
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 DELETED
@@ -1,155 +0,0 @@
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
- /**
64
- * Load the brand context (profile + settings + credentials) from UserDB.
65
- *
66
- * Profile selection:
67
- * 1. If PROFILE_ID env var is set → SELECT by that id (multi-profile DBs)
68
- * 2. Otherwise → SELECT the only profile in the DB (single-profile default)
69
- * 3. If DB has >1 profile and PROFILE_ID unset → throw with guidance
70
- */
71
- export async function getBrandContext(client?: Client): Promise<BrandContext> {
72
- if (!client && _ctx) return _ctx
73
-
74
- // libSQL Client's `execute` has a strict `InStatement` type; our `db` wrapper
75
- // accepts the looser `Stmt`. When an external Client is injected (phase 2),
76
- // we cast through `any` to share call shapes.
77
- const exec = (sql: string, args?: unknown[]) =>
78
- (client
79
- ? (client.execute as any)(args ? { sql, args } : sql)
80
- : _defaultDB.execute(args ? { sql, args } : sql))
81
-
82
- const pid = process.env.PROFILE_ID?.trim()
83
-
84
- const profileRow = pid
85
- ? await exec('SELECT * FROM profiles WHERE id=? LIMIT 1', [pid]).then((r: any) => r.rows[0])
86
- : await (async () => {
87
- const { rows } = await exec('SELECT * FROM profiles LIMIT 2')
88
- if (rows.length > 1) {
89
- throw new Error(
90
- `UserDB has ${rows.length}+ profiles. Set PROFILE_ID in .env ` +
91
- `to pick one (see .env.example).`,
92
- )
93
- }
94
- return rows[0]
95
- })()
96
-
97
- if (!profileRow) {
98
- throw new Error(
99
- pid
100
- ? `No profile found with id=${pid}. Check PROFILE_ID in .env.`
101
- : 'No profile found — is your Turso DB provisioned? Run BusinessKit onboarding first.',
102
- )
103
- }
104
- const p = profileRow
105
-
106
- const [[s], [c]] = await Promise.all([
107
- exec('SELECT * FROM settings WHERE profile_id=? LIMIT 1', [p.id]).then((r: any) => r.rows),
108
- exec('SELECT * FROM credentials WHERE profile_id=? LIMIT 1', [p.id]).then((r: any) => r.rows),
109
- ])
110
-
111
- const parse = (v: unknown, fb: unknown) => { try { return JSON.parse(v as string) } catch { return fb } }
112
- const str = (v: unknown) => (v as string | null) ?? null
113
-
114
- const profile: Profile = {
115
- id: p.id as string, user_id: p.user_id as string,
116
- slug: p.slug as string, title: p.title as string,
117
- bio: str(p.bio), tagline: str(p.tagline), avatar_url: str(p.avatar_url),
118
- social_links: parse(p.social_links, []),
119
- enabled_categories: parse(p.enabled_categories, []),
120
- }
121
-
122
- const settings: Settings = {
123
- site_title: str(s?.site_title ?? p.site_title),
124
- logo_url: str(s?.logo_url),
125
- theme: parse(s?.theme, {}),
126
- }
127
-
128
- const credentials: Credentials = {
129
- resend_api_key: str(c?.resend_api_key),
130
- ses_access_key: str(c?.ses_access_key),
131
- ses_secret_key: str(c?.ses_secret_key),
132
- ses_region: str(c?.ses_region),
133
- ses_from_email: str(c?.ses_from_email),
134
- anthropic_api_key: str(c?.anthropic_api_key),
135
- openai_api_key: str(c?.openai_api_key),
136
- gemini_api_key: str(c?.gemini_api_key),
137
- twitter_api_key: str(c?.twitter_api_key),
138
- twitter_api_secret: str(c?.twitter_api_secret),
139
- twitter_access_token: str(c?.twitter_access_token),
140
- twitter_access_secret: str(c?.twitter_access_secret),
141
- linkedin_access_token: str(c?.linkedin_access_token),
142
- linkedin_person_urn: str(c?.linkedin_person_urn),
143
- facebook_page_id: str(c?.facebook_page_id),
144
- facebook_page_token: str(c?.facebook_page_token),
145
- instagram_account_id: str(c?.instagram_account_id),
146
- instagram_access_token: str(c?.instagram_access_token),
147
- n8n_webhook_url: str(c?.n8n_webhook_url),
148
- }
149
-
150
- const result = { profile, settings, credentials }
151
- if (!client) _ctx = result
152
- return result
153
- }
154
-
155
- export const getProfile = async (client?: Client) => (await getBrandContext(client)).profile