@anthropic-ai/sdk 0.119.0 → 0.121.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 (466) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/helpers/beta/environments.d.mts +5 -4
  3. package/helpers/beta/environments.d.mts.map +1 -1
  4. package/helpers/beta/environments.d.ts +5 -4
  5. package/helpers/beta/environments.d.ts.map +1 -1
  6. package/helpers/beta/environments.js +5 -4
  7. package/helpers/beta/environments.js.map +1 -1
  8. package/helpers/beta/environments.mjs +5 -4
  9. package/helpers/beta/environments.mjs.map +1 -1
  10. package/helpers/beta/standard-schema.d.mts +45 -0
  11. package/helpers/beta/standard-schema.d.mts.map +1 -0
  12. package/helpers/beta/standard-schema.d.ts +45 -0
  13. package/helpers/beta/standard-schema.d.ts.map +1 -0
  14. package/helpers/beta/standard-schema.js +58 -0
  15. package/helpers/beta/standard-schema.js.map +1 -0
  16. package/helpers/beta/standard-schema.mjs +54 -0
  17. package/helpers/beta/standard-schema.mjs.map +1 -0
  18. package/internal/detect-platform.js +1 -1
  19. package/internal/detect-platform.js.map +1 -1
  20. package/internal/detect-platform.mjs +1 -1
  21. package/internal/detect-platform.mjs.map +1 -1
  22. package/internal/file-store.d.mts +136 -0
  23. package/internal/file-store.d.mts.map +1 -0
  24. package/internal/file-store.d.ts +136 -0
  25. package/internal/file-store.d.ts.map +1 -0
  26. package/internal/file-store.js +531 -0
  27. package/internal/file-store.js.map +1 -0
  28. package/internal/file-store.mjs +523 -0
  29. package/internal/file-store.mjs.map +1 -0
  30. package/internal/utils/values.d.mts +6 -0
  31. package/internal/utils/values.d.mts.map +1 -1
  32. package/internal/utils/values.d.ts +6 -0
  33. package/internal/utils/values.d.ts.map +1 -1
  34. package/internal/utils/values.js +7 -0
  35. package/internal/utils/values.js.map +1 -1
  36. package/internal/utils/values.mjs +6 -0
  37. package/internal/utils/values.mjs.map +1 -1
  38. package/lib/BetaMessageStream.d.mts.map +1 -1
  39. package/lib/BetaMessageStream.d.ts.map +1 -1
  40. package/lib/BetaMessageStream.js +3 -4
  41. package/lib/BetaMessageStream.js.map +1 -1
  42. package/lib/BetaMessageStream.mjs +1 -2
  43. package/lib/BetaMessageStream.mjs.map +1 -1
  44. package/lib/MessageStream.d.mts.map +1 -1
  45. package/lib/MessageStream.d.ts.map +1 -1
  46. package/lib/MessageStream.js +3 -4
  47. package/lib/MessageStream.js.map +1 -1
  48. package/lib/MessageStream.mjs +1 -2
  49. package/lib/MessageStream.mjs.map +1 -1
  50. package/lib/environments/poller.d.mts +6 -0
  51. package/lib/environments/poller.d.mts.map +1 -1
  52. package/lib/environments/poller.d.ts +6 -0
  53. package/lib/environments/poller.d.ts.map +1 -1
  54. package/lib/environments/poller.js +46 -1
  55. package/lib/environments/poller.js.map +1 -1
  56. package/lib/environments/poller.mjs +46 -1
  57. package/lib/environments/poller.mjs.map +1 -1
  58. package/lib/environments/worker.d.mts +89 -12
  59. package/lib/environments/worker.d.mts.map +1 -1
  60. package/lib/environments/worker.d.ts +89 -12
  61. package/lib/environments/worker.d.ts.map +1 -1
  62. package/lib/environments/worker.js +336 -67
  63. package/lib/environments/worker.js.map +1 -1
  64. package/lib/environments/worker.mjs +336 -68
  65. package/lib/environments/worker.mjs.map +1 -1
  66. package/lib/sessions/accumulate.d.mts.map +1 -1
  67. package/lib/sessions/accumulate.d.ts.map +1 -1
  68. package/lib/sessions/accumulate.js +3 -4
  69. package/lib/sessions/accumulate.js.map +1 -1
  70. package/lib/sessions/accumulate.mjs +1 -2
  71. package/lib/sessions/accumulate.mjs.map +1 -1
  72. package/lib/standard-schema.d.mts +131 -0
  73. package/lib/standard-schema.d.mts.map +1 -0
  74. package/lib/standard-schema.d.ts +131 -0
  75. package/lib/standard-schema.d.ts.map +1 -0
  76. package/lib/standard-schema.js +45 -0
  77. package/lib/standard-schema.js.map +1 -0
  78. package/lib/standard-schema.mjs +41 -0
  79. package/lib/standard-schema.mjs.map +1 -0
  80. package/lib/tools/BetaToolRunner.d.mts.map +1 -1
  81. package/lib/tools/BetaToolRunner.d.ts.map +1 -1
  82. package/lib/tools/BetaToolRunner.js +35 -6
  83. package/lib/tools/BetaToolRunner.js.map +1 -1
  84. package/lib/tools/BetaToolRunner.mjs +35 -6
  85. package/lib/tools/BetaToolRunner.mjs.map +1 -1
  86. package/package.json +2 -11
  87. package/resources/beta/agents/agents.d.mts +322 -27
  88. package/resources/beta/agents/agents.d.mts.map +1 -1
  89. package/resources/beta/agents/agents.d.ts +322 -27
  90. package/resources/beta/agents/agents.d.ts.map +1 -1
  91. package/resources/beta/agents/agents.js.map +1 -1
  92. package/resources/beta/agents/agents.mjs.map +1 -1
  93. package/resources/beta/agents/index.d.mts +1 -1
  94. package/resources/beta/agents/index.d.mts.map +1 -1
  95. package/resources/beta/agents/index.d.ts +1 -1
  96. package/resources/beta/agents/index.d.ts.map +1 -1
  97. package/resources/beta/agents/index.js.map +1 -1
  98. package/resources/beta/agents/index.mjs.map +1 -1
  99. package/resources/beta/beta.d.mts +7 -3
  100. package/resources/beta/beta.d.mts.map +1 -1
  101. package/resources/beta/beta.d.ts +7 -3
  102. package/resources/beta/beta.d.ts.map +1 -1
  103. package/resources/beta/beta.js +4 -0
  104. package/resources/beta/beta.js.map +1 -1
  105. package/resources/beta/beta.mjs +4 -0
  106. package/resources/beta/beta.mjs.map +1 -1
  107. package/resources/beta/environments/environments.d.mts +8 -1
  108. package/resources/beta/environments/environments.d.mts.map +1 -1
  109. package/resources/beta/environments/environments.d.ts +8 -1
  110. package/resources/beta/environments/environments.d.ts.map +1 -1
  111. package/resources/beta/environments/environments.js.map +1 -1
  112. package/resources/beta/environments/environments.mjs.map +1 -1
  113. package/resources/beta/environments/work.d.mts +5 -1
  114. package/resources/beta/environments/work.d.mts.map +1 -1
  115. package/resources/beta/environments/work.d.ts +5 -1
  116. package/resources/beta/environments/work.d.ts.map +1 -1
  117. package/resources/beta/environments/work.js +0 -17
  118. package/resources/beta/environments/work.js.map +1 -1
  119. package/resources/beta/environments/work.mjs +0 -17
  120. package/resources/beta/environments/work.mjs.map +1 -1
  121. package/resources/beta/index.d.mts +2 -1
  122. package/resources/beta/index.d.mts.map +1 -1
  123. package/resources/beta/index.d.ts +2 -1
  124. package/resources/beta/index.d.ts.map +1 -1
  125. package/resources/beta/index.js +11 -9
  126. package/resources/beta/index.js.map +1 -1
  127. package/resources/beta/index.mjs +1 -0
  128. package/resources/beta/index.mjs.map +1 -1
  129. package/resources/beta/memory-stores/memories.d.mts +6 -5
  130. package/resources/beta/memory-stores/memories.d.mts.map +1 -1
  131. package/resources/beta/memory-stores/memories.d.ts +6 -5
  132. package/resources/beta/memory-stores/memories.d.ts.map +1 -1
  133. package/resources/beta/memory-stores/memory-versions.d.mts +8 -5
  134. package/resources/beta/memory-stores/memory-versions.d.mts.map +1 -1
  135. package/resources/beta/memory-stores/memory-versions.d.ts +8 -5
  136. package/resources/beta/memory-stores/memory-versions.d.ts.map +1 -1
  137. package/resources/beta/messages/messages.d.mts +51 -9
  138. package/resources/beta/messages/messages.d.mts.map +1 -1
  139. package/resources/beta/messages/messages.d.ts +51 -9
  140. package/resources/beta/messages/messages.d.ts.map +1 -1
  141. package/resources/beta/messages/messages.js.map +1 -1
  142. package/resources/beta/messages/messages.mjs.map +1 -1
  143. package/resources/beta/organization/api-keys.d.mts +177 -0
  144. package/resources/beta/organization/api-keys.d.mts.map +1 -0
  145. package/resources/beta/organization/api-keys.d.ts +177 -0
  146. package/resources/beta/organization/api-keys.d.ts.map +1 -0
  147. package/resources/beta/organization/api-keys.js +56 -0
  148. package/resources/beta/organization/api-keys.js.map +1 -0
  149. package/resources/beta/organization/api-keys.mjs +52 -0
  150. package/resources/beta/organization/api-keys.mjs.map +1 -0
  151. package/resources/beta/organization/external-keys.d.mts +269 -0
  152. package/resources/beta/organization/external-keys.d.mts.map +1 -0
  153. package/resources/beta/organization/external-keys.d.ts +269 -0
  154. package/resources/beta/organization/external-keys.d.ts.map +1 -0
  155. package/resources/beta/organization/external-keys.js +119 -0
  156. package/resources/beta/organization/external-keys.js.map +1 -0
  157. package/resources/beta/organization/external-keys.mjs +115 -0
  158. package/resources/beta/organization/external-keys.mjs.map +1 -0
  159. package/resources/beta/organization/federation/federation.d.mts +14 -0
  160. package/resources/beta/organization/federation/federation.d.mts.map +1 -0
  161. package/resources/beta/organization/federation/federation.d.ts +14 -0
  162. package/resources/beta/organization/federation/federation.d.ts.map +1 -0
  163. package/resources/beta/organization/federation/federation.js +21 -0
  164. package/resources/beta/organization/federation/federation.js.map +1 -0
  165. package/resources/beta/organization/federation/federation.mjs +16 -0
  166. package/resources/beta/organization/federation/federation.mjs.map +1 -0
  167. package/resources/beta/organization/federation/index.d.mts +4 -0
  168. package/resources/beta/organization/federation/index.d.mts.map +1 -0
  169. package/resources/beta/organization/federation/index.d.ts +4 -0
  170. package/resources/beta/organization/federation/index.d.ts.map +1 -0
  171. package/resources/beta/organization/federation/index.js +11 -0
  172. package/resources/beta/organization/federation/index.js.map +1 -0
  173. package/resources/beta/organization/federation/index.mjs +5 -0
  174. package/resources/beta/organization/federation/index.mjs.map +1 -0
  175. package/resources/beta/organization/federation/issuers.d.mts +353 -0
  176. package/resources/beta/organization/federation/issuers.d.mts.map +1 -0
  177. package/resources/beta/organization/federation/issuers.d.ts +353 -0
  178. package/resources/beta/organization/federation/issuers.d.ts.map +1 -0
  179. package/resources/beta/organization/federation/issuers.js +169 -0
  180. package/resources/beta/organization/federation/issuers.js.map +1 -0
  181. package/resources/beta/organization/federation/issuers.mjs +165 -0
  182. package/resources/beta/organization/federation/issuers.mjs.map +1 -0
  183. package/resources/beta/organization/federation/rules/index.d.mts +3 -0
  184. package/resources/beta/organization/federation/rules/index.d.mts.map +1 -0
  185. package/resources/beta/organization/federation/rules/index.d.ts +3 -0
  186. package/resources/beta/organization/federation/rules/index.d.ts.map +1 -0
  187. package/resources/beta/organization/federation/rules/index.js +9 -0
  188. package/resources/beta/organization/federation/rules/index.js.map +1 -0
  189. package/resources/beta/organization/federation/rules/index.mjs +4 -0
  190. package/resources/beta/organization/federation/rules/index.mjs.map +1 -0
  191. package/resources/beta/organization/federation/rules/rules.d.mts +468 -0
  192. package/resources/beta/organization/federation/rules/rules.d.mts.map +1 -0
  193. package/resources/beta/organization/federation/rules/rules.d.ts +468 -0
  194. package/resources/beta/organization/federation/rules/rules.d.ts.map +1 -0
  195. package/resources/beta/organization/federation/rules/rules.js +198 -0
  196. package/resources/beta/organization/federation/rules/rules.js.map +1 -0
  197. package/resources/beta/organization/federation/rules/rules.mjs +193 -0
  198. package/resources/beta/organization/federation/rules/rules.mjs.map +1 -0
  199. package/resources/beta/organization/federation/rules/workspaces.d.mts +124 -0
  200. package/resources/beta/organization/federation/rules/workspaces.d.mts.map +1 -0
  201. package/resources/beta/organization/federation/rules/workspaces.d.ts +124 -0
  202. package/resources/beta/organization/federation/rules/workspaces.d.ts.map +1 -0
  203. package/resources/beta/organization/federation/rules/workspaces.js +114 -0
  204. package/resources/beta/organization/federation/rules/workspaces.js.map +1 -0
  205. package/resources/beta/organization/federation/rules/workspaces.mjs +110 -0
  206. package/resources/beta/organization/federation/rules/workspaces.mjs.map +1 -0
  207. package/resources/beta/organization/federation/rules.d.mts +2 -0
  208. package/resources/beta/organization/federation/rules.d.mts.map +1 -0
  209. package/resources/beta/organization/federation/rules.d.ts +2 -0
  210. package/resources/beta/organization/federation/rules.d.ts.map +1 -0
  211. package/resources/beta/organization/federation/rules.js +6 -0
  212. package/resources/beta/organization/federation/rules.js.map +1 -0
  213. package/resources/beta/organization/federation/rules.mjs +3 -0
  214. package/resources/beta/organization/federation/rules.mjs.map +1 -0
  215. package/resources/beta/organization/federation.d.mts +2 -0
  216. package/resources/beta/organization/federation.d.mts.map +1 -0
  217. package/resources/beta/organization/federation.d.ts +2 -0
  218. package/resources/beta/organization/federation.d.ts.map +1 -0
  219. package/resources/beta/organization/federation.js +6 -0
  220. package/resources/beta/organization/federation.js.map +1 -0
  221. package/resources/beta/organization/federation.mjs +3 -0
  222. package/resources/beta/organization/federation.mjs.map +1 -0
  223. package/resources/beta/organization/index.d.mts +10 -0
  224. package/resources/beta/organization/index.d.mts.map +1 -0
  225. package/resources/beta/organization/index.d.ts +10 -0
  226. package/resources/beta/organization/index.d.ts.map +1 -0
  227. package/resources/beta/organization/index.js +23 -0
  228. package/resources/beta/organization/index.js.map +1 -0
  229. package/resources/beta/organization/index.mjs +11 -0
  230. package/resources/beta/organization/index.mjs.map +1 -0
  231. package/resources/beta/organization/invites.d.mts +162 -0
  232. package/resources/beta/organization/invites.d.mts.map +1 -0
  233. package/resources/beta/organization/invites.d.ts +162 -0
  234. package/resources/beta/organization/invites.d.ts.map +1 -0
  235. package/resources/beta/organization/invites.js +76 -0
  236. package/resources/beta/organization/invites.js.map +1 -0
  237. package/resources/beta/organization/invites.mjs +72 -0
  238. package/resources/beta/organization/invites.mjs.map +1 -0
  239. package/resources/beta/organization/organization.d.mts +69 -0
  240. package/resources/beta/organization/organization.d.mts.map +1 -0
  241. package/resources/beta/organization/organization.d.ts +69 -0
  242. package/resources/beta/organization/organization.d.ts.map +1 -0
  243. package/resources/beta/organization/organization.js +58 -0
  244. package/resources/beta/organization/organization.js.map +1 -0
  245. package/resources/beta/organization/organization.mjs +53 -0
  246. package/resources/beta/organization/organization.mjs.map +1 -0
  247. package/resources/beta/organization/rate-limits.d.mts +78 -0
  248. package/resources/beta/organization/rate-limits.d.mts.map +1 -0
  249. package/resources/beta/organization/rate-limits.d.ts +78 -0
  250. package/resources/beta/organization/rate-limits.d.ts.map +1 -0
  251. package/resources/beta/organization/rate-limits.js +32 -0
  252. package/resources/beta/organization/rate-limits.js.map +1 -0
  253. package/resources/beta/organization/rate-limits.mjs +28 -0
  254. package/resources/beta/organization/rate-limits.mjs.map +1 -0
  255. package/resources/beta/organization/service-accounts/index.d.mts +3 -0
  256. package/resources/beta/organization/service-accounts/index.d.mts.map +1 -0
  257. package/resources/beta/organization/service-accounts/index.d.ts +3 -0
  258. package/resources/beta/organization/service-accounts/index.d.ts.map +1 -0
  259. package/resources/beta/organization/service-accounts/index.js +9 -0
  260. package/resources/beta/organization/service-accounts/index.js.map +1 -0
  261. package/resources/beta/organization/service-accounts/index.mjs +4 -0
  262. package/resources/beta/organization/service-accounts/index.mjs.map +1 -0
  263. package/resources/beta/organization/service-accounts/service-accounts.d.mts +258 -0
  264. package/resources/beta/organization/service-accounts/service-accounts.d.mts.map +1 -0
  265. package/resources/beta/organization/service-accounts/service-accounts.d.ts +258 -0
  266. package/resources/beta/organization/service-accounts/service-accounts.d.ts.map +1 -0
  267. package/resources/beta/organization/service-accounts/service-accounts.js +174 -0
  268. package/resources/beta/organization/service-accounts/service-accounts.js.map +1 -0
  269. package/resources/beta/organization/service-accounts/service-accounts.mjs +169 -0
  270. package/resources/beta/organization/service-accounts/service-accounts.mjs.map +1 -0
  271. package/resources/beta/organization/service-accounts/workspaces.d.mts +141 -0
  272. package/resources/beta/organization/service-accounts/workspaces.d.mts.map +1 -0
  273. package/resources/beta/organization/service-accounts/workspaces.d.ts +141 -0
  274. package/resources/beta/organization/service-accounts/workspaces.d.ts.map +1 -0
  275. package/resources/beta/organization/service-accounts/workspaces.js +125 -0
  276. package/resources/beta/organization/service-accounts/workspaces.js.map +1 -0
  277. package/resources/beta/organization/service-accounts/workspaces.mjs +121 -0
  278. package/resources/beta/organization/service-accounts/workspaces.mjs.map +1 -0
  279. package/resources/beta/organization/service-accounts.d.mts +2 -0
  280. package/resources/beta/organization/service-accounts.d.mts.map +1 -0
  281. package/resources/beta/organization/service-accounts.d.ts +2 -0
  282. package/resources/beta/organization/service-accounts.d.ts.map +1 -0
  283. package/resources/beta/organization/service-accounts.js +6 -0
  284. package/resources/beta/organization/service-accounts.js.map +1 -0
  285. package/resources/beta/organization/service-accounts.mjs +3 -0
  286. package/resources/beta/organization/service-accounts.mjs.map +1 -0
  287. package/resources/beta/organization/users.d.mts +124 -0
  288. package/resources/beta/organization/users.d.mts.map +1 -0
  289. package/resources/beta/organization/users.d.ts +124 -0
  290. package/resources/beta/organization/users.d.ts.map +1 -0
  291. package/resources/beta/organization/users.js +67 -0
  292. package/resources/beta/organization/users.js.map +1 -0
  293. package/resources/beta/organization/users.mjs +63 -0
  294. package/resources/beta/organization/users.mjs.map +1 -0
  295. package/resources/beta/organization/workspaces/index.d.mts +5 -0
  296. package/resources/beta/organization/workspaces/index.d.mts.map +1 -0
  297. package/resources/beta/organization/workspaces/index.d.ts +5 -0
  298. package/resources/beta/organization/workspaces/index.d.ts.map +1 -0
  299. package/resources/beta/organization/workspaces/index.js +13 -0
  300. package/resources/beta/organization/workspaces/index.js.map +1 -0
  301. package/resources/beta/organization/workspaces/index.mjs +6 -0
  302. package/resources/beta/organization/workspaces/index.mjs.map +1 -0
  303. package/resources/beta/organization/workspaces/members.d.mts +135 -0
  304. package/resources/beta/organization/workspaces/members.d.mts.map +1 -0
  305. package/resources/beta/organization/workspaces/members.d.ts +135 -0
  306. package/resources/beta/organization/workspaces/members.d.ts.map +1 -0
  307. package/resources/beta/organization/workspaces/members.js +102 -0
  308. package/resources/beta/organization/workspaces/members.js.map +1 -0
  309. package/resources/beta/organization/workspaces/members.mjs +98 -0
  310. package/resources/beta/organization/workspaces/members.mjs.map +1 -0
  311. package/resources/beta/organization/workspaces/rate-limits.d.mts +84 -0
  312. package/resources/beta/organization/workspaces/rate-limits.d.mts.map +1 -0
  313. package/resources/beta/organization/workspaces/rate-limits.d.ts +84 -0
  314. package/resources/beta/organization/workspaces/rate-limits.d.ts.map +1 -0
  315. package/resources/beta/organization/workspaces/rate-limits.js +35 -0
  316. package/resources/beta/organization/workspaces/rate-limits.js.map +1 -0
  317. package/resources/beta/organization/workspaces/rate-limits.mjs +31 -0
  318. package/resources/beta/organization/workspaces/rate-limits.mjs.map +1 -0
  319. package/resources/beta/organization/workspaces/service-accounts.d.mts +210 -0
  320. package/resources/beta/organization/workspaces/service-accounts.d.mts.map +1 -0
  321. package/resources/beta/organization/workspaces/service-accounts.d.ts +210 -0
  322. package/resources/beta/organization/workspaces/service-accounts.d.ts.map +1 -0
  323. package/resources/beta/organization/workspaces/service-accounts.js +189 -0
  324. package/resources/beta/organization/workspaces/service-accounts.js.map +1 -0
  325. package/resources/beta/organization/workspaces/service-accounts.mjs +185 -0
  326. package/resources/beta/organization/workspaces/service-accounts.mjs.map +1 -0
  327. package/resources/beta/organization/workspaces/workspaces.d.mts +287 -0
  328. package/resources/beta/organization/workspaces/workspaces.d.mts.map +1 -0
  329. package/resources/beta/organization/workspaces/workspaces.d.ts +287 -0
  330. package/resources/beta/organization/workspaces/workspaces.d.ts.map +1 -0
  331. package/resources/beta/organization/workspaces/workspaces.js +112 -0
  332. package/resources/beta/organization/workspaces/workspaces.js.map +1 -0
  333. package/resources/beta/organization/workspaces/workspaces.mjs +107 -0
  334. package/resources/beta/organization/workspaces/workspaces.mjs.map +1 -0
  335. package/resources/beta/organization/workspaces.d.mts +2 -0
  336. package/resources/beta/organization/workspaces.d.mts.map +1 -0
  337. package/resources/beta/organization/workspaces.d.ts +2 -0
  338. package/resources/beta/organization/workspaces.d.ts.map +1 -0
  339. package/resources/beta/organization/workspaces.js +6 -0
  340. package/resources/beta/organization/workspaces.js.map +1 -0
  341. package/resources/beta/organization/workspaces.mjs +3 -0
  342. package/resources/beta/organization/workspaces.mjs.map +1 -0
  343. package/resources/beta/organization.d.mts +2 -0
  344. package/resources/beta/organization.d.mts.map +1 -0
  345. package/resources/beta/organization.d.ts +2 -0
  346. package/resources/beta/organization.d.ts.map +1 -0
  347. package/resources/beta/organization.js +6 -0
  348. package/resources/beta/organization.js.map +1 -0
  349. package/resources/beta/organization.mjs +3 -0
  350. package/resources/beta/organization.mjs.map +1 -0
  351. package/resources/beta/sessions/threads/threads.d.mts +2 -1
  352. package/resources/beta/sessions/threads/threads.d.mts.map +1 -1
  353. package/resources/beta/sessions/threads/threads.d.ts +2 -1
  354. package/resources/beta/sessions/threads/threads.d.ts.map +1 -1
  355. package/resources/beta/sessions/threads/threads.js.map +1 -1
  356. package/resources/beta/sessions/threads/threads.mjs.map +1 -1
  357. package/resources/messages/messages.d.mts +1 -1
  358. package/resources/messages/messages.d.ts +1 -1
  359. package/src/helpers/beta/environments.ts +5 -4
  360. package/src/helpers/beta/standard-schema.ts +99 -0
  361. package/src/internal/detect-platform.ts +1 -1
  362. package/src/internal/file-store.ts +550 -0
  363. package/src/internal/utils/values.ts +7 -0
  364. package/src/lib/BetaMessageStream.ts +1 -3
  365. package/src/lib/MessageStream.ts +1 -3
  366. package/src/lib/environments/poller.ts +47 -1
  367. package/src/lib/environments/worker.ts +419 -79
  368. package/src/lib/sessions/accumulate.ts +1 -3
  369. package/src/lib/standard-schema.ts +209 -0
  370. package/src/lib/tools/BetaToolRunner.ts +38 -6
  371. package/src/resources/beta/agents/agents.ts +435 -30
  372. package/src/resources/beta/agents/index.ts +17 -0
  373. package/src/resources/beta/beta.ts +52 -1
  374. package/src/resources/beta/environments/environments.ts +8 -1
  375. package/src/resources/beta/environments/work.ts +7 -0
  376. package/src/resources/beta/index.ts +18 -0
  377. package/src/resources/beta/memory-stores/memories.ts +6 -5
  378. package/src/resources/beta/memory-stores/memory-versions.ts +8 -5
  379. package/src/resources/beta/messages/messages.ts +51 -9
  380. package/src/resources/beta/organization/api-keys.ts +231 -0
  381. package/src/resources/beta/organization/external-keys.ts +362 -0
  382. package/src/resources/beta/organization/federation/federation.ts +71 -0
  383. package/src/resources/beta/organization/federation/index.ts +31 -0
  384. package/src/resources/beta/organization/federation/issuers.ts +486 -0
  385. package/src/resources/beta/organization/federation/rules/index.ts +23 -0
  386. package/src/resources/beta/organization/federation/rules/rules.ts +624 -0
  387. package/src/resources/beta/organization/federation/rules/workspaces.ts +196 -0
  388. package/src/resources/beta/organization/federation/rules.ts +3 -0
  389. package/src/resources/beta/organization/federation.ts +3 -0
  390. package/src/resources/beta/organization/index.ts +83 -0
  391. package/src/resources/beta/organization/invites.ts +207 -0
  392. package/src/resources/beta/organization/organization.ts +245 -0
  393. package/src/resources/beta/organization/rate-limits.ts +105 -0
  394. package/src/resources/beta/organization/service-accounts/index.ts +21 -0
  395. package/src/resources/beta/organization/service-accounts/service-accounts.ts +389 -0
  396. package/src/resources/beta/organization/service-accounts/workspaces.ts +217 -0
  397. package/src/resources/beta/organization/service-accounts.ts +3 -0
  398. package/src/resources/beta/organization/users.ts +163 -0
  399. package/src/resources/beta/organization/workspaces/index.ts +43 -0
  400. package/src/resources/beta/organization/workspaces/members.ts +209 -0
  401. package/src/resources/beta/organization/workspaces/rate-limits.ts +114 -0
  402. package/src/resources/beta/organization/workspaces/service-accounts.ts +325 -0
  403. package/src/resources/beta/organization/workspaces/workspaces.ts +434 -0
  404. package/src/resources/beta/organization/workspaces.ts +3 -0
  405. package/src/resources/beta/organization.ts +3 -0
  406. package/src/resources/beta/sessions/threads/threads.ts +2 -1
  407. package/src/resources/messages/messages.ts +1 -1
  408. package/src/tools/agent-toolset/fs-util.ts +40 -24
  409. package/src/tools/agent-toolset/memories.ts +1017 -0
  410. package/src/tools/agent-toolset/node.browser.ts +69 -1
  411. package/src/tools/agent-toolset/node.ts +143 -57
  412. package/src/tools/agent-toolset/skills.ts +29 -9
  413. package/src/tools/agent-toolset/sync-interval.ts +30 -0
  414. package/src/version.ts +1 -1
  415. package/tools/agent-toolset/fs-util.d.mts +23 -10
  416. package/tools/agent-toolset/fs-util.d.mts.map +1 -1
  417. package/tools/agent-toolset/fs-util.d.ts +23 -10
  418. package/tools/agent-toolset/fs-util.d.ts.map +1 -1
  419. package/tools/agent-toolset/fs-util.js +40 -25
  420. package/tools/agent-toolset/fs-util.js.map +1 -1
  421. package/tools/agent-toolset/fs-util.mjs +38 -25
  422. package/tools/agent-toolset/fs-util.mjs.map +1 -1
  423. package/tools/agent-toolset/memories.d.mts +173 -0
  424. package/tools/agent-toolset/memories.d.mts.map +1 -0
  425. package/tools/agent-toolset/memories.d.ts +173 -0
  426. package/tools/agent-toolset/memories.d.ts.map +1 -0
  427. package/tools/agent-toolset/memories.js +902 -0
  428. package/tools/agent-toolset/memories.js.map +1 -0
  429. package/tools/agent-toolset/memories.mjs +895 -0
  430. package/tools/agent-toolset/memories.mjs.map +1 -0
  431. package/tools/agent-toolset/node.browser.d.mts +32 -1
  432. package/tools/agent-toolset/node.browser.d.mts.map +1 -1
  433. package/tools/agent-toolset/node.browser.d.ts +32 -1
  434. package/tools/agent-toolset/node.browser.d.ts.map +1 -1
  435. package/tools/agent-toolset/node.browser.js +59 -1
  436. package/tools/agent-toolset/node.browser.js.map +1 -1
  437. package/tools/agent-toolset/node.browser.mjs +54 -0
  438. package/tools/agent-toolset/node.browser.mjs.map +1 -1
  439. package/tools/agent-toolset/node.d.mts +56 -24
  440. package/tools/agent-toolset/node.d.mts.map +1 -1
  441. package/tools/agent-toolset/node.d.ts +56 -24
  442. package/tools/agent-toolset/node.d.ts.map +1 -1
  443. package/tools/agent-toolset/node.js +83 -44
  444. package/tools/agent-toolset/node.js.map +1 -1
  445. package/tools/agent-toolset/node.mjs +77 -44
  446. package/tools/agent-toolset/node.mjs.map +1 -1
  447. package/tools/agent-toolset/skills.d.mts +16 -7
  448. package/tools/agent-toolset/skills.d.mts.map +1 -1
  449. package/tools/agent-toolset/skills.d.ts +16 -7
  450. package/tools/agent-toolset/skills.d.ts.map +1 -1
  451. package/tools/agent-toolset/skills.js +27 -9
  452. package/tools/agent-toolset/skills.js.map +1 -1
  453. package/tools/agent-toolset/skills.mjs +27 -9
  454. package/tools/agent-toolset/skills.mjs.map +1 -1
  455. package/tools/agent-toolset/sync-interval.d.mts +19 -0
  456. package/tools/agent-toolset/sync-interval.d.mts.map +1 -0
  457. package/tools/agent-toolset/sync-interval.d.ts +19 -0
  458. package/tools/agent-toolset/sync-interval.d.ts.map +1 -0
  459. package/tools/agent-toolset/sync-interval.js +29 -0
  460. package/tools/agent-toolset/sync-interval.js.map +1 -0
  461. package/tools/agent-toolset/sync-interval.mjs +25 -0
  462. package/tools/agent-toolset/sync-interval.mjs.map +1 -0
  463. package/version.d.mts +1 -1
  464. package/version.d.ts +1 -1
  465. package/version.js +1 -1
  466. package/version.mjs +1 -1
