@agentstep/agent-sdk 0.5.1 → 0.5.3

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 (186) hide show
  1. package/dist/auth/middleware.js +8 -8
  2. package/dist/backends/claude/args.js +7 -7
  3. package/dist/backends/claude/index.js +11 -11
  4. package/dist/backends/codex/auth.js +6 -6
  5. package/dist/backends/codex/index.js +11 -11
  6. package/dist/backends/factory/auth.js +6 -6
  7. package/dist/backends/factory/index.js +13 -13
  8. package/dist/backends/gemini/auth.js +6 -6
  9. package/dist/backends/gemini/index.js +11 -11
  10. package/dist/backends/opencode/auth.js +6 -6
  11. package/dist/backends/opencode/index.js +15 -15
  12. package/dist/backends/pi/auth.js +6 -6
  13. package/dist/backends/pi/index.js +13 -13
  14. package/dist/backends/registry.js +30 -30
  15. package/dist/backends/shared/wrap-prompt.js +1 -1
  16. package/dist/{chunk-4LHJJXH3.js → chunk-23CUQSLR.js} +2 -2
  17. package/dist/{chunk-57LAR6EM.js → chunk-2FKWZKV2.js} +4 -4
  18. package/dist/chunk-2YPJLPTR.js +166 -0
  19. package/dist/{chunk-FYBHPBWY.js → chunk-335F7KSU.js} +2 -2
  20. package/dist/chunk-3LUY2POB.js +50 -0
  21. package/dist/{chunk-HMOSAXVZ.js → chunk-4A4F4L4H.js} +2 -2
  22. package/dist/{chunk-JWHSUEDE.js → chunk-5NCA624D.js} +23 -7
  23. package/dist/{chunk-7SY65LWY.js → chunk-62CZZBEE.js} +4 -4
  24. package/dist/{chunk-GD3WXIHX.js → chunk-65XQ72BF.js} +1 -1
  25. package/dist/{chunk-RT5S5KRX.js → chunk-6DPJVMEC.js} +1 -1
  26. package/dist/{chunk-NBYCX6L4.js → chunk-6KJS42ZL.js} +7 -6
  27. package/dist/{chunk-QJ6QQO6D.js → chunk-6KQFP32G.js} +2 -2
  28. package/dist/{chunk-GIUB2OPA.js → chunk-6TJBZXD4.js} +1 -1
  29. package/dist/{chunk-UMVZZQKD.js → chunk-6ZM7XNH3.js} +1 -1
  30. package/dist/{chunk-ZY2U24QP.js → chunk-75XURMV5.js} +51 -12
  31. package/dist/{chunk-H6OT5GUL.js → chunk-7APAOJIZ.js} +3 -3
  32. package/dist/{chunk-HVLYE4S5.js → chunk-7EDLLXFQ.js} +1 -1
  33. package/dist/chunk-7IYL2O7H.js +185 -0
  34. package/dist/{chunk-KGBKIJPF.js → chunk-7JAUY5SG.js} +3 -3
  35. package/dist/{chunk-T7BHW3CP.js → chunk-7JWW4ZQI.js} +70 -24
  36. package/dist/{chunk-YZZHDZ7B.js → chunk-7XIAKW75.js} +1 -1
  37. package/dist/{chunk-USIMPXUH.js → chunk-A2W3USEZ.js} +1 -1
  38. package/dist/{chunk-WU74DV5R.js → chunk-A7AXD5AM.js} +2 -2
  39. package/dist/chunk-ACPP4KN7.js +164 -0
  40. package/dist/{chunk-22OUZJAV.js → chunk-AESA3ARX.js} +3 -3
  41. package/dist/{chunk-37C5BNVV.js → chunk-AIAF5ZZA.js} +1 -1
  42. package/dist/{chunk-YYMUSVUI.js → chunk-ANS2TQYT.js} +3 -3
  43. package/dist/{chunk-T3FQPTOA.js → chunk-BCBDHUFY.js} +2 -2
  44. package/dist/{chunk-COZG53R3.js → chunk-BCBRLP33.js} +2 -2
  45. package/dist/{chunk-MCWCRZM4.js → chunk-BLTCDZ3O.js} +4 -4
  46. package/dist/{chunk-VP527YC5.js → chunk-BYIU4WAQ.js} +3 -3
  47. package/dist/{chunk-R6EXYBCT.js → chunk-C52BVTYC.js} +8 -8
  48. package/dist/{chunk-DMMNAQUM.js → chunk-C5GVKLNS.js} +10 -18
  49. package/dist/{chunk-B5EY2VJC.js → chunk-C7BU4RX6.js} +3 -3
  50. package/dist/{chunk-T3IGOI6Z.js → chunk-DTQ7J35Q.js} +2 -2
  51. package/dist/{chunk-5M47X54D.js → chunk-DZGFZMUE.js} +5 -5
  52. package/dist/{chunk-3NKK4M23.js → chunk-E2OYBE5D.js} +2 -2
  53. package/dist/{chunk-L35CBI7F.js → chunk-E35XHOFL.js} +5 -5
  54. package/dist/{chunk-CE366H6Z.js → chunk-EHMKMOXH.js} +5 -5
  55. package/dist/{chunk-3S4CGFKJ.js → chunk-EQ32JFKT.js} +3 -3
  56. package/dist/{chunk-PZNAQBHQ.js → chunk-FILGQF2G.js} +2 -2
  57. package/dist/{chunk-MZYJFU4K.js → chunk-FSVDF57K.js} +5 -5
  58. package/dist/{chunk-XSNJ7NT2.js → chunk-G4DTLYOD.js} +1 -1
  59. package/dist/{chunk-IEZFRNLC.js → chunk-GBLR2CPP.js} +107 -9
  60. package/dist/{chunk-C35ZTCBP.js → chunk-IAKR572X.js} +8 -8
  61. package/dist/{chunk-W3JMIUHV.js → chunk-KQTTKYZY.js} +1 -1
  62. package/dist/{chunk-LIXSR7BG.js → chunk-LHFEBLOE.js} +7 -7
  63. package/dist/{chunk-BCIFFAGW.js → chunk-M3752GFZ.js} +15 -5
  64. package/dist/{chunk-5U5LRAFJ.js → chunk-MTLM36QD.js} +2 -2
  65. package/dist/{chunk-CKFJN5XK.js → chunk-MV42BTU3.js} +1 -1
  66. package/dist/{chunk-ZWC5V2DB.js → chunk-NJ6KNTZR.js} +17 -17
  67. package/dist/{chunk-5MERXOLJ.js → chunk-NRX5WHHN.js} +4 -4
  68. package/dist/{chunk-2YIMCZJK.js → chunk-NUOCXBFP.js} +68 -20
  69. package/dist/{chunk-T3HMVHDG.js → chunk-O2X4XBU7.js} +1 -1
  70. package/dist/{chunk-2YZOIFVN.js → chunk-P4NU74SP.js} +47 -0
  71. package/dist/{chunk-BJP5BIHE.js → chunk-PGJSOKPH.js} +3 -3
  72. package/dist/{chunk-IMPLRDOV.js → chunk-Q2JYAAJO.js} +9 -9
  73. package/dist/{chunk-56XDLNEW.js → chunk-RJDYM2HR.js} +1 -1
  74. package/dist/{chunk-4MKBT3KA.js → chunk-T6F4TFHD.js} +4 -4
  75. package/dist/{chunk-74E7GKUG.js → chunk-TE6KCRPP.js} +1 -1
  76. package/dist/{chunk-VJWNFMMQ.js → chunk-TF36SWHG.js} +2 -2
  77. package/dist/{chunk-KUWJJD6O.js → chunk-TSR33JMZ.js} +14 -5
  78. package/dist/{chunk-L3IACZ72.js → chunk-TWH4UH6G.js} +1 -1
  79. package/dist/{chunk-445EL6J5.js → chunk-UAEVL47I.js} +1 -1
  80. package/dist/{chunk-6RFQCFL2.js → chunk-UALRSWXY.js} +44 -14
  81. package/dist/{chunk-GQYSSSVA.js → chunk-UGH5JDXX.js} +2 -2
  82. package/dist/{chunk-I26QP3A3.js → chunk-UQZFFG7U.js} +1 -1
  83. package/dist/{chunk-Q4XF3OBK.js → chunk-UYP3VGYB.js} +8 -8
  84. package/dist/{chunk-ILHIHMO3.js → chunk-VC5DELR4.js} +37 -2
  85. package/dist/{chunk-O56RNR7B.js → chunk-VMLXV2H6.js} +1 -1
  86. package/dist/{chunk-FCUXFLNK.js → chunk-VY6IWBSK.js} +17 -4
  87. package/dist/{chunk-NL4UNA53.js → chunk-VYY4RHIF.js} +2 -2
  88. package/dist/{chunk-NRXTWATQ.js → chunk-WFRHLTKI.js} +3 -3
  89. package/dist/{chunk-UMRDMOB6.js → chunk-WRLCJNQF.js} +1 -1
  90. package/dist/{chunk-DRNZ24RF.js → chunk-WXMEJVLS.js} +4 -4
  91. package/dist/{chunk-63AKPSCV.js → chunk-X4ARJS6I.js} +10 -10
  92. package/dist/{chunk-MXMXJYN4.js → chunk-XXGVNVPI.js} +5 -5
  93. package/dist/{chunk-A46RUKGA.js → chunk-Y4MI27HU.js} +1 -1
  94. package/dist/{chunk-TG3S4RVJ.js → chunk-Y7NMJ662.js} +2 -2
  95. package/dist/{chunk-FVBDEOTZ.js → chunk-YE2RMJY7.js} +18 -4
  96. package/dist/{chunk-EDUTIJAU.js → chunk-YIY47OVD.js} +6 -6
  97. package/dist/{chunk-HZZ6ZLKP.js → chunk-YL6IQUJC.js} +4 -4
  98. package/dist/{chunk-WDACZSRU.js → chunk-Z6OPLBPQ.js} +1 -1
  99. package/dist/{chunk-UQ3LKJPM.js → chunk-ZG3PHDZJ.js} +3 -3
  100. package/dist/{chunk-2YFS435Z.js → chunk-ZGI6YG2G.js} +42 -4
  101. package/dist/config/index.js +5 -5
  102. package/dist/containers/client.js +6 -6
  103. package/dist/containers/exec.js +6 -6
  104. package/dist/containers/lifecycle.js +44 -42
  105. package/dist/containers/setup.js +8 -8
  106. package/dist/db/agents.js +6 -6
  107. package/dist/db/api_keys.js +5 -5
  108. package/dist/db/audit.js +3 -3
  109. package/dist/db/batch.js +10 -10
  110. package/dist/db/client.js +2 -2
  111. package/dist/db/credentials.js +3 -3
  112. package/dist/db/drizzle.js +4 -4
  113. package/dist/db/environments.js +6 -6
  114. package/dist/db/events.js +5 -5
  115. package/dist/db/files.js +5 -5
  116. package/dist/db/memory.js +13 -5
  117. package/dist/db/migrations.js +1 -1
  118. package/dist/db/proxy.js +5 -5
  119. package/dist/db/schema.js +5 -1
  120. package/dist/db/session-resources.js +5 -5
  121. package/dist/db/sessions.js +8 -8
  122. package/dist/db/sync.js +5 -5
  123. package/dist/db/tenants.js +3 -3
  124. package/dist/db/threads.js +27 -0
  125. package/dist/db/traces.js +5 -5
  126. package/dist/db/upstream_keys.js +3 -3
  127. package/dist/db/vaults.js +6 -6
  128. package/dist/dreaming/prompts.js +9 -0
  129. package/dist/dreaming/review.js +22 -0
  130. package/dist/handlers/agents.js +58 -58
  131. package/dist/handlers/api_keys.js +59 -59
  132. package/dist/handlers/audit.js +59 -59
  133. package/dist/handlers/batch.js +59 -59
  134. package/dist/handlers/credentials.js +59 -59
  135. package/dist/handlers/environments.js +59 -59
  136. package/dist/handlers/events.js +62 -62
  137. package/dist/handlers/files.js +59 -59
  138. package/dist/handlers/index.js +158 -143
  139. package/dist/handlers/license.js +58 -58
  140. package/dist/handlers/memory.js +65 -59
  141. package/dist/handlers/metrics.js +58 -58
  142. package/dist/handlers/models.js +59 -59
  143. package/dist/handlers/providers.js +58 -58
  144. package/dist/handlers/resources.js +58 -58
  145. package/dist/handlers/sessions.js +62 -61
  146. package/dist/handlers/settings.js +58 -58
  147. package/dist/handlers/skills-write.js +58 -58
  148. package/dist/handlers/skills.js +59 -59
  149. package/dist/handlers/stream.js +58 -58
  150. package/dist/handlers/tenants.js +59 -59
  151. package/dist/handlers/threads.js +69 -60
  152. package/dist/handlers/traces.js +59 -59
  153. package/dist/handlers/upstream_keys.js +61 -61
  154. package/dist/handlers/vaults.js +58 -58
  155. package/dist/handlers/whoami.js +58 -58
  156. package/dist/http.js +57 -57
  157. package/dist/index.js +71 -66
  158. package/dist/init.js +54 -54
  159. package/dist/lib/model-registry.js +6 -6
  160. package/dist/lib/skills-cache.js +6 -6
  161. package/dist/observability/otlp.js +12 -12
  162. package/dist/observability/redactor.js +8 -8
  163. package/dist/providers/fly.js +5 -5
  164. package/dist/providers/modal.js +5 -5
  165. package/dist/providers/registry.js +1 -1
  166. package/dist/providers/resolve-secrets.js +7 -7
  167. package/dist/providers/sprites.js +7 -7
  168. package/dist/providers/upstream-keys.js +12 -12
  169. package/dist/providers/vercel.js +6 -6
  170. package/dist/proxy/forward.js +6 -6
  171. package/dist/queue/index.js +6 -6
  172. package/dist/sessions/bus.js +10 -10
  173. package/dist/sessions/driver.js +47 -47
  174. package/dist/sessions/grader.js +5 -5
  175. package/dist/sessions/secrets.js +8 -8
  176. package/dist/sessions/sweeper.js +43 -43
  177. package/dist/sessions/threads.js +120 -54
  178. package/dist/shutdown.js +44 -44
  179. package/dist/sync/anthropic.js +10 -10
  180. package/dist/sync/container-file-sync.js +24 -6
  181. package/dist/sync/file-sync.js +17 -17
  182. package/dist/sync/memory-sync.js +79 -0
  183. package/package.json +1 -1
  184. package/dist/chunk-AQB3P5ZP.js +0 -48
  185. package/dist/{chunk-JRQB3SHR.js → chunk-LT5PRO54.js} +0 -0
  186. package/dist/{dist-EY25RQ2S.js → dist-S64ZABZX.js} +3 -3
