@farazirfan/costar-server-executor 1.7.13 → 1.7.15

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 (70) hide show
  1. package/dist/agent/agent.d.ts +3 -22
  2. package/dist/agent/agent.d.ts.map +1 -1
  3. package/dist/agent/agent.js +11 -116
  4. package/dist/agent/agent.js.map +1 -1
  5. package/dist/agent/pi-embedded-runner/system-prompt.d.ts.map +1 -1
  6. package/dist/agent/pi-embedded-runner/system-prompt.js +32 -0
  7. package/dist/agent/pi-embedded-runner/system-prompt.js.map +1 -1
  8. package/dist/agent/pi-embedded-runner/tools.d.ts +2 -9
  9. package/dist/agent/pi-embedded-runner/tools.d.ts.map +1 -1
  10. package/dist/agent/pi-embedded-runner/tools.js +2 -65
  11. package/dist/agent/pi-embedded-runner/tools.js.map +1 -1
  12. package/dist/config/types.d.ts +0 -2
  13. package/dist/config/types.d.ts.map +1 -1
  14. package/dist/heartbeat/runner.d.ts +15 -11
  15. package/dist/heartbeat/runner.d.ts.map +1 -1
  16. package/dist/heartbeat/runner.js +128 -73
  17. package/dist/heartbeat/runner.js.map +1 -1
  18. package/dist/memory/curation-state.d.ts +2 -16
  19. package/dist/memory/curation-state.d.ts.map +1 -1
  20. package/dist/memory/curation-state.js +0 -18
  21. package/dist/memory/curation-state.js.map +1 -1
  22. package/dist/memory/curator.d.ts +9 -13
  23. package/dist/memory/curator.d.ts.map +1 -1
  24. package/dist/memory/curator.js +32 -79
  25. package/dist/memory/curator.js.map +1 -1
  26. package/dist/memory/index.d.ts +2 -3
  27. package/dist/memory/index.d.ts.map +1 -1
  28. package/dist/memory/index.js +2 -4
  29. package/dist/memory/index.js.map +1 -1
  30. package/dist/supabase/activity.d.ts +103 -0
  31. package/dist/supabase/activity.d.ts.map +1 -0
  32. package/dist/supabase/activity.js +313 -0
  33. package/dist/supabase/activity.js.map +1 -0
  34. package/dist/supabase/index.d.ts +2 -3
  35. package/dist/supabase/index.d.ts.map +1 -1
  36. package/dist/supabase/index.js +3 -2
  37. package/dist/supabase/index.js.map +1 -1
  38. package/dist/supabase/types.d.ts +6 -2
  39. package/dist/supabase/types.d.ts.map +1 -1
  40. package/dist/supabase/workspace-storage.d.ts +0 -24
  41. package/dist/supabase/workspace-storage.d.ts.map +1 -1
  42. package/dist/supabase/workspace-storage.js +4 -86
  43. package/dist/supabase/workspace-storage.js.map +1 -1
  44. package/dist/tools/complete-turn.d.ts +26 -0
  45. package/dist/tools/complete-turn.d.ts.map +1 -0
  46. package/dist/tools/complete-turn.js +60 -0
  47. package/dist/tools/complete-turn.js.map +1 -0
  48. package/dist/tools/index.d.ts +4 -3
  49. package/dist/tools/index.d.ts.map +1 -1
  50. package/dist/tools/index.js +8 -4
  51. package/dist/tools/index.js.map +1 -1
  52. package/dist/tools/memory.d.ts +2 -2
  53. package/dist/tools/memory.js +10 -10
  54. package/dist/tools/memory.js.map +1 -1
  55. package/dist/web-server.d.ts.map +1 -1
  56. package/dist/web-server.js +1 -4
  57. package/dist/web-server.js.map +1 -1
  58. package/dist/workspace/index.d.ts +2 -2
  59. package/dist/workspace/index.d.ts.map +1 -1
  60. package/dist/workspace/index.js +2 -2
  61. package/dist/workspace/index.js.map +1 -1
  62. package/dist/workspace/templates.d.ts +3 -2
  63. package/dist/workspace/templates.d.ts.map +1 -1
  64. package/dist/workspace/templates.js +27 -14
  65. package/dist/workspace/templates.js.map +1 -1
  66. package/dist/workspace/workspace.d.ts +2 -1
  67. package/dist/workspace/workspace.d.ts.map +1 -1
  68. package/dist/workspace/workspace.js +5 -1
  69. package/dist/workspace/workspace.js.map +1 -1
  70. package/package.json +1 -1
@@ -2,33 +2,30 @@
2
2
  * CoStar Server Executor - Memory Curator
3
3
  *
4
4
  * Incremental, cursor-based memory curation.
5
- * Fetches only new/unprocessed data (client conversations + daily logs),
5
+ * Fetches only new/unprocessed client conversations from agent_activity,
6
6
  * builds a compact digest, and produces a curation prompt to append to heartbeats.
7
7
  *