@@ -1,11 +1,14 @@
1
- import { AnthropicError } from '../../core/error';
1
+ import { AnthropicError, APIError } from '../../core/error';
2
2
  import type { Anthropic } from '../../client';
3
- import type { BetaSelfHostedWork } from '../../resources/beta/environments/work';
3
+ import type { BetaSelfHostedWork, BetaWorkSecret } from '../../resources/beta/environments/work';
4
4
  import { loggerFor, type Logger } from '../../internal/utils/log';
5
+ import { fromBase64 } from '../../internal/utils/base64';
6
+ import { decodeUTF8 } from '../../internal/utils/bytes';
5
7
  import { readEnv } from '../../internal/utils/env';
6
8
  import { sleep } from '../../internal/utils/sleep';
7
9
  import { isFatal4xx, isStatus } from '../../internal/utils/backoff';
8
10
  import { linkAbort } from '../../internal/utils/abort';
11
+ import { isObj } from '../../internal/utils/values';
9
12
  import { buildHeaders } from '../../internal/headers';
10
13
  import type { BetaRunnableTool } from '../tools/BetaRunnableTool';
11
14
  import type { BetaToolRunnerRequestOptions } from '../tools/BetaToolRunner';
@@ -18,7 +21,9 @@ import { copyClientForHelper } from '../helper-client';
18
21
  // per-item handler. That keeps this file free of Node-only deps in the static