@@ -0,0 +1,185 @@
1
+ import {
2
+ getAgent
3
+ } from "./chunk-M3752GFZ.js";
4
+ import {
5
+ init_ids,
6
+ newId
7
+ } from "./chunk-F4WUVOLE.js";
8
+ import {
9
+ init_clock,
10
+ nowMs,
11
+ toIso
12
+ } from "./chunk-HFDLUBWN.js";
13
+ import {
14
+ getDrizzle,
15
+ init_drizzle
16
+ } from "./chunk-FILGQF2G.js";
17
+ import {
18
+ schema_exports
19
+ } from "./chunk-VC5DELR4.js";
20
+
21
+ // src/db/threads.ts
22
+ init_drizzle();
23
+ import { eq, and, isNull, lt, gt, asc, desc } from "drizzle-orm";
24
+ init_ids();
25
+ init_clock();
26
+ var MAX_THREADS_PER_SESSION = 25;
27
+ function hydrate(row) {
28
+ const agent = getAgent(row.agent_id, row.agent_version);
29
+ const agentEmbed = agent ? {
30
+ type: "agent",
31
+ id: agent.id,
32
+ version: agent.version,
33
+ name: agent.name,
34
+ description: agent.description,
35
+ model: agent.model,
36
+ system: agent.system,
37
+ tools: agent.tools,
38
+ mcp_servers: agent.mcp_servers,
39
+ skills: agent.skills
40
+ } : {
41
+ type: "agent",
42
+ id: row.agent_id,
43
+ version: row.agent_version,
44
+ name: "",
45
+ description: "",
46
+ model: { id: "" },
47
+ system: null,
48
+ tools: [],
49
+ mcp_servers: [],
50
+ skills: []
51
+ };
52
+ return {
53
+ type: "session_thread",
54
+ id: row.id,
55
+ session_id: row.session_id,
56
+ status: row.status,
57
+ agent: agentEmbed,
58
+ parent_thread_id: row.parent_thread_id ?? null,
59
+ created_at: toIso(row.created_at),
60
+ updated_at: toIso(row.updated_at),
61
+ archived_at: row.archived_at ? toIso(row.archived_at) : null,
62
+ usage: {
63
+ input_tokens: row.usage_input_tokens,
64
+ output_tokens: row.usage_output_tokens,
65
+ cache_read_input_tokens: row.usage_cache_read_input_tokens,
66
+ cache_creation: {
67
+ ephemeral_5m_input_tokens: row.usage_cache_creation_input_tokens,
68
+ ephemeral_1h_input_tokens: 0
69
+ }
70
+ },
71
+ stop_reason: row.stop_reason ?? null
72
+ };
73
+ }
74
+ function createThread(opts) {
75
+ const db = getDrizzle();
76
+ const existing = db.select({ id: schema_exports.sessionThreads.id }).from(schema_exports.sessionThreads).where(
77
+ and(
78
+ eq(schema_exports.sessionThreads.session_id, opts.sessionId),
79
+ isNull(schema_exports.sessionThreads.archived_at)
80
+ )
81
+ ).all();
82
+ if (existing.length >= MAX_THREADS_PER_SESSION) {
83
+ throw new Error(`max threads per session reached (${MAX_THREADS_PER_SESSION})`);
84
+ }
85
+ const id = newId("sth");
86
+ const now = nowMs();
87
+ db.insert(schema_exports.sessionThreads).values({
88
+ id,
89
+ session_id: opts.sessionId,
90
+ agent_id: opts.agentId,
91
+ agent_version: opts.agentVersion,
92
+ parent_thread_id: opts.parentThreadId ?? null,
93
+ status: "idle",
94
+ usage_input_tokens: 0,
95
+ usage_output_tokens: 0,
96
+ usage_cache_read_input_tokens: 0,
97
+ usage_cache_creation_input_tokens: 0,
98
+ created_at: now,
99
+ updated_at: now
100
+ }).run();
101
+ return getThread(opts.sessionId, id);
102
+ }
103
+ function getThread(sessionId, threadId) {
104
+ const db = getDrizzle();
105
+ const row = db.select().from(schema_exports.sessionThreads).where(
106
+ and(
107
+ eq(schema_exports.sessionThreads.id, threadId),
108
+ eq(schema_exports.sessionThreads.session_id, sessionId)
109
+ )
110
+ ).get();
111
+ if (!row) return void 0;
112
+ return hydrate(row);
113
+ }
114
+ function listThreads(sessionId, opts) {
115
+ const db = getDrizzle();
116
+ const limit = Math.min(Math.max(opts?.limit ?? 50, 1), 100);
117
+ const orderDir = opts?.order === "asc" ? "asc" : "desc";
118
+ const conditions = [eq(schema_exports.sessionThreads.session_id, sessionId)];
119
+ if (opts?.cursor) {
120
+ conditions.push(
121
+ orderDir === "desc" ? lt(schema_exports.sessionThreads.id, opts.cursor) : gt(schema_exports.sessionThreads.id, opts.cursor)
122
+ );
123
+ }
124
+ const orderClause = orderDir === "desc" ? desc(schema_exports.sessionThreads.created_at) : asc(schema_exports.sessionThreads.created_at);
125
+ const rows = db.select().from(schema_exports.sessionThreads).where(and(...conditions)).orderBy(orderClause).limit(limit).all();
126
+ return rows.map(hydrate);
127
+ }
128
+ function updateThreadStatus(threadId, status, stopReason) {
129
+ const db = getDrizzle();
130
+ const now = nowMs();
131
+ db.update(schema_exports.sessionThreads).set({
132
+ status,
133
+ stop_reason: stopReason ?? null,
134
+ updated_at: now
135
+ }).where(eq(schema_exports.sessionThreads.id, threadId)).run();
136
+ }
137
+ function updateThreadUsage(threadId, usage) {
138
+ const db = getDrizzle();
139
+ const now = nowMs();
140
+ const row = db.select().from(schema_exports.sessionThreads).where(eq(schema_exports.sessionThreads.id, threadId)).get();
141
+ if (!row) return;
142
+ db.update(schema_exports.sessionThreads).set({
143
+ usage_input_tokens: row.usage_input_tokens + (usage.input_tokens ?? 0),
144
+ usage_output_tokens: row.usage_output_tokens + (usage.output_tokens ?? 0),
145
+ usage_cache_read_input_tokens: row.usage_cache_read_input_tokens + (usage.cache_read_input_tokens ?? 0),
146
+ usage_cache_creation_input_tokens: row.usage_cache_creation_input_tokens + (usage.cache_creation_input_tokens ?? 0),
147
+ updated_at: now
148
+ }).where(eq(schema_exports.sessionThreads.id, threadId)).run();
149
+ }
150
+ function archiveThread(sessionId, threadId) {
151
+ const db = getDrizzle();
152
+ const row = db.select().from(schema_exports.sessionThreads).where(
153
+ and(
154
+ eq(schema_exports.sessionThreads.id, threadId),
155
+ eq(schema_exports.sessionThreads.session_id, sessionId)
156
+ )
157
+ ).get();
158
+ if (!row) return void 0;
159
+ if (row.status !== "idle") {
160
+ throw new Error(`cannot archive thread in status "${row.status}" \u2014 must be idle`);
161
+ }
162
+ const now = nowMs();
163
+ db.update(schema_exports.sessionThreads).set({ archived_at: now, updated_at: now }).where(eq(schema_exports.sessionThreads.id, threadId)).run();
164
+ return getThread(sessionId, threadId);
165
+ }
166
+ function countActiveThreads(sessionId) {
167
+ const db = getDrizzle();
168
+ const rows = db.select({ id: schema_exports.sessionThreads.id }).from(schema_exports.sessionThreads).where(
169
+ and(
170
+ eq(schema_exports.sessionThreads.session_id, sessionId),
171
+ isNull(schema_exports.sessionThreads.archived_at)
172
+ )
173
+ ).all();
174
+ return rows.length;
175
+ }
176
+
177
+ export {
178
+ createThread,
179
+ getThread,
180
+ listThreads,
181
+ updateThreadStatus,
182
+ updateThreadUsage,
183
+ archiveThread,
184
+ countActiveThreads
185
+ };
@@ -10,14 +10,14 @@ import {
10
10
  import {
11
11
  getDrizzle,
12
12
  init_drizzle
13
- } from "./chunk-PZNAQBHQ.js";
13
+ } from "./chunk-FILGQF2G.js";
14
14
  import {
15
15
  schema_exports
16
- } from "./chunk-ILHIHMO3.js";
16
+ } from "./chunk-VC5DELR4.js";
17
17
  import {
18
18
  getDb,
19
19
  init_client
20
- } from "./chunk-W3JMIUHV.js";
20
+ } from "./chunk-KQTTKYZY.js";
21
21
 
