adam-agent-server 0.1.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 (86) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +424 -0
  3. package/dist/App-23CRAK2P.js +9 -0
  4. package/dist/adam-tools-MKUMZWCR.js +1 -0
  5. package/dist/approval-handler-SBFVVFGH.js +4 -0
  6. package/dist/channels-CNLMTKHM.js +1 -0
  7. package/dist/channels-VNG7U6UQ.js +1 -0
  8. package/dist/chunk-37OAKNKA.js +15 -0
  9. package/dist/chunk-3DAK2XWP.js +1 -0
  10. package/dist/chunk-3HM54J2N.js +1 -0
  11. package/dist/chunk-3OYRYMJW.js +11 -0
  12. package/dist/chunk-5AKFAMQL.js +29 -0
  13. package/dist/chunk-5BAD3NCT.js +1 -0
  14. package/dist/chunk-5GMYXCL3.js +1 -0
  15. package/dist/chunk-62PXAOD6.js +7 -0
  16. package/dist/chunk-B3CVXD44.js +104 -0
  17. package/dist/chunk-CV3ROBUM.js +1 -0
  18. package/dist/chunk-EJJDJY34.js +5 -0
  19. package/dist/chunk-F2IS5LWD.js +1 -0
  20. package/dist/chunk-FCV2DPZQ.js +1 -0
  21. package/dist/chunk-FUBKGVWI.js +8 -0
  22. package/dist/chunk-HMXDNPFE.js +5 -0
  23. package/dist/chunk-J5YZQQTS.js +3 -0
  24. package/dist/chunk-MMIO6BCA.js +10 -0
  25. package/dist/chunk-Q3N5LVPZ.js +5 -0
  26. package/dist/chunk-QOPUUA7O.js +1 -0
  27. package/dist/chunk-TGQYM4TH.js +6 -0
  28. package/dist/chunk-TYR3QUCL.js +23 -0
  29. package/dist/chunk-VURJZLM6.js +49 -0
  30. package/dist/chunk-W6JITSZF.js +569 -0
  31. package/dist/chunk-WGRTN6TX.js +1 -0
  32. package/dist/chunk-ZN5Q3YET.js +1 -0
  33. package/dist/cli.js +15 -0
  34. package/dist/config-42ZJPZDM.js +1 -0
  35. package/dist/db-ZDEA7EUY.js +1 -0
  36. package/dist/delivery-log-7DQ36UGP.js +1 -0
  37. package/dist/dist-CDWBOTZS.js +1 -0
  38. package/dist/engine-7VBPXTGK.js +1 -0
  39. package/dist/evolution-audit-MDA2ZVJW.js +1 -0
  40. package/dist/external-api-T7FFXVHL.js +1 -0
  41. package/dist/index.js +152 -0
  42. package/dist/logger-BEG4WFIM.js +1 -0
  43. package/dist/memories-BUNOVQVG.js +1 -0
  44. package/dist/onnxruntime_binding-6Q6HXASN.node +0 -0
  45. package/dist/onnxruntime_binding-EKZT2NRK.node +0 -0
  46. package/dist/onnxruntime_binding-P6S7V3CI.node +0 -0
  47. package/dist/onnxruntime_binding-PJNNIIUO.node +0 -0
  48. package/dist/onnxruntime_binding-UN6SPTQK.node +0 -0
  49. package/dist/role-presets-2X3VW75D.js +1 -0
  50. package/dist/roles-CMV5FMIA.js +1 -0
  51. package/dist/runtime-772O2XKZ.js +1 -0
  52. package/dist/server-bus-N5LCY73J.js +1 -0
  53. package/dist/session-manager-KO4CR3W6.js +1 -0
  54. package/dist/task-templates-AKQB7RRB.js +1 -0
  55. package/package.json +77 -0
  56. package/web/dist/assets/Card-BpwkRtmi.js +1 -0
  57. package/web/dist/assets/ChannelDetail-050qK78l.js +1 -0
  58. package/web/dist/assets/Channels-DA4gN6nU.js +12 -0
  59. package/web/dist/assets/Chat-LzhfKGQ5.js +1 -0
  60. package/web/dist/assets/Dashboard-Bh32YC_E.js +1 -0
  61. package/web/dist/assets/EmptyState-B08f3BH6.js +1 -0
  62. package/web/dist/assets/Evolution-BwsOuVbZ.js +3 -0
  63. package/web/dist/assets/GoalDetail-Zo16ZrYD.js +1 -0
  64. package/web/dist/assets/Goals-BmfVadFN.js +1 -0
  65. package/web/dist/assets/Logs-CYfQ9k_6.js +1 -0
  66. package/web/dist/assets/Memories-CgSb60RC.js +1 -0
  67. package/web/dist/assets/Plugins-DHgIfely.js +1 -0
  68. package/web/dist/assets/RoleDetail-CNJkMSuz.js +1 -0
  69. package/web/dist/assets/Roles-DGpN5Vm6.js +1 -0
  70. package/web/dist/assets/Settings-PjFyeX8n.js +1 -0
  71. package/web/dist/assets/Strategies-DBp2jYdi.js +1 -0
  72. package/web/dist/assets/Switch-yk5-dsti.js +1 -0
  73. package/web/dist/assets/Table-DWR4p9xA.js +1 -0
  74. package/web/dist/assets/TaskDetail-DMg-JAbC.js +2 -0
  75. package/web/dist/assets/Work-BYgMw2qj.js +1 -0
  76. package/web/dist/assets/dist-jv3vbjrx.js +1 -0
  77. package/web/dist/assets/format-DvtQjPZn.js +1 -0
  78. package/web/dist/assets/index-CWY8H-cU.js +52 -0
  79. package/web/dist/assets/index-OXMtvYRJ.css +2 -0
  80. package/web/dist/assets/rolldown-runtime-DF2fYuay.js +1 -0
  81. package/web/dist/assets/vendor-icons-DqHipOFA.js +1 -0
  82. package/web/dist/assets/vendor-react-C2hDj0vl.js +11 -0
  83. package/web/dist/assets/vendor-state-CRsbPXtF.js +1 -0
  84. package/web/dist/favicon.svg +1 -0
  85. package/web/dist/icons.svg +24 -0
  86. package/web/dist/index.html +19 -0