19
22
  // import graph, which is what lets `client.beta.environments.work.worker()`
20
23
  // exist as a resource method without pulling Node built-ins into the SDK core.
21
- import type { AgentToolContext } from '../../tools/agent-toolset/node';
24
+ import type { AgentToolContext, MemoryDeleteMode, SessionMemoryStores } from '../../tools/agent-toolset/node';
25
+ import { checkMemorySyncInterval } from '../../tools/agent-toolset/sync-interval';
26
+ import type { BetaManagedAgentsSession } from '../../resources/beta/sessions/sessions';
22
27
 
23
28
  const HEARTBEAT_DEFAULT_MS = 30_000;
24
29
  const HEARTBEAT_TTL_DEFAULT_MS = 90_000;
@@ -42,10 +47,11 @@ export interface EnvironmentWorkerOptions {
42
47
  */
43
48
  environmentId?: string;
44
49
  /**
45
- * The environment key — the single credential for the runner. It authenticates
46
- * the work-poll calls and every per-session call (event stream, lease
47
- * heartbeat, force-stop). Required by {@link EnvironmentWorker.run}; falls back
48
- * to `ANTHROPIC_ENVIRONMENT_KEY` in {@link EnvironmentWorker.handleItem}.
50
+ * The environment key — the worker's standing credential: polling always
51
+ * uses it, and per-session calls fall back to it when a claimed item's
52
+ * `secret` doesn't yield a sessions token. Required by
53
+ * {@link EnvironmentWorker.run}; falls back to `ANTHROPIC_ENVIRONMENT_KEY` in
54
+ * {@link EnvironmentWorker.handleItem}.
49
55
  */
50
56
  environmentKey?: string;
51
57
  /**
@@ -60,12 +66,41 @@ export interface EnvironmentWorkerOptions {
60
66
  tools?: EnvironmentWorkerTools;
61
67
  /** Base directory for the per-session {@link AgentToolContext}. Defaults to `process.cwd()`. */
62
68
  workdir?: string;
63
- /** Forwarded to the per-session {@link AgentToolContext}. */
69
+ /**
70
+ * @deprecated No longer accepted: the file tools are always confined to
71
+ * `workdir` plus `allowedRoots`, which is neither behavior this flag used to
72
+ * select, so passing either value throws. Remove it; list extra directories
73
+ * in {@link AgentToolContext.allowedRoots}. The property is removed in a
74
+ * future release.
75
+ */
64
76
  unrestrictedPaths?: boolean;
65
77
  /** Forwarded to the per-session {@link AgentToolContext} (`maxFileBytes`). */
66
78
  maxFileBytes?: number | null;
67
79
  /** Forwarded to {@link SessionToolRunner} (`maxIdleMs`). */
68
80
  maxIdleMs?: number;
81
+ /**
82
+ * How often (milliseconds) to sync the session's attached memory stores back
83
+ * while it runs — checked after each dispatched tool call, plus one final
84
+ * sync when the session ends cleanly. Defaults to
85
+ * `DEFAULT_MEMORY_SYNC_INTERVAL_MS` (15s); the constructor throws for
86
+ * values below `MIN_MEMORY_SYNC_INTERVAL_MS` (5s). Every teardown also runs
87
+ * a push-only flush of changed files; that flush and the final sync are
88
+ * each bounded by `MEMORY_FLUSH_TIMEOUT_MS`, and a warning is logged when
89
+ * either bound cuts work off. `null` disables memory download and sync
90
+ * entirely. Memory stores are only touched for work items whose `secret`
91
+ * carries a `sessions_token`; while sync is enabled, an item without one
92
+ * fails when its session has memory stores attached, because those stores
93
+ * cannot be mounted without the token. With `null` the same item runs,
94
+ * without memory, and nothing is logged — turning sync off is the
95
+ * operator's explicit choice.
96
+ */
97
+ memorySyncIntervalMs?: number | null;
98
+ /**
99
+ * Whether local file deletions may delete on the server — see
100
+ * {@link MemoryDeleteMode}. Uploads and pulls are unaffected.
101
+ * Defaults to `"enabled"`.
102
+ */
103
+ memorySyncDeletions?: MemoryDeleteMode;
69
104
  /** Forwarded to the {@link WorkPoller}. */
70
105
  workerId?: string;
71
106
  /** External abort signal; aborting it ends the run. */
@@ -100,12 +135,62 @@ export interface HandleItemOptions {
100
135
  * `ANTHROPIC_ENVIRONMENT_KEY`.
101
136
  */
102
137
  environmentKey?: string;
138
+ /**
139
+ * The work item's per-item `secret` payload from the poll response. Falls
140
+ * back to `ANTHROPIC_WORK_SECRET`. Unlike the others it is optional — when
141
+ * present, the sessions token extracted from it is preferred as the Bearer
142
+ * credential for this item's heartbeat / force-stop / skill-download /
143
+ * session calls; when absent (or undecodable) those calls use the
144
+ * environment key.
145
+ */
146
+ workSecret?: string;
103
147
  /** External abort signal; aborting it ends the run. Defaults to the constructor's signal. */
104
148
  signal?: AbortSignal;
105
149
  }
106
150
 
107
- /** The fields of {@link BetaSelfHostedWork} the per-item flow reads. */
108
- type ClaimedWork = Pick<BetaSelfHostedWork, 'id' | 'environment_id' | 'data'>;
151
+ /**
152
+ * The fields of {@link BetaSelfHostedWork} the per-item flow reads. `secret` is
153
+ * declared here rather than picked because the generated model does not carry
154
+ * it — only the poll response populates it.
155
+ */
156
+ type ClaimedWork = Pick<BetaSelfHostedWork, 'id' | 'environment_id' | 'data'> & {
157
+ secret?: string | null;
158
+ };
159
+
160
+ /** True when the session has at least one memory store attached. */
161
+ function hasMemoryStore(session: BetaManagedAgentsSession): boolean {
162
+ return session.resources.some((r) => r.type === 'memory_store');
163
+ }
164
+
165
+ /**
166
+ * Extract the per-item sessions token from a work item's `secret` payload.
167
+ *
168
+ * The `secret` the poll response populates is not itself a credential: it is a
169
+ * URL-safe base64 JSON payload matching {@link BetaWorkSecret} — the
170
+ * `sessions_token` (the bearer for this item's work lifecycle and
171
+ * session-level calls) plus fields this worker does not consume. Returns the
172
+ * sessions token, or `null` (meaning: fall back to the environment key) when
173
+ * the payload is missing, doesn't decode, or carries no token. Never log the
174
+ * payload or anything extracted from it.
175
+ */
176
+ export function sessionsTokenFromSecret(secret: string | null | undefined): string | null {
177
+ if (!secret) return null;
178
+ let parsed: unknown;
179
+ try {
180
+ // The payload may arrive URL-safe and without base64 padding; normalize
181
+ // both before decoding.
182
+ const normalized = secret.replace(/-/g, '+').replace(/_/g, '/');
183
+ const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
184
+ parsed = JSON.parse(decodeUTF8(fromBase64(padded)));
185
+ } catch {
186
+ return null;
187
+ }
188
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
189
+ // The payload is untrusted input, so the token is still checked at runtime
190
+ // rather than trusted to match the schema.
191
+ const token = (parsed as Partial<BetaWorkSecret>).sessions_token;
192
+ return typeof token === 'string' && token !== '' ? token : null;
193
+ }
109
194
 
110
195
  /**
111
196
  * The self-hosted environment runner, composed from the control-plane
@@ -115,9 +200,17 @@ type ClaimedWork = Pick<BetaSelfHostedWork, 'id' | 'environment_id' | 'data'>;
115
200
  * {@link AgentToolContext}, downloads the session agent's skills
116
201
  * (`setupSkills`), then runs a {@link SessionToolRunner} for the session
117
202
  * while heartbeating the work-item lease on the same event loop; on exit it
118
- * force-stops the work item, cleans up the downloaded skills, and loops to the
119
- * next one. The lease heartbeat reports `state === "stopping"` / a lost lease
120
- * back into the run by aborting the session runner.
203
+ * force-stops the work item (unless the lease was lost, in which case the item
204
+ * is left to whoever holds it now), cleans up the downloaded skills, and loops
205
+ * to the next one. The lease heartbeat reports `state === "stopping"` / a lost
206
+ * lease back into the run by aborting the session runner.
207
+ *
208
+ * The `environmentKey` is the worker's standing credential. When a claimed
209
+ * work item carries a per-item `secret` (a short-lived payload the poll
210
+ * response may populate), the sessions token extracted from it is preferred
211
+ * over the environment key for that item's heartbeat / force-stop /
212
+ * skill-download / session calls; polling itself always uses the environment
213
+ * key, and items without a usable secret fall back to it entirely.
121
214
  *
122
215
  * Use {@link EnvironmentWorker.handleItem} if you already hold a claimed work
123
216
  * item (e.g. a `worker poll --on-work` script handed one to a fresh process) and
@@ -144,22 +237,42 @@ export class EnvironmentWorker {
144
237
  readonly environmentKey: string | undefined;
145
238
  readonly tools: EnvironmentWorkerTools | undefined;
146
239
  readonly workdir: string;
240
+ /** @deprecated Never set; see {@link EnvironmentWorkerOptions.unrestrictedPaths}. */
147
241
  readonly unrestrictedPaths: boolean | undefined;
148
242
  readonly maxFileBytes: number | null | undefined;
149
243
  readonly maxIdleMs: number | undefined;
244
+ readonly memorySyncIntervalMs: number | null | undefined;
245
+ readonly memorySyncDeletions: MemoryDeleteMode;
150
246
  readonly workerId: string | undefined;
151
247
  readonly requestOptions: BetaToolRunnerRequestOptions | undefined;
152
248
  readonly #signal: AbortSignal | undefined;
153
249
 
250
+ constructor(opts: Omit<EnvironmentWorkerOptions, 'unrestrictedPaths'>);
251
+ /** @deprecated `unrestrictedPaths` is no longer accepted — see {@link EnvironmentWorkerOptions.unrestrictedPaths}. */
252
+ constructor(opts: Omit<EnvironmentWorkerOptions, 'unrestrictedPaths'> & { unrestrictedPaths: boolean }); // help language servers see deprecation
154
253
  constructor(opts: EnvironmentWorkerOptions) {
254
+ if (opts.unrestrictedPaths !== undefined) {
255
+ throw new AnthropicError(
256
+ 'The `unrestrictedPaths` option you passed to EnvironmentWorker (or ' +
257
+ 'client.beta.environments.work.worker()) is no longer supported. ' +
258
+ "The worker's file tools (read, write, edit, glob, grep) are now always confined to `workdir` " +
259
+ "plus the session's memory folders. Remove `unrestrictedPaths` from your options; to let the " +
260
+ 'file tools reach any other directory, add it to `AgentToolContext.allowedRoots` from a ' +
261
+ '`tools` factory.',
262
+ );
263
+ }
155
264
  this.client = opts.client;
156
265
  this.environmentId = opts.environmentId;
157
266
  this.environmentKey = opts.environmentKey;
158
267
  this.tools = opts.tools;
159
268
  this.workdir = opts.workdir ?? process.cwd();
160
- this.unrestrictedPaths = opts.unrestrictedPaths;
161
269
  this.maxFileBytes = opts.maxFileBytes;
162
270
  this.maxIdleMs = opts.maxIdleMs;
271
+ if (opts.memorySyncIntervalMs != null) {
272
+ checkMemorySyncInterval(opts.memorySyncIntervalMs, 'memorySyncIntervalMs');
273
+ }
274
+ this.memorySyncIntervalMs = opts.memorySyncIntervalMs;
275
+ this.memorySyncDeletions = opts.memorySyncDeletions ?? 'enabled';
163
276
  this.workerId = opts.workerId;
164
277
  this.requestOptions = opts.requestOptions;
165
278
  this.#signal = opts.signal;
@@ -185,13 +298,23 @@ export class EnvironmentWorker {
185
298
  ...(this.workerId !== undefined ? { workerId: this.workerId } : {}),
186
299
  ...(externalSignal ? { signal: externalSignal } : {}),
187
300
  ...(this.requestOptions !== undefined ? { requestOptions: this.requestOptions } : {}),
188
- // The per-item handler force-stops every work item on exit; let it be the
189
- // single owner of `work.stop` rather than double-posting from the poller.
301
+ // The per-item handler stops or releases every work item on exit; let it
302
+ // be the single owner of `work.stop` rather than double-posting from the
303
+ // poller.
190
304
  autoStop: false,
191
305
  });
192
306
 
193
307
  for await (const work of poller) {
194
- await this.#handleItem(work, environmentKey, poller.signal);
308
+ try {
309
+ await this.#handleItem(work, environmentKey, poller.signal);
310
+ } catch (e) {
311
+ // One bad item fails that item, not the worker: the handler's teardown
312
+ // already stopped or released it, so the next poll claims the next
313
+ // item. A store directory left behind by a killed worker would
314
+ // otherwise crashloop this process forever.
315
+ if (poller.signal?.aborted) throw e;
316
+ loggerFor(this.client).error('work item failed', { work_id: work.id, error: String(e) });
317
+ }
195
318
  }
196
319
  }