22
22
  // src/db/events.ts
23
23
  init_client();
@@ -1,6 +1,15 @@
1
1
  import {
2
2
  parseNDJSONLines
3
3
  } from "./chunk-PJZ5TQYW.js";
4
+ import {
5
+ incrementRetry,
6
+ resetRetry,
7
+ retryDelay,
8
+ shouldRetry
9
+ } from "./chunk-72BKGVBE.js";
10
+ import {
11
+ loadSessionSecrets
12
+ } from "./chunk-4A4F4L4H.js";
4
13
  import {
5
14
  childSpan,
6
15
  newTrace
@@ -13,32 +22,23 @@ import {
13
22
  import {
14
23
  injectMcpAuthHeaders
15
24
  } from "./chunk-DBFPJSOY.js";
16
- import {
17
- incrementRetry,
18
- resetRetry,
19
- retryDelay,
20
- shouldRetry
21
- } from "./chunk-72BKGVBE.js";
22
- import {
23
- loadSessionSecrets
24
- } from "./chunk-HMOSAXVZ.js";
25
25
  import {
26
26
  isProxied
27
- } from "./chunk-5U5LRAFJ.js";
27
+ } from "./chunk-MTLM36QD.js";
28
28
  import {
29
29
  acquireForFirstTurn,
30
30
  installSkills,
31
31
  provisionResources,
32
32
  wrapProviderWithSecrets
33
- } from "./chunk-ZY2U24QP.js";
33
+ } from "./chunk-75XURMV5.js";
34
34
  import {
35
35
  BLOCKED_ENV_KEYS,
36
36
  resolveVaultSecrets
37
- } from "./chunk-T3HMVHDG.js";
37
+ } from "./chunk-O2X4XBU7.js";
38
38
  import {
39
39
  appendEvent,
40
40
  appendEventsBatch
41
- } from "./chunk-5MERXOLJ.js";
41
+ } from "./chunk-NRX5WHHN.js";
42
42
  import {
43
43
  bumpSessionStats,
44
44
  getOutcomeCriteria,
@@ -49,26 +49,26 @@ import {
49
49
  setOutcomeCriteria,
50
50
  updateSessionMutable,
51
51
  updateSessionStatus
52
- } from "./chunk-KUWJJD6O.js";
52
+ } from "./chunk-TSR33JMZ.js";
53
53
  import {
54
54
  listEvents,
55
55
  markUserEventProcessed
56
- } from "./chunk-KGBKIJPF.js";
56
+ } from "./chunk-7JAUY5SG.js";
57
57
  import {
58
58
  getBySession
59
59
  } from "./chunk-EFOIR7R3.js";