8
- * The LLM then processes the digest and updates MEMORY.md, USER.md,
9
- * and the daily log in a single heartbeat turn.
8
+ * The LLM then processes the digest and updates MEMORY.md and USER.md
9
+ * in a single heartbeat turn.
10
10
  */
11
- import { getNewUserRequestsSince } from "../supabase/requests.js";
12
- import { readDailyLogSince, todayDateString } from "./daily-log.js";
11
+ import { getNewClientActivitySince } from "../supabase/activity.js";
13
12
  /**
14
13
  * Fetch unprocessed data since the last curation cursors.
15
14
  *
16
- * 1. Queries user_requests after lastProcessedRequestAt (new client conversations)
17
- * 2. Reads today's daily log from lastProcessedLogSize offset (new LLM-written entries)
18
- * Also checks yesterday if lastProcessedLogDate != today (handles midnight rollover)
19
- * 3. Returns only the delta — if both empty, hasNewData = false
15
+ * Queries agent_activity after lastProcessedRequestAt (new client conversations).
16
+ * Returns only the delta if empty, hasNewData = false.
20
17
  *
21
18
  * @param userId - User ID for querying conversations
22
- * @param workspaceDir - Workspace root for reading daily logs
19
+ * @param _workspaceDir - Workspace root (unused, kept for API compatibility)
23
20
  * @param state - Current curation state (cursors)
24
21
  * @param maxConversations - Max conversations to fetch per curation cycle
25
22
  * @returns The delta of new data
26
23
  */