197
320
 
@@ -201,7 +324,9 @@ export class EnvironmentWorker {
201
324
  * download the session agent's skills (`setupSkills`), run a
202
325
  * {@link SessionToolRunner} for the session while heartbeating the work-item
203
326
  * lease, and force-stop the work item on exit (whether the runner finishes
204
- * normally, throws, or the heartbeat loop signals shutdown).
327
+ * normally, throws, or the control plane signals shutdown). The one
328
+ * exception is a lost lease: the item then belongs to the queue or another
329
+ * worker and is left alone.
205
330
  *
206
331
  * Use this when something else does the claiming — e.g. a `worker poll
207
332
  * --on-work` script that hands an already-claimed item to a fresh process. The
@@ -211,7 +336,16 @@ export class EnvironmentWorker {
211
336
  * option, then the worker's own `environmentKey`, then
212
337
  * `ANTHROPIC_ENVIRONMENT_KEY`. With no arguments inside that command it just
213
338
  * works. Throws a clear error naming the first of the four required values
214
- * still missing after resolution.
339
+ * still missing after resolution. Throws `SessionMemoryError` when the
340
+ * session has memory stores attached but they cannot be mounted — the work
341
+ * item carried no sessions token (unless `memorySyncIntervalMs` turned
342
+ * memory off), or a store failed to download.
343
+ *
344
+ * `workSecret` is the work item's per-item `secret` payload from the poll
345
+ * response, falling back to `ANTHROPIC_WORK_SECRET`; unlike the others it is
346
+ * optional — when present, the sessions token extracted from it is preferred
347
+ * as the Bearer credential for this item's heartbeat / force-stop / session
348
+ * calls; when absent (or undecodable) those calls use the environment key.
215
349
  */
216
350
  async handleItem(opts?: HandleItemOptions): Promise<void> {
217
351
  const workId = opts?.workId ?? readEnv('ANTHROPIC_WORK_ID');
@@ -219,6 +353,9 @@ export class EnvironmentWorker {
219
353
  const sessionId = opts?.sessionId ?? readEnv('ANTHROPIC_SESSION_ID');
220
354
  const environmentKey =
221
355
  opts?.environmentKey ?? this.environmentKey ?? readEnv('ANTHROPIC_ENVIRONMENT_KEY');
356
+ // `||` rather than `??` so an empty option still falls through to the env
357
+ // var and then to null (matching how `readEnv` treats empty values).
358
+ const workSecret = opts?.workSecret || readEnv('ANTHROPIC_WORK_SECRET') || null;
222
359
 
223
360
  if (!workId) {
224
361
  throw new AnthropicError('handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID');
@@ -240,6 +377,7 @@ export class EnvironmentWorker {
240
377
  const work: ClaimedWork = {
241
378
  id: workId,
242
379
  environment_id: environmentId,
380
+ secret: workSecret,
243
381
  data: { type: 'session', id: sessionId },
244
382
  };
245
383
  await this.#handleItem(work, environmentKey, opts?.signal ?? this.#signal);
@@ -248,8 +386,14 @@ export class EnvironmentWorker {
248
386
  /**
249
387
  * The per-item body shared by {@link EnvironmentWorker.run}'s poll loop and
250
388
  * {@link EnvironmentWorker.handleItem}: run a {@link SessionToolRunner} for the
251
- * work item's session while heartbeating its lease, force-stopping on exit.
252
- * Non-session work items are ignored.
389
+ * work item's session while heartbeating its lease, force-stopping on exit
390
+ * unless the lease was lost. Non-session work items are ignored.
391
+ *
392
+ * When the poll response carried a per-item `secret` (a short-lived payload
393
+ * scoped to this work item), the sessions token extracted from it is
394
+ * preferred over `environmentKey` as the Bearer credential for those
395
+ * per-item calls; a missing/undecodable secret falls back to
396
+ * `environmentKey` unchanged.
253
397
  */
254
398
  async #handleItem(
255
399
  work: ClaimedWork,
@@ -257,14 +401,27 @@ export class EnvironmentWorker {
257
401
  externalSignal: AbortSignal | undefined,
258
402
  ): Promise<void> {
259
403
  const log = loggerFor(this.client);
404
+ // The per-item credential: the sessions token carried inside the work
405
+ // item's secret payload when the server issued one, otherwise the
406
+ // environment key. Never log this value.
407
+ const sessionsToken = sessionsTokenFromSecret(work.secret);
408
+ if (work.secret && sessionsToken === null) {
409
+ log.warn(
410
+ 'work item carried a secret payload but no sessions token could be extracted; ' +
411
+ 'falling back to the environment key',
412
+ { work_id: work.id },
413
+ );
414
+ }
415
+ const itemCredential = sessionsToken ?? environmentKey;
260
416
  // Every per-session call — the SessionToolRunner event stream/list/send, the
261
- // lease heartbeat, and the work force-stop — authenticates with the
262
- // environment key. Scope a client to it once and thread that through.
263
- // `copyClientForHelper` also clears the parent's `apiKey`, so the sub-client
264
- // emits *only* the bearer credential on the wire (a plain
265
- // `withOptions({authToken})` would leave `X-Api-Key` set as well).
417
+ // lease heartbeat, the skill download, and the work force-stop —
418
+ // authenticates with the per-item credential. Scope a client to it once and
419
+ // thread that through. `copyClientForHelper` also clears the parent's
420
+ // `apiKey`, so the sub-client emits *only* the bearer credential on the
421
+ // wire (a plain `withOptions({authToken})` would leave `X-Api-Key` set as
422
+ // well).
266
423
  const sessionClient = copyClientForHelper(this.client, {
267
- authToken: environmentKey,
424
+ authToken: itemCredential,
268
425
  helper: 'environments-worker',
269
426
  });
270
427
 
@@ -272,68 +429,191 @@ export class EnvironmentWorker {
272
429
  // single owner of `work.stop` for every claimed item.
273
430
  const sessionId = work.data.id;
274
431
 
275
- const ctx: AgentToolContext = {
276
- workdir: this.workdir,
277
- client: this.client,
278
- sessionId,
279
- ...(this.unrestrictedPaths !== undefined ? { unrestrictedPaths: this.unrestrictedPaths } : {}),
280
- ...(this.maxFileBytes !== undefined ? { maxFileBytes: this.maxFileBytes } : {}),
281
- };
282
- // Lazily load the Node-only toolset module — see the import note at the top.
283
- const agentToolset = await import('../../tools/agent-toolset/node');
284
- let cleanupSkills: () => Promise<void> = async () => {};
285
- try {
286
- cleanupSkills = await agentToolset.setupSkills(ctx);
287
- } catch (e) {
288
- log.warn('skill setup failed', { session_id: sessionId, work_id: work.id, error: String(e) });
289
- }
290
- const tools =
291
- typeof this.tools === 'function' ?
292
- this.tools(ctx)
293
- : this.tools ?? agentToolset.betaAgentToolset20260401(ctx);
294
-
295
432
  // A per-session controller: aborts when the supplied signal aborts, when the
296
433
  // session runner finishes, or when the lease heartbeat says to stop.
297
434
  const ctrl = new AbortController();
298
435
  const detachExternal = linkAbort(externalSignal, ctrl);
436
+ const lease = new Lease(ctrl);
299
437
 
300
- // Inert until iterated below.
301
- const runner = new SessionToolRunner(sessionId, {
302
- client: sessionClient,
303
- tools,
304
- ...(this.maxIdleMs !== undefined ? { maxIdleMs: this.maxIdleMs } : {}),
305
- ...(this.requestOptions !== undefined ? { requestOptions: this.requestOptions } : {}),
306
- signal: ctrl.signal,
307
- });
438
+ // Lazily load the Node-only toolset module — see the import note at the top.
439
+ const agentToolset = await import('../../tools/agent-toolset/node');
308
440
 
441
+ // Start the lease heartbeat BEFORE the session fetch and the skill /
442
+ // memory downloads: those can take longer than the lease TTL, and an
443
+ // unheartbeated lease lapsing mid-download would let another worker
444
+ // reclaim the item and serve the same session (split-brain).
445
+ //
309
446
  // Each heartbeat reports the lease TTL the server is enforcing; it becomes
310
447
  // the runner's tool-result send retry window so a send keeps retrying
311
- // exactly as long as the lease could still be live.
312
- const heartbeatPromise = heartbeatLoop(sessionClient, work, ctrl, log, this.requestOptions, (ttlMs) =>
313
- runner._setSendRetryWindow(ttlMs),
314
- ).catch((e) => {
448
+ // exactly as long as the lease could still be live. The runner is only
449
+ // built after the downloads, so hold the latest TTL until then.
450
+ let leaseTtlMs: number | undefined;
451
+ let runner: SessionToolRunner | undefined;
452
+ const heartbeatPromise = heartbeatLoop(sessionClient, work, lease, log, this.requestOptions, (ttlMs) => {
453
+ leaseTtlMs = ttlMs;
454
+ runner?._setSendRetryWindow(ttlMs);
455
+ }).catch((e) => {
315
456
  if (!ctrl.signal.aborted) log.error('heartbeat loop failed', { work_id: work.id, error: String(e) });
316
457
  ctrl.abort();
317
458
  });
318
459
 
460
+ let cleanupSkills: () => Promise<void> = async () => {};
461
+ let stores: SessionMemoryStores | undefined;
462
+ let cleanEnd = false;
319
463
  try {
464
+ if (work.data.type !== 'session') {
465
+ log.debug('skipping non-session work item', { work_id: work.id, type: work.data.type });
466
+ return;
467
+ }
468
+ // One session fetch, shared by the skills download and the memory-store
469
+ // download — two fetches could disagree about the attached resources.
470
+ // A failed fetch fails the work item (the teardown below still stops
471
+ // or releases it).
472
+ const session: BetaManagedAgentsSession = await sessionClient.beta.sessions.retrieve(sessionId);
473
+ // Only with the session in hand can we tell one that simply has no
474
+ // memory from one whose memory we cannot mount. Turning memory off
475
+ // with the interval knob is a deliberate opt-out and stays quiet.
476
+ if (sessionsToken === null && this.memorySyncIntervalMs !== null && hasMemoryStore(session)) {
477
+ throw new agentToolset.SessionMemoryError(
478
+ `cannot mount the session's memories: the work item carried no sessions token ` +
479
+ `(work_id=${work.id}, session_id=${sessionId}); ` +
480
+ 'the memory endpoints reject the environment key, so the poller must issue a per-item ' +
481
+ '`secret` carrying `sessions_token`, or set `memorySyncIntervalMs: null` to run without memory',
482
+ );
483
+ }
484
+
485
+ const ctx: AgentToolContext = {
486
+ workdir: this.workdir,
487
+ // The scoped sub-client, not the parent: the skill download
488
+ // `setupSkills` performs for this session rides the same per-item
489
+ // credential as every other per-item call.
490
+ client: sessionClient,
491
+ session,
492
+ ...(this.maxFileBytes !== undefined ? { maxFileBytes: this.maxFileBytes } : {}),
493
+ };
494
+ try {
495
+ cleanupSkills = await agentToolset.setupSkills(ctx);
496
+ } catch (e) {
497
+ log.warn('skill setup failed', { session_id: sessionId, work_id: work.id, error: String(e) });
498
+ }
499
+
500
+ // Memory stores: the memory_stores endpoints accept the per-item sessions
501
+ // token but reject the environment key, so download and sync only run when
502
+ // the item carried a usable secret (and the interval is set).
503
+ // `sessionClient` is already scoped to that token then, so the memory
504
+ // calls ride the same sub-client. A store that cannot be materialised
505
+ // throws `SessionMemoryError` out of `download` and fails the item.
506
+ if (sessionsToken !== null && this.memorySyncIntervalMs !== null) {
507
+ stores = new agentToolset.SessionMemoryStores(sessionClient, {
508
+ workdir: this.workdir,
509
+ ...(this.memorySyncIntervalMs !== undefined ? { syncIntervalMs: this.memorySyncIntervalMs } : {}),
510
+ syncDeletions: this.memorySyncDeletions,
511
+ });
512
+ await stores.download(session);
513
+ // A store mounted outside the workdir must stay reachable by the file
514
+ // tools; read-only stores still refuse writes.
515
+ ctx.allowedRoots = stores.roots;
516
+ ctx.readOnlyRoots = stores.readOnlyRoots;
517
+ } else {
518
+ log.debug('memory stores disabled for this item', { work_id: work.id });
519
+ }
520
+
521
+ const tools =
522
+ typeof this.tools === 'function' ?
523
+ this.tools(ctx)
524
+ : this.tools ?? agentToolset.betaAgentToolset20260401(ctx);
525
+
526
+ runner = new SessionToolRunner(sessionId, {
527
+ client: sessionClient,
528
+ tools,
529
+ ...(this.maxIdleMs !== undefined ? { maxIdleMs: this.maxIdleMs } : {}),
530
+ ...(this.requestOptions !== undefined ? { requestOptions: this.requestOptions } : {}),
531
+ signal: ctrl.signal,
532
+ });
533
+ if (leaseTtlMs !== undefined) runner._setSendRetryWindow(leaseTtlMs);
320
534
  for await (const _ of runner) {
321
535
  // Drive the runner to completion; per-call observability is not part
322
536
  // of this composition's surface — use `SessionToolRunner` directly
323
537
  // (via `client.beta.sessions.events.toolRunner`) if you want it.
538
+ if (stores) await stores.syncIfDue();
324
539
  }
540
+ // Only a clean stream end earns the last full sync; it runs in the
541
+ // teardown below.
542
+ cleanEnd = !ctrl.signal.aborted;
325
543
  } finally {
326
- ctrl.abort();
544
+ // The heartbeat keeps the lease alive until this teardown is done.
545
+ try {
546
+ // cleanupSkills first, so its failure cannot skip the memory flush.
547
+ await cleanupSkills().catch((e) => {
548
+ log.warn('skill cleanup failed', { session_id: sessionId, work_id: work.id, error: String(e) });
549
+ });
550
+ } finally {
551
+ if (stores) {
552
+ const boundMs = agentToolset.MEMORY_FLUSH_TIMEOUT_MS;
553
+ if (cleanEnd) {
554
+ const finishCutOff = await withTimeout(stores.finish(), boundMs);
555
+ if (finishCutOff) {
556
+ log.warn(
557
+ `final memory sync cut off after ${boundMs}ms; the flush that follows still uploads changed files`,
558
+ { session_id: sessionId, work_id: work.id },
559
+ );
560
+ }
561
+ }
562
+ // Also after finish(): it swallows its own failures, and a
563
+ // clean flush is a no-op.
564
+ const flushBound = new AbortController();
565
+ const flushCutOff = await withTimeout(stores.flushWrites(flushBound.signal), boundMs);
566
+ if (flushCutOff) {
567
+ flushBound.abort();
568
+ log.warn(
569
+ `memory flush cut off after ${boundMs}ms; changed files it had not uploaded yet are not saved`,
570
+ { session_id: sessionId, work_id: work.id },
571
+ );
572
+ }
573
+ await stores.dispose().catch((e) => {
574
+ log.warn('memory store cleanup failed', {
575
+ session_id: sessionId,
576
+ work_id: work.id,
577
+ error: String(e),
578
+ });
579
+ });
580
+ }
581
+ }
582
+ lease.finish('runner_done');
327
583
  detachExternal();
328
584
  await heartbeatPromise;
329
- await cleanupSkills().catch((e) => {
330
- log.warn('skill cleanup failed', { session_id: sessionId, work_id: work.id, error: String(e) });
331
- });
332
- await forceStop(sessionClient, work, log, this.requestOptions);
585
+ // Stop only an item this worker still holds — after a lost lease it
586
+ // belongs to the queue or another worker.
587
+ if (lease.lost) {
588
+ log.info('lease lost; released without stopping it', { session_id: sessionId, work_id: work.id });
589
+ } else {
590
+ await forceStop(sessionClient, work, log, this.requestOptions);
591
+ }
333
592
  }
334
593
  }
335
594
  }
336
595
 
596
+ /**
597
+ * Resolve when `p` settles or `ms` elapses — `true` when `ms` elapsed
598
+ * first. A timed-out `p` keeps running — JS cannot cancel a promise.
599
+ */
600
+ async function withTimeout(p: Promise<void>, ms: number): Promise<boolean> {
601
+ let timer: ReturnType<typeof setTimeout> | undefined;
602
+ try {
603
+ return await Promise.race([
604
+ p.then(
605
+ () => false,
606
+ () => false,
607
+ ),
608
+ new Promise<boolean>((resolve) => {
609
+ timer = setTimeout(() => resolve(true), ms);
610
+ }),
611
+ ]);
612
+ } finally {
613
+ if (timer !== undefined) clearTimeout(timer);
614
+ }
615
+ }
616
+
337
617
  /** Force-stop a claimed work item, swallowing the 409 that means it's already stopped. */
338
618
  async function forceStop(
339
619
  client: Anthropic,
@@ -357,18 +637,67 @@ async function forceStop(
357
637
  }
358
638
  }
359
639
 
640
+ /** Why heartbeating of a work item ended, as recorded on its {@link Lease}. */
641
+ type LeaseEndReason =
642
+ | 'runner_done'
643
+ | 'control_plane_stop'
644
+ | 'lease_lost'
645
+ | 'heartbeat_rejected'
646
+ | 'assumed_lost';
647
+
360
648
  /**
361
- * Keep the work-item lease alive while a session is being served. Aborts `ctrl`
362
- * when the control plane reports the work is `stopping`/`stopped`, when the
363
- * lease is no longer extended, on a permanent heartbeat failure, or when no
649
+ * This worker's view of one work-item lease: the per-item abort signal plus
650
+ * why heartbeating ended. The first recorded reason wins, so a run aborted
651
+ * *because* the lease was lost still reads as lost afterwards; an abort with
652
+ * no recorded reason (the external signal) is not lost.
653
+ */
654
+ class Lease {
655
+ readonly #ctrl: AbortController;
656
+ #endReason: LeaseEndReason | undefined;
657
+
658
+ constructor(ctrl: AbortController) {
659
+ this.#ctrl = ctrl;
660
+ }
661
+
662
+ get signal(): AbortSignal {
663
+ return this.#ctrl.signal;
664
+ }
665
+
666
+ finish(reason: LeaseEndReason): void {
667
+ this.#endReason ??= reason;
668
+ this.#ctrl.abort();
669
+ }
670
+
671
+ /** True once the item belongs to the queue or another worker. */
672
+ get lost(): boolean {
673
+ return this.#endReason === 'lease_lost' || this.#endReason === 'assumed_lost';
674
+ }
675
+ }
676
+
677
+ /** The server's view of the lease carried by a 412 heartbeat response, or empty if absent. */
678
+ function serverLeaseState(e: unknown): Record<string, unknown> {
679
+ let node: unknown = e instanceof APIError ? e.error : undefined;
680
+ for (const key of ['error', 'details', 'current_state']) {
681
+ if (!isObj(node)) return {};
682
+ node = node[key];
683
+ }
684
+ return isObj(node) ? node : {};
685
+ }
686
+
687
+ /**
688
+ * Keep the work-item lease alive while a session is being served. Runs until
689
+ * `lease` ends, and ends it itself when the control plane reports the work is
690
+ * `stopping`/`stopped` or no longer extends the lease, when a heartbeat is
691
+ * rejected (a 412 means the lease already belongs to someone else), or when no
364
692
  * heartbeat has succeeded for longer than the lease ttl (the lease is assumed
365
- * lost). Each heartbeat call is cut off after the current beat interval so a
366
- * hung request cannot outlive the lease it is meant to renew.
693
+ * lost, so two runners don't end up serving the same work). Each heartbeat
694
+ * call is cut off after the current beat interval so a hung request cannot
695
+ * outlive the lease it is meant to renew.
367
696
  */
368
697
  async function heartbeatLoop(
369
698
  client: Anthropic,
370
699
  work: Pick<BetaSelfHostedWork, 'id' | 'environment_id'>,
371
- ctrl: AbortController,
700
+ lease: Lease,
372
701
  logger: Logger,
373
702
  requestOptions?: BetaToolRunnerRequestOptions,
374
703
  /** Called with the server-reported lease TTL after every successful beat. */
@@ -382,7 +711,7 @@ async function heartbeatLoop(
382
711
  // Not the request `timeout` option: the core client retries timeouts, so
383
712
  // it would not bound the call as a whole.
384
713
  const beatCtrl = new AbortController();
385
- const detach = linkAbort(ctrl.signal, beatCtrl);
714
+ const detach = linkAbort(lease.signal, beatCtrl);
386
715
  const cutoff = setTimeout(() => beatCtrl.abort(), intervalMs);
387
716
  try {
388
717
  const resp = await client.beta.environments.work.heartbeat(
@@ -399,19 +728,30 @@ async function heartbeatLoop(
399
728
  }
400
729
  if (resp.state === 'stopping' || resp.state === 'stopped') {
401
730
  logger.info('heartbeat signals shutdown', { work_id: work.id, state: resp.state });
402
- ctrl.abort();
731
+ lease.finish('control_plane_stop');
403
732
  }
404
733
  if (!resp.lease_extended) {
405
734
  logger.warn('lease not extended, shutting down', { work_id: work.id });
406
- ctrl.abort();
735
+ lease.finish('control_plane_stop');
407
736
  }
408
737
  } catch (e) {
409
738
  // An abort throws to unwind the caller (the `heartbeatLoop(...).catch`
410
739
  // in `#handleItem`) rather than returning early.
411
- ctrl.signal.throwIfAborted();
740
+ lease.signal.throwIfAborted();
741
+ if (isStatus(e, 412)) {
742
+ const server = serverLeaseState(e);
743
+ logger.error('lease lost: heartbeat precondition failed', {
744
+ work_id: work.id,
745
+ server_state: server['state'],
746
+ server_ttl_seconds: server['ttl_seconds'],
747
+ server_last_heartbeat: server['last_heartbeat'],
748
+ });
749
+ lease.finish('lease_lost');
750
+ return;
751
+ }
412
752
  if (isFatal4xx(e)) {
413
753
  logger.error('permanent heartbeat failure', { work_id: work.id, error: String(e) });
414
- ctrl.abort();
754
+ lease.finish('heartbeat_rejected');
415
755
  throw e;
416
756
  }
417
757
  if (Date.now() - lastSuccessMs > ttlMs) {
@@ -420,7 +760,7 @@ async function heartbeatLoop(
420
760
  ttl_ms: ttlMs,
421
761
  error: String(e),
422
762
  });
423
- ctrl.abort();
763
+ lease.finish('assumed_lost');
424
764
  return;
425
765
  }
426
766
  logger.warn('transient heartbeat failure', { work_id: work.id, error: String(e) });
@@ -431,9 +771,9 @@ async function heartbeatLoop(
431
771
  };
432
772
 
433
773
  await beat();
434
- while (!ctrl.signal.aborted) {
435
- await sleep(intervalMs, ctrl.signal);
436
- ctrl.signal.throwIfAborted();
774
+ while (!lease.signal.aborted) {
775
+ await sleep(intervalMs, lease.signal);
776
+ lease.signal.throwIfAborted();
437
777
  await beat();
438
778
  }
439
779
  }