60
60
  import {
61
61
  resolveContainerProvider
62
- } from "./chunk-JRQB3SHR.js";
62
+ } from "./chunk-LT5PRO54.js";
63
63
  import {
64
64
  getEnvironment
65
- } from "./chunk-H6OT5GUL.js";
65
+ } from "./chunk-7APAOJIZ.js";
66
66
  import {
67
67
  getAgent
68
- } from "./chunk-BCIFFAGW.js";
68
+ } from "./chunk-M3752GFZ.js";
69
69
  import {
70
70
  resolveBackend
71
- } from "./chunk-IMPLRDOV.js";
71
+ } from "./chunk-Q2JYAAJO.js";
72
72
  import {
73
73
  PERMISSION_BRIDGE_PENDING_PATH,
74
74
  PERMISSION_BRIDGE_REQUEST_PATH,
@@ -84,7 +84,7 @@ import {
84
84
  } from "./chunk-XBHDQK4Z.js";
85
85
  import {
86
86
  getConfig
87
- } from "./chunk-GQYSSSVA.js";
87
+ } from "./chunk-UGH5JDXX.js";
88
88
  import {
89
89
  init_clock,
90
90
  nowMs
@@ -266,13 +266,36 @@ async function runTurn(sessionId, inputs, _depth = 0, parentTrace) {
266
266
  content: i.content
267
267
  }));