@@ -0,0 +1,569 @@
1
+ import{d as a,f as L}from"./chunk-F2IS5LWD.js";import{c}from"./chunk-FCV2DPZQ.js";import d from"better-sqlite3";import{existsSync as I,mkdirSync as A}from"fs";import{dirname as R}from"path";function X(e){e.exec(`
2
+ CREATE TABLE IF NOT EXISTS server_state (
3
+ id INTEGER PRIMARY KEY CHECK(id = 1),
4
+ sdk_session_id TEXT,
5
+ user_task_session_id TEXT,
6
+ workspace_path TEXT,
7
+ schema_version INTEGER DEFAULT 0,
8
+ created_at INTEGER NOT NULL DEFAULT (unixepoch('now') * 1000),
9
+ last_active_at INTEGER
10
+ );
11
+ `),e.prepare("PRAGMA table_info(server_state)").all().some(T=>T.name==="schema_version")||e.exec("ALTER TABLE server_state ADD COLUMN schema_version INTEGER DEFAULT 0");let o=e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0;if(o<2){let T=["delivery_log","delivery_rules","manager_decisions","skill_scores","approval_rules","task_plans","calibration_history","task_plugins","marketplaces","plugins","trials","strategies","metric_tree","goals","chat_messages","chat_sessions","channels","evolution_audit","step_logs","task_templates","memories","tasks","config","memories_fts","memories_fts_config","memories_fts_data","memories_fts_docsize","memories_fts_idx"];for(let E of T)try{e.exec(`DROP TABLE IF EXISTS ${E}`)}catch{}for(let E of["memories_fts_insert","memories_fts_delete","memories_fts_update"])try{e.exec(`DROP TRIGGER IF EXISTS ${E}`)}catch{}}e.exec(`
12
+ CREATE TABLE IF NOT EXISTS tasks (
13
+ id TEXT PRIMARY KEY,
14
+ parent_id TEXT,
15
+ status TEXT NOT NULL DEFAULT 'pending',
16
+ prompt TEXT NOT NULL,
17
+ config TEXT NOT NULL,
18
+ result TEXT,
19
+ error TEXT,
20
+ sdk_session_id TEXT,
21
+ template_id TEXT,
22
+ original_prompt TEXT,
23
+ role_id TEXT,
24
+ source_session_id TEXT,
25
+ notify_targets TEXT,
26
+ deliver_to TEXT,
27
+ report_to TEXT,
28
+ created_at INTEGER NOT NULL,
29
+ started_at INTEGER,
30
+ completed_at INTEGER,
31
+ cost_usd REAL,
32
+ token_usage TEXT,
33
+ num_turns INTEGER,
34
+ total_duration_ms INTEGER
35
+ );
36
+
37
+ CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status);
38
+ CREATE INDEX IF NOT EXISTS idx_tasks_created_at ON tasks(created_at);
39
+ CREATE INDEX IF NOT EXISTS idx_tasks_template_id ON tasks(template_id);
40
+ CREATE INDEX IF NOT EXISTS idx_tasks_role_id ON tasks(role_id);
41
+
42
+ CREATE TABLE IF NOT EXISTS step_logs (
43
+ id TEXT PRIMARY KEY,
44
+ task_id TEXT NOT NULL,
45
+ "index" INTEGER NOT NULL,
46
+ type TEXT NOT NULL,
47
+ content TEXT NOT NULL,
48
+ tool_name TEXT,
49
+ tool_input TEXT,
50
+ tool_output TEXT,
51
+ truncated INTEGER DEFAULT 0,
52
+ timestamp INTEGER NOT NULL,
53
+ token_usage TEXT,
54
+ plan_step_index INTEGER
55
+ );
56
+
57
+ CREATE INDEX IF NOT EXISTS idx_step_logs_task_index ON step_logs(task_id, "index");
58
+
59
+ CREATE TABLE IF NOT EXISTS config (
60
+ key TEXT PRIMARY KEY,
61
+ value TEXT NOT NULL
62
+ );
63
+
64
+ CREATE TABLE IF NOT EXISTS evolution_audit (
65
+ id TEXT PRIMARY KEY,
66
+ timestamp INTEGER NOT NULL,
67
+ old_rules TEXT,
68
+ new_rules TEXT,
69
+ diff TEXT,
70
+ trigger_task_id TEXT,
71
+ role_id TEXT,
72
+ source TEXT DEFAULT 'reflection'
73
+ );
74
+
75
+ CREATE INDEX IF NOT EXISTS idx_evolution_audit_role_id ON evolution_audit(role_id);
76
+
77
+ CREATE TABLE IF NOT EXISTS memories (
78
+ id TEXT PRIMARY KEY,
79
+ role_id TEXT NOT NULL,
80
+ type TEXT NOT NULL CHECK(type IN ('event', 'thought', 'reflection')),
81
+ content TEXT NOT NULL,
82
+ embedding BLOB,
83
+ keywords TEXT,
84
+ importance INTEGER NOT NULL CHECK(importance BETWEEN 1 AND 5),
85
+ source_type TEXT NOT NULL,
86
+ source_task_id TEXT,
87
+ evidence TEXT,
88
+ created_at INTEGER NOT NULL,
89
+ last_accessed INTEGER NOT NULL,
90
+ retrieved_count INTEGER DEFAULT 0
91
+ );
92
+
93
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
94
+ content,
95
+ keywords,
96
+ content='memories',
97
+ content_rowid='rowid'
98
+ );
99
+
100
+ CREATE INDEX IF NOT EXISTS idx_memories_role_id ON memories(role_id);
101
+ CREATE INDEX IF NOT EXISTS idx_memories_created_at ON memories(created_at);
102
+ CREATE INDEX IF NOT EXISTS idx_memories_type ON memories(type);
103
+
104
+ -- FTS5 content sync triggers
105
+ CREATE TRIGGER IF NOT EXISTS memories_fts_insert AFTER INSERT ON memories BEGIN
106
+ INSERT INTO memories_fts(rowid, content, keywords) VALUES (new.rowid, new.content, new.keywords);
107
+ END;
108
+ CREATE TRIGGER IF NOT EXISTS memories_fts_delete AFTER DELETE ON memories BEGIN
109
+ INSERT INTO memories_fts(memories_fts, rowid, content, keywords) VALUES ('delete', old.rowid, old.content, old.keywords);
110
+ END;
111
+ CREATE TRIGGER IF NOT EXISTS memories_fts_update AFTER UPDATE ON memories BEGIN
112
+ INSERT INTO memories_fts(memories_fts, rowid, content, keywords) VALUES ('delete', old.rowid, old.content, old.keywords);
113
+ INSERT INTO memories_fts(rowid, content, keywords) VALUES (new.rowid, new.content, new.keywords);
114
+ END;
115
+ `),e.exec(`
116
+ CREATE TABLE IF NOT EXISTS goals (
117
+ id TEXT PRIMARY KEY,
118
+ name TEXT NOT NULL,
119
+ description TEXT,
120
+ role TEXT NOT NULL,
121
+ metric_type TEXT NOT NULL,
122
+ target_value REAL NOT NULL,
123
+ current_value REAL NOT NULL DEFAULT 0,
124
+ deadline INTEGER NOT NULL,
125
+ budget_usd REAL NOT NULL,
126
+ status TEXT NOT NULL DEFAULT 'pending',
127
+ created_at INTEGER NOT NULL,
128
+ updated_at INTEGER,
129
+ notify_targets TEXT,
130
+ deliver_to TEXT
131
+ );
132
+
133
+ CREATE INDEX IF NOT EXISTS idx_goals_status ON goals(status);
134
+ CREATE INDEX IF NOT EXISTS idx_goals_deadline ON goals(deadline);
135
+
136
+ CREATE TABLE IF NOT EXISTS metric_tree (
137
+ id TEXT PRIMARY KEY,
138
+ goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
139
+ level TEXT NOT NULL CHECK(level IN ('L0', 'L1', 'L2', 'L3')),
140
+ parent_id TEXT REFERENCES metric_tree(id) ON DELETE SET NULL,
141
+ name TEXT NOT NULL,
142
+ description TEXT,
143
+ weight REAL NOT NULL DEFAULT 1.0,
144
+ calibration_factor REAL DEFAULT 1.0,
145
+ created_at INTEGER NOT NULL
146
+ );
147
+
148
+ CREATE INDEX IF NOT EXISTS idx_metric_tree_goal_id ON metric_tree(goal_id);
149
+ CREATE INDEX IF NOT EXISTS idx_metric_tree_level ON metric_tree(level);
150
+ CREATE INDEX IF NOT EXISTS idx_metric_tree_parent_id ON metric_tree(parent_id);
151
+
152
+ CREATE TABLE IF NOT EXISTS strategies (
153
+ id TEXT PRIMARY KEY,
154
+ role_id TEXT NOT NULL,
155
+ task_type TEXT NOT NULL,
156
+ name TEXT NOT NULL,
157
+ prompt_template TEXT NOT NULL,
158
+ alpha REAL NOT NULL DEFAULT 0.5,
159
+ beta REAL NOT NULL DEFAULT 0.5,
160
+ total_trials INTEGER DEFAULT 0,
161
+ avg_reward REAL,
162
+ created_at INTEGER NOT NULL,
163
+ updated_at INTEGER
164
+ );
165
+
166
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_strategies_role_task_type ON strategies(role_id, task_type, name);
167
+ CREATE INDEX IF NOT EXISTS idx_strategies_role ON strategies(role_id);
168
+
169
+ CREATE TABLE IF NOT EXISTS trials (
170
+ id TEXT PRIMARY KEY,
171
+ strategy_id TEXT NOT NULL REFERENCES strategies(id) ON DELETE CASCADE,
172
+ goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
173
+ task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL,
174
+ reward REAL,
175
+ metric_l2_score REAL,
176
+ metric_l3_score REAL,
177
+ context TEXT,
178
+ completed_at INTEGER NOT NULL
179
+ );
180
+
181
+ CREATE INDEX IF NOT EXISTS idx_trials_strategy_id ON trials(strategy_id);
182
+ CREATE INDEX IF NOT EXISTS idx_trials_goal_id ON trials(goal_id);
183
+ CREATE INDEX IF NOT EXISTS idx_trials_task_id ON trials(task_id);
184
+ CREATE INDEX IF NOT EXISTS idx_trials_completed_at ON trials(completed_at);
185
+
186
+ CREATE TABLE IF NOT EXISTS task_templates (
187
+ id TEXT PRIMARY KEY,
188
+ name TEXT NOT NULL,
189
+ description TEXT,
190
+ trigger_type TEXT NOT NULL,
191
+ trigger_cron TEXT,
192
+ trigger_event TEXT,
193
+ steps TEXT NOT NULL,
194
+ role_preference TEXT,
195
+ config TEXT,
196
+ tags TEXT,
197
+ enabled INTEGER DEFAULT 1,
198
+ created_at INTEGER NOT NULL,
199
+ updated_at INTEGER,
200
+ source_session_id TEXT,
201
+ notify_targets TEXT,
202
+ deliver_to TEXT,
203
+ goal_ids TEXT
204
+ );
205
+
206
+ CREATE TABLE IF NOT EXISTS task_plugins (
207
+ id TEXT PRIMARY KEY,
208
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
209
+ plugin_path TEXT NOT NULL,
210
+ plugin_name TEXT NOT NULL,
211
+ role_id TEXT,
212
+ used_at INTEGER NOT NULL
213
+ );
214
+
215
+ CREATE INDEX IF NOT EXISTS idx_task_plugins_task_id ON task_plugins(task_id);
216
+ CREATE INDEX IF NOT EXISTS idx_task_plugins_plugin_path ON task_plugins(plugin_path);
217
+ CREATE INDEX IF NOT EXISTS idx_task_plugins_role_id ON task_plugins(role_id);
218
+ `),e.exec(`
219
+ CREATE TABLE IF NOT EXISTS chat_sessions (
220
+ id TEXT PRIMARY KEY,
221
+ status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active', 'archived')),
222
+ source_type TEXT NOT NULL,
223
+ source_channel_id TEXT,
224
+ source_chat_id TEXT,
225
+ title TEXT,
226
+ created_at INTEGER NOT NULL,
227
+ last_active_at INTEGER NOT NULL,
228
+ archived_at INTEGER,
229
+ message_count INTEGER DEFAULT 0
230
+ );
231
+
232
+ CREATE INDEX IF NOT EXISTS idx_sessions_status ON chat_sessions(status);
233
+ CREATE INDEX IF NOT EXISTS idx_sessions_last_active ON chat_sessions(last_active_at);
234
+ CREATE INDEX IF NOT EXISTS idx_sessions_source ON chat_sessions(source_type, source_channel_id, source_chat_id);
235
+
236
+ CREATE TABLE IF NOT EXISTS chat_messages (
237
+ id TEXT PRIMARY KEY,
238
+ session_id TEXT NOT NULL REFERENCES chat_sessions(id) ON DELETE CASCADE,
239
+ role TEXT NOT NULL CHECK(role IN ('user', 'assistant')),
240
+ content TEXT NOT NULL,
241
+ source_type TEXT NOT NULL,
242
+ task_id TEXT REFERENCES tasks(id),
243
+ channel_message_id TEXT,
244
+ metadata TEXT,
245
+ created_at INTEGER NOT NULL
246
+ );
247
+
248
+ CREATE INDEX IF NOT EXISTS idx_messages_session ON chat_messages(session_id, created_at);
249
+ CREATE INDEX IF NOT EXISTS idx_messages_task ON chat_messages(task_id);
250
+
251
+ CREATE TABLE IF NOT EXISTS channels (
252
+ id TEXT PRIMARY KEY,
253
+ name TEXT NOT NULL,
254
+ platform TEXT NOT NULL,
255
+ enabled INTEGER DEFAULT 1,
256
+ status TEXT NOT NULL DEFAULT 'disconnected',
257
+ config TEXT NOT NULL,
258
+ linked_role_id TEXT,
259
+ allowed_chat_ids TEXT,
260
+ created_at INTEGER NOT NULL,
261
+ updated_at INTEGER,
262
+ last_message_at INTEGER,
263
+ message_count INTEGER DEFAULT 0
264
+ );
265
+
266
+ CREATE INDEX IF NOT EXISTS idx_channels_platform ON channels(platform);
267
+ CREATE INDEX IF NOT EXISTS idx_channels_enabled ON channels(enabled);
268
+ CREATE INDEX IF NOT EXISTS idx_channels_linked_role_id ON channels(linked_role_id);
269
+ `),e.exec(`
270
+ CREATE TABLE IF NOT EXISTS task_plans (
271
+ id TEXT PRIMARY KEY,
272
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
273
+ plan_json TEXT NOT NULL,
274
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'approved', 'denied', 'completed')),
275
+ approval_type TEXT CHECK(approval_type IN ('once', 'permanent')),
276
+ deviation_report_json TEXT,
277
+ learned_rules_json TEXT,
278
+ created_at INTEGER NOT NULL,
279
+ approved_at INTEGER,
280
+ reviewed_at INTEGER
281
+ );
282
+
283
+ CREATE INDEX IF NOT EXISTS idx_task_plans_task_id ON task_plans(task_id);
284
+ CREATE INDEX IF NOT EXISTS idx_task_plans_status ON task_plans(status);
285
+
286
+ CREATE TABLE IF NOT EXISTS approval_rules (
287
+ id TEXT PRIMARY KEY,
288
+ role_id TEXT,
289
+ task_pattern TEXT NOT NULL,
290
+ max_risk_level TEXT NOT NULL CHECK(max_risk_level IN ('low', 'medium', 'high')),
291
+ created_at INTEGER NOT NULL,
292
+ created_by_task_id TEXT REFERENCES tasks(id)
293
+ );
294
+
295
+ CREATE INDEX IF NOT EXISTS idx_approval_rules_role_id ON approval_rules(role_id);
296
+ `),e.exec(`
297
+ CREATE TABLE IF NOT EXISTS role_scores (
298
+ id TEXT PRIMARY KEY,
299
+ role_id TEXT NOT NULL,
300
+ task_id TEXT NOT NULL REFERENCES tasks(id),
301
+ score_json TEXT NOT NULL,
302
+ ema_score REAL NOT NULL,
303
+ created_at INTEGER NOT NULL
304
+ );
305
+
306
+ CREATE INDEX IF NOT EXISTS idx_role_scores_role_id ON role_scores(role_id);
307
+ CREATE INDEX IF NOT EXISTS idx_role_scores_task_id ON role_scores(task_id);
308
+ CREATE INDEX IF NOT EXISTS idx_role_scores_created_at ON role_scores(created_at);
309
+ `),e.exec(`
310
+ CREATE TABLE IF NOT EXISTS manager_decisions (
311
+ id TEXT PRIMARY KEY,
312
+ task_id TEXT NOT NULL REFERENCES tasks(id),
313
+ role_id TEXT,
314
+ decision_type TEXT NOT NULL,
315
+ boundary_json TEXT,
316
+ reason TEXT,
317
+ created_at INTEGER NOT NULL
318
+ );
319
+
320
+ CREATE INDEX IF NOT EXISTS idx_manager_decisions_task_id ON manager_decisions(task_id);
321
+ CREATE INDEX IF NOT EXISTS idx_manager_decisions_role_id ON manager_decisions(role_id);
322
+ `),e.exec(`
323
+ CREATE TABLE IF NOT EXISTS delivery_rules (
324
+ id TEXT PRIMARY KEY,
325
+ event_type TEXT NOT NULL,
326
+ match_criteria TEXT NOT NULL,
327
+ target TEXT NOT NULL,
328
+ format_template TEXT,
329
+ max_per_minute INTEGER DEFAULT 5,
330
+ skip_origin_channel INTEGER DEFAULT 1,
331
+ enabled INTEGER DEFAULT 1,
332
+ created_at INTEGER NOT NULL,
333
+ created_by TEXT
334
+ );
335
+
336
+ CREATE INDEX IF NOT EXISTS idx_delivery_rules_event_type ON delivery_rules(event_type);
337
+ CREATE INDEX IF NOT EXISTS idx_delivery_rules_enabled ON delivery_rules(enabled);
338
+
339
+ CREATE TABLE IF NOT EXISTS delivery_log (
340
+ id TEXT PRIMARY KEY,
341
+ rule_id TEXT NOT NULL REFERENCES delivery_rules(id),
342
+ task_id TEXT REFERENCES tasks(id),
343
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'delivered', 'failed', 'expired')),
344
+ target TEXT NOT NULL,
345
+ content TEXT NOT NULL,
346
+ attempts INTEGER DEFAULT 0,
347
+ error TEXT,
348
+ created_at INTEGER NOT NULL,
349
+ delivered_at INTEGER,
350
+ expires_at INTEGER NOT NULL
351
+ );
352
+
353
+ CREATE INDEX IF NOT EXISTS idx_delivery_log_status ON delivery_log(status);
354
+ CREATE INDEX IF NOT EXISTS idx_delivery_log_expires ON delivery_log(expires_at);
355
+ CREATE INDEX IF NOT EXISTS idx_delivery_log_rule_id ON delivery_log(rule_id);
356
+ `),e.exec(`
357
+ CREATE TABLE IF NOT EXISTS calibration_history (
358
+ id TEXT PRIMARY KEY,
359
+ goal_id TEXT NOT NULL,
360
+ factors_json TEXT NOT NULL,
361
+ l0_score REAL NOT NULL,
362
+ l1_trend REAL NOT NULL,
363
+ l2_trend REAL NOT NULL,
364
+ l3_trend REAL NOT NULL,
365
+ applied INTEGER NOT NULL DEFAULT 0,
366
+ computed_at INTEGER NOT NULL
367
+ );
368
+
369
+ CREATE INDEX IF NOT EXISTS idx_calibration_goal ON calibration_history(goal_id);
370
+ CREATE INDEX IF NOT EXISTS idx_calibration_computed ON calibration_history(computed_at);
371
+ `);try{e.exec("ALTER TABLE server_state ADD COLUMN schema_version INTEGER DEFAULT 1")}catch{}if(e.exec("UPDATE server_state SET schema_version = 2 WHERE id = 1"),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<4&&(e.exec(`
372
+ CREATE TABLE IF NOT EXISTS roles (
373
+ id TEXT PRIMARY KEY,
374
+ name TEXT NOT NULL UNIQUE,
375
+ cag_prompt TEXT NOT NULL DEFAULT '',
376
+ learned_rules TEXT,
377
+ memory_stream_id TEXT NOT NULL,
378
+ status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active', 'inactive', 'retired', 'probation', 'dead')),
379
+ performance_score REAL,
380
+ preferences TEXT,
381
+ created_at INTEGER NOT NULL,
382
+ updated_at INTEGER,
383
+ importance_trigger_curr INTEGER DEFAULT 150,
384
+ allowed_tools TEXT,
385
+ disallowed_tools TEXT,
386
+ evaluation_criteria TEXT,
387
+ execution_mode TEXT DEFAULT 'isolated',
388
+ model TEXT,
389
+ max_budget_usd REAL,
390
+ approval_required TEXT,
391
+ source TEXT DEFAULT 'system',
392
+ additional_directories TEXT,
393
+ allowed_channels TEXT,
394
+ mcp_servers TEXT,
395
+ inherit_user_settings INTEGER DEFAULT 0
396
+ );
397
+
398
+ CREATE INDEX IF NOT EXISTS idx_roles_status ON roles(status);
399
+ CREATE INDEX IF NOT EXISTS idx_roles_name ON roles(name);
400
+
401
+ CREATE TABLE IF NOT EXISTS role_plugins (
402
+ role_id TEXT NOT NULL,
403
+ plugin_id TEXT NOT NULL,
404
+ bound_at INTEGER NOT NULL,
405
+ PRIMARY KEY (role_id, plugin_id)
406
+ );
407
+ `),e.prepare("PRAGMA table_info(tasks)").all().some(E=>E.name==="role_id")||(e.exec("ALTER TABLE tasks ADD COLUMN role_id TEXT"),e.exec("CREATE INDEX IF NOT EXISTS idx_tasks_role_id ON tasks(role_id)")),e.exec("UPDATE server_state SET schema_version = 4 WHERE id = 1")),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<5&&(e.exec(`
408
+ DROP TABLE IF EXISTS memories;
409
+ CREATE TABLE memories (
410
+ id TEXT PRIMARY KEY,
411
+ role_id TEXT NOT NULL,
412
+ type TEXT NOT NULL CHECK(type IN ('event', 'thought', 'reflection')),
413
+ content TEXT NOT NULL,
414
+ embedding BLOB,
415
+ keywords TEXT,
416
+ importance INTEGER NOT NULL CHECK(importance BETWEEN 1 AND 5),
417
+ source_type TEXT NOT NULL,
418
+ source_task_id TEXT,
419
+ evidence TEXT,
420
+ created_at INTEGER NOT NULL,
421
+ last_accessed INTEGER NOT NULL,
422
+ retrieved_count INTEGER DEFAULT 0
423
+ );
424
+ CREATE INDEX IF NOT EXISTS idx_memories_role_id ON memories(role_id);
425
+ CREATE INDEX IF NOT EXISTS idx_memories_created_at ON memories(created_at);
426
+ CREATE INDEX IF NOT EXISTS idx_memories_type ON memories(type);
427
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
428
+ content, keywords,
429
+ content='memories',
430
+ content_rowid='rowid'
431
+ );
432
+ CREATE TRIGGER IF NOT EXISTS memories_fts_insert AFTER INSERT ON memories BEGIN
433
+ INSERT INTO memories_fts(rowid, content, keywords) VALUES (new.rowid, new.content, new.keywords);
434
+ END;
435
+ CREATE TRIGGER IF NOT EXISTS memories_fts_delete AFTER DELETE ON memories BEGIN
436
+ INSERT INTO memories_fts(memories_fts, rowid, content, keywords) VALUES ('delete', old.rowid, old.content, old.keywords);
437
+ END;
438
+ CREATE TRIGGER IF NOT EXISTS memories_fts_update AFTER UPDATE ON memories BEGIN
439
+ INSERT INTO memories_fts(memories_fts, rowid, content, keywords) VALUES ('delete', old.rowid, old.content, old.keywords);
440
+ INSERT INTO memories_fts(rowid, content, keywords) VALUES (new.rowid, new.content, new.keywords);
441
+ END;
442
+ `),e.exec(`
443
+ DROP TABLE IF EXISTS skill_scores;
444
+ CREATE TABLE IF NOT EXISTS role_scores (
445
+ id TEXT PRIMARY KEY,
446
+ role_id TEXT NOT NULL,
447
+ task_id TEXT NOT NULL REFERENCES tasks(id),
448
+ score_json TEXT NOT NULL,
449
+ ema_score REAL NOT NULL,
450
+ created_at INTEGER NOT NULL
451
+ );
452
+ CREATE INDEX IF NOT EXISTS idx_role_scores_role_id ON role_scores(role_id);
453
+ CREATE INDEX IF NOT EXISTS idx_role_scores_task_id ON role_scores(task_id);
454
+ CREATE INDEX IF NOT EXISTS idx_role_scores_created_at ON role_scores(created_at);
455
+ `),e.exec(`
456
+ DROP TABLE IF EXISTS evolution_audit;
457
+ CREATE TABLE evolution_audit (
458
+ id TEXT PRIMARY KEY,
459
+ timestamp INTEGER NOT NULL,
460
+ old_rules TEXT,
461
+ new_rules TEXT,
462
+ diff TEXT,
463
+ trigger_task_id TEXT,
464
+ role_id TEXT,
465
+ source TEXT DEFAULT 'reflection'
466
+ );
467
+ CREATE INDEX IF NOT EXISTS idx_evolution_audit_role_id ON evolution_audit(role_id);
468
+ `),e.exec("UPDATE server_state SET schema_version = 5 WHERE id = 1")),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<6&&(e.prepare("PRAGMA table_info(roles)").all().some(E=>E.name==="importance_trigger_curr")||e.exec("ALTER TABLE roles ADD COLUMN importance_trigger_curr INTEGER DEFAULT 150"),e.exec("UPDATE server_state SET schema_version = 6 WHERE id = 1")),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<7&&(e.prepare("PRAGMA table_info(tasks)").all().some(E=>E.name==="source_session_id")||e.exec("ALTER TABLE tasks ADD COLUMN source_session_id TEXT"),e.exec("UPDATE server_state SET schema_version = 7 WHERE id = 1")),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<8){let T=e.prepare("PRAGMA table_info(goals)").all();T.some(s=>s.name==="source_session_id")||e.exec("ALTER TABLE goals ADD COLUMN source_session_id TEXT"),T.some(s=>s.name==="notify_targets")||e.exec("ALTER TABLE goals ADD COLUMN notify_targets TEXT");let E=e.prepare("PRAGMA table_info(task_templates)").all();E.some(s=>s.name==="source_session_id")||e.exec("ALTER TABLE task_templates ADD COLUMN source_session_id TEXT"),E.some(s=>s.name==="notify_targets")||e.exec("ALTER TABLE task_templates ADD COLUMN notify_targets TEXT"),E.some(s=>s.name==="goal_ids")||e.exec("ALTER TABLE task_templates ADD COLUMN goal_ids TEXT"),e.exec("UPDATE goals SET status = 'active' WHERE status IN ('pending','planning','executing','evaluating','replanning')"),e.exec("UPDATE server_state SET schema_version = 8 WHERE id = 1")}if((e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<10){e.exec("PRAGMA foreign_keys = OFF"),e.exec("DROP TABLE IF EXISTS tasks_new"),e.exec("DROP TABLE IF EXISTS chat_sessions_new"),e.exec("DROP TABLE IF EXISTS task_plans_new"),e.exec("DROP TABLE IF EXISTS task_plugins_new"),e.exec("DROP TABLE IF EXISTS approval_rules_new"),e.exec("DROP TABLE IF EXISTS manager_decisions_new"),e.exec("DROP TABLE IF EXISTS channels_new");let T=e.prepare("PRAGMA table_info(roles)").all();T.some(t=>t.name==="allowed_tools")||e.exec("ALTER TABLE roles ADD COLUMN allowed_tools TEXT"),T.some(t=>t.name==="disallowed_tools")||e.exec("ALTER TABLE roles ADD COLUMN disallowed_tools TEXT"),T.some(t=>t.name==="evaluation_criteria")||e.exec("ALTER TABLE roles ADD COLUMN evaluation_criteria TEXT"),T.some(t=>t.name==="execution_mode")||e.exec("ALTER TABLE roles ADD COLUMN execution_mode TEXT DEFAULT 'isolated'"),T.some(t=>t.name==="model")||e.exec("ALTER TABLE roles ADD COLUMN model TEXT"),T.some(t=>t.name==="max_budget_usd")||e.exec("ALTER TABLE roles ADD COLUMN max_budget_usd REAL"),T.some(t=>t.name==="approval_required")||e.exec("ALTER TABLE roles ADD COLUMN approval_required TEXT"),T.some(t=>t.name==="source")||e.exec("ALTER TABLE roles ADD COLUMN source TEXT DEFAULT 'system'"),e.exec("DROP TABLE IF EXISTS agents"),e.exec("DROP TABLE IF EXISTS role_skills"),e.exec(`
469
+ CREATE TABLE IF NOT EXISTS tasks_new (
470
+ id TEXT PRIMARY KEY,
471
+ parent_id TEXT,
472
+ status TEXT NOT NULL DEFAULT 'pending',
473
+ prompt TEXT NOT NULL,
474
+ config TEXT NOT NULL,
475
+ result TEXT,
476
+ error TEXT,
477
+ sdk_session_id TEXT,
478
+ template_id TEXT,
479
+ original_prompt TEXT,
480
+ role_id TEXT,
481
+ source_session_id TEXT,
482
+ notify_targets TEXT,
483
+ deliver_to TEXT,
484
+ report_to TEXT,
485
+ created_at INTEGER NOT NULL,
486
+ started_at INTEGER,
487
+ completed_at INTEGER,
488
+ cost_usd REAL,
489
+ token_usage TEXT,
490
+ num_turns INTEGER,
491
+ total_duration_ms INTEGER
492
+ );
493
+ `);let E=new Set(["id","status","prompt","config","created_at"]),s=["id","parent_id","status","prompt","config","result","error","sdk_session_id","template_id","original_prompt","role_id","source_session_id","notify_targets","deliver_to","report_to","created_at","started_at","completed_at","cost_usd","token_usage","num_turns","total_duration_ms"],i=new Set(e.prepare("PRAGMA table_info(tasks)").all().map(t=>t.name)),r=s.map(t=>i.has(t)?E.has(t)?`COALESCE(${t}, '')`:t:"NULL").join(",");e.exec(`INSERT INTO tasks_new SELECT ${r} FROM tasks`),e.exec("DROP TABLE tasks"),e.exec("ALTER TABLE tasks_new RENAME TO tasks"),e.exec("CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status)"),e.exec("CREATE INDEX IF NOT EXISTS idx_tasks_created_at ON tasks(created_at)"),e.exec("CREATE INDEX IF NOT EXISTS idx_tasks_template_id ON tasks(template_id)"),e.exec("CREATE INDEX IF NOT EXISTS idx_tasks_role_id ON tasks(role_id)"),e.exec(`
494
+ CREATE TABLE IF NOT EXISTS chat_sessions_new (
495
+ id TEXT PRIMARY KEY,
496
+ status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active', 'archived')),
497
+ source_type TEXT NOT NULL,
498
+ source_channel_id TEXT,
499
+ source_chat_id TEXT,
500
+ title TEXT,
501
+ created_at INTEGER NOT NULL,
502
+ last_active_at INTEGER NOT NULL,
503
+ archived_at INTEGER,
504
+ message_count INTEGER DEFAULT 0
505
+ );
506
+ `),e.exec("INSERT INTO chat_sessions_new SELECT id,status,source_type,source_channel_id,source_chat_id,title,created_at,last_active_at,archived_at,message_count FROM chat_sessions"),e.exec("DROP TABLE chat_sessions"),e.exec("ALTER TABLE chat_sessions_new RENAME TO chat_sessions"),e.exec("CREATE INDEX IF NOT EXISTS idx_sessions_status ON chat_sessions(status)"),e.exec("CREATE INDEX IF NOT EXISTS idx_sessions_last_active ON chat_sessions(last_active_at)"),e.exec("CREATE INDEX IF NOT EXISTS idx_sessions_source ON chat_sessions(source_type, source_channel_id, source_chat_id)"),e.exec(`
507
+ CREATE TABLE IF NOT EXISTS task_plans_new (
508
+ id TEXT PRIMARY KEY,
509
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
510
+ plan_json TEXT NOT NULL,
511
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'approved', 'denied', 'completed')),
512
+ approval_type TEXT CHECK(approval_type IN ('once', 'permanent')),
513
+ deviation_report_json TEXT,
514
+ learned_rules_json TEXT,
515
+ created_at INTEGER NOT NULL,
516
+ approved_at INTEGER,
517
+ reviewed_at INTEGER
518
+ );
519
+ `),e.exec("INSERT INTO task_plans_new SELECT id,task_id,plan_json,status,approval_type,deviation_report_json,learned_rules_json,created_at,approved_at,reviewed_at FROM task_plans"),e.exec("DROP TABLE task_plans"),e.exec("ALTER TABLE task_plans_new RENAME TO task_plans"),e.exec("CREATE INDEX IF NOT EXISTS idx_task_plans_task_id ON task_plans(task_id)"),e.exec("CREATE INDEX IF NOT EXISTS idx_task_plans_status ON task_plans(status)"),e.prepare("PRAGMA table_info(task_plugins)").all().some(t=>t.name==="skill_id")&&(e.exec(`
520
+ CREATE TABLE IF NOT EXISTS task_plugins_new (
521
+ id TEXT PRIMARY KEY,
522
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
523
+ plugin_path TEXT NOT NULL,
524
+ plugin_name TEXT NOT NULL,
525
+ role_id TEXT,
526
+ used_at INTEGER NOT NULL
527
+ );
528
+ `),e.exec("INSERT INTO task_plugins_new SELECT id,task_id,plugin_path,plugin_name,skill_id,used_at FROM task_plugins"),e.exec("DROP TABLE task_plugins"),e.exec("ALTER TABLE task_plugins_new RENAME TO task_plugins")),e.exec("CREATE INDEX IF NOT EXISTS idx_task_plugins_task_id ON task_plugins(task_id)"),e.exec("CREATE INDEX IF NOT EXISTS idx_task_plugins_plugin_path ON task_plugins(plugin_path)"),e.exec("CREATE INDEX IF NOT EXISTS idx_task_plugins_role_id ON task_plugins(role_id)"),e.prepare("PRAGMA table_info(approval_rules)").all().some(t=>t.name==="skill_id")&&(e.exec(`
529
+ CREATE TABLE IF NOT EXISTS approval_rules_new (
530
+ id TEXT PRIMARY KEY,
531
+ role_id TEXT,
532
+ task_pattern TEXT NOT NULL,
533
+ max_risk_level TEXT NOT NULL CHECK(max_risk_level IN ('low', 'medium', 'high')),
534
+ created_at INTEGER NOT NULL,
535
+ created_by_task_id TEXT REFERENCES tasks(id)
536
+ );
537
+ `),e.exec("INSERT INTO approval_rules_new SELECT id,skill_id,task_pattern,max_risk_level,created_at,created_by_task_id FROM approval_rules"),e.exec("DROP TABLE approval_rules"),e.exec("ALTER TABLE approval_rules_new RENAME TO approval_rules")),e.exec("CREATE INDEX IF NOT EXISTS idx_approval_rules_role_id ON approval_rules(role_id)"),e.prepare("PRAGMA table_info(manager_decisions)").all().some(t=>t.name==="skill_id")&&(e.exec(`
538
+ CREATE TABLE IF NOT EXISTS manager_decisions_new (
539
+ id TEXT PRIMARY KEY,
540
+ task_id TEXT NOT NULL REFERENCES tasks(id),
541
+ role_id TEXT,
542
+ decision_type TEXT NOT NULL,
543
+ boundary_json TEXT,
544
+ reason TEXT,
545
+ created_at INTEGER NOT NULL
546
+ );
547
+ `),e.exec("INSERT INTO manager_decisions_new SELECT id,task_id,skill_id,decision_type,boundary_json,reason,created_at FROM manager_decisions"),e.exec("DROP TABLE manager_decisions"),e.exec("ALTER TABLE manager_decisions_new RENAME TO manager_decisions")),e.exec("CREATE INDEX IF NOT EXISTS idx_manager_decisions_task_id ON manager_decisions(task_id)"),e.exec("CREATE INDEX IF NOT EXISTS idx_manager_decisions_role_id ON manager_decisions(role_id)"),e.prepare("PRAGMA table_info(channels)").all().some(t=>t.name==="linked_skill_id")&&(e.exec(`
548
+ CREATE TABLE IF NOT EXISTS channels_new (
549
+ id TEXT PRIMARY KEY,
550
+ name TEXT NOT NULL,
551
+ platform TEXT NOT NULL,
552
+ enabled INTEGER DEFAULT 1,
553
+ status TEXT NOT NULL DEFAULT 'disconnected',
554
+ config TEXT NOT NULL,
555
+ linked_role_id TEXT,
556
+ allowed_chat_ids TEXT,
557
+ created_at INTEGER NOT NULL,
558
+ updated_at INTEGER,
559
+ last_message_at INTEGER,
560
+ message_count INTEGER DEFAULT 0
561
+ );
562
+ `),e.exec("INSERT INTO channels_new SELECT id,name,platform,enabled,status,config,linked_skill_id,allowed_chat_ids,created_at,updated_at,last_message_at,message_count FROM channels"),e.exec("DROP TABLE channels"),e.exec("ALTER TABLE channels_new RENAME TO channels")),e.exec("CREATE INDEX IF NOT EXISTS idx_channels_platform ON channels(platform)"),e.exec("CREATE INDEX IF NOT EXISTS idx_channels_enabled ON channels(enabled)"),e.exec("CREATE INDEX IF NOT EXISTS idx_channels_linked_role_id ON channels(linked_role_id)"),e.exec(`
563
+ CREATE TABLE IF NOT EXISTS role_plugins (
564
+ role_id TEXT NOT NULL,
565
+ plugin_id TEXT NOT NULL,
566
+ bound_at INTEGER NOT NULL,
567
+ PRIMARY KEY (role_id, plugin_id)
568
+ );
569
+ `),e.exec("UPDATE server_state SET schema_version = 10 WHERE id = 1"),e.exec("PRAGMA foreign_keys = ON")}if(o<11){try{e.exec("ALTER TABLE task_templates RENAME COLUMN skill_preference TO role_preference")}catch(T){let E=e.prepare("PRAGMA table_info(task_templates)").all(),s=E.some(r=>r.name==="role_preference"),i=E.some(r=>r.name==="skill_preference");if(!s&&i)throw T}e.exec("UPDATE server_state SET schema_version = 11 WHERE id = 1")}if(o<12&&(e.prepare("PRAGMA table_info(server_state)").all().some(E=>E.name==="tools_fingerprint")||e.exec("ALTER TABLE server_state ADD COLUMN tools_fingerprint TEXT"),e.exec("UPDATE server_state SET schema_version = 12 WHERE id = 1")),o<13&&(e.prepare("PRAGMA table_info(roles)").all().some(E=>E.name==="additional_directories")||e.exec("ALTER TABLE roles ADD COLUMN additional_directories TEXT"),e.exec("UPDATE server_state SET schema_version = 13 WHERE id = 1")),o<14){let T=e.prepare("PRAGMA table_info(roles)").all();T.some(i=>i.name==="allowed_channels")||e.exec("ALTER TABLE roles ADD COLUMN allowed_channels TEXT"),T.some(i=>i.name==="mcp_servers")||e.exec("ALTER TABLE roles ADD COLUMN mcp_servers TEXT");let E=e.prepare("PRAGMA table_info(tasks)").all();E.some(i=>i.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),E.some(i=>i.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT"),e.prepare("PRAGMA table_info(goals)").all().some(i=>i.name==="deliver_to")||e.exec("ALTER TABLE goals ADD COLUMN deliver_to TEXT"),e.exec("UPDATE server_state SET schema_version = 14 WHERE id = 1")}if(o<15&&(e.prepare("PRAGMA table_info(roles)").all().some(E=>E.name==="inherit_user_settings")||e.exec("ALTER TABLE roles ADD COLUMN inherit_user_settings INTEGER DEFAULT 0"),e.exec("UPDATE server_state SET schema_version = 15 WHERE id = 1")),o<16&&(e.prepare("PRAGMA table_info(task_templates)").all().some(E=>E.name==="deliver_to")||e.exec("ALTER TABLE task_templates ADD COLUMN deliver_to TEXT"),e.exec("UPDATE server_state SET schema_version = 16 WHERE id = 1")),o<17){e.exec("PRAGMA foreign_keys = OFF"),e.exec("DROP TABLE IF EXISTS plugins"),e.exec("DROP TABLE IF EXISTS role_plugins"),e.exec("DROP TABLE IF EXISTS marketplaces"),e.exec("DROP INDEX IF EXISTS idx_plugins_source"),e.exec("DROP INDEX IF EXISTS idx_plugins_enabled");try{let s=e.prepare("SELECT id, additional_directories FROM roles WHERE additional_directories IS NOT NULL").all();for(let i of s)try{let r=JSON.parse(i.additional_directories);if(r.length>0&&typeof r[0]=="object"&&r[0]!==null&&"path"in r[0])continue;let l=r.map(n=>typeof n=="string"?{path:n}:n);e.prepare("UPDATE roles SET additional_directories = ? WHERE id = ?").run(JSON.stringify(l),i.id)}catch{}}catch{}let T=e.prepare("PRAGMA table_info(tasks)").all();T.some(s=>s.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),T.some(s=>s.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT");let E=e.prepare("PRAGMA table_info(strategies)").all();E.some(s=>s.name==="role")&&!E.some(s=>s.name==="role_id")&&(e.exec("ALTER TABLE strategies RENAME COLUMN role TO role_id"),e.exec("DROP INDEX IF EXISTS idx_strategies_role_task_type"),e.exec("DROP INDEX IF EXISTS idx_strategies_role"),e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_strategies_role_task_type ON strategies(role_id, task_type, name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_strategies_role ON strategies(role_id)")),e.exec("UPDATE server_state SET schema_version = 17 WHERE id = 1"),e.exec("PRAGMA foreign_keys = ON")}if(o<18){let T=e.prepare("PRAGMA table_info(tasks)").all();T.some(s=>s.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),T.some(s=>s.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT");let E=e.prepare("PRAGMA table_info(strategies)").all();E.some(s=>s.name==="role")&&!E.some(s=>s.name==="role_id")&&(e.exec("ALTER TABLE strategies RENAME COLUMN role TO role_id"),e.exec("DROP INDEX IF EXISTS idx_strategies_role_task_type"),e.exec("DROP INDEX IF EXISTS idx_strategies_role"),e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_strategies_role_task_type ON strategies(role_id, task_type, name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_strategies_role ON strategies(role_id)")),e.exec("UPDATE server_state SET schema_version = 18 WHERE id = 1")}}function h(){if(_)return _;let e=process.env.ADAM_DB_PATH||a,N=R(e);return I(N)||A(N,{recursive:!0}),_=new d(e),_.pragma("journal_mode = WAL"),_.pragma("foreign_keys = ON"),X(_),_}function y(){_&&(_.close(),_=null)}var _,O=c(()=>{L();_=null});export{X as a,h as b,y as c,O as d};
@@ -0,0 +1 @@
1
+ import{EventEmitter as n}from"events";var a=class{emitter=new n;on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.removeListener(t,e)}emit(t){this.emitter.emit(t.type,t)}},d=new a;export{d as a};
@@ -0,0 +1 @@
1
+ import{c as e,f as t}from"./chunk-F2IS5LWD.js";t();var s={defaults:{timeout:600,maxTurns:100,maxBudgetUsd:5,effort:"high",model:"",settingSources:["user","project"],allowedTools:[],disallowedTools:[],fileAccess:{allowedPaths:["./","~/.claude"],deniedPaths:["~/.ssh","~/.aws","~/.config"]},approvalRequired:["rm -rf","git push","git reset","curl.*POST"],approvalTimeout:300,env:{},plugins:[],workspacePath:e,workspaceRetention:"immediate"},externalApis:[],server:{port:7100,host:"0.0.0.0",timezone:"system"},logging:{level:"info"},roles:{presets:[],evolution:{triggerEvery:5,reflectionThreshold:150,retirementThreshold:.4,probationTasks:5}},chat:{sessionTimeoutMinutes:30,maxSessionTurns:20,autoTitle:!0,archiveExtractMemory:!0},watchdog:{enabled:!0,intervalMinutes:5,rules:{managerHealthCheck:{enabled:!0,action:"notify",staleDurationMinutes:15},staleTasks:{enabled:!0,action:"notify",maxPendingMinutes:30},staleRunningTasks:{enabled:!0,action:"notify",maxRunningMinutes:15},dbMaintenance:{enabled:!0,action:"ignore",walCheckpointThresholdMB:100}}},execution:{maxConcurrent:5,maxBudgetPerTaskUsd:5,pollIntervalMs:3e4}};export{s as a};
package/dist/cli.js ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import{a as G,b as p,c as q,e as W}from"./chunk-3HM54J2N.js";import{a as _,b as H,c as M,d as J}from"./chunk-VURJZLM6.js";import"./chunk-TGQYM4TH.js";import{a as U}from"./chunk-CV3ROBUM.js";import"./chunk-ZN5Q3YET.js";import"./chunk-5BAD3NCT.js";import"./chunk-W6JITSZF.js";import{e as j,f as ao}from"./chunk-F2IS5LWD.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";import{Command as bo}from"commander";import{fork as lo}from"child_process";import{readFileSync as E,writeFileSync as co,existsSync as w,unlinkSync as T,mkdirSync as mo,openSync as uo}from"fs";import{join as x}from"path";import{homedir as po}from"os";var D=x(po(),".adam"),v=x(D,"adam.pid"),S=x(D,"adam.port"),b=x(D,"server.log");function go(){w(D)||mo(D,{recursive:!0})}function C(){if(!w(v))return null;let o=parseInt(E(v,"utf-8").trim(),10);return isNaN(o)?null:o}function fo(){if(!w(S))return null;let o=parseInt(E(S,"utf-8").trim(),10);return isNaN(o)?null:o}function O(o){try{return process.kill(o,0),!0}catch{return!1}}async function L(){go();let o=C();if(o&&O(o))throw new Error(`Server already running (PID ${o})`);w(v)&&T(v),w(S)&&T(S);let e=uo(b,"a"),n=x(_,"dist/index.js"),t=lo(n,[],{detached:!0,stdio:["ignore",e,e,"ipc"]}),i=await new Promise((s,l)=>{let k=setTimeout(()=>{t.kill(),l(new Error(`Server start timeout. Check logs: ${b}`))},1e4);t.on("message",u=>{if(u&&typeof u=="object"&&u.type==="ready"){clearTimeout(k);let a=u.port;a?s(a):l(new Error("Ready signal received but missing port"))}}),t.on("exit",u=>{clearTimeout(k);let a=w(b)?E(b,"utf-8").split(`
3
+ `).slice(-10).join(`
4
+ `):"";l(new Error(`Server exited with code ${u}.
5
+ ${a?`Last log lines:
6
+ ${a}`:`Check logs: ${b}`}`))}),t.on("error",u=>{clearTimeout(k),l(u)})});return co(v,String(t.pid)),t.disconnect(),t.unref(),{pid:t.pid,port:i}}async function N(){let o=C();if(!o)throw new Error("No PID file found \u2014 server not running?");if(!O(o))throw w(v)&&T(v),w(S)&&T(S),new Error("Server not running (stale PID file)");process.kill(o,"SIGTERM"),await new Promise(e=>{let n=0,t=setInterval(()=>{O(o)?(n++,n>=10&&(clearInterval(t),process.kill(o,"SIGKILL"),e())):(clearInterval(t),e())},500)}),w(v)&&T(v),w(S)&&T(S)}function I(){let o=C(),e=o?O(o):!1,n=fo();return{running:e,pid:o,port:n}}function z(){return b}import{readFileSync as To,existsSync as Io,createReadStream as Po}from"fs";import Do from"react";import{render as xo}from"ink";import c from"chalk";import*as K from"readline";async function B(o,e){try{let n={};e.model&&(n.model=e.model),e.timeout&&(n.timeout=e.timeout),e.budget&&(n.maxBudgetUsd=e.budget),e.workspace&&(n.workspacePath=e.workspace);let{taskId:t}=await p("/tasks",{method:"POST",body:{prompt:o,config:Object.keys(n).length>0?n:void 0}});e.json?console.log(JSON.stringify({taskId:t,status:"submitted"})):console.log(c.dim(`Task ${t} submitted`));let i=()=>{p(`/tasks/${t}/cancel`,{method:"POST"}).catch(()=>{}),e.json||console.log(c.yellow(`
7
+ Task cancelled.`)),process.exit(130)};process.on("SIGINT",i);let s=new W(t);await s.connect();let l=[];await new Promise(u=>{s.on("reasoning",a=>{let r=a;e.json?l.push({type:"reasoning",...r}):process.stdout.write(c.gray(r.content??""))}),s.on("tool_call",a=>{let r=a;e.json?l.push({type:"tool_call",...r}):console.log(c.blue(`
8
+ [tool] ${r.toolName??"unknown"}`))}),s.on("tool_result",a=>{let r=a;if(e.json)l.push({type:"tool_result",...r});else{let g=r.content??"",f=g.split(`
9
+ `);f.length>5?console.log(c.green(`[result] (${f.length} lines) \u25B8 truncated`)):console.log(c.green(`[result] ${g}`))}}),s.on("error",a=>{let r=a;e.json?l.push({type:"error",...r}):console.error(c.red(`
10
+ [error] ${r.error??"unknown error"}`))}),s.on("approval_needed",a=>{let r=a;if(e.approval===!1){p(`/tasks/${t}/approve`,{method:"POST",body:{approvalId:r.approvalId,reason:"auto-approved via --no-approval"}}).catch(()=>{});return}if(e.json){l.push({type:"approval_needed",...r}),p(`/tasks/${t}/approve`,{method:"POST",body:{approvalId:r.approvalId}}).catch(()=>{});return}console.log(c.yellow(`
11
+ \u26A0 Approval needed: ${r.toolName}`)),console.log(c.yellow(` Pattern: ${r.matchedPattern}`)),console.log(c.yellow(` Input: ${JSON.stringify(r.toolInput)}`));let g=K.createInterface({input:process.stdin,output:process.stdout});g.question(c.yellow(" [a]pprove / [r]eject: "),f=>{g.close();let A=f.toLowerCase().startsWith("a")?"approve":"reject";p(`/tasks/${t}/${A}`,{method:"POST",body:{approvalId:r.approvalId}}).catch(()=>{})})}),s.on("complete",a=>{let r=a;e.json?console.log(JSON.stringify({taskId:t,status:"completed",events:l,result:r})):(console.log(c.dim(`
12
+ \u2500\u2500\u2500 Task complete \u2500\u2500\u2500`)),r.costUsd!==void 0&&console.log(c.dim(`Cost: $${r.costUsd.toFixed(4)}`)),r.numTurns!==void 0&&console.log(c.dim(`Turns: ${r.numTurns}`))),s.close(),u()}),s.on("*",a=>{a.type})});let k=await p(`/tasks/${t}`);(k.task.status==="failed"||k.task.status==="cancelled")&&process.exit(1),process.exit(0)}catch(n){e.json?console.log(JSON.stringify({error:n.message})):console.error(c.red(n.message)),process.exit(1)}}import m from"chalk";var wo={pending:m.gray,queued:m.gray,running:m.yellow,paused:m.yellow,completed:m.green,failed:m.red,cancelled:m.gray};function Z(o){return(wo[o]??m.white)(o)}function V(o,e){return o.length<=e?o:o.slice(0,e-3)+"..."}function Q(o){if(o<1e3)return`${o}ms`;let e=Math.floor(o/1e3);if(e<60)return`${e}s`;let n=Math.floor(e/60),t=e%60;return`${n}m ${t}s`}async function X(o){try{let e=new URLSearchParams;o.status&&e.set("status",o.status),o.limit&&e.set("limit",o.limit);let n=e.toString(),{tasks:t}=await p(`/tasks${n?`?${n}`:""}`);if(t.length===0){console.log(m.dim("No tasks found"));return}console.log(m.bold($("ID",10)+$("STATUS",12)+$("PROMPT",40)+$("DURATION",10)+"COST"));for(let i of t){let s=i.totalDurationMs?Q(i.totalDurationMs):"\u2014",l=i.costUsd!==void 0?`$${i.costUsd.toFixed(4)}`:"\u2014";console.log($(i.id.slice(0,8),10)+$(Z(i.status),22)+$(V(i.prompt,38),40)+$(s,10)+l)}}catch(e){console.error(m.red(e.message)),process.exit(1)}}async function Y(o){try{let{task:e}=await p(`/tasks/${o}`);console.log(m.bold("Task Details")),console.log(` ID: ${e.id}`),console.log(` Status: ${Z(e.status)}`),console.log(` Prompt: ${e.prompt}`),console.log(` Created: ${new Date(e.createdAt).toLocaleString()}`),e.startedAt&&console.log(` Started: ${new Date(e.startedAt).toLocaleString()}`),e.completedAt&&console.log(` Finished: ${new Date(e.completedAt).toLocaleString()}`),e.totalDurationMs&&console.log(` Duration: ${Q(e.totalDurationMs)}`),e.costUsd!==void 0&&console.log(` Cost: $${e.costUsd.toFixed(4)}`),e.result&&console.log(` Result: ${V(e.result,200)}`),e.error&&console.log(` Error: ${m.red(e.error)}`)}catch(e){console.error(m.red(e.message)),process.exit(1)}}async function oo(o){try{await p(`/tasks/${o}/cancel`,{method:"POST"}),console.log(`Task ${o} cancelled`)}catch(e){console.error(m.red(e.message)),process.exit(1)}}function $(o,e){return o.length>=e?o:o+" ".repeat(e-o.length)}ao();import P from"chalk";import{readFileSync as yo,existsSync as ko}from"fs";import{parse as vo}from"yaml";async function eo(o){try{M(),J();let e=j;ko(e)||(console.error(P.red(`Config file not found: ${e}`)),process.exit(1));let n=yo(e,"utf-8"),t=vo(n);o.json?console.log(JSON.stringify(t,null,2)):(console.log(P.bold(`Adam Configuration
13
+ `)),to(t,0))}catch(e){console.error(P.red(e.message)),process.exit(1)}}function to(o,e){let n=" ".repeat(e);for(let[t,i]of Object.entries(o))if(i&&typeof i=="object"&&!Array.isArray(i))console.log(`${n}${P.cyan(t)}:`),to(i,e+1);else if(Array.isArray(i)){console.log(`${n}${P.cyan(t)}:`);for(let s of i)console.log(`${n} - ${String(s)}`)}else{let s=t.toLowerCase().includes("key")||t.toLowerCase().includes("token")?ho(String(i)):String(i);console.log(`${n}${P.cyan(t)}: ${s}`)}}function ho(o){return!o||o.length<8?"****":o.slice(0,4)+"****"}import h from"chalk";async function ro(o){try{let e=o.limit??"20",n=await p(`/evolution-audit?limit=${e}`);if(n.length===0){console.log(h.dim("No evolution records yet"));return}console.log(h.bold(`Evolution Audit Log (${n.length} records)
14
+ `));for(let t of n){let i=new Date(t.timestamp).toLocaleString();console.log(h.bold(`[${i}]`)+(t.triggerTaskId?h.dim(` task: ${t.triggerTaskId.slice(0,8)}`):"")),console.log(h.dim(" Diff:"));for(let s of t.diff.split(`
15
+ `))s.startsWith("+")?console.log(h.green(` ${s}`)):s.startsWith("-")?console.log(h.red(` ${s}`)):console.log(h.dim(` ${s}`));console.log()}}catch(e){console.error(h.red(e.message)),process.exit(1)}}import d from"chalk";import{WebSocket as $o}from"ws";function So(){try{let o=U().server?.timezone;return o==="system"||!o?void 0:o}catch{return}}function no(o){let e=So();return new Date(o).toLocaleTimeString(void 0,e?{timeZone:e}:void 0)}async function so(o){let e=I(),n=o.port?Number(o.port):e.port??7100,t=G(),i=new URL(`ws://localhost:${n}/events`);t&&i.searchParams.set("api_key",t);let s=i.toString(),l=o.component,k=o.level;function u(){let r=new $o(s);r.on("open",()=>{console.log(d.dim(`Connected to ${s}`)),o.follow&&console.log(d.dim("Following logs... (Ctrl+C to exit)"))}),r.on("message",g=>{try{let f=JSON.parse(g.toString());if(f.type==="log_event"&&f.msg){if(l&&f.component!==l||k&&f.level!==k)return;a(f)}}catch{}}),r.on("error",g=>{console.error(d.red(`WebSocket error: ${g.message}`))}),r.on("close",()=>{o.follow&&(console.log(d.yellow("Connection closed, reconnecting...")),setTimeout(u,1e3))})}function a(r){let g=no(r.timestamp),A={debug:d.gray,info:d.blue,warn:d.yellow,error:d.red,fatal:d.bgRed.white}[r.level]||d.white,io=d.cyan(`[${r.component}]`);console.log(`${d.dim(g)} ${A(r.level.toUpperCase().padEnd(5))} ${io} ${r.msg}`),r.metadata&&typeof r.metadata=="object"&&Object.keys(r.metadata).length>0&&console.log(d.dim(" ")+d.dim(JSON.stringify(r.metadata)))}u(),await new Promise(r=>{process.on("SIGINT",()=>r()),process.on("SIGTERM",()=>r()),o.follow||setTimeout(r,3e3)})}var y=new bo;y.name("adam").description("Adam Agent Server CLI").version("0.2.0");var R=y.command("server").description("Server management");R.command("start").description("Start the server daemon").action(async()=>{try{let{pid:o,port:e}=await L();console.log(`Server started (PID ${o}, port ${e})`)}catch(o){console.error("Failed to start server:",o.message),process.exit(1)}});R.command("stop").description("Stop the server daemon").action(async()=>{try{await N(),console.log("Server stopped")}catch(o){console.error("Failed to stop server:",o.message),process.exit(1)}});R.command("restart").description("Restart the server daemon").action(async()=>{try{I().running&&(await N(),console.log("Server stopped"));let{pid:e,port:n}=await L();console.log(`Server restarted (PID ${e}, port ${n})`)}catch(o){console.error("Failed to restart server:",o.message),process.exit(1)}});R.command("status").description("Show server status").action(()=>{let o=I();o.running?console.log(`Server is running (PID ${o.pid}, port ${o.port})`):o.pid?console.log("Server not running (stale PID file)"):console.log("Server not running")});R.command("logs").description("Show server logs").option("-f, --follow","Follow log output").action(async o=>{let e=z();if(!Io(e)){console.log("No log file found");return}if(o.follow){let n=Po(e,{encoding:"utf-8"});for await(let t of n)process.stdout.write(t)}else console.log(To(e,"utf-8"))});y.command("run <prompt>").description("Submit a task and stream output").option("--model <model>","Model to use").option("--timeout <seconds>","Task timeout",parseInt).option("--budget <usd>","Max budget in USD",parseFloat).option("--template <name>","Task template to use").option("--workspace <path>","Workspace directory").option("--no-approval","Auto-approve all approval requests").option("--json","Output as JSON").option("--server <url>","Server URL").action(B);var F=y.command("tasks").description("Task management");F.command("list").description("List recent tasks").option("-s, --status <status>","Filter by status").option("-l, --limit <number>","Limit results","20").action(X);F.command("show <id>").description("Show task details").action(Y);F.command("cancel <id>").description("Cancel a running task").action(oo);y.command("config").description("Display current configuration").option("--json","Output as JSON").action(eo);y.command("evolution").description("Show self-evolution audit log").option("-l, --limit <number>","Limit results","20").action(ro);y.command("logs").description("Stream server logs in real-time via WebSocket").option("-f, --follow","Follow logs continuously").option("-c, --component <component>","Filter by component (manager, worker, scheduler, api, ws)").option("-l, --level <level>","Filter by level (debug, info, warn, error)").option("-p, --port <port>","Server port").action(so);y.command("register-ai-digest").description("Register the AI Hourly Digest task template (cron: every hour)").action(()=>{try{H(),console.log("AI Digest template registered successfully")}catch(o){console.error("Failed to register AI Digest template:",o.message),process.exit(1)}});y.action(async()=>{try{await q()}catch{I().running?console.error("Server is running but not responding. Check: adam server logs"):console.error("Server not running. Run: adam server start"),process.exit(1)}let o=(await import("./App-23CRAK2P.js")).default,{waitUntilExit:e}=xo(Do.createElement(o));await e()});y.parse();
@@ -0,0 +1 @@
1
+ import{a as b,b as c,c as d}from"./chunk-CV3ROBUM.js";import{a}from"./chunk-ZN5Q3YET.js";import"./chunk-5BAD3NCT.js";import"./chunk-F2IS5LWD.js";import"./chunk-FCV2DPZQ.js";export{a as DEFAULT_CONFIG,d as getChatConfig,c as getDefaults,b as loadConfig};
@@ -0,0 +1 @@
1
+ import{a,b,c,d}from"./chunk-W6JITSZF.js";import"./chunk-F2IS5LWD.js";import"./chunk-FCV2DPZQ.js";d();export{c as closeDb,b as getDb,a as runMigrations};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f,g,h}from"./chunk-Q3N5LVPZ.js";import"./chunk-W6JITSZF.js";import"./chunk-F2IS5LWD.js";import"./chunk-FCV2DPZQ.js";export{a as TTL_MS,g as cleanupExpired,b as createDeliveryLog,h as getDeliveryLogByRule,f as getFailedDeliveries,e as getPendingDeliveries,d as markDelivered,c as updateDeliveryLogStatus};