27
- export async function fetchUnprocessedData(userId, workspaceDir, state, maxConversations = 20) {
28
- // 1. Fetch new client conversations from user_requests
24
+ export async function fetchUnprocessedData(userId, _workspaceDir, state, maxConversations = 20) {
25
+ // Fetch new client conversations from agent_activity
29
26
  const newConversations = [];
30
27
  try {
31
- const rows = await getNewUserRequestsSince(userId, state.lastProcessedRequestAt, maxConversations);
28
+ const rows = await getNewClientActivitySince(userId, state.lastProcessedRequestAt, maxConversations);
32
29
  for (const row of rows) {
33
30
  newConversations.push({
34
31
  id: row.id,
@@ -39,41 +36,11 @@ export async function fetchUnprocessedData(userId, workspaceDir, state, maxConve
39
36
  }
40
37
  }
41
38
  catch (err) {
42
- console.warn("[MEMORY] Failed to fetch new user requests:", err);
39
+ console.warn("[MEMORY] Failed to fetch new client activity:", err);
43
40
  }
44
- // 2. Read new daily log content
45
- let newLogContent = "";
46
- const today = todayDateString();
47
- try {
48
- // If the last processed log was from a previous day, read yesterday's remaining content
49
- if (state.lastProcessedLogDate && state.lastProcessedLogDate !== today) {
50
- const yesterdayResult = readDailyLogSince(workspaceDir, state.lastProcessedLogDate, state.lastProcessedLogSize);
51
- if (yesterdayResult.content) {
52
- newLogContent += yesterdayResult.content;
53
- }
54
- // For today's log, start from 0 since we haven't read it yet
55
- const todayResult = readDailyLogSince(workspaceDir, today, 0);
56
- if (todayResult.content) {
57
- newLogContent += (newLogContent ? "\n\n" : "") + todayResult.content;
58
- }
59
- }
60
- else {
61
- // Same day or first run — read from last offset
62
- const offset = state.lastProcessedLogDate === today ? state.lastProcessedLogSize : 0;
63
- const result = readDailyLogSince(workspaceDir, today, offset);
64
- if (result.content) {
65
- newLogContent = result.content;
66
- }
67
- }
68
- }
69
- catch (err) {
70
- console.warn("[MEMORY] Failed to read daily log:", err);
71
- }
72
- const hasNewData = newConversations.length > 0 || newLogContent.length > 0;
73
41
  return {
74
42
  newConversations,
75
- newLogContent: newLogContent.trim(),
76
- hasNewData,
43
+ hasNewData: newConversations.length > 0,
77
44
  };
78
45
  }
79
46
  /**
@@ -98,11 +65,6 @@ export function buildCurationDigest(delta, maxChars = 3000) {
98
65
  parts.push("");
99
66
  }
100
67
  }
101
- // Format new daily log content
102
- if (delta.newLogContent) {
103
- parts.push("### Server Activity (new daily log entries)");
104
- parts.push(delta.newLogContent);
105
- }
106
68
  let digest = parts.join("\n");
107
69
  // Trim if over budget
108
70
  if (digest.length > maxChars) {
@@ -124,35 +86,34 @@ MEMORY CURATION + PROACTIVE SIGNALS: New activity since your last check is below
124
86
  MEMORY CURATION — review and update:
125
87
  1. Update MEMORY.md with new facts, preferences, decisions, or lessons worth keeping.
126
88
  2. Update USER.md if you learned something new about the user.
127
- 3. Write today's notes to memory/${todayDateString()}.md (create memory/ dir if needed).
128
- 4. Do NOT duplicate what's already in MEMORY.md or USER.md.
129
- 5. Keep MEMORY.md concise it is loaded in every session's system prompt.
130
- 6. Remove outdated entries from MEMORY.md if no longer relevant.
131
- 7. Conversations below are from the user's mobile app — treat as context, don't re-execute.
89
+ 3. Do NOT duplicate what's already in MEMORY.md or USER.md.
90
+ 4. Keep MEMORY.md concise it is loaded in every session's system prompt.
91
+ 5. Remove outdated entries from MEMORY.md if no longer relevant.
92
+ 6. Conversations below are from the user's mobile app — treat as context, don't re-execute.
132
93
 
133
94
  PROACTIVE ACTION — analyze the activity below and cross-reference with what you know from MEMORY.md and USER.md. Think about what a thoughtful human assistant would do — not just monitoring, but real, substantive help:
134
95
 
135
96
  TAKE ACTION NOW (during this heartbeat turn) when you spot opportunities to:
136
- 8. Do research the user would find valuable (competitor analysis, market trends, topic deep-dives)
137
- 9. Create useful documents (meeting prep notes, trip itineraries, project summaries, comparison tables)
138
- 10. Prepare for upcoming events (gather context for tomorrow's meeting, draft agendas, check travel details)
139
- 11. Follow up on things the user started but didn't finish (drafts, half-explored ideas, pending decisions)
140
- 12. Find information the user will need soon (based on their calendar, projects, or recent conversations)
97
+ 7. Do research the user would find valuable (competitor analysis, market trends, topic deep-dives)
98
+ 8. Create useful documents (meeting prep notes, trip itineraries, project summaries, comparison tables)
99
+ 9. Prepare for upcoming events (gather context for tomorrow's meeting, draft agendas, check travel details)
100
+ 10. Follow up on things the user started but didn't finish (drafts, half-explored ideas, pending decisions)
101
+ 11. Find information the user will need soon (based on their calendar, projects, or recent conversations)
141
102
  Save substantial outputs to /home/user/task/ (auto-synced to user's device) and notify via message tool.
142
103
 
143
104
  UPDATE HEARTBEAT.md for ongoing monitoring when you detect:
144
- 13. Recurring interests worth periodic checking (stocks, products, topics, people)
145
- 14. Things the user is waiting on (replies, deliveries, results, approvals)
146
- 15. Deadlines or events that need tracking over time
147
- 16. Behavioral patterns worth supporting (daily routines, recurring needs)
105
+ 12. Recurring interests worth periodic checking (stocks, products, topics, people)
106
+ 13. Things the user is waiting on (replies, deliveries, results, approvals)
107
+ 14. Deadlines or events that need tracking over time
108
+ 15. Behavioral patterns worth supporting (daily routines, recurring needs)
148
109
  Read HEARTBEAT.md first, then add: "- [ ] Check X — alert user if Y"
149
110
 
150
111
  HEARTBEAT.md RULES:
151
- 17. Do NOT add items already in HEARTBEAT.md — check before adding.
152
- 18. Remove stale or resolved items (event passed, task done, user said stop).
153
- 19. PRESERVE items the user added via the app — never remove user-requested monitoring.
154
- 20. Keep under 10 items — each costs tokens every 30 minutes.
155
- 21. If nothing warrants action or monitoring, that's fine. Don't force it.
112
+ 16. Do NOT add items already in HEARTBEAT.md — check before adding.
113
+ 17. Remove stale or resolved items (event passed, task done, user said stop).
114
+ 18. PRESERVE items the user added via the app — never remove user-requested monitoring.
115
+ 19. Keep under 10 items — each costs tokens every 30 minutes.
116
+ 20. If nothing warrants action or monitoring, that's fine. Don't force it.
156
117
 
157
118
  ## New Since Last Check
158
119
  ${digest}
@@ -163,11 +124,10 @@ ${digest}
163
124
  *
164
125
  * @param state - Previous curation state
165
126
  * @param delta - The delta that was just processed
166
- * @param workspaceDir - Workspace root for reading current log size
127
+ * @param _workspaceDir - Workspace root (unused, kept for API compatibility)
167
128
  * @returns New curation state with updated cursors
168
129
  */
169
- export function updatedCursors(state, delta, workspaceDir) {
170
- const today = todayDateString();
130
+ export function updatedCursors(state, delta, _workspaceDir) {
171
131
  const newState = { ...state };
172
132
  // Update conversation cursor to the last processed request
173
133
  if (delta.newConversations.length > 0) {
@@ -175,15 +135,8 @@ export function updatedCursors(state, delta, workspaceDir) {
175
135
  newState.lastProcessedRequestId = lastConv.id;
176
136
  newState.lastProcessedRequestAt = lastConv.createdAt;
177
137
  }
178
- // Update daily log cursor to today's current file size
179
- const todayLogResult = readDailyLogSince(workspaceDir, today, 0);
180
- newState.lastProcessedLogDate = today;
181
- newState.lastProcessedLogSize = todayLogResult.newSize;
182
138
  // Increment total entries curated
183
139
  newState.totalEntriesCurated += delta.newConversations.length;
184
- if (delta.newLogContent.length > 0) {
185
- newState.totalEntriesCurated += 1; // Count new log content as one entry
186
- }
187
140
  return newState;
188
141
  }
189
142
  // ---------- Helpers ----------
@@ -1 +1 @@
1
- {"version":3,"file":"curator.js","sourceRoot":"","sources":["../../src/memory/curator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAyBpE;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,MAAc,EACd,YAAoB,EACpB,KAAoB,EACpB,mBAA2B,EAAE;IAE7B,uDAAuD;IACvD,MAAM,gBAAgB,GAAwB,EAAE,CAAC;IACjD,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,uBAAuB,CACxC,MAAM,EACN,KAAK,CAAC,sBAAsB,EAC5B,gBAAgB,CACjB,CAAC;QAEF,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,gBAAgB,CAAC,IAAI,CAAC;gBACpB,EAAE,EAAE,GAAG,CAAC,EAAE;gBACV,OAAO,EAAE,GAAG,CAAC,OAAO;gBACpB,QAAQ,EAAE,GAAG,CAAC,QAAQ,IAAI,IAAI;gBAC9B,SAAS,EAAE,GAAG,CAAC,UAAU;aAC1B,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,IAAI,CAAC,6CAA6C,EAAE,GAAG,CAAC,CAAC;IACnE,CAAC;IAED,gCAAgC;IAChC,IAAI,aAAa,GAAG,EAAE,CAAC;IACvB,MAAM,KAAK,GAAG,eAAe,EAAE,CAAC;IAEhC,IAAI,CAAC;QACH,wFAAwF;QACxF,IAAI,KAAK,CAAC,oBAAoB,IAAI,KAAK,CAAC,oBAAoB,KAAK,KAAK,EAAE,CAAC;YACvE,MAAM,eAAe,GAAG,iBAAiB,CACvC,YAAY,EACZ,KAAK,CAAC,o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ACH,MAAM,UAAU,cAAc,CAC5B,KAAoB,EACpB,KAAoB,EACpB,aAAqB;IAErB,MAAM,QAAQ,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;IAE9B,2DAA2D;IAC3D,IAAI,KAAK,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACtC,MAAM,QAAQ,GAAG,KAAK,CAAC,gBAAgB,CAAC,KAAK,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC3E,QAAQ,CAAC,sBAAsB,GAAG,QAAQ,CAAC,EAAE,CAAC;QAC9C,QAAQ,CAAC,sBAAsB,GAAG,QAAQ,CAAC,SAAS,CAAC;IACvD,CAAC;IAED,kCAAkC;IAClC,QAAQ,CAAC,mBAAmB,IAAI,KAAK,CAAC,gBAAgB,CAAC,MAAM,CAAC;IAE9D,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,gCAAgC;AAEhC;;GAEG;AACH,SAAS,QAAQ,CAAC,IAAY,EAAE,MAAc;IAC5C,IAAI,IAAI,CAAC,MAAM,IAAI,MAAM;QAAE,OAAO,IAAI,CAAC;IACvC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC;AAC3C,CAAC"}
@@ -2,9 +2,8 @@
2
2
  * CoStar Server Executor - Memory Module
3
3
  *
4
4
  * Incremental, cursor-based memory curation system.
5
- * LLM-written daily logs + automatic curation into MEMORY.md and USER.md.
5
+ * Fetches client conversations from agent_activity, curates into MEMORY.md and USER.md.
6
6
  */
7
- export { ensureMemoryDir, readDailyLogSince, listDailyLogFiles, pruneOldDailyLogs, pruneOldDailyLogsFromStorage, todayDateString, } from "./daily-log.js";
8
- export { loadCurationState, saveCurationState, shouldPrune, type CurationState, } from "./curation-state.js";
7
+ export { loadCurationState, saveCurationState, type CurationState, } from "./curation-state.js";
9
8
  export { fetchUnprocessedData, buildCurationDigest, buildCurationPrompt, updatedCursors, type CurationDelta, type ConversationEntry, } from "./curator.js";
10
9
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/memory/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EACL,eAAe,EACf,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,4BAA4B,EAC5B,eAAe,GAChB,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,EACX,KAAK,aAAa,GACnB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,EACd,KAAK,aAAa,EAClB,KAAK,iBAAiB,GACvB,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/memory/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,KAAK,aAAa,GACnB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,EACd,KAAK,aAAa,EAClB,KAAK,iBAAiB,GACvB,MAAM,cAAc,CAAC"}
@@ -2,12 +2,10 @@
2
2
  * CoStar Server Executor - Memory Module
3
3
  *
4
4
  * Incremental, cursor-based memory curation system.
5
- * LLM-written daily logs + automatic curation into MEMORY.md and USER.md.
5
+ * Fetches client conversations from agent_activity, curates into MEMORY.md and USER.md.
6
6
  */
7
- // Daily log utilities (read + prune only — LLM writes via tools)
8
- export { ensureMemoryDir, readDailyLogSince, listDailyLogFiles, pruneOldDailyLogs, pruneOldDailyLogsFromStorage, todayDateString, } from "./daily-log.js";
9
7
  // Curation state (cursor tracking)
10
- export { loadCurationState, saveCurationState, shouldPrune, } from "./curation-state.js";
8
+ export { loadCurationState, saveCurationState, } from "./curation-state.js";
11
9
  // Memory curator (fetch delta, build digest, build prompt)
12
10
  export { fetchUnprocessedData, buildCurationDigest, buildCurationPrompt, updatedCursors, } from "./curator.js";
13
11
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/memory/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,iEAAiE;AACjE,OAAO,EACL,eAAe,EACf,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,4BAA4B,EAC5B,eAAe,GAChB,MAAM,gBAAgB,CAAC;AAExB,mCAAmC;AACnC,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,GAEZ,MAAM,qBAAqB,CAAC;AAE7B,2DAA2D;AAC3D,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,GAGf,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/memory/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,mCAAmC;AACnC,OAAO,EACL,iBAAiB,EACjB,iBAAiB,GAElB,MAAM,qBAAqB,CAAC;AAE7B,2DAA2D;AAC3D,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,GAGf,MAAM,cAAc,CAAC"}
@@ -0,0 +1,103 @@
1
+ /**
2
+ * CoStar Server Executor - Agent Activity Supabase Adapter
3
+ *
4
+ * Manages the agent_activity table (formerly user_requests).
5
+ * Both client and server executors write activity entries here.
6
+ */
7
+ import type { AgentActivity } from "./types.js";
8
+ /**
9
+ * Create a new agent activity entry
10
+ */
11
+ export declare function createAgentActivity(params: {
12
+ userId: string;
13
+ request: string;
14
+ executor: "client" | "server";
15
+ source?: string;
16
+ }): Promise<AgentActivity>;
17
+ /**
18
+ * Update agent activity with response and completion status
19
+ */
20
+ export declare function completeAgentActivity(params: {
21
+ activityId: string;
22
+ response: string;
23
+ request?: string;
24
+ toolCalls?: number;
25
+ duration?: number;
26
+ }): Promise<AgentActivity>;
27
+ /**
28
+ * Mark agent activity as failed
29
+ */
30
+ export declare function failAgentActivity(params: {
31
+ activityId: string;
32
+ error: string;
33
+ duration?: number;
34
+ }): Promise<AgentActivity>;
35
+ /**
36
+ * Get agent activity by ID
37
+ */
38
+ export declare function getAgentActivityById(activityId: string): Promise<AgentActivity | null>;
39
+ /**
40
+ * Get recent agent activity
41
+ */
42
+ export declare function getRecentAgentActivity(userId: string, limit?: number): Promise<AgentActivity[]>;
43
+ /**
44
+ * Get agent activity by status
45
+ */
46
+ export declare function getAgentActivityByStatus(userId: string, status: "pending" | "completed" | "failed", limit?: number): Promise<AgentActivity[]>;
47
+ /**
48
+ * Search agent activity using text search (for memory recall)
49
+ * This searches both request and response fields across both executors.
50
+ */
51
+ export declare function searchAgentActivity(params: {
52
+ userId: string;
53
+ query: string;
54
+ limit?: number;
55
+ daysBack?: number;
56
+ }): Promise<Array<{
57
+ id: string;
58
+ request: string;
59
+ response: string | null;
60
+ created_at: string;
61
+ score: number;
62
+ }>>;
63
+ /**
64
+ * Get new agent activity since a given cursor (timestamp + optional ID).
65
+ * Used by the memory curation system to fetch only unprocessed client conversations.
66
+ * Filters to client executor only to prevent server from curating its own actions.
67
+ *
68
+ * @param userId - User ID to filter by
69
+ * @param afterTimestamp - Only return entries created after this ISO timestamp (exclusive)
70
+ * @param limit - Max number of entries to return (default: 30)
71
+ * @returns Completed client activity ordered by created_at ASC (oldest first)
72
+ */
73
+ export declare function getNewClientActivitySince(userId: string, afterTimestamp?: string | null, limit?: number): Promise<AgentActivity[]>;
74
+ /**
75
+ * Get agent activity statistics
76
+ */
77
+ export declare function getAgentActivityStats(userId: string): Promise<{
78
+ total: number;
79
+ pending: number;
80
+ completed: number;
81
+ failed: number;
82
+ avgDuration?: number;
83
+ avgToolCalls?: number;
84
+ }>;
85
+ /** @deprecated Use createAgentActivity instead */
86
+ export declare const createUserRequest: typeof createAgentActivity;
87
+ /** @deprecated Use completeAgentActivity instead */
88
+ export declare const completeUserRequest: typeof completeAgentActivity;
89
+ /** @deprecated Use failAgentActivity instead */
90
+ export declare const failUserRequest: typeof failAgentActivity;
91
+ /** @deprecated Use getAgentActivityById instead */
92
+ export declare const getUserRequestById: typeof getAgentActivityById;
93
+ /** @deprecated Use getRecentAgentActivity instead */
94
+ export declare const getRecentUserRequests: typeof getRecentAgentActivity;
95
+ /** @deprecated Use getAgentActivityByStatus instead */
96
+ export declare const getUserRequestsByStatus: typeof getAgentActivityByStatus;
97
+ /** @deprecated Use searchAgentActivity instead */
98
+ export declare const searchUserRequests: typeof searchAgentActivity;
99
+ /** @deprecated Use getNewClientActivitySince instead */
100
+ export declare const getNewUserRequestsSince: typeof getNewClientActivitySince;
101
+ /** @deprecated Use getAgentActivityStats instead */
102
+ export declare const getUserRequestsStats: typeof getAgentActivityStats;
103
+ //# sourceMappingURL=activity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"activity.d.ts","sourceRoot":"","sources":["../../src/supabase/activity.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD;;GAEG;AACH,wBAAsB,mBAAmB,CAAC,MAAM,EAAE;IAChD,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC,aAAa,CAAC,CAuBzB;AAED;;GAEG;AACH,wBAAsB,qBAAqB,CAAC,MAAM,EAAE;IAClD,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,GAAG,OAAO,CAAC,aAAa,CAAC,CA6Bz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AM,EAAE,MAAM,GAAG,OAAO,CAAC;IACnE,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC,CAuDD;AAQD,kDAAkD;AAClD,eAAO,MAAM,iBAAiB,4BAAsB,CAAC;AACrD,oDAAoD;AACpD,eAAO,MAAM,mBAAmB,8BAAwB,CAAC;AACzD,gDAAgD;AAChD,eAAO,MAAM,eAAe,0BAAoB,CAAC;AACjD,mDAAmD;AACnD,eAAO,MAAM,kBAAkB,6BAAuB,CAAC;AACvD,qDAAqD;AACrD,eAAO,MAAM,qBAAqB,+BAAyB,CAAC;AAC5D,uDAAuD;AACvD,eAAO,MAAM,uBAAuB,iCAA2B,CAAC;AAChE,kDAAkD;AAClD,eAAO,MAAM,kBAAkB,4BAAsB,CAAC;AACtD,wDAAwD;AACxD,eAAO,MAAM,uBAAuB,kCAA4B,CAAC;AACjE,oDAAoD;AACpD,eAAO,MAAM,oBAAoB,8BAAwB,CAAC"}
@@ -0,0 +1,313 @@
1
+ /**
2
+ * CoStar Server Executor - Agent Activity Supabase Adapter
3
+ *
4
+ * Manages the agent_activity table (formerly user_requests).
5
+ * Both client and server executors write activity entries here.
6
+ */
7
+ import { getSupabase } from "./client.js";
8
+ /**
9
+ * Create a new agent activity entry
10
+ */
11
+ export async function createAgentActivity(params) {
12
+ const supabase = getSupabase();
13
+ const { data, error } = await supabase
14
+ .from("agent_activity")
15
+ .insert({
16
+ user_id: params.userId,
17
+ request: params.request,
18
+ executor: params.executor,
19
+ source: params.source ?? (params.executor === "server" ? "executor" : undefined),
20
+ status: "pending",
21
+ created_at: new Date().toISOString(),
22
+ updated_at: new Date().toISOString(),
23
+ })
24
+ .select()
25
+ .single();
26
+ if (error) {
27
+ console.error("[SUPABASE] Error creating agent activity:", error);
28
+ throw new Error(`Failed to create agent activity: ${error.message}`);
29
+ }
30
+ return data;
31
+ }
32
+ /**
33
+ * Update agent activity with response and completion status
34
+ */
35
+ export async function completeAgentActivity(params) {
36
+ const supabase = getSupabase();
37
+ const updateFields = {
38
+ response: params.response,
39
+ status: "completed",
40
+ tool_calls: params.toolCalls,
41
+ duration: params.duration,
42
+ updated_at: new Date().toISOString(),
43
+ };
44
+ // Allow overwriting the request field with LLM-generated title
45
+ if (params.request) {
46
+ updateFields.request = params.request;
47
+ }
48
+ const { data, error } = await supabase
49
+ .from("agent_activity")
50
+ .update(updateFields)
51
+ .eq("id", params.activityId)
52
+ .select()
53
+ .single();
54
+ if (error) {
55
+ console.error("[SUPABASE] Error completing agent activity:", error);
56
+ throw new Error(`Failed to complete agent activity: ${error.message}`);
57
+ }
58
+ return data;
59
+ }
60
+ /**
61
+ * Mark agent activity as failed
62
+ */
63
+ export async function failAgentActivity(params) {
64
+ const supabase = getSupabase();
65
+ const { data, error: supabaseError } = await supabase
66
+ .from("agent_activity")
67
+ .update({
68
+ status: "failed",
69
+ error: params.error,
70
+ duration: params.duration,
71
+ updated_at: new Date().toISOString(),
72
+ })
73
+ .eq("id", params.activityId)
74
+ .select()
75
+ .single();
76
+ if (supabaseError) {
77
+ console.error("[SUPABASE] Error failing agent activity:", supabaseError);
78
+ throw new Error(`Failed to update agent activity: ${supabaseError.message}`);
79
+ }
80
+ return data;
81
+ }
82
+ /**
83
+ * Get agent activity by ID
84
+ */
85
+ export async function getAgentActivityById(activityId) {
86
+ const supabase = getSupabase();
87
+ const { data, error } = await supabase
88
+ .from("agent_activity")
89
+ .select("*")
90
+ .eq("id", activityId)
91
+ .single();
92
+ if (error) {
93
+ if (error.code === "PGRST116") {
94
+ // Not found
95
+ return null;
96
+ }
97
+ console.error("[SUPABASE] Error getting agent activity:", error);
98
+ throw new Error(`Failed to get agent activity: ${error.message}`);
99
+ }
100
+ return data;
101
+ }
102
+ /**
103
+ * Get recent agent activity
104
+ */
105
+ export async function getRecentAgentActivity(userId, limit = 50) {
106
+ const supabase = getSupabase();
107
+ const { data, error } = await supabase
108
+ .from("agent_activity")
109
+ .select("*")
110
+ .eq("user_id", userId)
111
+ .order("created_at", { ascending: false })
112
+ .limit(limit);
113
+ if (error) {
114
+ console.error("[SUPABASE] Error getting recent agent activity:", error);
115
+ throw new Error(`Failed to get recent agent activity: ${error.message}`);
116
+ }
117
+ return (data || []);
118
+ }
119
+ /**
120
+ * Get agent activity by status
121
+ */
122
+ export async function getAgentActivityByStatus(userId, status, limit = 50) {
123
+ const supabase = getSupabase();
124
+ const { data, error } = await supabase
125
+ .from("agent_activity")
126
+ .select("*")
127
+ .eq("user_id", userId)
128
+ .eq("status", status)
129
+ .order("created_at", { ascending: false })
130
+ .limit(limit);
131
+ if (error) {
132
+ console.error("[SUPABASE] Error getting agent activity by status:", error);
133
+ throw new Error(`Failed to get agent activity by status: ${error.message}`);
134
+ }
135
+ return (data || []);
136
+ }
137
+ /**
138
+ * Search agent activity using text search (for memory recall)
139
+ * This searches both request and response fields across both executors.
140
+ */
141
+ export async function searchAgentActivity(params) {
142
+ const supabase = getSupabase();
143
+ const limit = params.limit || 10;
144
+ // Calculate date filter if daysBack is specified
145
+ let dateFilter = null;
146
+ if (params.daysBack) {
147
+ const cutoffDate = new Date();
148
+ cutoffDate.setDate(cutoffDate.getDate() - params.daysBack);
149
+ dateFilter = cutoffDate.toISOString();
150
+ }
151
+ try {
152
+ let query = supabase
153
+ .from("agent_activity")
154
+ .select("id, request, response, created_at")
155
+ .eq("user_id", params.userId)
156
+ .eq("status", "completed")
157
+ .order("created_at", { ascending: false })
158
+ .limit(limit * 2); // Get more to filter
159
+ if (dateFilter) {
160
+ query = query.gte("created_at", dateFilter);
161
+ }
162
+ const { data, error } = await query;
163
+ if (error) {
164
+ console.error("[SUPABASE] Error searching agent activity:", error);
165
+ throw new Error(`Failed to search agent activity: ${error.message}`);
166
+ }
167
+ if (!data || data.length === 0) {
168
+ return [];
169
+ }
170
+ // Simple keyword matching for scoring
171
+ // In production, you'd use pgvector for semantic search
172
+ const queryTerms = params.query.toLowerCase().split(/\s+/);
173
+ const scored = data
174
+ .map((row) => {
175
+ const requestText = (row.request || "").toLowerCase();
176
+ const responseText = (row.response || "").toLowerCase();
177
+ const fullText = `${requestText} ${responseText}`;
178
+ // Calculate simple relevance score based on term matches
179
+ let matchCount = 0;
180
+ for (const term of queryTerms) {
181
+ if (fullText.includes(term)) {
182
+ matchCount++;
183
+ }
184
+ }
185
+ const score = queryTerms.length > 0 ? matchCount / queryTerms.length : 0;
186
+ return {
187
+ id: row.id,
188
+ request: row.request,
189
+ response: row.response,
190
+ created_at: row.created_at,
191
+ score,
192
+ };
193
+ })
194
+ .filter((row) => row.score > 0)
195
+ .sort((a, b) => b.score - a.score)
196
+ .slice(0, limit);
197
+ return scored;
198
+ }
199
+ catch (err) {
200
+ console.error("[SUPABASE] Error in searchAgentActivity:", err);
201
+ throw err;
202
+ }
203
+ }
204
+ /**
205
+ * Get new agent activity since a given cursor (timestamp + optional ID).
206
+ * Used by the memory curation system to fetch only unprocessed client conversations.
207
+ * Filters to client executor only to prevent server from curating its own actions.
208
+ *
209
+ * @param userId - User ID to filter by
210
+ * @param afterTimestamp - Only return entries created after this ISO timestamp (exclusive)
211
+ * @param limit - Max number of entries to return (default: 30)
212
+ * @returns Completed client activity ordered by created_at ASC (oldest first)
213
+ */
214
+ export async function getNewClientActivitySince(userId, afterTimestamp, limit = 30) {
215
+ const supabase = getSupabase();
216
+ try {
217
+ let query = supabase
218
+ .from("agent_activity")
219
+ .select("*")
220
+ .eq("user_id", userId)
221
+ .eq("status", "completed")
222
+ .eq("executor", "client") // Only curate client conversations
223
+ .order("created_at", { ascending: true })
224
+ .limit(limit);
225
+ if (afterTimestamp) {
226
+ query = query.gt("created_at", afterTimestamp);
227
+ }
228
+ const { data, error } = await query;
229
+ if (error) {
230
+ console.error("[SUPABASE] Error fetching new client activity:", error);
231
+ return [];
232
+ }
233
+ return (data || []);
234
+ }
235
+ catch (err) {
236
+ console.error("[SUPABASE] Error in getNewClientActivitySince:", err);
237
+ return [];
238
+ }
239
+ }
240
+ /**
241
+ * Get agent activity statistics
242
+ */
243
+ export async function getAgentActivityStats(userId) {
244
+ const supabase = getSupabase();
245
+ // Get counts by status
246
+ const { data, error } = await supabase
247
+ .from("agent_activity")
248
+ .select("status, duration, tool_calls")
249
+ .eq("user_id", userId);
250
+ if (error) {
251
+ console.error("[SUPABASE] Error getting agent activity stats:", error);
252
+ throw new Error(`Failed to get agent activity stats: ${error.message}`);
253
+ }
254
+ const stats = {
255
+ total: data.length,
256
+ pending: 0,
257
+ completed: 0,
258
+ failed: 0,
259
+ avgDuration: undefined,
260
+ avgToolCalls: undefined,
261
+ };
262
+ let totalDuration = 0;
263
+ let durationCount = 0;
264
+ let totalToolCalls = 0;
265
+ let toolCallsCount = 0;
266
+ for (const entry of data) {
267
+ if (entry.status === "pending")
268
+ stats.pending++;
269
+ if (entry.status === "completed")
270
+ stats.completed++;
271
+ if (entry.status === "failed")
272
+ stats.failed++;
273
+ if (entry.duration !== null && entry.duration !== undefined) {
274
+ totalDuration += entry.duration;
275
+ durationCount++;
276
+ }
277
+ if (entry.tool_calls !== null && entry.tool_calls !== undefined) {
278
+ totalToolCalls += entry.tool_calls;
279
+ toolCallsCount++;
280
+ }
281
+ }
282
+ if (durationCount > 0) {
283
+ stats.avgDuration = Math.round(totalDuration / durationCount);
284
+ }
285
+ if (toolCallsCount > 0) {
286
+ stats.avgToolCalls = Math.round((totalToolCalls / toolCallsCount) * 10) / 10;
287
+ }
288
+ return stats;
289
+ }
290
+ // ═══════════════════════════════════════════════════
291
+ // BACKWARD COMPATIBILITY ALIASES
292
+ // These maintain the old function names so existing code
293
+ // can be migrated incrementally. Will be removed in a future version.
294
+ // ═══════════════════════════════════════════════════
295
+ /** @deprecated Use createAgentActivity instead */
296
+ export const createUserRequest = createAgentActivity;
297
+ /** @deprecated Use completeAgentActivity instead */
298
+ export const completeUserRequest = completeAgentActivity;
299
+ /** @deprecated Use failAgentActivity instead */
300
+ export const failUserRequest = failAgentActivity;
301
+ /** @deprecated Use getAgentActivityById instead */
302
+ export const getUserRequestById = getAgentActivityById;
303
+ /** @deprecated Use getRecentAgentActivity instead */
304
+ export const getRecentUserRequests = getRecentAgentActivity;
305
+ /** @deprecated Use getAgentActivityByStatus instead */
306
+ export const getUserRequestsByStatus = getAgentActivityByStatus;
307
+ /** @deprecated Use searchAgentActivity instead */
308
+ export const searchUserRequests = searchAgentActivity;
309
+ /** @deprecated Use getNewClientActivitySince instead */
310
+ export const getNewUserRequestsSince = getNewClientActivitySince;
311
+ /** @deprecated Use getAgentActivityStats instead */
312
+ export const getUserRequestsStats = getAgentActivityStats;
313
+ //# sourceMappingURL=activity.js.map