268
268
  const agentForTurn = injectMcpAuthHeaders(agent, vaultEntries);
269
+ let mountedMemoryStores;
270
+ try {
271
+ const { listResources: listSessionResources } = await import("./db/session-resources.js");
272
+ const { getMemoryStore } = await import("./db/memory.js");
273
+ const sessionResources = listSessionResources(sessionId);
274
+ const memStoreResources = sessionResources.filter((r) => r.type === "memory_store" && r.memory_store_id);
275
+ if (memStoreResources.length > 0) {
276
+ mountedMemoryStores = [];
277
+ for (const r of memStoreResources) {
278
+ const store = getMemoryStore(r.memory_store_id);
279
+ if (store) {
280
+ mountedMemoryStores.push({
281
+ name: store.name,
282
+ access: r.access ?? "read_write",
283
+ description: store.description,
284
+ instructions: r.instructions
285
+ });
286
+ }
287
+ }
288
+ }
289
+ } catch {
290
+ }
269
291
  let turnBuild;
270
292
  try {
271
293
  turnBuild = backend.buildTurn({
272
294
  agent: agentForTurn,
273
295
  backendSessionId: getSessionRow(sessionId)?.claude_session_id ?? null,
274
296
  promptText,
275
- toolResults
297
+ toolResults,
298
+ memoryStores: mountedMemoryStores
276
299
  });
277
300
  } catch (err) {
278
301
  const msg = err instanceof ApiError ? err.message : err instanceof Error ? err.message : String(err);
@@ -613,6 +636,17 @@ ${turnBuild.stdin}`;
613
636
  } catch (err) {
614
637
  console.warn("[driver] container file sync failed:", err?.stack ?? err);
615
638
  }
639
+ try {
640
+ const { syncMemoryStores } = await import("./sync/memory-sync.js");
641
+ await syncMemoryStores({
642
+ sessionId,
643
+ sandboxName: sessionRowForSync.sandbox_name,
644
+ provider,
645
+ secrets
646
+ });
647
+ } catch (err) {
648
+ console.warn("[driver] memory store sync failed:", err?.stack ?? err);
649
+ }
616
650
  }
617
651
  const now = nowMs();
618
652
  const stopReason = result?.stopReason ?? "end_turn";
@@ -670,11 +704,12 @@ ${turnBuild.stdin}`;
670
704
  setIdleSince(sessionId, now);
671
705
  if (stopReason === "end_turn") {
672
706
  const criteria = getOutcomeCriteria(sessionId);
673
- if (criteria?.rubric) {
707
+ if (criteria?.rubric && criteria?.status === "running") {
674
708
  try {
675
709
  const { runGraderEvaluation } = await import("./sessions/grader.js");
676
710
  const maxIter = criteria.max_iterations ?? 3;
677
711
  const iteration = criteria.grader_iteration ?? 0;
712
+ const outcomeId = criteria.outcome_id ?? null;
678
713
  const recentEvents = listEvents(sessionId, { limit: 50, order: "desc" });
679
714
  let lastAgentText = "";
680
715
  for (const evt of recentEvents) {
@@ -687,7 +722,7 @@ ${turnBuild.stdin}`;
687
722
  }
688
723
  }
689
724
  }
690
- emit("span.outcome_evaluation_start", { iteration });
725
+ emit("span.outcome_evaluation_start", { outcome_id: outcomeId, iteration });
691
726
  const evaluation = await runGraderEvaluation(
692
727
  criteria.rubric,
693
728
  lastAgentText,
@@ -706,10 +741,21 @@ ${turnBuild.stdin}`;
706
741
  });
707
742
  const finalResult = iteration + 1 >= maxIter && evaluation.result === "needs_revision" ? "max_iterations_reached" : evaluation.result;
708
743
  emit("span.outcome_evaluation_end", {
744
+ outcome_id: outcomeId,
709
745
  result: finalResult,
746
+ explanation: evaluation.feedback,
710
747
  iteration,
711
- feedback: evaluation.feedback
748
+ usage: evaluation.usage
712
749
  });
750
+ if (finalResult === "satisfied" || finalResult === "max_iterations_reached" || finalResult === "failed") {
751
+ setOutcomeCriteria(sessionId, {
752
+ ...criteria,
753
+ grader_iteration: iteration + 1,
754
+ status: finalResult,
755
+ completed_at: new Date(nowMs()).toISOString(),
756
+ explanation: evaluation.feedback
757
+ });
758
+ }
713
759
  if (evaluation.result === "needs_revision" && iteration + 1 < maxIter) {
714
760
  await runTurn(sessionId, [{
715
761
  kind: "text",
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getConfig
3
- } from "./chunk-GQYSSSVA.js";
3
+ } from "./chunk-UGH5JDXX.js";
4
4
 
5
5
  // src/backends/factory/auth.ts
6
6
  function buildFactoryAuthEnv() {
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getConfig
3
- } from "./chunk-GQYSSSVA.js";
3
+ } from "./chunk-UGH5JDXX.js";
4
4
  import {
5
5
  ApiError
6
6
  } from "./chunk-EZYKRG4W.js";
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  BatchError,
3
3
  executeBatch
4
- } from "./chunk-MCWCRZM4.js";
4
+ } from "./chunk-BLTCDZ3O.js";
5
5
  import {
6
6
  jsonOk,
7
7
  routeWrap
8
- } from "./chunk-T3IGOI6Z.js";
8
+ } from "./chunk-DTQ7J35Q.js";
9
9
  import {
10
10
  badRequest
11
11
  } from "./chunk-EZYKRG4W.js";
@@ -0,0 +1,164 @@
1
+ import {
2
+ DREAMING_SYSTEM_PROMPT,
3
+ UPDATE_MEMORIES_TOOL
4
+ } from "./chunk-3LUY2POB.js";
5
+ import {
6
+ createOrUpsertMemory,
7
+ deleteMemory,
8
+ getMemoryByPath,
9
+ getMemoryStore,
10
+ listMemories
11
+ } from "./chunk-GBLR2CPP.js";
12
+ import {
13
+ listSessions
14
+ } from "./chunk-TSR33JMZ.js";
15
+ import {
16
+ listEvents
17
+ } from "./chunk-7JAUY5SG.js";
18
+ import {
19
+ init_clock,
20
+ nowMs
21
+ } from "./chunk-HFDLUBWN.js";
22
+
23
+ // src/dreaming/review.ts
24
+ init_clock();
25
+ var MAX_SESSIONS = 20;
26
+ var MAX_EVENTS_PER_SESSION = 50;
27
+ var RELEVANT_EVENT_TYPES = ["user.message", "agent.message", "session.error"];
28
+ function extractSessionSummary(sessionId, title, events) {
29
+ const parts = [];
30
+ const errors = [];
31
+ for (const evt of events) {
32
+ let payload;
33
+ try {
34
+ payload = JSON.parse(evt.payload_json);
35
+ } catch {
36
+ continue;
37
+ }
38
+ if (evt.type === "user.message") {
39
+ const content = payload.content;
40
+ if (Array.isArray(content)) {
41
+ const text = content.filter((b) => b.type === "text").map((b) => b.text ?? "").join(" ");
42
+ if (text) parts.push(`[User] ${text.slice(0, 500)}`);
43
+ } else if (typeof content === "string") {
44
+ parts.push(`[User] ${content.slice(0, 500)}`);
45
+ }
46
+ } else if (evt.type === "agent.message") {
47
+ const content = payload.content;
48
+ if (Array.isArray(content)) {
49
+ const text = content.filter((b) => b.type === "text").map((b) => b.text ?? "").join(" ");
50
+ if (text) parts.push(`[Agent] ${text.slice(0, 500)}`);
51
+ } else if (typeof content === "string") {
52
+ parts.push(`[Agent] ${content.slice(0, 500)}`);
53
+ }
54
+ } else if (evt.type === "session.error") {
55
+ const msg = payload.message ?? payload.error ?? JSON.stringify(payload);
56
+ errors.push(msg.slice(0, 200));
57
+ }
58
+ }
59
+ const header = `Session ${sessionId}${title ? ` (${title})` : ""}:`;
60
+ const body = parts.join("\n");
61
+ const errorSection = errors.length ? `
62
+ Errors: ${errors.join("; ")}` : "";
63
+ return `${header}
64
+ ${body}${errorSection}`;
65
+ }
66
+ async function reviewSessions(opts) {
67
+ const { storeId, lookbackMs, dryRun } = opts;
68
+ const store = getMemoryStore(storeId);
69
+ if (!store) {
70
+ throw new Error(`Memory store not found: ${storeId}`);
71
+ }
72
+ const apiKey = opts.apiKey || process.env.ANTHROPIC_API_KEY;
73
+ if (!apiKey) {
74
+ throw new Error("No Anthropic API key provided. Use --api-key or set ANTHROPIC_API_KEY.");
75
+ }
76
+ const cutoff = nowMs() - lookbackMs;
77
+ const sessions = listSessions({
78
+ statuses: ["idle", "terminated"],
79
+ createdGt: cutoff,
80
+ limit: MAX_SESSIONS,
81
+ order: "desc"
82
+ });
83
+ if (sessions.length === 0) {
84
+ return { sessionCount: 0, proposedChanges: [], applied: false };
85
+ }
86
+ const summaries = [];
87
+ for (const session of sessions) {
88
+ const events = listEvents(session.id, {
89
+ limit: MAX_EVENTS_PER_SESSION,
90
+ order: "asc"
91
+ });
92
+ const relevant = events.filter((e) => RELEVANT_EVENT_TYPES.includes(e.type));
93
+ if (relevant.length === 0) continue;
94
+ const summary = extractSessionSummary(session.id, session.title ?? null, relevant);
95
+ summaries.push(summary);
96
+ }
97
+ if (summaries.length === 0) {
98
+ return { sessionCount: sessions.length, proposedChanges: [], applied: false };
99
+ }
100
+ const memories = listMemories(storeId);
101
+ const memorySection = memories.length > 0 ? `## Current Memory Store Contents
102
+
103
+ ${memories.map((m) => `### ${m.path}
104
+ ${m.content}`).join("\n\n")}` : "## Current Memory Store Contents\n\n(empty \u2014 no memories yet)";
105
+ const sessionSection = `## Recent Sessions (${summaries.length})
106
+
107
+ ${summaries.join("\n\n---\n\n")}`;
108
+ const userMessage = `${sessionSection}
109
+
110
+ ${memorySection}
111
+
112
+ Analyze the sessions above and propose memory changes using the update_memories tool.`;
113
+ const maxChars = 2e5;
114
+ const truncatedMessage = userMessage.length > maxChars ? userMessage.slice(0, maxChars) + "\n\n[... truncated for context limits]" : userMessage;
115
+ const response = await fetch("https://api.anthropic.com/v1/messages", {
116
+ method: "POST",
117
+ headers: {
118
+ "content-type": "application/json",
119
+ "x-api-key": apiKey,
120
+ "anthropic-version": "2023-06-01"
121
+ },
122
+ body: JSON.stringify({
123
+ model: "claude-sonnet-4-20250514",
124
+ max_tokens: 4096,
125
+ system: DREAMING_SYSTEM_PROMPT,
126
+ tools: [UPDATE_MEMORIES_TOOL],
127
+ tool_choice: { type: "tool", name: "update_memories" },
128
+ messages: [{ role: "user", content: truncatedMessage }]
129
+ })
130
+ });
131
+ if (!response.ok) {
132
+ const errText = await response.text().catch(() => "");
133
+ throw new Error(`Anthropic API error (${response.status}): ${errText}`);
134
+ }
135
+ const data = await response.json();
136
+ const toolUse = data.content.find(
137
+ (b) => b.type === "tool_use" && b.name === "update_memories"
138
+ );
139
+ const changes = toolUse?.input?.changes ?? [];
140
+ if (!dryRun && changes.length > 0) {
141
+ for (const change of changes) {
142
+ if (change.operation === "create" || change.operation === "update") {
143
+ if (change.content) {
144
+ createOrUpsertMemory(storeId, change.path, change.content, "dream");
145
+ }
146
+ } else if (change.operation === "delete") {
147
+ const existing = getMemoryByPath(storeId, change.path);
148
+ if (existing) {
149
+ deleteMemory(existing.id, "dream");
150
+ }
151
+ }
152
+ }
153
+ }
154
+ return {
155
+ sessionCount: sessions.length,
156
+ proposedChanges: changes,
157
+ applied: !dryRun && changes.length > 0
158
+ };
159
+ }
160
+
161
+ export {
162
+ extractSessionSummary,
163
+ reviewSessions
164
+ };
@@ -5,14 +5,14 @@ import {
5
5
  import {
6
6
  getDrizzle,
7
7
  init_drizzle
8
- } from "./chunk-PZNAQBHQ.js";
8
+ } from "./chunk-FILGQF2G.js";
9
9
  import {
10
10
  schema_exports
11
- } from "./chunk-ILHIHMO3.js";
11
+ } from "./chunk-VC5DELR4.js";
12
12
  import {
13
13
  getDb,
14
14
  init_client
15
- } from "./chunk-W3JMIUHV.js";
15
+ } from "./chunk-KQTTKYZY.js";
16
16
 
