@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
package/agents/_base.ts CHANGED
@@ -1,63 +1,371 @@
1
- import { db } from '../lib/db.ts'
1
+ // agents/_base.ts
2
+ // BaseAgent — every agent extends this.
3
+ // Wires: profile isolation, idempotency, transactions, audit, memory cap.
4
+ //
5
+ // P0-1: generateIdempotencyKey() on every insert/update/archive
6
+ // P0-2: txn() for multi-statement flows (Turso atomic batch)
7
+ // P0-3: SQLITE_BUSY retry — via lib/db.ts (db.execute/write/txn all retry)
8
+ // P0-6: audit rows bundled in the same txn as every mutation helper
9
+ // P0-7: APPEND_ONLY guard — throws before hitting DB trigger
10
+ // P1-2: logMemory() trims to last 20 rows per agent
11
+ // P1-7: create() factory validates single-profile before construction
12
+ //
13
+ // Back-compat surface (every agent file uses these — keep stable):
14
+ // this.ctx / this.profileId / this.userId
15
+ // this.init() / this.archive() / this.publish() / this.count()
16
+ // re-exports: db, ulid, iso, now
17
+
18
+ import { db, type Stmt } from '../lib/db.ts'
2
19
  import { getBrandContext, type BrandContext } from '../lib/profile.ts'