17
17
  // src/db/sync.ts
18
18
  init_drizzle();
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getConfig
3
- } from "./chunk-GQYSSSVA.js";
3
+ } from "./chunk-UGH5JDXX.js";
4
4
  import {
5
5
  serverBusy
6
6
  } from "./chunk-EZYKRG4W.js";
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  withGatewayPreamble
3
- } from "./chunk-FVBDEOTZ.js";
3
+ } from "./chunk-YE2RMJY7.js";
4
4
  import {
5
5
  resolveToolset
6
6
  } from "./chunk-XBHDQK4Z.js";
7
7
  import {
8
8
  getConfig
9
- } from "./chunk-GQYSSSVA.js";
9
+ } from "./chunk-UGH5JDXX.js";
10
10
 
11
11
  // src/backends/claude/args.ts
12
12
  function buildClaudeArgs(input) {
@@ -28,7 +28,7 @@ function buildClaudeArgs(input) {
28
28
  argv.push("--resume", input.claudeSessionId);
29
29
  }
30
30
  const tools = resolveToolset(input.agent.tools);
31
- let systemPrompt = withGatewayPreamble(input.agent.system);
31
+ let systemPrompt = withGatewayPreamble(input.agent.system, input.memoryStores);
32
32
  if (tools.customToolNames.size > 0) {
33
33
  const toolList = Array.from(tools.customToolNames).map((name) => `mcp__tool-bridge__${name}`).join(", ");
34
34
  systemPrompt += `
@@ -9,10 +9,10 @@ import {
9
9
  import {
10
10
  getDrizzle,
11
11
  init_drizzle
12
- } from "./chunk-PZNAQBHQ.js";
12
+ } from "./chunk-FILGQF2G.js";
13
13
  import {
14
14
  schema_exports
15
- } from "./chunk-ILHIHMO3.js";
15
+ } from "./chunk-VC5DELR4.js";
16
16
 
17
17
  // src/db/api_keys.ts
18
18
  init_drizzle();
@@ -4,11 +4,11 @@ import {
4
4
  getSources,
5
5
  getStats,
6
6
  searchSkills
7
- } from "./chunk-74E7GKUG.js";
7
+ } from "./chunk-TE6KCRPP.js";
8
8
  import {
9
9
  jsonOk,
10
10
  routeWrap
11
- } from "./chunk-T3IGOI6Z.js";
11
+ } from "./chunk-DTQ7J35Q.js";
12
12
 
13
13
  // src/handlers/skills.ts
14
14
  async function handleGetSkillsCatalog(request) {