3
- import { ulid, now, iso } from '../lib/id.ts'
4
- import type { Client } from '@libsql/client'
5
-
6
- /** Singleton Turso client — agents may import `db` for raw queries */
7
- export { db, ulid, now, iso }
8
-
9
- /**
10
- * BaseAgent — extend this for every agent.
11
- *
12
- * Provides:
13
- * - this.ctx → BrandContext (profile, settings, credentials)
14
- * - this.profileId → enforced on every write
15
- * - this.userId → from profile
16
- * - this.archive() → soft delete (hidden=1) for any table
17
- * - this.publish() → flip published=1 for any table
18
- * - this.count() → content inventory for any table
19
- */
20
+ import {
21
+ ulid, iso, now,
22
+ generateIdempotencyKey,
23
+ } from '../lib/id.ts'
24
+
25
+ export { db, ulid, iso, now }
26
+
20
27
  export abstract class BaseAgent {
21
28
  protected ctx!: BrandContext
22
- protected db: Client
29
+ protected readonly agentType: string
30
+
31
+ // Back-compat constructor — agents still do `new CEO()` as module singletons.
32
+ // Profile is loaded lazily via init() on first method call.
33
+ // Phase 2 will swap to BaseAgent.create() + sharedMap-injected client.
34
+ constructor(agentType?: string) {
35
+ this.agentType = agentType ?? this.constructor.name.toLowerCase()
36
+ }
37
+
38
+ // P1-1: schema-version cache — populated once per process on first init()
39
+ private static _migrations: Set<string> | null = null
40
+
41
+ /** Call at the start of any method that reads ctx / profileId / userId. */
42
+ protected async init(): Promise<void> {
43
+ if (!this.ctx) this.ctx = await getBrandContext()
44
+ if (BaseAgent._migrations === null) {
45
+ BaseAgent._migrations = new Set<string>()
46
+ try {
47
+ const { rows } = await db.execute(`SELECT id FROM _schema_migrations`)
48
+ for (const r of rows) BaseAgent._migrations.add(String(r.id))
49
+ } catch { /* pre-migration UserDB — empty set is fine */ }
50
+ }
51
+ }
52
+
53
+ /** P1-1: gate features on app-side migrations being applied. */
54
+ protected hasMigration(id: string): boolean {
55
+ return BaseAgent._migrations?.has(id) ?? false
56
+ }
23
57
 
24
- constructor(injectedDB?: Client) {
25
- this.db = injectedDB ?? db
58
+ protected get profileId(): string { return this.ctx.profile.id }
59
+ protected get userId(): string { return this.ctx.profile.user_id }
60
+
61
+ // P1-7: factory — asserts a profile will resolve before constructing.
62
+ // Single-profile UserDBs (the normal case) auto-pick. Multi-profile DBs
63
+ // must set PROFILE_ID in .env; that check lives in lib/profile.ts.
64
+ static async create<T extends BaseAgent>(
65
+ Cls: new (agentType?: string) => T,
66
+ agentType?: string,
67
+ ): Promise<T> {
68
+ const { rows } = await db.execute(`SELECT COUNT(*) as n FROM profiles`)
69
+ const n = Number(rows[0]?.n ?? 0)
70
+ if (n === 0) throw new Error('No profile in this UserDB — complete BusinessKit onboarding first')
71
+ const instance = new Cls(agentType)
72
+ await (instance as any).init() // throws with guidance if PROFILE_ID needed
73
+ return instance
74
+ }
75
+
76
+ // ── P0-2: atomic multi-statement batch ─────────────────────────────────────
77
+ protected async txn(stmts: Stmt[]): Promise<void> {
78
+ await db.txn(stmts)
26
79
  }
27
80
 
28
- /** Call at the start of any agent method that needs the DB */
29
- protected async init() {
30
- if (!this.ctx) this.ctx = await getBrandContext(this.db)
81
+ // ── P0-6: audit helper — always bundle inside txn with the mutation ────────
82
+ // Private: subclasses shouldn't call this directly, and renaming keeps
83
+ // agent-level `audit()` methods (e.g. SEOAgent.audit) free.
84
+ private auditStmt(opts: {
85
+ action: 'insert' | 'update' | 'archive'
86
+ table: string
87
+ rowId: string
88
+ diff: Record<string, unknown>
89
+ ikey: string
90
+ }): Stmt {
91
+ const raw = JSON.stringify(opts.diff)
92
+ const payload = raw.length > 4096
93
+ ? JSON.stringify({ _truncated: true, original_size_bytes: raw.length })
94
+ : raw
95
+ return {
96
+ sql: `INSERT OR IGNORE INTO agent_audit
97
+ (id, ts, agent_type, table_name, row_id, action, diff, idempotency_key)
98
+ VALUES (?,?,?,?,?,?,?,?)`,
99
+ args: [ulid(), now(), this.agentType, opts.table, opts.rowId, opts.action, payload, opts.ikey],
100
+ }
31
101
  }
32
102
 
33
- protected get profileId() { return this.ctx.profile.id }
34
- protected get userId() { return this.ctx.profile.user_id }
103
+ // ── P0-1 + P0-2 + P0-6: insert with idempotency + audit in one txn ─────────
104
+ // Silently falls back to plain INSERT if agent_audit doesn't exist yet
105
+ // (pre-migration UserDB). Never blocks agent progress on audit.
106
+ protected async insert(opts: {
107
+ table: string
108
+ id?: string
109
+ cols: Record<string, unknown>
110
+ }): Promise<{ inserted: boolean; id: string }> {
111
+ await this.init()
112
+ const id = opts.id ?? ulid()
113
+ const ikey = generateIdempotencyKey()
114
+ const row = { id, profile_id: this.profileId, ...opts.cols }
115
+ const keys = Object.keys(row)
116
+ const sql = `INSERT OR IGNORE INTO ${opts.table}
117
+ (${keys.join(',')}) VALUES (${keys.map(() => '?').join(',')})`
118
+ const args = Object.values(row)
35
119
 
36
- /** Soft delete — never hard delete */
37
- protected async archive(table: string, id: string | number) {
38
- const ts = typeof id === 'number'
39
- ? `updated_at='${iso()}'`
40
- : `updated_at=${now()}`
41
- await this.db.execute({ sql: `UPDATE ${table} SET hidden=1,${ts} WHERE id=?`, args: [id] })
120
+ try {
121
+ await this.txn([
122
+ { sql, args },
123
+ this.auditStmt({ action: 'insert', table: opts.table, rowId: id, diff: row, ikey }),
124
+ ])
125
+ } catch (e: any) {
126
+ if (/agent_audit/i.test(e?.message ?? '')) await db.write({ sql, args })
127
+ else throw e
128
+ }
129
+
130
+ const { rows } = await db.execute({ sql: `SELECT id FROM ${opts.table} WHERE id=?`, args: [id] })
131
+ return { inserted: rows.length > 0, id }
42
132
  }
43
133
 
44
- /** Publish any content row */
45
- protected async publish(table: string, id: string | number) {
46
- const ts = typeof id === 'number'
47
- ? `updated_at='${iso()}'`
48
- : `updated_at=${now()}`
49
- await this.db.execute({ sql: `UPDATE ${table} SET published=1,${ts} WHERE id=?`, args: [id] })
134
+ // ── P0-7: append-only guard — throws before the DB trigger does ────────────
135
+ // Matches the app-side schema: these tables block DELETE, not UPDATE.
136
+ // crm_activities in particular legitimately UPDATEs approval_status
137
+ // (pending_approval → approved|rejected|auto_sent) and read_at — the
138
+ // schema comment (crm.ts) explicitly calls this out.
139
+ // We only guard against UPDATEs on tables the app fully locks: agent_reports,
140
+ // email_events, clicks_analytics. crm_activities is excluded.
141
+ private static APPEND_ONLY = new Set([
142
+ 'agent_reports',
143
+ 'email_events',
144
+ 'clicks_analytics',
145
+ ])
146
+
147
+ // ── P0-2 + P0-6: UPDATE with audit in one txn ──────────────────────────────
148
+ protected async update(opts: {
149
+ table: string
150
+ id: string
151
+ cols: Record<string, unknown>
152
+ }): Promise<void> {
153
+ if (BaseAgent.APPEND_ONLY.has(opts.table))
154
+ throw new Error(`${opts.table} is append-only — insert a correcting row instead`)
155
+
156
+ await this.init()
157
+ const ikey = generateIdempotencyKey()
158
+ const sets = Object.keys(opts.cols).map(k => `${k}=?`).join(', ')
159
+ const sql = `UPDATE ${opts.table} SET ${sets}, updated_at=?
160
+ WHERE id=? AND profile_id=?`
161
+ const args = [...Object.values(opts.cols), iso(), opts.id, this.profileId]
162
+
163
+ try {
164
+ await this.txn([
165
+ { sql, args },
166
+ this.auditStmt({ action: 'update', table: opts.table, rowId: opts.id, diff: opts.cols, ikey }),
167
+ ])
168
+ } catch (e: any) {
169
+ if (/agent_audit/i.test(e?.message ?? '')) await db.write({ sql, args })
170
+ else throw e
171
+ }
50
172
  }
51
173
 
52
- /** Quick inventory: { total, live, drafts } */
53
- protected async count(table: string) {
54
- const { rows: [r] } = await this.db.execute({
174
+ // ── Soft-delete — never hard delete ───────────────────────────────────────
175
+ // Back-compat signature: (table, id) where id can be string or number.
176
+ protected async archive(table: string, id: string | number): Promise<void> {
177
+ if (BaseAgent.APPEND_ONLY.has(table))
178
+ throw new Error(`${table} is append-only — archive not allowed`)
179
+
180
+ await this.init()
181
+ const ikey = generateIdempotencyKey()
182
+ const tsCol = typeof id === 'number' ? now() : iso()
183
+ const sql = `UPDATE ${table} SET hidden=1, updated_at=? WHERE id=? AND profile_id=?`
184
+ const args = [tsCol, id, this.profileId]
185
+
186
+ try {
187
+ await this.txn([
188
+ { sql, args },
189
+ this.auditStmt({ action: 'archive', table, rowId: String(id), diff: { hidden: 1 }, ikey }),
190
+ ])
191
+ } catch (e: any) {
192
+ if (/agent_audit/i.test(e?.message ?? '')) await db.write({ sql, args })
193
+ else throw e
194
+ }
195
+ }
196
+
197
+ /** Publish any content row (flip published=1). Returns unknown so subclasses
198
+ * can override and return their fetched row. */
199
+ protected async publish(table: string, id: string | number): Promise<unknown> {
200
+ await this.init()
201
+ const tsCol = typeof id === 'number' ? now() : iso()
202
+ await db.write({
203
+ sql: `UPDATE ${table} SET published=1, updated_at=? WHERE id=? AND profile_id=?`,
204
+ args: [tsCol, id, this.profileId],
205
+ })
206
+ return undefined
207
+ }
208
+
209
+ /** Quick inventory: { total, live, drafts }. */
210
+ protected async count(table: string): Promise<{ total: number; live: number; drafts: number }> {
211
+ await this.init()
212
+ const { rows: [r] } = await db.execute({
55
213
  sql: `SELECT COUNT(*) total,
56
- SUM(CASE WHEN published=1 AND hidden=0 THEN 1 ELSE 0 END) live,
57
- SUM(CASE WHEN published=0 AND hidden=0 THEN 1 ELSE 0 END) drafts
214
+ SUM(CASE WHEN published=1 AND hidden=0 THEN 1 ELSE 0 END) live,
215
+ SUM(CASE WHEN published=0 AND hidden=0 THEN 1 ELSE 0 END) drafts
58
216
  FROM ${table} WHERE profile_id=?`,
59
217
  args: [this.profileId],
60
218
  })
61
- return { total: Number(r?.total ?? 0), live: Number(r?.live ?? 0), drafts: Number(r?.drafts ?? 0) }
219
+ return {
220
+ total: Number(r?.total ?? 0),
221
+ live: Number(r?.live ?? 0),
222
+ drafts: Number(r?.drafts ?? 0),
223
+ }
224
+ }
225
+
226
+ // ── P1-2: logMemory — write then trim to last 20 rows per agent ────────────
227
+ // agent_memory.id is INTEGER AUTOINCREMENT — let SQLite assign it.
228
+ // idempotency_key has a unique partial index; retries dedupe automatically.
229
+ protected async logMemory(action: string, meta: Record<string, unknown> = {}): Promise<void> {
230
+ await this.init()
231
+ try {
232
+ const ikey = generateIdempotencyKey()
233
+ await db.write({
234
+ sql: `INSERT OR IGNORE INTO agent_memory
235
+ (profile_id, session_date, agent, action, metadata, idempotency_key)
236
+ VALUES (?,?,?,?,?,?)`,
237
+ args: [
238
+ this.profileId, iso().slice(0, 10),
239
+ this.agentType, action, JSON.stringify(meta), ikey,
240
+ ],
241
+ })
242
+ await db.write({
243
+ sql: `DELETE FROM agent_memory
244
+ WHERE agent=? AND profile_id=?
245
+ AND id NOT IN (
246
+ SELECT id FROM agent_memory
247
+ WHERE agent=? AND profile_id=?
248
+ ORDER BY id DESC LIMIT 20
249
+ )`,
250
+ args: [this.agentType, this.profileId, this.agentType, this.profileId],
251
+ })
252
+ } catch { /* memory is best-effort — never block the agent */ }
253
+ }
254
+
255
+ // ── Agent tasks (kanban board — app-side dashboard renders these) ──────────
256
+ // Tables in `agent_tasks` (see businesskit-files/agent.ts). Each task has:
257
+ // status = 'pending' | 'active' | 'running' | 'done' | 'paused' | 'failed' | 'cancelled'
258
+ // source = 'user' | 'agent'
259
+ // schedule = optional cron string (NULL = on-demand)
260
+
261
+ /** Create a kanban task for an agent. Shows up in /dashboard/agents/tasks. */
262
+ protected async createAgentTask(opts: {
263
+ agent?: string // default: this agent
264
+ title: string
265
+ description?: string
266
+ command: string // e.g. 'weeklyBriefing', 'hotLeads', 'runPublishQueue'
267
+ params?: Record<string, unknown>
268
+ source?: 'user' | 'agent'
269
+ schedule?: string // cron; NULL = on-demand
270
+ timezone?: string
271
+ run_once?: boolean
272
+ next_run_at?: number
273
+ idempotency_key?: string
274
+ }): Promise<string> {
275
+ await this.init()
276
+ const id = ulid()
277
+ const ts = now()
278
+ const ikey = opts.idempotency_key ?? generateIdempotencyKey()
279
+ await db.write({
280
+ sql: `INSERT OR IGNORE INTO agent_tasks
281
+ (id, profile_id, agent, title, description, command, params, source,
282
+ schedule, timezone, run_once, status, next_run_at, idempotency_key,
283
+ created_at, updated_at)
284
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,'pending',?,?,?,?)`,
285
+ args: [
286
+ id, this.profileId, opts.agent ?? this.agentType,
287
+ opts.title, opts.description ?? null, opts.command,
288
+ JSON.stringify(opts.params ?? {}),
289
+ opts.source ?? 'agent',
290
+ opts.schedule ?? null, opts.timezone ?? 'UTC',
291
+ opts.run_once ? 1 : 0,
292
+ opts.next_run_at ?? null, ikey, ts, ts,
293
+ ],
294
+ })
295
+ return id
296
+ }
297
+
298
+ /** Move a task across the kanban: pending → active → running → done. */
299
+ protected async updateTaskStatus(
300
+ taskId: string,
301
+ status: 'pending' | 'active' | 'running' | 'done' | 'paused' | 'failed' | 'cancelled',
302
+ lastRunStatus?: string,
303
+ ): Promise<void> {
304
+ await this.init()
305
+ const ts = now()
306
+ const isTerminal = status === 'done' || status === 'failed' || status === 'cancelled'
307
+ await db.write({
308
+ sql: `UPDATE agent_tasks
309
+ SET status=?, last_run_status=?, last_run_at=?,
310
+ run_count=run_count+CASE WHEN ?=1 THEN 1 ELSE 0 END,
311
+ updated_at=?
312
+ WHERE id=? AND profile_id=?`,
313
+ args: [status, lastRunStatus ?? null, isTerminal ? ts : null,
314
+ isTerminal ? 1 : 0, ts, taskId, this.profileId],
315
+ })
316
+ }
317
+
318
+ /** List tasks for the kanban view. */
319
+ protected async listAgentTasks(opts: {
320
+ agent?: string
321
+ status?: 'pending' | 'active' | 'running' | 'done' | 'paused' | 'failed' | 'cancelled'
322
+ limit?: number
323
+ } = {}): Promise<unknown[]> {
324
+ await this.init()
325
+ let where = 'WHERE profile_id=? AND hidden=0'
326
+ const args: unknown[] = [this.profileId]
327
+ if (opts.agent) { where += ' AND agent=?'; args.push(opts.agent) }
328
+ if (opts.status) { where += ' AND status=?'; args.push(opts.status) }
329
+ const { rows } = await db.execute({
330
+ sql: `SELECT id, agent, title, description, command, status,
331
+ schedule, next_run_at, last_run_at, last_run_status,
332
+ run_count, created_at
333
+ FROM agent_tasks ${where}
334
+ ORDER BY CASE status
335
+ WHEN 'running' THEN 0 WHEN 'active' THEN 1 WHEN 'pending' THEN 2
336
+ WHEN 'paused' THEN 3 WHEN 'done' THEN 4 ELSE 5 END,
337
+ created_at DESC LIMIT ?`,
338
+ args: [...args, opts.limit ?? 100],
339
+ })
340
+ return rows
341
+ }
342
+
343
+ // ── Agent reports — append-only, idempotent, mid-session safe ─────────────
344
+ // agent_reports has a unique partial index on idempotency_key — retries dedupe.
345
+ protected async pushReport(opts: {
346
+ title: string
347
+ type: string
348
+ content: string
349
+ summary?: string
350
+ html?: string
351
+ meta?: Record<string, unknown>
352
+ idempotency_key?: string
353
+ }): Promise<string> {
354
+ await this.init()
355
+ const id = ulid()
356
+ const ikey = opts.idempotency_key ?? generateIdempotencyKey()
357
+ await db.write({
358
+ sql: `INSERT OR IGNORE INTO agent_reports
359
+ (id, profile_id, agent, title, type, content, summary, html,
360
+ metadata, hidden, idempotency_key)
361
+ VALUES (?,?,?,?,?,?,?,?,?,0,?)`,
362
+ args: [
363
+ id, this.profileId, this.agentType,
364
+ opts.title, opts.type, opts.content,
365
+ opts.summary ?? null, opts.html ?? null,
366
+ JSON.stringify(opts.meta ?? {}), ikey,
367
+ ],
368
+ })
369
+ return id
62
370
  }
63
371
  }
@@ -0,0 +1,11 @@
1
+ # analytics
2
+
3
+ Placeholder SOUL. See CLAUDE.md routing table and skills/analytics/SKILL.md (if present) for scope.
4
+
5
+ ## Rules
6
+
7
+ - Load skills on demand
8
+ - Draft before publish
9
+ - Archive not delete (hidden=1)
10
+ - Log every action to agent_memory
11
+ - Push reports to agent_reports mid-session