@stigmer/server-slim 3.40.0 → 3.40.1

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 (584) hide show
  1. package/console/404.html +1 -1
  2. package/console/__next.__PAGE__.txt +2 -2
  3. package/console/__next._full.txt +14 -14
  4. package/console/__next._head.txt +4 -4
  5. package/console/__next._index.txt +9 -9
  6. package/console/__next._tree.txt +1 -1
  7. package/console/_next/static/chunks/01hep6fbspt.0.js +1 -0
  8. package/console/_next/static/chunks/05uzu4-_sp1yp.js +1 -0
  9. package/console/_next/static/chunks/{12i_a9yn.gms7.js → 072g980hrxnyl.js} +1 -1
  10. package/console/_next/static/chunks/0rh6tj~41xah0.js +34 -0
  11. package/console/_next/static/chunks/0s7rm5b3t2blp.js +1 -0
  12. package/console/_next/static/chunks/0xy23zns071f6.js +1 -0
  13. package/console/_next/static/chunks/161o._k~z2-bu.js +1 -0
  14. package/console/_not-found/__next._full.txt +14 -14
  15. package/console/_not-found/__next._head.txt +4 -4
  16. package/console/_not-found/__next._index.txt +9 -9
  17. package/console/_not-found/__next._not-found.__PAGE__.txt +3 -3
  18. package/console/_not-found/__next._not-found.txt +3 -3
  19. package/console/_not-found/__next._tree.txt +1 -1
  20. package/console/_not-found.html +1 -1
  21. package/console/_not-found.txt +14 -14
  22. package/console/auth/callback/__next._full.txt +16 -16
  23. package/console/auth/callback/__next._head.txt +4 -4
  24. package/console/auth/callback/__next._index.txt +9 -9
  25. package/console/auth/callback/__next._tree.txt +1 -1
  26. package/console/auth/callback/__next.auth.callback.__PAGE__.txt +4 -4
  27. package/console/auth/callback/__next.auth.callback.txt +3 -3
  28. package/console/auth/callback/__next.auth.txt +3 -3
  29. package/console/auth/callback.html +1 -1
  30. package/console/auth/callback.txt +16 -16
  31. package/console/auth/github/callback/__next._full.txt +16 -16
  32. package/console/auth/github/callback/__next._head.txt +4 -4
  33. package/console/auth/github/callback/__next._index.txt +9 -9
  34. package/console/auth/github/callback/__next._tree.txt +1 -1
  35. package/console/auth/github/callback/__next.auth.github.callback.__PAGE__.txt +4 -4
  36. package/console/auth/github/callback/__next.auth.github.callback.txt +3 -3
  37. package/console/auth/github/callback/__next.auth.github.txt +3 -3
  38. package/console/auth/github/callback/__next.auth.txt +3 -3
  39. package/console/auth/github/callback.html +1 -1
  40. package/console/auth/github/callback.txt +16 -16
  41. package/console/auth/oauth/callback/__next._full.txt +16 -16
  42. package/console/auth/oauth/callback/__next._head.txt +4 -4
  43. package/console/auth/oauth/callback/__next._index.txt +9 -9
  44. package/console/auth/oauth/callback/__next._tree.txt +1 -1
  45. package/console/auth/oauth/callback/__next.auth.oauth.callback.__PAGE__.txt +4 -4
  46. package/console/auth/oauth/callback/__next.auth.oauth.callback.txt +3 -3
  47. package/console/auth/oauth/callback/__next.auth.oauth.txt +3 -3
  48. package/console/auth/oauth/callback/__next.auth.txt +3 -3
  49. package/console/auth/oauth/callback.html +1 -1
  50. package/console/auth/oauth/callback.txt +16 -16
  51. package/console/chat/__placeholder__/__placeholder__/__next._full.txt +15 -15
  52. package/console/chat/__placeholder__/__placeholder__/__next._head.txt +4 -4
  53. package/console/chat/__placeholder__/__placeholder__/__next._index.txt +9 -9
  54. package/console/chat/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  55. package/console/chat/__placeholder__/__placeholder__/__next.chat.$d$org.$d$slug.__PAGE__.txt +3 -3
  56. package/console/chat/__placeholder__/__placeholder__/__next.chat.$d$org.$d$slug.txt +3 -3
  57. package/console/chat/__placeholder__/__placeholder__/__next.chat.$d$org.txt +3 -3
  58. package/console/chat/__placeholder__/__placeholder__/__next.chat.txt +3 -3
  59. package/console/chat/__placeholder__/__placeholder__.html +1 -1
  60. package/console/chat/__placeholder__/__placeholder__.txt +15 -15
  61. package/console/conversations/__next._full.txt +15 -15
  62. package/console/conversations/__next._head.txt +4 -4
  63. package/console/conversations/__next._index.txt +9 -9
  64. package/console/conversations/__next._tree.txt +1 -1
  65. package/console/conversations/__next.conversations.__PAGE__.txt +3 -3
  66. package/console/conversations/__next.conversations.txt +3 -3
  67. package/console/conversations/__placeholder__/__placeholder__/__next._full.txt +15 -15
  68. package/console/conversations/__placeholder__/__placeholder__/__next._head.txt +4 -4
  69. package/console/conversations/__placeholder__/__placeholder__/__next._index.txt +9 -9
  70. package/console/conversations/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  71. package/console/conversations/__placeholder__/__placeholder__/__next.conversations.$d$channelId.$d$key.__PAGE__.txt +3 -3
  72. package/console/conversations/__placeholder__/__placeholder__/__next.conversations.$d$channelId.$d$key.txt +3 -3
  73. package/console/conversations/__placeholder__/__placeholder__/__next.conversations.$d$channelId.txt +3 -3
  74. package/console/conversations/__placeholder__/__placeholder__/__next.conversations.txt +3 -3
  75. package/console/conversations/__placeholder__/__placeholder__.html +1 -1
  76. package/console/conversations/__placeholder__/__placeholder__.txt +15 -15
  77. package/console/conversations.html +1 -1
  78. package/console/conversations.txt +15 -15
  79. package/console/dashboard/__next._full.txt +15 -15
  80. package/console/dashboard/__next._head.txt +4 -4
  81. package/console/dashboard/__next._index.txt +9 -9
  82. package/console/dashboard/__next._tree.txt +1 -1
  83. package/console/dashboard/__next.dashboard.__PAGE__.txt +3 -3
  84. package/console/dashboard/__next.dashboard.txt +3 -3
  85. package/console/dashboard.html +1 -1
  86. package/console/dashboard.txt +15 -15
  87. package/console/desktop/billing/__next._full.txt +16 -16
  88. package/console/desktop/billing/__next._head.txt +4 -4
  89. package/console/desktop/billing/__next._index.txt +9 -9
  90. package/console/desktop/billing/__next._tree.txt +1 -1
  91. package/console/desktop/billing/__next.desktop.billing.__PAGE__.txt +4 -4
  92. package/console/desktop/billing/__next.desktop.billing.txt +3 -3
  93. package/console/desktop/billing/__next.desktop.txt +3 -3
  94. package/console/desktop/billing.html +1 -1
  95. package/console/desktop/billing.txt +16 -16
  96. package/console/executions/__placeholder__/__next._full.txt +14 -14
  97. package/console/executions/__placeholder__/__next._head.txt +4 -4
  98. package/console/executions/__placeholder__/__next._index.txt +9 -9
  99. package/console/executions/__placeholder__/__next._tree.txt +1 -1
  100. package/console/executions/__placeholder__/__next.executions.$d$id.__PAGE__.txt +2 -2
  101. package/console/executions/__placeholder__/__next.executions.$d$id.txt +3 -3
  102. package/console/executions/__placeholder__/__next.executions.txt +3 -3
  103. package/console/executions/__placeholder__.html +1 -1
  104. package/console/executions/__placeholder__.txt +14 -14
  105. package/console/index.html +1 -1
  106. package/console/index.txt +14 -14
  107. package/console/invite/__placeholder__/__next._full.txt +15 -15
  108. package/console/invite/__placeholder__/__next._head.txt +4 -4
  109. package/console/invite/__placeholder__/__next._index.txt +9 -9
  110. package/console/invite/__placeholder__/__next._tree.txt +1 -1
  111. package/console/invite/__placeholder__/__next.invite.$d$token.__PAGE__.txt +3 -3
  112. package/console/invite/__placeholder__/__next.invite.$d$token.txt +3 -3
  113. package/console/invite/__placeholder__/__next.invite.txt +3 -3
  114. package/console/invite/__placeholder__.html +1 -1
  115. package/console/invite/__placeholder__.txt +15 -15
  116. package/console/library/__next._full.txt +17 -17
  117. package/console/library/__next._head.txt +4 -4
  118. package/console/library/__next._index.txt +9 -9
  119. package/console/library/__next._tree.txt +1 -1
  120. package/console/library/__next.library.__PAGE__.txt +3 -3
  121. package/console/library/__next.library.txt +5 -5
  122. package/console/library/agents/__next._full.txt +17 -17
  123. package/console/library/agents/__next._head.txt +4 -4
  124. package/console/library/agents/__next._index.txt +9 -9
  125. package/console/library/agents/__next._tree.txt +1 -1
  126. package/console/library/agents/__next.library.agents.__PAGE__.txt +3 -3
  127. package/console/library/agents/__next.library.agents.txt +3 -3
  128. package/console/library/agents/__next.library.txt +5 -5
  129. package/console/library/agents/__placeholder__/__placeholder__/__next._full.txt +17 -17
  130. package/console/library/agents/__placeholder__/__placeholder__/__next._head.txt +4 -4
  131. package/console/library/agents/__placeholder__/__placeholder__/__next._index.txt +9 -9
  132. package/console/library/agents/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  133. package/console/library/agents/__placeholder__/__placeholder__/__next.library.agents.$d$org.$d$slug.__PAGE__.txt +3 -3
  134. package/console/library/agents/__placeholder__/__placeholder__/__next.library.agents.$d$org.$d$slug.txt +3 -3
  135. package/console/library/agents/__placeholder__/__placeholder__/__next.library.agents.$d$org.txt +3 -3
  136. package/console/library/agents/__placeholder__/__placeholder__/__next.library.agents.txt +3 -3
  137. package/console/library/agents/__placeholder__/__placeholder__/__next.library.txt +5 -5
  138. package/console/library/agents/__placeholder__/__placeholder__.html +1 -1
  139. package/console/library/agents/__placeholder__/__placeholder__.txt +17 -17
  140. package/console/library/agents/new/__next._full.txt +18 -18
  141. package/console/library/agents/new/__next._head.txt +4 -4
  142. package/console/library/agents/new/__next._index.txt +9 -9
  143. package/console/library/agents/new/__next._tree.txt +1 -1
  144. package/console/library/agents/new/__next.library.agents.new.__PAGE__.txt +4 -4
  145. package/console/library/agents/new/__next.library.agents.new.txt +3 -3
  146. package/console/library/agents/new/__next.library.agents.txt +3 -3
  147. package/console/library/agents/new/__next.library.txt +5 -5
  148. package/console/library/agents/new.html +1 -1
  149. package/console/library/agents/new.txt +18 -18
  150. package/console/library/agents.html +1 -1
  151. package/console/library/agents.txt +17 -17
  152. package/console/library/mcp-servers/__next._full.txt +17 -17
  153. package/console/library/mcp-servers/__next._head.txt +4 -4
  154. package/console/library/mcp-servers/__next._index.txt +9 -9
  155. package/console/library/mcp-servers/__next._tree.txt +1 -1
  156. package/console/library/mcp-servers/__next.library.mcp-servers.__PAGE__.txt +3 -3
  157. package/console/library/mcp-servers/__next.library.mcp-servers.txt +3 -3
  158. package/console/library/mcp-servers/__next.library.txt +5 -5
  159. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next._full.txt +17 -17
  160. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next._head.txt +4 -4
  161. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next._index.txt +9 -9
  162. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  163. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next.library.mcp-servers.$d$org.$d$slug.__PAGE__.txt +3 -3
  164. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next.library.mcp-servers.$d$org.$d$slug.txt +3 -3
  165. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next.library.mcp-servers.$d$org.txt +3 -3
  166. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next.library.mcp-servers.txt +3 -3
  167. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next.library.txt +5 -5
  168. package/console/library/mcp-servers/__placeholder__/__placeholder__.html +1 -1
  169. package/console/library/mcp-servers/__placeholder__/__placeholder__.txt +17 -17
  170. package/console/library/mcp-servers/new/__next._full.txt +18 -18
  171. package/console/library/mcp-servers/new/__next._head.txt +4 -4
  172. package/console/library/mcp-servers/new/__next._index.txt +9 -9
  173. package/console/library/mcp-servers/new/__next._tree.txt +1 -1
  174. package/console/library/mcp-servers/new/__next.library.mcp-servers.new.__PAGE__.txt +4 -4
  175. package/console/library/mcp-servers/new/__next.library.mcp-servers.new.txt +3 -3
  176. package/console/library/mcp-servers/new/__next.library.mcp-servers.txt +3 -3
  177. package/console/library/mcp-servers/new/__next.library.txt +5 -5
  178. package/console/library/mcp-servers/new.html +1 -1
  179. package/console/library/mcp-servers/new.txt +18 -18
  180. package/console/library/mcp-servers.html +1 -1
  181. package/console/library/mcp-servers.txt +17 -17
  182. package/console/library/plugins/__next._full.txt +17 -17
  183. package/console/library/plugins/__next._head.txt +4 -4
  184. package/console/library/plugins/__next._index.txt +9 -9
  185. package/console/library/plugins/__next._tree.txt +1 -1
  186. package/console/library/plugins/__next.library.plugins.__PAGE__.txt +3 -3
  187. package/console/library/plugins/__next.library.plugins.txt +3 -3
  188. package/console/library/plugins/__next.library.txt +5 -5
  189. package/console/library/plugins/__placeholder__/__placeholder__/__next._full.txt +17 -17
  190. package/console/library/plugins/__placeholder__/__placeholder__/__next._head.txt +4 -4
  191. package/console/library/plugins/__placeholder__/__placeholder__/__next._index.txt +9 -9
  192. package/console/library/plugins/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  193. package/console/library/plugins/__placeholder__/__placeholder__/__next.library.plugins.$d$org.$d$slug.__PAGE__.txt +3 -3
  194. package/console/library/plugins/__placeholder__/__placeholder__/__next.library.plugins.$d$org.$d$slug.txt +3 -3
  195. package/console/library/plugins/__placeholder__/__placeholder__/__next.library.plugins.$d$org.txt +3 -3
  196. package/console/library/plugins/__placeholder__/__placeholder__/__next.library.plugins.txt +3 -3
  197. package/console/library/plugins/__placeholder__/__placeholder__/__next.library.txt +5 -5
  198. package/console/library/plugins/__placeholder__/__placeholder__.html +1 -1
  199. package/console/library/plugins/__placeholder__/__placeholder__.txt +17 -17
  200. package/console/library/plugins/upload/__next._full.txt +18 -18
  201. package/console/library/plugins/upload/__next._head.txt +4 -4
  202. package/console/library/plugins/upload/__next._index.txt +9 -9
  203. package/console/library/plugins/upload/__next._tree.txt +1 -1
  204. package/console/library/plugins/upload/__next.library.plugins.txt +3 -3
  205. package/console/library/plugins/upload/__next.library.plugins.upload.__PAGE__.txt +4 -4
  206. package/console/library/plugins/upload/__next.library.plugins.upload.txt +3 -3
  207. package/console/library/plugins/upload/__next.library.txt +5 -5
  208. package/console/library/plugins/upload.html +1 -1
  209. package/console/library/plugins/upload.txt +18 -18
  210. package/console/library/plugins.html +1 -1
  211. package/console/library/plugins.txt +17 -17
  212. package/console/library/schedules/__next._full.txt +17 -17
  213. package/console/library/schedules/__next._head.txt +4 -4
  214. package/console/library/schedules/__next._index.txt +9 -9
  215. package/console/library/schedules/__next._tree.txt +1 -1
  216. package/console/library/schedules/__next.library.schedules.__PAGE__.txt +3 -3
  217. package/console/library/schedules/__next.library.schedules.txt +3 -3
  218. package/console/library/schedules/__next.library.txt +5 -5
  219. package/console/library/schedules/__placeholder__/__placeholder__/__next._full.txt +17 -17
  220. package/console/library/schedules/__placeholder__/__placeholder__/__next._head.txt +4 -4
  221. package/console/library/schedules/__placeholder__/__placeholder__/__next._index.txt +9 -9
  222. package/console/library/schedules/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  223. package/console/library/schedules/__placeholder__/__placeholder__/__next.library.schedules.$d$org.$d$slug.__PAGE__.txt +3 -3
  224. package/console/library/schedules/__placeholder__/__placeholder__/__next.library.schedules.$d$org.$d$slug.txt +3 -3
  225. package/console/library/schedules/__placeholder__/__placeholder__/__next.library.schedules.$d$org.txt +3 -3
  226. package/console/library/schedules/__placeholder__/__placeholder__/__next.library.schedules.txt +3 -3
  227. package/console/library/schedules/__placeholder__/__placeholder__/__next.library.txt +5 -5
  228. package/console/library/schedules/__placeholder__/__placeholder__.html +1 -1
  229. package/console/library/schedules/__placeholder__/__placeholder__.txt +17 -17
  230. package/console/library/schedules/new/__next._full.txt +18 -18
  231. package/console/library/schedules/new/__next._head.txt +4 -4
  232. package/console/library/schedules/new/__next._index.txt +9 -9
  233. package/console/library/schedules/new/__next._tree.txt +1 -1
  234. package/console/library/schedules/new/__next.library.schedules.new.__PAGE__.txt +4 -4
  235. package/console/library/schedules/new/__next.library.schedules.new.txt +3 -3
  236. package/console/library/schedules/new/__next.library.schedules.txt +3 -3
  237. package/console/library/schedules/new/__next.library.txt +5 -5
  238. package/console/library/schedules/new.html +1 -1
  239. package/console/library/schedules/new.txt +18 -18
  240. package/console/library/schedules.html +1 -1
  241. package/console/library/schedules.txt +17 -17
  242. package/console/library/skills/__next._full.txt +17 -17
  243. package/console/library/skills/__next._head.txt +4 -4
  244. package/console/library/skills/__next._index.txt +9 -9
  245. package/console/library/skills/__next._tree.txt +1 -1
  246. package/console/library/skills/__next.library.skills.__PAGE__.txt +3 -3
  247. package/console/library/skills/__next.library.skills.txt +3 -3
  248. package/console/library/skills/__next.library.txt +5 -5
  249. package/console/library/skills/__placeholder__/__placeholder__/__next._full.txt +17 -17
  250. package/console/library/skills/__placeholder__/__placeholder__/__next._head.txt +4 -4
  251. package/console/library/skills/__placeholder__/__placeholder__/__next._index.txt +9 -9
  252. package/console/library/skills/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  253. package/console/library/skills/__placeholder__/__placeholder__/__next.library.skills.$d$org.$d$slug.__PAGE__.txt +3 -3
  254. package/console/library/skills/__placeholder__/__placeholder__/__next.library.skills.$d$org.$d$slug.txt +3 -3
  255. package/console/library/skills/__placeholder__/__placeholder__/__next.library.skills.$d$org.txt +3 -3
  256. package/console/library/skills/__placeholder__/__placeholder__/__next.library.skills.txt +3 -3
  257. package/console/library/skills/__placeholder__/__placeholder__/__next.library.txt +5 -5
  258. package/console/library/skills/__placeholder__/__placeholder__.html +1 -1
  259. package/console/library/skills/__placeholder__/__placeholder__.txt +17 -17
  260. package/console/library/skills/new/__next._full.txt +18 -18
  261. package/console/library/skills/new/__next._head.txt +4 -4
  262. package/console/library/skills/new/__next._index.txt +9 -9
  263. package/console/library/skills/new/__next._tree.txt +1 -1
  264. package/console/library/skills/new/__next.library.skills.new.__PAGE__.txt +4 -4
  265. package/console/library/skills/new/__next.library.skills.new.txt +3 -3
  266. package/console/library/skills/new/__next.library.skills.txt +3 -3
  267. package/console/library/skills/new/__next.library.txt +5 -5
  268. package/console/library/skills/new.html +1 -1
  269. package/console/library/skills/new.txt +18 -18
  270. package/console/library/skills.html +1 -1
  271. package/console/library/skills.txt +17 -17
  272. package/console/library/workflows/__next._full.txt +17 -17
  273. package/console/library/workflows/__next._head.txt +4 -4
  274. package/console/library/workflows/__next._index.txt +9 -9
  275. package/console/library/workflows/__next._tree.txt +1 -1
  276. package/console/library/workflows/__next.library.txt +5 -5
  277. package/console/library/workflows/__next.library.workflows.__PAGE__.txt +3 -3
  278. package/console/library/workflows/__next.library.workflows.txt +3 -3
  279. package/console/library/workflows/__placeholder__/__placeholder__/__next._full.txt +17 -17
  280. package/console/library/workflows/__placeholder__/__placeholder__/__next._head.txt +4 -4
  281. package/console/library/workflows/__placeholder__/__placeholder__/__next._index.txt +9 -9
  282. package/console/library/workflows/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  283. package/console/library/workflows/__placeholder__/__placeholder__/__next.library.txt +5 -5
  284. package/console/library/workflows/__placeholder__/__placeholder__/__next.library.workflows.$d$org.$d$slug.__PAGE__.txt +3 -3
  285. package/console/library/workflows/__placeholder__/__placeholder__/__next.library.workflows.$d$org.$d$slug.txt +3 -3
  286. package/console/library/workflows/__placeholder__/__placeholder__/__next.library.workflows.$d$org.txt +3 -3
  287. package/console/library/workflows/__placeholder__/__placeholder__/__next.library.workflows.txt +3 -3
  288. package/console/library/workflows/__placeholder__/__placeholder__.html +1 -1
  289. package/console/library/workflows/__placeholder__/__placeholder__.txt +17 -17
  290. package/console/library/workflows/executions/__next._full.txt +17 -17
  291. package/console/library/workflows/executions/__next._head.txt +4 -4
  292. package/console/library/workflows/executions/__next._index.txt +9 -9
  293. package/console/library/workflows/executions/__next._tree.txt +1 -1
  294. package/console/library/workflows/executions/__next.library.txt +5 -5
  295. package/console/library/workflows/executions/__next.library.workflows.executions.__PAGE__.txt +3 -3
  296. package/console/library/workflows/executions/__next.library.workflows.executions.txt +3 -3
  297. package/console/library/workflows/executions/__next.library.workflows.txt +3 -3
  298. package/console/library/workflows/executions.html +1 -1
  299. package/console/library/workflows/executions.txt +17 -17
  300. package/console/library/workflows/new/__next._full.txt +18 -18
  301. package/console/library/workflows/new/__next._head.txt +4 -4
  302. package/console/library/workflows/new/__next._index.txt +9 -9
  303. package/console/library/workflows/new/__next._tree.txt +1 -1
  304. package/console/library/workflows/new/__next.library.txt +5 -5
  305. package/console/library/workflows/new/__next.library.workflows.new.__PAGE__.txt +4 -4
  306. package/console/library/workflows/new/__next.library.workflows.new.txt +3 -3
  307. package/console/library/workflows/new/__next.library.workflows.txt +3 -3
  308. package/console/library/workflows/new.html +1 -1
  309. package/console/library/workflows/new.txt +18 -18
  310. package/console/library/workflows.html +1 -1
  311. package/console/library/workflows.txt +17 -17
  312. package/console/library.html +1 -1
  313. package/console/library.txt +17 -17
  314. package/console/login/__next._full.txt +16 -16
  315. package/console/login/__next._head.txt +4 -4
  316. package/console/login/__next._index.txt +9 -9
  317. package/console/login/__next._tree.txt +1 -1
  318. package/console/login/__next.login.__PAGE__.txt +4 -4
  319. package/console/login/__next.login.txt +3 -3
  320. package/console/login.html +1 -1
  321. package/console/login.txt +16 -16
  322. package/console/marketplace/__next._full.txt +15 -15
  323. package/console/marketplace/__next._head.txt +4 -4
  324. package/console/marketplace/__next._index.txt +9 -9
  325. package/console/marketplace/__next._tree.txt +1 -1
  326. package/console/marketplace/__next.marketplace.__PAGE__.txt +3 -3
  327. package/console/marketplace/__next.marketplace.txt +3 -3
  328. package/console/marketplace.html +1 -1
  329. package/console/marketplace.txt +15 -15
  330. package/console/oauth/slack/callback/__next._full.txt +16 -16
  331. package/console/oauth/slack/callback/__next._head.txt +4 -4
  332. package/console/oauth/slack/callback/__next._index.txt +9 -9
  333. package/console/oauth/slack/callback/__next._tree.txt +1 -1
  334. package/console/oauth/slack/callback/__next.oauth.slack.callback.__PAGE__.txt +4 -4
  335. package/console/oauth/slack/callback/__next.oauth.slack.callback.txt +3 -3
  336. package/console/oauth/slack/callback/__next.oauth.slack.txt +3 -3
  337. package/console/oauth/slack/callback/__next.oauth.txt +3 -3
  338. package/console/oauth/slack/callback.html +1 -1
  339. package/console/oauth/slack/callback.txt +16 -16
  340. package/console/sessions/__placeholder__/__next._full.txt +14 -14
  341. package/console/sessions/__placeholder__/__next._head.txt +4 -4
  342. package/console/sessions/__placeholder__/__next._index.txt +9 -9
  343. package/console/sessions/__placeholder__/__next._tree.txt +1 -1
  344. package/console/sessions/__placeholder__/__next.sessions.$d$id.__PAGE__.txt +2 -2
  345. package/console/sessions/__placeholder__/__next.sessions.$d$id.txt +3 -3
  346. package/console/sessions/__placeholder__/__next.sessions.txt +3 -3
  347. package/console/sessions/__placeholder__.html +1 -1
  348. package/console/sessions/__placeholder__.txt +14 -14
  349. package/console/settings/__next._full.txt +18 -18
  350. package/console/settings/__next._head.txt +4 -4
  351. package/console/settings/__next._index.txt +9 -9
  352. package/console/settings/__next._tree.txt +1 -1
  353. package/console/settings/__next.settings.__PAGE__.txt +4 -4
  354. package/console/settings/__next.settings.txt +5 -5
  355. package/console/settings/account-preferences/__next._full.txt +17 -17
  356. package/console/settings/account-preferences/__next._head.txt +4 -4
  357. package/console/settings/account-preferences/__next._index.txt +9 -9
  358. package/console/settings/account-preferences/__next._tree.txt +1 -1
  359. package/console/settings/account-preferences/__next.settings.account-preferences.__PAGE__.txt +3 -3
  360. package/console/settings/account-preferences/__next.settings.account-preferences.txt +3 -3
  361. package/console/settings/account-preferences/__next.settings.txt +5 -5
  362. package/console/settings/account-preferences.html +1 -1
  363. package/console/settings/account-preferences.txt +17 -17
  364. package/console/settings/api-keys/__next._full.txt +17 -17
  365. package/console/settings/api-keys/__next._head.txt +4 -4
  366. package/console/settings/api-keys/__next._index.txt +9 -9
  367. package/console/settings/api-keys/__next._tree.txt +1 -1
  368. package/console/settings/api-keys/__next.settings.api-keys.__PAGE__.txt +3 -3
  369. package/console/settings/api-keys/__next.settings.api-keys.txt +3 -3
  370. package/console/settings/api-keys/__next.settings.txt +5 -5
  371. package/console/settings/api-keys.html +1 -1
  372. package/console/settings/api-keys.txt +17 -17
  373. package/console/settings/billing/__next._full.txt +18 -18
  374. package/console/settings/billing/__next._head.txt +4 -4
  375. package/console/settings/billing/__next._index.txt +9 -9
  376. package/console/settings/billing/__next._tree.txt +1 -1
  377. package/console/settings/billing/__next.settings.billing.__PAGE__.txt +4 -4
  378. package/console/settings/billing/__next.settings.billing.txt +3 -3
  379. package/console/settings/billing/__next.settings.txt +5 -5
  380. package/console/settings/billing.html +1 -1
  381. package/console/settings/billing.txt +18 -18
  382. package/console/settings/channel-apps/__next._full.txt +18 -18
  383. package/console/settings/channel-apps/__next._head.txt +4 -4
  384. package/console/settings/channel-apps/__next._index.txt +9 -9
  385. package/console/settings/channel-apps/__next._tree.txt +1 -1
  386. package/console/settings/channel-apps/__next.settings.channel-apps.__PAGE__.txt +3 -3
  387. package/console/settings/channel-apps/__next.settings.channel-apps.txt +3 -3
  388. package/console/settings/channel-apps/__next.settings.txt +5 -5
  389. package/console/settings/channel-apps.html +1 -1
  390. package/console/settings/channel-apps.txt +18 -18
  391. package/console/settings/cursor-accounts/__next._full.txt +18 -18
  392. package/console/settings/cursor-accounts/__next._head.txt +4 -4
  393. package/console/settings/cursor-accounts/__next._index.txt +9 -9
  394. package/console/settings/cursor-accounts/__next._tree.txt +1 -1
  395. package/console/settings/cursor-accounts/__next.settings.cursor-accounts.__PAGE__.txt +4 -4
  396. package/console/settings/cursor-accounts/__next.settings.cursor-accounts.txt +3 -3
  397. package/console/settings/cursor-accounts/__next.settings.txt +5 -5
  398. package/console/settings/cursor-accounts.html +1 -1
  399. package/console/settings/cursor-accounts.txt +18 -18
  400. package/console/settings/environments/__next._full.txt +17 -17
  401. package/console/settings/environments/__next._head.txt +4 -4
  402. package/console/settings/environments/__next._index.txt +9 -9
  403. package/console/settings/environments/__next._tree.txt +1 -1
  404. package/console/settings/environments/__next.settings.environments.__PAGE__.txt +3 -3
  405. package/console/settings/environments/__next.settings.environments.txt +3 -3
  406. package/console/settings/environments/__next.settings.txt +5 -5
  407. package/console/settings/environments.html +1 -1
  408. package/console/settings/environments.txt +17 -17
  409. package/console/settings/identity-providers/__next._full.txt +17 -17
  410. package/console/settings/identity-providers/__next._head.txt +4 -4
  411. package/console/settings/identity-providers/__next._index.txt +9 -9
  412. package/console/settings/identity-providers/__next._tree.txt +1 -1
  413. package/console/settings/identity-providers/__next.settings.identity-providers.__PAGE__.txt +3 -3
  414. package/console/settings/identity-providers/__next.settings.identity-providers.txt +3 -3
  415. package/console/settings/identity-providers/__next.settings.txt +5 -5
  416. package/console/settings/identity-providers.html +1 -1
  417. package/console/settings/identity-providers.txt +17 -17
  418. package/console/settings/invitations/__next._full.txt +17 -17
  419. package/console/settings/invitations/__next._head.txt +4 -4
  420. package/console/settings/invitations/__next._index.txt +9 -9
  421. package/console/settings/invitations/__next._tree.txt +1 -1
  422. package/console/settings/invitations/__next.settings.invitations.__PAGE__.txt +3 -3
  423. package/console/settings/invitations/__next.settings.invitations.txt +3 -3
  424. package/console/settings/invitations/__next.settings.txt +5 -5
  425. package/console/settings/invitations.html +1 -1
  426. package/console/settings/invitations.txt +17 -17
  427. package/console/settings/licenses/__next._full.txt +18 -18
  428. package/console/settings/licenses/__next._head.txt +4 -4
  429. package/console/settings/licenses/__next._index.txt +9 -9
  430. package/console/settings/licenses/__next._tree.txt +1 -1
  431. package/console/settings/licenses/__next.settings.licenses.__PAGE__.txt +4 -4
  432. package/console/settings/licenses/__next.settings.licenses.txt +3 -3
  433. package/console/settings/licenses/__next.settings.txt +5 -5
  434. package/console/settings/licenses.html +1 -1
  435. package/console/settings/licenses.txt +18 -18
  436. package/console/settings/members/__next._full.txt +17 -17
  437. package/console/settings/members/__next._head.txt +4 -4
  438. package/console/settings/members/__next._index.txt +9 -9
  439. package/console/settings/members/__next._tree.txt +1 -1
  440. package/console/settings/members/__next.settings.members.__PAGE__.txt +3 -3
  441. package/console/settings/members/__next.settings.members.txt +3 -3
  442. package/console/settings/members/__next.settings.txt +5 -5
  443. package/console/settings/members.html +1 -1
  444. package/console/settings/members.txt +17 -17
  445. package/console/settings/memory/__next._full.txt +17 -17
  446. package/console/settings/memory/__next._head.txt +4 -4
  447. package/console/settings/memory/__next._index.txt +9 -9
  448. package/console/settings/memory/__next._tree.txt +1 -1
  449. package/console/settings/memory/__next.settings.memory.__PAGE__.txt +3 -3
  450. package/console/settings/memory/__next.settings.memory.txt +3 -3
  451. package/console/settings/memory/__next.settings.txt +5 -5
  452. package/console/settings/memory.html +1 -1
  453. package/console/settings/memory.txt +17 -17
  454. package/console/settings/oauth-apps/__next._full.txt +17 -17
  455. package/console/settings/oauth-apps/__next._head.txt +4 -4
  456. package/console/settings/oauth-apps/__next._index.txt +9 -9
  457. package/console/settings/oauth-apps/__next._tree.txt +1 -1
  458. package/console/settings/oauth-apps/__next.settings.oauth-apps.__PAGE__.txt +3 -3
  459. package/console/settings/oauth-apps/__next.settings.oauth-apps.txt +3 -3
  460. package/console/settings/oauth-apps/__next.settings.txt +5 -5
  461. package/console/settings/oauth-apps.html +1 -1
  462. package/console/settings/oauth-apps.txt +17 -17
  463. package/console/settings/org-preferences/__next._full.txt +17 -17
  464. package/console/settings/org-preferences/__next._head.txt +4 -4
  465. package/console/settings/org-preferences/__next._index.txt +9 -9
  466. package/console/settings/org-preferences/__next._tree.txt +1 -1
  467. package/console/settings/org-preferences/__next.settings.org-preferences.__PAGE__.txt +3 -3
  468. package/console/settings/org-preferences/__next.settings.org-preferences.txt +3 -3
  469. package/console/settings/org-preferences/__next.settings.txt +5 -5
  470. package/console/settings/org-preferences.html +1 -1
  471. package/console/settings/org-preferences.txt +17 -17
  472. package/console/settings/org-profile/__next._full.txt +17 -17
  473. package/console/settings/org-profile/__next._head.txt +4 -4
  474. package/console/settings/org-profile/__next._index.txt +9 -9
  475. package/console/settings/org-profile/__next._tree.txt +1 -1
  476. package/console/settings/org-profile/__next.settings.org-profile.__PAGE__.txt +3 -3
  477. package/console/settings/org-profile/__next.settings.org-profile.txt +3 -3
  478. package/console/settings/org-profile/__next.settings.txt +5 -5
  479. package/console/settings/org-profile.html +1 -1
  480. package/console/settings/org-profile.txt +17 -17
  481. package/console/settings/plans/__next._full.txt +18 -18
  482. package/console/settings/plans/__next._head.txt +4 -4
  483. package/console/settings/plans/__next._index.txt +9 -9
  484. package/console/settings/plans/__next._tree.txt +1 -1
  485. package/console/settings/plans/__next.settings.plans.__PAGE__.txt +4 -4
  486. package/console/settings/plans/__next.settings.plans.txt +3 -3
  487. package/console/settings/plans/__next.settings.txt +5 -5
  488. package/console/settings/plans.html +1 -1
  489. package/console/settings/plans.txt +18 -18
  490. package/console/settings/platform-clients/__next._full.txt +17 -17
  491. package/console/settings/platform-clients/__next._head.txt +4 -4
  492. package/console/settings/platform-clients/__next._index.txt +9 -9
  493. package/console/settings/platform-clients/__next._tree.txt +1 -1
  494. package/console/settings/platform-clients/__next.settings.platform-clients.__PAGE__.txt +3 -3
  495. package/console/settings/platform-clients/__next.settings.platform-clients.txt +3 -3
  496. package/console/settings/platform-clients/__next.settings.txt +5 -5
  497. package/console/settings/platform-clients.html +1 -1
  498. package/console/settings/platform-clients.txt +17 -17
  499. package/console/settings/pricing-governance/__next._full.txt +18 -18
  500. package/console/settings/pricing-governance/__next._head.txt +4 -4
  501. package/console/settings/pricing-governance/__next._index.txt +9 -9
  502. package/console/settings/pricing-governance/__next._tree.txt +1 -1
  503. package/console/settings/pricing-governance/__next.settings.pricing-governance.__PAGE__.txt +4 -4
  504. package/console/settings/pricing-governance/__next.settings.pricing-governance.txt +3 -3
  505. package/console/settings/pricing-governance/__next.settings.txt +5 -5
  506. package/console/settings/pricing-governance.html +1 -1
  507. package/console/settings/pricing-governance.txt +18 -18
  508. package/console/settings/provider-standing/__next._full.txt +18 -18
  509. package/console/settings/provider-standing/__next._head.txt +4 -4
  510. package/console/settings/provider-standing/__next._index.txt +9 -9
  511. package/console/settings/provider-standing/__next._tree.txt +1 -1
  512. package/console/settings/provider-standing/__next.settings.provider-standing.__PAGE__.txt +4 -4
  513. package/console/settings/provider-standing/__next.settings.provider-standing.txt +3 -3
  514. package/console/settings/provider-standing/__next.settings.txt +5 -5
  515. package/console/settings/provider-standing.html +1 -1
  516. package/console/settings/provider-standing.txt +18 -18
  517. package/console/settings/teams/__next._full.txt +17 -17
  518. package/console/settings/teams/__next._head.txt +4 -4
  519. package/console/settings/teams/__next._index.txt +9 -9
  520. package/console/settings/teams/__next._tree.txt +1 -1
  521. package/console/settings/teams/__next.settings.teams.__PAGE__.txt +3 -3
  522. package/console/settings/teams/__next.settings.teams.txt +3 -3
  523. package/console/settings/teams/__next.settings.txt +5 -5
  524. package/console/settings/teams.html +1 -1
  525. package/console/settings/teams.txt +17 -17
  526. package/console/settings/usage/__next._full.txt +17 -17
  527. package/console/settings/usage/__next._head.txt +4 -4
  528. package/console/settings/usage/__next._index.txt +9 -9
  529. package/console/settings/usage/__next._tree.txt +1 -1
  530. package/console/settings/usage/__next.settings.txt +5 -5
  531. package/console/settings/usage/__next.settings.usage.__PAGE__.txt +3 -3
  532. package/console/settings/usage/__next.settings.usage.txt +3 -3
  533. package/console/settings/usage.html +1 -1
  534. package/console/settings/usage.txt +17 -17
  535. package/console/settings.html +1 -1
  536. package/console/settings.txt +18 -18
  537. package/console/workflows/__next._full.txt +14 -14
  538. package/console/workflows/__next._head.txt +4 -4
  539. package/console/workflows/__next._index.txt +9 -9
  540. package/console/workflows/__next._tree.txt +1 -1
  541. package/console/workflows/__next.workflows.__PAGE__.txt +2 -2
  542. package/console/workflows/__next.workflows.txt +3 -3
  543. package/console/workflows/__placeholder__/__placeholder__/__next._full.txt +15 -15
  544. package/console/workflows/__placeholder__/__placeholder__/__next._head.txt +4 -4
  545. package/console/workflows/__placeholder__/__placeholder__/__next._index.txt +9 -9
  546. package/console/workflows/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  547. package/console/workflows/__placeholder__/__placeholder__/__next.workflows.$d$org.$d$slug.__PAGE__.txt +3 -3
  548. package/console/workflows/__placeholder__/__placeholder__/__next.workflows.$d$org.$d$slug.txt +3 -3
  549. package/console/workflows/__placeholder__/__placeholder__/__next.workflows.$d$org.txt +3 -3
  550. package/console/workflows/__placeholder__/__placeholder__/__next.workflows.txt +3 -3
  551. package/console/workflows/__placeholder__/__placeholder__.html +1 -1
  552. package/console/workflows/__placeholder__/__placeholder__.txt +15 -15
  553. package/console/workflows/executions/__next._full.txt +14 -14
  554. package/console/workflows/executions/__next._head.txt +4 -4
  555. package/console/workflows/executions/__next._index.txt +9 -9
  556. package/console/workflows/executions/__next._tree.txt +1 -1
  557. package/console/workflows/executions/__next.workflows.executions.__PAGE__.txt +2 -2
  558. package/console/workflows/executions/__next.workflows.executions.txt +3 -3
  559. package/console/workflows/executions/__next.workflows.txt +3 -3
  560. package/console/workflows/executions/__placeholder__/__next._full.txt +15 -15
  561. package/console/workflows/executions/__placeholder__/__next._head.txt +4 -4
  562. package/console/workflows/executions/__placeholder__/__next._index.txt +9 -9
  563. package/console/workflows/executions/__placeholder__/__next._tree.txt +1 -1
  564. package/console/workflows/executions/__placeholder__/__next.workflows.executions.$d$id.__PAGE__.txt +3 -3
  565. package/console/workflows/executions/__placeholder__/__next.workflows.executions.$d$id.txt +3 -3
  566. package/console/workflows/executions/__placeholder__/__next.workflows.executions.txt +3 -3
  567. package/console/workflows/executions/__placeholder__/__next.workflows.txt +3 -3
  568. package/console/workflows/executions/__placeholder__.html +1 -1
  569. package/console/workflows/executions/__placeholder__.txt +15 -15
  570. package/console/workflows/executions.html +1 -1
  571. package/console/workflows/executions.txt +14 -14
  572. package/console/workflows.html +1 -1
  573. package/console/workflows.txt +14 -14
  574. package/main.js +2 -2
  575. package/package.json +6 -6
  576. package/console/_next/static/chunks/01t5bq-0-a_i1.js +0 -1
  577. package/console/_next/static/chunks/034-2xp~e539n.js +0 -1
  578. package/console/_next/static/chunks/0lq22-4n7_uyt.js +0 -34
  579. package/console/_next/static/chunks/0m94l3p58m6us.js +0 -1
  580. package/console/_next/static/chunks/0ruvic3m1tid0.js +0 -1
  581. package/console/_next/static/chunks/0vx4g_lnlck8u.js +0 -1
  582. /package/console/_next/static/{HRj8nfJ74nB80EJaNY136 → 8QW0GR8B_i8LjUXDFgwS7}/_buildManifest.js +0 -0
  583. /package/console/_next/static/{HRj8nfJ74nB80EJaNY136 → 8QW0GR8B_i8LjUXDFgwS7}/_clientMiddlewareManifest.js +0 -0
  584. /package/console/_next/static/{HRj8nfJ74nB80EJaNY136 → 8QW0GR8B_i8LjUXDFgwS7}/_ssgManifest.js +0 -0
package/main.js CHANGED
@@ -485,7 +485,7 @@ caused by: ${_Layerr.fullStack(cause)}`:err2.stack??""}static info(err2){assertE
485
485
  `);return}let root5=import_node_path10.default.resolve(basePath),filePath=import_node_path10.default.resolve(root5,key);if(filePath!==root5&&!filePath.startsWith(root5+import_node_path10.default.sep)){res.writeHead(404),res.end(`404 page not found
486
486
  `);return}let info;try{info=await(0,import_promises5.stat)(filePath)}catch{res.writeHead(404),res.end(`404 page not found
487
487
  `);return}if(!info.isFile()){res.writeHead(404),res.end(`404 page not found
488
- `);return}let headers2={"Content-Length":String(info.size)},downloadName=url.searchParams.get(LOCAL_DOWNLOAD_QUERY_PARAM)??"";if(downloadName!==""&&(headers2["Content-Disposition"]=contentDispositionAttachment(downloadName)),res.writeHead(200,headers2),req.method==="HEAD"){res.end();return}let stream=(0,import_node_fs7.createReadStream)(filePath);stream.on("error",error2=>{logger2.error("artifact file stream failed",{key,error:error2.message}),res.destroy()}),stream.pipe(res)}catch(error2){logger2.error("artifact file server request failed",{error:error2 instanceof Error?error2.message:String(error2)}),res.headersSent||res.writeHead(500),res.end()}}async function warnOnLegacyArtifactLayout(basePath,logger2){for(let sub of["attachments","artifacts"]){let legacy=import_node_path10.default.join(basePath,"artifacts",sub);try{if((await(0,import_promises5.stat)(legacy)).isDirectory()){logger2.warn("Detected artifacts under a pre-#285 layout at <base>/artifacts/*. The artifact root is now <base> itself. Move <base>/artifacts/* up into <base> (or set ARTIFACT_LOCAL_BASE_PATH to the old <base>/artifacts) so existing artifacts remain reachable.",{legacyDir:import_node_path10.default.join(basePath,"artifacts"),artifactRoot:basePath});return}}catch{}}}var file_ai_stigmer_agentic_channelapp_v1_command=fileDesc("Ci5haS9zdGlnbWVyL2FnZW50aWMvY2hhbm5lbGFwcC92MS9jb21tYW5kLnByb3RvEiBhaS5zdGlnbWVyLmFnZW50aWMuY2hhbm5lbGFwcC52MTKOBQobQ2hhbm5lbEFwcENvbW1hbmRDb250cm9sbGVyEmMKBWFwcGx5EiwuYWkuc3RpZ21lci5hZ2VudGljLmNoYW5uZWxhcHAudjEuQ2hhbm5lbEFwcBosLmFpLnN0aWdtZXIuYWdlbnRpYy5jaGFubmVsYXBwLnYxLkNoYW5uZWxBcHAStQEKBmNyZWF0ZRIsLmFpLnN0aWdtZXIuYWdlbnRpYy5jaGFubmVsYXBwLnYxLkNoYW5uZWxBcHAaLC5haS5zdGlnbWVyLmFnZW50aWMuY2hhbm5lbGFwcC52MS5DaGFubmVsQXBwIk/CuBhLCB8QHiIMbWV0YWRhdGEub3JnKjd1bmF1dGhvcml6ZWQgdG8gY3JlYXRlIGNoYW5uZWwgYXBwIGluIHRoaXMgb3JnYW5pemF0aW9uEp8BCgZ1cGRhdGUSLC5haS5zdGlnbWVyLmFnZW50aWMuY2hhbm5lbGFwcC52MS5DaGFubmVsQXBwGiwuYWkuc3RpZ21lci5hZ2VudGljLmNoYW5uZWxhcHAudjEuQ2hhbm5lbEFwcCI5wrgYNQgCEDAiC21ldGFkYXRhLmlkKiJ1bmF1dGhvcml6ZWQgdG8gdXBkYXRlIGNoYW5uZWwgYXBwEqkBCgZkZWxldGUSNi5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VEZWxldGVJbnB1dBosLmFpLnN0aWdtZXIuYWdlbnRpYy5jaGFubmVsYXBwLnYxLkNoYW5uZWxBcHAiOcK4GDUIAxAwIgtyZXNvdXJjZV9pZCoidW5hdXRob3JpemVkIHRvIGRlbGV0ZSBjaGFubmVsIGFwcBoEoP8rMGIGcHJvdG8z",[file_ai_stigmer_agentic_channelapp_v1_api,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),ChannelAppCommandController=serviceDesc(file_ai_stigmer_agentic_channelapp_v1_command,0);var file_ai_stigmer_agentic_channelapp_v1_io=fileDesc("CilhaS9zdGlnbWVyL2FnZW50aWMvY2hhbm5lbGFwcC92MS9pby5wcm90bxIgYWkuc3RpZ21lci5hZ2VudGljLmNoYW5uZWxhcHAudjEiTAoLQ2hhbm5lbEFwcHMSPQoHZW50cmllcxgBIAMoCzIsLmFpLnN0aWdtZXIuYWdlbnRpYy5jaGFubmVsYXBwLnYxLkNoYW5uZWxBcHAiMQoZTGlzdENoYW5uZWxBcHBzQnlPcmdJbnB1dBIUCgNvcmcYASABKAlCB7pIBHICEAFiBnByb3RvMw",[file_ai_stigmer_agentic_channelapp_v1_api,file_buf_validate_validate]),ChannelAppsSchema=messageDesc2(file_ai_stigmer_agentic_channelapp_v1_io,0);var file_ai_stigmer_agentic_channelapp_v1_query=fileDesc("CixhaS9zdGlnbWVyL2FnZW50aWMvY2hhbm5lbGFwcC92MS9xdWVyeS5wcm90bxIgYWkuc3RpZ21lci5hZ2VudGljLmNoYW5uZWxhcHAudjEy9gMKGUNoYW5uZWxBcHBRdWVyeUNvbnRyb2xsZXISlQEKA2dldBItLmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZUlkGiwuYWkuc3RpZ21lci5hZ2VudGljLmNoYW5uZWxhcHAudjEuQ2hhbm5lbEFwcCIxwrgYLQgBEDAiBXZhbHVlKiB1bmF1dGhvcml6ZWQgdG8gdmlldyBjaGFubmVsIGFwcBJ6Cg5nZXRCeVJlZmVyZW5jZRI0LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVJlZmVyZW5jZRosLmFpLnN0aWdtZXIuYWdlbnRpYy5jaGFubmVsYXBwLnYxLkNoYW5uZWxBcHAiBNC4GAESvgEKCWxpc3RCeU9yZxI7LmFpLnN0aWdtZXIuYWdlbnRpYy5jaGFubmVsYXBwLnYxLkxpc3RDaGFubmVsQXBwc0J5T3JnSW5wdXQaLS5haS5zdGlnbWVyLmFnZW50aWMuY2hhbm5lbGFwcC52MS5DaGFubmVsQXBwcyJFwrgYQQgBEB4iA29yZyo2dW5hdXRob3JpemVkIHRvIGxpc3QgY2hhbm5lbCBhcHBzIGluIHRoaXMgb3JnYW5pemF0aW9uGgSg/yswYgZwcm90bzM",[file_ai_stigmer_agentic_channelapp_v1_api,file_ai_stigmer_agentic_channelapp_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),ChannelAppQueryController=serviceDesc(file_ai_stigmer_agentic_channelapp_v1_query,0);async function destroySecretBackingState(secretService,logger2,fields2,storedValues){for(let storedValue of storedValues)if(storedValue!=="")try{await secretService.delete(storedValue)}catch(error2){logger2.error("secret backing-state destruction failed after persist \u2014 external state may be orphaned",{...fields2,error:error2 instanceof Error?error2.message:String(error2)})}}function newDestroySecretBackingStateStep(secretService,logger2,extractSecretValues){return{name:"DestroySecretBackingState",async execute(ctx){let deleted=ctx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)return;let metadata=deleted.metadata;await destroySecretBackingState(secretService,logger2,{kind:getKindName(ctx.apiResourceKind),resourceId:metadata?.id??""},extractSecretValues(deleted))}}}var REDACTED_MARKER2="***REDACTED***";function plaintextRequiredMessage(fieldName){return`${fieldName} must be plaintext \u2014 values carrying the 'enc:' encryption prefix are not accepted from clients`}function markerOnCreateMessage(fieldName){return`cannot use the redaction marker as ${fieldName} on create`}function noExistingSecretMessage(fieldName){return`cannot preserve ${fieldName}: no existing secret value found`}var PROVIDER_IMMUTABLE_MESSAGE="the provider of a channel app cannot be changed";function deleteBlockedByChannelMessage(org,slug,channelName){return`cannot delete ChannelApp '${org}/${slug}': referenced by agent channel '${channelName}'`}function redactChannelApp(app){let provider=app.spec?.providerConfig;switch(provider?.case){case"slack":redactSlack(provider.value);return;case"whatsapp":redactWhatsApp(provider.value);return;case void 0:return;default:{let exhaustive=provider;throw new Error(`unhandled provider arm: ${String(exhaustive)}`)}}}function redactSlack(slack){slack.clientSecret!==""&&(slack.clientSecret=REDACTED_MARKER2),slack.signingSecret!==""&&(slack.signingSecret=REDACTED_MARKER2)}function redactWhatsApp(whatsapp){whatsapp.appSecret!==""&&(whatsapp.appSecret=REDACTED_MARKER2),whatsapp.accessToken!==""&&(whatsapp.accessToken=REDACTED_MARKER2),whatsapp.verifyToken!==""&&(whatsapp.verifyToken=REDACTED_MARKER2)}function secretValuesOfChannelApp(app){let provider=app.spec?.providerConfig;switch(provider?.case){case"slack":return[provider.value.clientSecret,provider.value.signingSecret];case"whatsapp":return[provider.value.appSecret,provider.value.accessToken,provider.value.verifyToken];case void 0:return[];default:{let exhaustive=provider;throw new Error(`unhandled provider arm: ${String(exhaustive)}`)}}}function newEncryptChannelAppSecretsForCreateStep(secretService,logger2){return newEncryptChannelAppSecretsStep(secretService,logger2,!0)}function newEncryptChannelAppSecretsForUpdateStep(secretService,logger2){return newEncryptChannelAppSecretsStep(secretService,logger2,!1)}function newEncryptChannelAppSecretsStep(secretService,logger2,isCreate){async function resolveSecret(ctx,fieldName,requestValue,readExisting){if(requestValue==="")return requestValue;if(requestValue===REDACTED_MARKER2)return preserveExistingSecret2(ctx,fieldName,readExisting);if(isCiphertextShaped(requestValue))throw invalidArgumentError(plaintextRequiredMessage(fieldName));if(!secretService.isEnabled())return logger2.warn(`Encryption disabled: ${fieldName} will be stored in plaintext`),requestValue;try{return await secretService.encrypt(requestValue,EncryptionScope.forOrganization(ctx.newState.metadata?.org??""))}catch(error2){throw internalError(error2,`failed to encrypt ${fieldName}`)}}function preserveExistingSecret2(ctx,fieldName,readExisting){if(isCreate)throw invalidArgumentError(markerOnCreateMessage(fieldName));let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)throw internalError(new Error("existing resource not loaded"),`cannot preserve ${fieldName}: existing resource not loaded`);let existingSecret=readExisting(existing);if(existingSecret==="")throw invalidArgumentError(noExistingSecretMessage(fieldName));return existingSecret}return{name:"EncryptChannelAppSecrets",async execute(ctx){let provider=ctx.newState.spec?.providerConfig;switch(provider?.case){case"slack":{let slack=provider.value;slack.clientSecret=await resolveSecret(ctx,"client_secret",slack.clientSecret,existing=>existing.spec?.providerConfig.case==="slack"?existing.spec.providerConfig.value.clientSecret:""),slack.signingSecret=await resolveSecret(ctx,"signing_secret",slack.signingSecret,existing=>existing.spec?.providerConfig.case==="slack"?existing.spec.providerConfig.value.signingSecret:"");return}case"whatsapp":{let whatsapp=provider.value;whatsapp.appSecret=await resolveSecret(ctx,"app_secret",whatsapp.appSecret,existing=>existing.spec?.providerConfig.case==="whatsapp"?existing.spec.providerConfig.value.appSecret:""),whatsapp.accessToken=await resolveSecret(ctx,"access_token",whatsapp.accessToken,existing=>existing.spec?.providerConfig.case==="whatsapp"?existing.spec.providerConfig.value.accessToken:""),whatsapp.verifyToken=await resolveSecret(ctx,"verify_token",whatsapp.verifyToken,existing=>existing.spec?.providerConfig.case==="whatsapp"?existing.spec.providerConfig.value.verifyToken:"");return}case void 0:return;default:{let exhaustive=provider;throw new Error(`unhandled provider arm: ${String(exhaustive)}`)}}}}}function newValidateProviderImmutableStep(){return{name:"ValidateProviderImmutable",execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)throw internalError(new Error("existing channel app not found in context"),"existing channel app not found in context");let existingCase=existing.spec?.providerConfig.case,inputCase=ctx.input.spec?.providerConfig.case;if(existingCase!==inputCase)throw invalidArgumentError(PROVIDER_IMMUTABLE_MESSAGE)}}}function newCheckNoReferencingChannelsStep(store,logger2){return{name:"CheckNoReferencingChannels",async execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)throw internalError(new Error("existing ChannelApp not loaded in delete pipeline"),"existing ChannelApp not loaded in delete pipeline");let org=existing.metadata?.org??"",slug=existing.metadata?.slug??"",rows;try{rows=await store.listResources(ApiResourceKind.agent_channel)}catch(error2){throw internalError(error2,"failed to list agent channels for referential integrity check")}for(let bytes of rows){let channel;try{channel=fromBinary2(AgentChannelSchema,bytes)}catch{logger2.warn("Failed to unmarshal agent channel during referential integrity check, skipping");continue}let ref=channel.spec?.appRef;if(ref===void 0||ref.slug==="")continue;if((ref.org!==""?ref.org:channel.metadata?.org??"")===org&&ref.slug===slug)throw failedPreconditionError(deleteBlockedByChannelMessage(org,slug,channel.metadata?.name??""))}}}}function registerChannelAppServices(router,deps){router.service(ChannelAppCommandController,{apply:(app,ctx)=>apply6(deps,app,ctx),create:(app,ctx)=>createChannelApp(deps,app,ctx),update:(app,ctx)=>update9(deps,app,ctx),delete:(input,ctx)=>deleteChannelApp(deps,input,ctx)}),router.service(ChannelAppQueryController,{get:(id,ctx)=>get12(deps,id,ctx),getByReference:(ref,ctx)=>getByReference6(deps,ref,ctx),listByOrg:(req,ctx)=>listByOrg(deps,req,ctx)})}function kindOf11(ctx){return ctx.values.get(apiResourceKindKey)}async function createChannelApp(deps,app,ctx){let reqCtx=new RequestContext(ChannelAppSchema,app,callerIdentityOf(ctx),kindOf11(ctx));return await newPipeline("channelapp-create",deps.logger).addStep(newAuthorizeStep(ChannelAppCommandController.method.create,deps.authorizer)).addStep(newResolveSlugStep()).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newEncryptChannelAppSecretsForCreateStep(deps.secretService,deps.logger)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).build().execute(reqCtx),redactChannelApp(reqCtx.newState),reqCtx.newState}async function update9(deps,app,ctx){let reqCtx=new RequestContext(ChannelAppSchema,app,callerIdentityOf(ctx),kindOf11(ctx));return await newPipeline("channelapp-update",deps.logger).addStep(newAuthorizeStep(ChannelAppCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingStep(deps.store)).addStep(newValidateProviderImmutableStep()).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newEncryptChannelAppSecretsForUpdateStep(deps.secretService,deps.logger)).addStep(newPersistStep(deps.store)).build().execute(reqCtx),redactChannelApp(reqCtx.newState),reqCtx.newState}async function apply6(deps,app,ctx){let reqCtx=new RequestContext(ChannelAppSchema,app,callerIdentityOf(ctx),kindOf11(ctx));await newPipeline("channelapp-apply",deps.logger).addStep(newAuthorizeStep(ChannelAppCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");return shouldCreate?createChannelApp(deps,app,ctx):update9(deps,withResolvedApplyId(ChannelAppSchema,app,reqCtx),ctx)}async function deleteChannelApp(deps,input,ctx){let reqCtx=new RequestContext(ChannelAppCommandController.method.delete.input,input,callerIdentityOf(ctx),kindOf11(ctx));reqCtx.set(RESOURCE_ID_KEY,input.resourceId),await newPipeline("channelapp-delete",deps.logger).addStep(newAuthorizeStep(ChannelAppCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingForDeleteStep(deps.store,ChannelAppSchema)).addStep(newCheckNoReferencingChannelsStep(deps.store,deps.logger)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDestroySecretBackingStateStep(deps.secretService,deps.logger,secretValuesOfChannelApp)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted ChannelApp not found in context"),"deleted ChannelApp not found in context");let app=deleted;return redactChannelApp(app),app}async function get12(deps,id,ctx){let reqCtx=new RequestContext(ChannelAppQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf11(ctx));await newPipeline("channelapp-get",deps.logger).addStep(newAuthorizeStep(ChannelAppQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,ChannelAppSchema)).build().execute(reqCtx);let app=reqCtx.get(TARGET_RESOURCE_KEY);return redactChannelApp(app),app}async function getByReference6(deps,ref,ctx){let reqCtx=new RequestContext(ChannelAppQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf11(ctx));await newPipeline("channelapp-get-by-reference",deps.logger).addStep(newAuthorizeStep(ChannelAppQueryController.method.getByReference,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadByReferenceStep(deps.store,ChannelAppSchema)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,loadedTargetAsMethod(ChannelAppQueryController.method.get))).build().execute(reqCtx);let app=reqCtx.get(TARGET_RESOURCE_KEY);return redactChannelApp(app),app}var LIST_RESULT_KEY4="listResult";async function listByOrg(deps,req,ctx){let reqCtx=new RequestContext(ChannelAppQueryController.method.listByOrg.input,req,callerIdentityOf(ctx),kindOf11(ctx));await newPipeline("channelapp-list-by-org",deps.logger).addStep(newAuthorizeStep(ChannelAppQueryController.method.listByOrg,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newListByOrgStep(deps.store,deps.logger)).build().execute(reqCtx);let result=reqCtx.get(LIST_RESULT_KEY4);if(result===void 0)throw internalError(new Error("ChannelApp list not found in context"),"ChannelApp list not found in context");return result}function newListByOrgStep(store,logger2){return{name:"ListByOrg",async execute(ctx){let org=ctx.input.org,rows;try{rows=await store.listResources(ApiResourceKind.channel_app)}catch(error2){throw internalError(error2,"failed to list ChannelApps")}let apps=[];for(let bytes of rows){let app;try{app=fromBinary2(ChannelAppSchema,bytes)}catch{logger2.warn("Failed to unmarshal ChannelApp, skipping");continue}(app.metadata?.org??"")===org&&(redactChannelApp(app),apps.push(app))}apps.sort((a5,b7)=>compareCreatedAtDesc(a5.status?.audit?.specAudit?.createdAt,b7.status?.audit?.specAudit?.createdAt)),ctx.set(LIST_RESULT_KEY4,create2(ChannelAppsSchema,{entries:apps}))}}}var file_ai_stigmer_agentic_environment_v1_command=fileDesc("Ci9haS9zdGlnbWVyL2FnZW50aWMvZW52aXJvbm1lbnQvdjEvY29tbWFuZC5wcm90bxIhYWkuc3RpZ21lci5hZ2VudGljLmVudmlyb25tZW50LnYxMoMKChxFbnZpcm9ubWVudENvbW1hbmRDb250cm9sbGVyEmcKBWFwcGx5Ei4uYWkuc3RpZ21lci5hZ2VudGljLmVudmlyb25tZW50LnYxLkVudmlyb25tZW50Gi4uYWkuc3RpZ21lci5hZ2VudGljLmVudmlyb25tZW50LnYxLkVudmlyb25tZW50ErkBCgZjcmVhdGUSLi5haS5zdGlnbWVyLmFnZW50aWMuZW52aXJvbm1lbnQudjEuRW52aXJvbm1lbnQaLi5haS5zdGlnbWVyLmFnZW50aWMuZW52aXJvbm1lbnQudjEuRW52aXJvbm1lbnQiT8K4GEsIDBAeIgxtZXRhZGF0YS5vcmcqN3VuYXV0aG9yaXplZCB0byBjcmVhdGUgZW52aXJvbm1lbnQgaW4gdGhpcyBvcmdhbml6YXRpb24SowEKBnVwZGF0ZRIuLmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5FbnZpcm9ubWVudBouLmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5FbnZpcm9ubWVudCI5wrgYNQgCEDUiC21ldGFkYXRhLmlkKiJ1bmF1dGhvcml6ZWQgdG8gdXBkYXRlIGVudmlyb25tZW50Er8BChB1cGRhdGVWaXNpYmlsaXR5EjUuYWkuc3RpZ21lci5jb21tb25zLmFwaXJlc291cmNlLlVwZGF0ZVZpc2liaWxpdHlJbnB1dBouLmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5FbnZpcm9ubWVudCJEwrgYQAgCEDUiC3Jlc291cmNlX2lkKi11bmF1dGhvcml6ZWQgdG8gdXBkYXRlIGVudmlyb25tZW50IHZpc2liaWxpdHkSqwEKBmRlbGV0ZRI2LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZURlbGV0ZUlucHV0Gi4uYWkuc3RpZ21lci5hZ2VudGljLmVudmlyb25tZW50LnYxLkVudmlyb25tZW50IjnCuBg1CAIQNSILcmVzb3VyY2VfaWQqInVuYXV0aG9yaXplZCB0byBkZWxldGUgZW52aXJvbm1lbnQSzwEKD3VwZGF0ZVZhcmlhYmxlcxJELmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5VcGRhdGVFbnZpcm9ubWVudFZhcmlhYmxlc1JlcXVlc3QaLi5haS5zdGlnbWVyLmFnZW50aWMuZW52aXJvbm1lbnQudjEuRW52aXJvbm1lbnQiRsK4GEIIAhA1Ig5lbnZpcm9ubWVudF9pZCosdW5hdXRob3JpemVkIHRvIHVwZGF0ZSBlbnZpcm9ubWVudCB2YXJpYWJsZXMSzwEKD3JlbW92ZVZhcmlhYmxlcxJELmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5SZW1vdmVFbnZpcm9ubWVudFZhcmlhYmxlc1JlcXVlc3QaLi5haS5zdGlnbWVyLmFnZW50aWMuZW52aXJvbm1lbnQudjEuRW52aXJvbm1lbnQiRsK4GEIIAhA1Ig5lbnZpcm9ubWVudF9pZCosdW5hdXRob3JpemVkIHRvIHJlbW92ZSBlbnZpcm9ubWVudCB2YXJpYWJsZXMaBKD/KzViBnByb3RvMw",[file_ai_stigmer_agentic_environment_v1_api,file_ai_stigmer_agentic_environment_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),EnvironmentCommandController=serviceDesc(file_ai_stigmer_agentic_environment_v1_command,0);var file_ai_stigmer_agentic_environment_v1_query=fileDesc("Ci1haS9zdGlnbWVyL2FnZW50aWMvZW52aXJvbm1lbnQvdjEvcXVlcnkucHJvdG8SIWFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MTKMBQoaRW52aXJvbm1lbnRRdWVyeUNvbnRyb2xsZXISlgEKA2dldBItLmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZUlkGi4uYWkuc3RpZ21lci5hZ2VudGljLmVudmlyb25tZW50LnYxLkVudmlyb25tZW50IjDCuBgsCAEQNSIFdmFsdWUqH3VuYXV0aG9yaXplZCB0byBnZXQgZW52aXJvbm1lbnQSfAoOZ2V0QnlSZWZlcmVuY2USNC5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VSZWZlcmVuY2UaLi5haS5zdGlnbWVyLmFnZW50aWMuZW52aXJvbm1lbnQudjEuRW52aXJvbm1lbnQiBNC4GAES0gEKDmdldFNlY3JldFZhbHVlEj4uYWkuc3RpZ21lci5hZ2VudGljLmVudmlyb25tZW50LnYxLkVudmlyb25tZW50U2VjcmV0VmFsdWVJbnB1dBozLmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5FbnZpcm9ubWVudFZhbHVlIkvCuBhHCBAQNSIOZW52aXJvbm1lbnRfaWQqMXVuYXV0aG9yaXplZCB0byByZWFkIHNlY3JldCB2YWx1ZXMgKGNyZWF0b3Itb25seSkSfAoEbGlzdBI6LmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5MaXN0RW52aXJvbm1lbnRzUmVxdWVzdBoyLmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5FbnZpcm9ubWVudExpc3QiBNC4GAEaBKD/KzViBnByb3RvMw",[file_ai_stigmer_agentic_environment_v1_api,file_ai_stigmer_agentic_environment_v1_io,file_ai_stigmer_agentic_environment_v1_spec,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),EnvironmentQueryController=serviceDesc(file_ai_stigmer_agentic_environment_v1_query,0);function redactEnvironmentSecrets(env2){let data=env2?.spec?.data;if(data!==void 0)for(let value of Object.values(data))value.isSecret&&value.value!==""&&(value.value=REDACTED_MARKER)}function shareRestrictionReason(metadata){let labels=metadata?.labels??{};return labels[PERSONAL_LABEL_KEY]===PERSONAL_LABEL_VALUE?PERSONAL_SHARE_RESTRICTION:labels[MANAGED_LABEL_KEY]===MANAGED_LABEL_VALUE?MANAGED_SHARE_RESTRICTION:""}var environmentSearchExtractor={kind:ApiResourceKind.environment,schema:EnvironmentSchema,getSearchSummary(resource){return resource.spec?.description??""},toSearchResult(resource,score){let env2=resource;return buildSearchResult({kind:ApiResourceKind.environment,metadata:env2.metadata,summary:env2.spec?.description??"",score,createdAt:env2.status?.audit?.specAudit?.createdAt,updatedAt:env2.status?.audit?.specAudit?.updatedAt})},getSearchIndexEntry(resource){let env2=resource,metadata=env2.metadata;if(metadata!==void 0)return{name:metadata.name,description:env2.spec?.description??"",tags:metadata.tags.join(" "),org:metadata.org,visibility:ApiResourceVisibility[metadata.visibility]??"",createdAt:Number(env2.status?.audit?.specAudit?.createdAt?.seconds??0n)}}};var SECRET_VALUE_KEY="secretValue",UPDATED_ENVIRONMENT_KEY="updatedEnvironment";function newPreserveRedactedSecretsStep(){return{name:"PreserveRedactedSecrets",execute(ctx){let data=ctx.newState.spec?.data;if(data===void 0||Object.keys(data).length===0)return;let existingData=ctx.get(EXISTING_RESOURCE_KEY)?.spec?.data??{};for(let[key,value]of Object.entries(data))if(value.isSecret){if(value.value===REDACTED_MARKER){let existingEntry=existingData[key];if(existingEntry!==void 0&&existingEntry.isSecret){data[key]=existingEntry;continue}throw invalidArgumentError(markerRejectionMessage(key))}if(isCiphertextShaped(value.value))throw invalidArgumentError(forgedCiphertextMessage(key))}}}}function newEncryptSecretValuesStep(secretService,logger2){return{name:"EncryptSecretValues",async execute(ctx){let env2=ctx.newState,data=env2.spec?.data;if(!(data===void 0||Object.keys(data).length===0)){if(!secretService.isEnabled()){hasNonEmptySecret(data)&&logger2.warn("Encryption disabled: environment secret values will be stored in plaintext",{environmentId:env2.metadata?.id??""});return}for(let[key,value]of Object.entries(data))if(!(!value.isSecret||value.value===""))try{value.value=await secretService.encrypt(value.value,EncryptionScope.forOrganization(env2.metadata?.org??""))}catch(error2){throw internalError(error2,`failed to encrypt secret value for variable '${key}'`)}}}}}function hasNonEmptySecret(data){return Object.values(data).some(v=>v.isSecret&&v.value!=="")}function newEnforcePersonalUniquenessStep(store){return{name:"EnforcePersonalEnvUniqueness",async execute(ctx){let metadata=ctx.newState.metadata;if(metadata===void 0||metadata.labels[PERSONAL_LABEL_KEY]!==PERSONAL_LABEL_VALUE)return;let existing;try{existing=await findResourceByLabelAndOrg(store,ctx.apiResourceKind,EnvironmentSchema,PERSONAL_LABEL_KEY,PERSONAL_LABEL_VALUE,metadata.org)}catch(error2){throw internalError(error2,"failed to check personal environment uniqueness")}if(existing!==void 0)throw new ConnectError(personalEnvironmentExistsMessage(existing.metadata?.id??""),Code.AlreadyExists)}}}function newLoadEnvironmentByIdStep(store){return{name:"LoadEnvironmentByID",async execute(ctx){let environmentId=ctx.input.environmentId;if(typeof environmentId!="string"||environmentId==="")throw invalidArgumentError("environment_id is required");let env2;try{env2=await store.getResource(ctx.apiResourceKind,environmentId,EnvironmentSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("environment",environmentId):internalError(error2,"failed to load environment")}ctx.set(TARGET_RESOURCE_KEY,env2)}}}function newExtractAndDecryptSingleKeyStep(secretService,logger2){return{name:"ExtractAndDecryptSingleKey",async execute(ctx){let key=ctx.input.key,env2=ctx.get(TARGET_RESOURCE_KEY);if(env2===void 0)throw internalError(new Error("targetResource missing or wrong type"),"environment not loaded in context");let envValue=env2.spec?.data[key];if(envValue===void 0)throw notFoundError("environment key",key);if(envValue.isSecret&&envValue.value!==""){let decrypted;try{decrypted=await secretService.decrypt(envValue.value)}catch(error2){throw logger2.error("Failed to decrypt secret value",{key,error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to decrypt secret value")}ctx.set(SECRET_VALUE_KEY,create2(EnvironmentValueSchema,{value:decrypted,isSecret:!0,description:envValue.description}));return}ctx.set(SECRET_VALUE_KEY,envValue)}}}function newMergeVariablesAndPersistStep(store,secretService,logger2){return{name:"MergeVariablesAndPersist",async execute(ctx){let env2=ctx.get(TARGET_RESOURCE_KEY);if(env2===void 0)throw internalError(new Error("targetResource missing or wrong type"),"environment not loaded in context");env2.spec===void 0&&(env2.spec=create2(EnvironmentSpecSchema,{}));let incoming=ctx.input.variables;for(let[key,incomingValue]of Object.entries(incoming)){let value=incomingValue;if(value.isSecret&&value.value===REDACTED_MARKER){let existing=env2.spec.data[key];if(existing!==void 0&&existing.isSecret)continue;throw invalidArgumentError(markerRejectionMessage(key))}if(value.isSecret&&isCiphertextShaped(value.value))throw invalidArgumentError(forgedCiphertextMessage(key));if(value.isSecret&&value.value!=="")if(!secretService.isEnabled())logger2.warn("Encryption disabled: environment secret value will be stored in plaintext",{key});else{let encrypted;try{encrypted=await secretService.encrypt(value.value,EncryptionScope.forOrganization(env2.metadata?.org??""))}catch(error2){throw internalError(error2,`failed to encrypt secret value for variable '${key}'`)}value=create2(EnvironmentValueSchema,{value:encrypted,isSecret:!0,description:value.description})}env2.spec.data[key]=value}try{setAuditFieldsForUpdate(EnvironmentSchema,env2,"spec_audit",ctx.callerIdentity)}catch(error2){throw internalError(error2,"failed to set audit fields")}try{await store.saveResource(ctx.apiResourceKind,env2.metadata?.id??"",EnvironmentSchema,env2)}catch(error2){throw internalError(error2,"failed to persist environment after merging variables")}ctx.set(UPDATED_ENVIRONMENT_KEY,env2)}}}function newRemoveVariableKeysAndPersistStep(store,secretService,logger2){return{name:"RemoveVariableKeysAndPersist",async execute(ctx){let env2=ctx.get(TARGET_RESOURCE_KEY);if(env2===void 0)throw internalError(new Error("targetResource missing or wrong type"),"environment not loaded in context");let keys=ctx.input.keys,removedSecretValues=[];if(env2.spec?.data!==void 0)for(let key of keys){let removed=env2.spec.data[key];removed!==void 0&&removed.isSecret&&removedSecretValues.push(removed.value),delete env2.spec.data[key]}try{setAuditFieldsForUpdate(EnvironmentSchema,env2,"spec_audit",ctx.callerIdentity)}catch(error2){throw internalError(error2,"failed to set audit fields")}try{await store.saveResource(ctx.apiResourceKind,env2.metadata?.id??"",EnvironmentSchema,env2)}catch(error2){throw internalError(error2,"failed to persist environment after removing variables")}await destroySecretBackingState(secretService,logger2,{kind:"environment",resourceId:env2.metadata?.id??"",operation:"removeVariables"},removedSecretValues),ctx.set(UPDATED_ENVIRONMENT_KEY,env2)}}}function newDestroyDroppedEnvironmentSecretsStep(secretService,logger2){return{name:"DestroyDroppedEnvironmentSecrets",async execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY),oldData=existing?.spec?.data;if(oldData===void 0)return;let newData=ctx.newState.spec?.data??{},droppedSecretValues=Object.entries(oldData).filter(([key,value])=>value.isSecret&&newData[key]===void 0).map(([,value])=>value.value);await destroySecretBackingState(secretService,logger2,{kind:"environment",resourceId:existing?.metadata?.id??"",operation:"update"},droppedSecretValues)}}}function secretValuesOfEnvironment(env2){return Object.values(env2.spec?.data??{}).filter(value=>value.isSecret).map(value=>value.value)}function registerEnvironmentServices(router,deps){router.service(EnvironmentCommandController,{apply:(env2,ctx)=>apply7(deps,env2,ctx),create:(env2,ctx)=>createEnvironment(deps,env2,ctx),update:(env2,ctx)=>update10(deps,env2,ctx),updateVisibility:(input,ctx)=>updateVisibility3(deps,input,ctx),delete:(input,ctx)=>deleteEnvironment(deps,input,ctx),updateVariables:(req,ctx)=>updateVariables(deps,req,ctx),removeVariables:(req,ctx)=>removeVariables(deps,req,ctx)}),router.service(EnvironmentQueryController,{get:(id,ctx)=>get13(deps,id,ctx),getByReference:(ref,ctx)=>getByReference7(deps,ref,ctx),getSecretValue:(input,ctx)=>getSecretValue(deps,input,ctx),list:(req,ctx)=>list8(deps,req,ctx)})}function kindOf12(ctx){return ctx.values.get(apiResourceKindKey)}async function createEnvironment(deps,env2,ctx){let reqCtx=new RequestContext(EnvironmentSchema,env2,callerIdentityOf(ctx),kindOf12(ctx));return await newPipeline("environment-create",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.create,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newResolveSlugStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newEnforcePersonalUniquenessStep(deps.store)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newPreserveRedactedSecretsStep()).addStep(newEncryptSecretValuesStep(deps.secretService,deps.logger)).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).addStep(newIndexSearchStep(deps.store,environmentSearchExtractor,deps.logger)).build().execute(reqCtx),redactEnvironmentSecrets(reqCtx.newState),reqCtx.newState}async function update10(deps,env2,ctx){let reqCtx=new RequestContext(EnvironmentSchema,env2,callerIdentityOf(ctx),kindOf12(ctx));return await newPipeline("environment-update",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingStep(deps.store)).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newPreserveRedactedSecretsStep()).addStep(newEncryptSecretValuesStep(deps.secretService,deps.logger)).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store)).addStep(newPersistStep(deps.store)).addStep(newDestroyDroppedEnvironmentSecretsStep(deps.secretService,deps.logger)).addStep(newIndexSearchStep(deps.store,environmentSearchExtractor,deps.logger)).build().execute(reqCtx),redactEnvironmentSecrets(reqCtx.newState),reqCtx.newState}async function apply7(deps,env2,ctx){let reqCtx=new RequestContext(EnvironmentSchema,env2,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-apply",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");return shouldCreate?createEnvironment(deps,env2,ctx):update10(deps,withResolvedApplyId(EnvironmentSchema,env2,reqCtx),ctx)}async function deleteEnvironment(deps,input,ctx){let reqCtx=new RequestContext(EnvironmentCommandController.method.delete.input,input,callerIdentityOf(ctx),kindOf12(ctx));reqCtx.set(RESOURCE_ID_KEY,input.resourceId),await newPipeline("environment-delete",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingForDeleteStep(deps.store,EnvironmentSchema)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDestroySecretBackingStateStep(deps.secretService,deps.logger,secretValuesOfEnvironment)).addStep(newDeleteSearchIndexStep(deps.store,deps.logger)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted environment not found in context"),"deleted environment not found in context");let env2=deleted;return redactEnvironmentSecrets(env2),env2}var UPDATE_VISIBILITY_ENVIRONMENT_KEY="updateVisibilityEnvironment";async function updateVisibility3(deps,input,ctx){let reqCtx=new RequestContext(EnvironmentCommandController.method.updateVisibility.input,input,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-update-visibility",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.updateVisibility,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadEnvironmentForVisibilityUpdateStep(deps.store)).addStep(newRecordVisibilityBeforeUpdateStep(UPDATE_VISIBILITY_ENVIRONMENT_KEY)).addStep(newValidateVisibilityUpdateStep()).addStep(newValidateEnvironmentShareRestrictionStep()).addStep(newSetEnvironmentVisibilityStep()).addStep(newPersistEnvironmentForVisibilityUpdateStep(deps.store)).addStep(newUpdateVisibilityTuplesStep(deps.authorizationLifecycle,UPDATE_VISIBILITY_ENVIRONMENT_KEY)).addStep(newIndexEnvironmentAfterVisibilityUpdateStep(deps.store,deps.logger)).build().execute(reqCtx);let env2=reqCtx.get(UPDATE_VISIBILITY_ENVIRONMENT_KEY);return redactEnvironmentSecrets(env2),env2}function newLoadEnvironmentForVisibilityUpdateStep(store){return{name:"LoadEnvironmentForVisibilityUpdate",async execute(ctx){let input=ctx.input,env2;try{env2=await store.getResource(ctx.apiResourceKind,input.resourceId,EnvironmentSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("environment",input.resourceId):internalError(error2,"failed to load environment")}ctx.set(UPDATE_VISIBILITY_ENVIRONMENT_KEY,env2)}}}function newValidateEnvironmentShareRestrictionStep(){return{name:"ValidateEnvironmentShareRestriction",execute(ctx){if(ctx.input.visibility!==ApiResourceVisibility.visibility_org)return;let env2=ctx.get(UPDATE_VISIBILITY_ENVIRONMENT_KEY),reason=shareRestrictionReason(env2.metadata);if(reason!=="")throw failedPreconditionError(reason)}}}function newSetEnvironmentVisibilityStep(){return{name:"SetVisibility",execute(ctx){let env2=ctx.get(UPDATE_VISIBILITY_ENVIRONMENT_KEY);env2.metadata!==void 0&&(env2.metadata.visibility=ctx.input.visibility),setAuditFieldsForUpdate(EnvironmentSchema,env2,"status_audit",ctx.callerIdentity)}}}function newPersistEnvironmentForVisibilityUpdateStep(store){return{name:"PersistEnvironmentForVisibilityUpdate",async execute(ctx){let env2=ctx.get(UPDATE_VISIBILITY_ENVIRONMENT_KEY);try{await store.saveResource(ctx.apiResourceKind,env2.metadata?.id??"",EnvironmentSchema,env2)}catch(error2){throw internalError(error2,"failed to save environment")}}}}function newIndexEnvironmentAfterVisibilityUpdateStep(store,logger2){return{name:"IndexEnvironmentAfterVisibilityUpdate",async execute(ctx){let env2=ctx.get(UPDATE_VISIBILITY_ENVIRONMENT_KEY),entry=environmentSearchExtractor.getSearchIndexEntry(env2);if(entry===void 0){logger2.warn("IndexEnvironmentAfterVisibilityUpdate: extractor returned nil, skipping",{id:env2.metadata?.id??""});return}try{await store.upsertSearchIndex(ctx.apiResourceKind,env2.metadata?.id??"",entry)}catch(error2){logger2.warn("IndexEnvironmentAfterVisibilityUpdate: failed (best-effort)",{id:env2.metadata?.id??"",error:error2 instanceof Error?error2.message:String(error2)})}}}}async function updateVariables(deps,req,ctx){let reqCtx=new RequestContext(EnvironmentCommandController.method.updateVariables.input,req,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-update-variables",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.updateVariables,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadEnvironmentByIdStep(deps.store)).addStep(newMergeVariablesAndPersistStep(deps.store,deps.secretService,deps.logger)).build().execute(reqCtx);let updated=reqCtx.get(UPDATED_ENVIRONMENT_KEY);return redactEnvironmentSecrets(updated),updated}async function removeVariables(deps,req,ctx){let reqCtx=new RequestContext(EnvironmentCommandController.method.removeVariables.input,req,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-remove-variables",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.removeVariables,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadEnvironmentByIdStep(deps.store)).addStep(newRemoveVariableKeysAndPersistStep(deps.store,deps.secretService,deps.logger)).build().execute(reqCtx);let updated=reqCtx.get(UPDATED_ENVIRONMENT_KEY);return redactEnvironmentSecrets(updated),updated}async function get13(deps,id,ctx){let reqCtx=new RequestContext(EnvironmentQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-get",deps.logger).addStep(newAuthorizeStep(EnvironmentQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,EnvironmentSchema)).build().execute(reqCtx);let env2=reqCtx.get(TARGET_RESOURCE_KEY);return redactEnvironmentSecrets(env2),env2}async function getByReference7(deps,ref,ctx){let reqCtx=new RequestContext(EnvironmentQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-get-by-reference",deps.logger).addStep(newAuthorizeStep(EnvironmentQueryController.method.getByReference,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadByReferenceStep(deps.store,EnvironmentSchema)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,loadedTargetAsMethod(EnvironmentQueryController.method.get))).build().execute(reqCtx);let env2=reqCtx.get(TARGET_RESOURCE_KEY);return redactEnvironmentSecrets(env2),env2}async function getSecretValue(deps,input,ctx){let reqCtx=new RequestContext(EnvironmentQueryController.method.getSecretValue.input,input,callerIdentityOf(ctx),kindOf12(ctx));return await newPipeline("environment-get-secret-value",deps.logger).addStep(newAuthorizeStep(EnvironmentQueryController.method.getSecretValue,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadEnvironmentByIdStep(deps.store)).addStep(newExtractAndDecryptSingleKeyStep(deps.secretService,deps.logger)).build().execute(reqCtx),reqCtx.get(SECRET_VALUE_KEY)}var LIST_RESULT_KEY5="listResult";async function list8(deps,req,ctx){let reqCtx=new RequestContext(EnvironmentQueryController.method.list.input,req,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-list",deps.logger).addStep(newAuthorizeStep(EnvironmentQueryController.method.list,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newListByOrgAndLabelsStep5(deps.store,deps.listReadScope)).build().execute(reqCtx);let result=reqCtx.get(LIST_RESULT_KEY5);if(result===void 0)throw internalError(new Error("environment list not found in context"),"environment list not found in context");return result}function newListByOrgAndLabelsStep5(store,listReadScope){return{name:"ListByOrgAndLabels",async execute(ctx){let{org,labels:filterLabels}=ctx.input,rows;try{rows=await store.listResources(ctx.apiResourceKind)}catch(error2){throw internalError(error2,"failed to list environments")}let decoded=[];for(let bytes of rows)try{decoded.push(fromBinary2(EnvironmentSchema,bytes))}catch{continue}let requested=decoded.filter(env2=>(env2.metadata?.org??"")===org&&matchesAllLabels(env2.metadata?.labels??{},filterLabels)),environments=await restrictListByReadScope(listReadScope,ctx.callerIdentity,ApiResourceKind.environment,requested,"");for(let env2 of environments)redactEnvironmentSecrets(env2);environments.sort((a5,b7)=>compareCreatedAtDesc(a5.status?.audit?.specAudit?.createdAt,b7.status?.audit?.specAudit?.createdAt)),ctx.set(LIST_RESULT_KEY5,create2(EnvironmentListSchema,{totalCount:environments.length,items:environments}))}}}var file_ai_stigmer_agentic_executioncontext_v1_command=fileDesc("CjRhaS9zdGlnbWVyL2FnZW50aWMvZXhlY3V0aW9uY29udGV4dC92MS9jb21tYW5kLnByb3RvEiZhaS5zdGlnbWVyLmFnZW50aWMuZXhlY3V0aW9uY29udGV4dC52MTLpAwohRXhlY3V0aW9uQ29udGV4dENvbW1hbmRDb250cm9sbGVyEnsKBWFwcGx5EjguYWkuc3RpZ21lci5hZ2VudGljLmV4ZWN1dGlvbmNvbnRleHQudjEuRXhlY3V0aW9uQ29udGV4dBo4LmFpLnN0aWdtZXIuYWdlbnRpYy5leGVjdXRpb25jb250ZXh0LnYxLkV4ZWN1dGlvbkNvbnRleHQSggEKBmNyZWF0ZRI4LmFpLnN0aWdtZXIuYWdlbnRpYy5leGVjdXRpb25jb250ZXh0LnYxLkV4ZWN1dGlvbkNvbnRleHQaOC5haS5zdGlnbWVyLmFnZW50aWMuZXhlY3V0aW9uY29udGV4dC52MS5FeGVjdXRpb25Db250ZXh0IgTQuBgBErsBCgZkZWxldGUSNi5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VEZWxldGVJbnB1dBo4LmFpLnN0aWdtZXIuYWdlbnRpYy5leGVjdXRpb25jb250ZXh0LnYxLkV4ZWN1dGlvbkNvbnRleHQiP8K4GDsIAhA2IgtyZXNvdXJjZV9pZCoodW5hdXRob3JpemVkIHRvIGRlbGV0ZSBleGVjdXRpb24gY29udGV4dBoEoP8rNmIGcHJvdG8z",[file_ai_stigmer_agentic_executioncontext_v1_api,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),ExecutionContextCommandController=serviceDesc(file_ai_stigmer_agentic_executioncontext_v1_command,0);var file_ai_stigmer_agentic_executioncontext_v1_io=fileDesc("Ci9haS9zdGlnbWVyL2FnZW50aWMvZXhlY3V0aW9uY29udGV4dC92MS9pby5wcm90bxImYWkuc3RpZ21lci5hZ2VudGljLmV4ZWN1dGlvbmNvbnRleHQudjEiKwoSRXhlY3V0aW9uQ29udGV4dElkEhUKBXZhbHVlGAEgASgJQga6SAPIAQEiQQogRXhlY3V0aW9uQ29udGV4dEV4ZWN1dGlvbklkSW5wdXQSHQoMZXhlY3V0aW9uX2lkGAEgASgJQge6SARyAhABYgZwcm90bzM",[file_buf_validate_validate]);var file_ai_stigmer_agentic_executioncontext_v1_query=fileDesc("CjJhaS9zdGlnbWVyL2FnZW50aWMvZXhlY3V0aW9uY29udGV4dC92MS9xdWVyeS5wcm90bxImYWkuc3RpZ21lci5hZ2VudGljLmV4ZWN1dGlvbmNvbnRleHQudjEyhQQKH0V4ZWN1dGlvbkNvbnRleHRRdWVyeUNvbnRyb2xsZXISswEKA2dldBI6LmFpLnN0aWdtZXIuYWdlbnRpYy5leGVjdXRpb25jb250ZXh0LnYxLkV4ZWN1dGlvbkNvbnRleHRJZBo4LmFpLnN0aWdtZXIuYWdlbnRpYy5leGVjdXRpb25jb250ZXh0LnYxLkV4ZWN1dGlvbkNvbnRleHQiNsK4GDIIARA2IgV2YWx1ZSoldW5hdXRob3JpemVkIHRvIGdldCBleGVjdXRpb24gY29udGV4dBKGAQoOZ2V0QnlSZWZlcmVuY2USNC5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VSZWZlcmVuY2UaOC5haS5zdGlnbWVyLmFnZW50aWMuZXhlY3V0aW9uY29udGV4dC52MS5FeGVjdXRpb25Db250ZXh0IgTQuBgBEpwBChBnZXRCeUV4ZWN1dGlvbklkEkguYWkuc3RpZ21lci5hZ2VudGljLmV4ZWN1dGlvbmNvbnRleHQudjEuRXhlY3V0aW9uQ29udGV4dEV4ZWN1dGlvbklkSW5wdXQaOC5haS5zdGlnbWVyLmFnZW50aWMuZXhlY3V0aW9uY29udGV4dC52MS5FeGVjdXRpb25Db250ZXh0IgTQuBgBGgSg/ys2YgZwcm90bzM",[file_ai_stigmer_agentic_executioncontext_v1_api,file_ai_stigmer_agentic_executioncontext_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),ExecutionContextQueryController=serviceDesc(file_ai_stigmer_agentic_executioncontext_v1_query,0);function redactExecutionContextSecrets(ec2){let data=ec2?.spec?.data;if(data!==void 0)for(let value of Object.values(data))value.isSecret&&value.value!==""&&(value.value=REDACTED_MARKER)}var import_node_crypto19=require("node:crypto"),CONNECT_EXECUTION_ID_PREFIX="connect-";function newConnectExecutionId(mcpServerId){return`${CONNECT_EXECUTION_ID_PREFIX}${mcpServerId}-${(0,import_node_crypto19.randomUUID)().slice(0,8)}`}function isConnectExecutionId(executionId){return executionId.startsWith(CONNECT_EXECUTION_ID_PREFIX)}function isTerminalWorkflowExecutionPhase(phase){switch(phase){case ExecutionPhase2.EXECUTION_COMPLETED:case ExecutionPhase2.EXECUTION_FAILED:case ExecutionPhase2.EXECUTION_CANCELLED:case ExecutionPhase2.EXECUTION_TERMINATED:return!0;default:return!1}}var RUNNER_VERIFIER_NAME="runner",RUNNER_CREDENTIAL_INVALID_MESSAGE="runner credential is not valid on this server",RUNNER_CREDENTIAL_NOT_LIVE_MESSAGE="runner credential names a run that is over or belongs to nobody this server recognizes",RUN_CREDENTIAL_NOT_RUNS_PERSON_MESSAGE="a run credential is minted only for the person whose run it is",WORKFLOW_LINEAGE_BINDING_MISMATCH_MESSAGE="workflow lineage label names a workflow execution this runner credential is not bound to",MEMORY_CAPTURE_ORG_MISMATCH_MESSAGE="memory capture is scoped to the session's organization";function boundExecutionKindOf(executionId){switch(kindByIdPrefix(executionId)){case ApiResourceKind.agent_execution:return"agent-execution";case ApiResourceKind.workflow_execution:return"workflow-execution";default:return isConnectExecutionId(executionId)?"mcp-connect":void 0}}function bindsARun(kind){switch(kind){case"agent-execution":case"workflow-execution":return!0;case"mcp-connect":return!1;default:{let exhaustive=kind;throw new Error(`unknown bound execution kind ${String(exhaustive)}`)}}}async function loadBoundExecution(store,executionId,now=Date.now()){let kind=boundExecutionKindOf(executionId);if(kind!==void 0)switch(kind){case"agent-execution":{let row=await getRow(store,ApiResourceKind.agent_execution,executionId,AgentExecutionSchema);return row===void 0?void 0:{kind,executionId,org:row.metadata?.org??"",createdBy:creatorStampOf(AgentExecutionSchema,row),sessionId:row.spec?.sessionId??"",live:isLive(row.status!==void 0&&isTerminalExecutionPhase(row.status.phase),row.status?.completedAt??"",now)}}case"workflow-execution":{let row=await getRow(store,ApiResourceKind.workflow_execution,executionId,WorkflowExecutionSchema);return row===void 0?void 0:{kind,executionId,org:row.metadata?.org??"",createdBy:creatorStampOf(WorkflowExecutionSchema,row),sessionId:"",live:isLive(row.status!==void 0&&isTerminalWorkflowExecutionPhase(row.status.phase),row.status?.completedAt??"",now)}}case"mcp-connect":{let row=await getExecutionContextRow(store,executionId);return row===void 0?void 0:{kind,executionId,org:row.metadata?.org??"",createdBy:creatorStampOf(ExecutionContextSchema,row),sessionId:"",live:!0}}default:{let exhaustive=kind;throw new Error(`unknown bound execution kind ${String(exhaustive)}`)}}}function isLive(terminal,completedAt,now){if(!terminal)return!0;let finishedAt=Date.parse(completedAt);return Number.isNaN(finishedAt)?!1:now-finishedAt<6e5}function creatorStampOf(schema2,row){return auditOf(schema2,row)?.specAudit?.createdBy?.id??""}async function getRow(store,kind,id,schema2){try{return await store.getResource(kind,id,schema2)}catch(error2){if(error2 instanceof ResourceNotFoundError)return;throw error2}}async function getExecutionContextRow(store,executionId){try{return await store.findByField(ApiResourceKind.execution_context,"spec.executionId",executionId,ExecutionContextSchema)}catch(error2){if(error2 instanceof ResourceNotFoundError)return;throw error2}}function ciphertextShapedMessage(key){return`value for '${key}' looks like stored ciphertext (enc:v<N>: prefix); supply the plaintext value`}var ENCRYPT_BATCH_FAILURE_MESSAGE="failed to encrypt secret values";function encryptionKeyMissingMessage(executionId,key){return`execution context for ${executionId} holds encrypted secret '${key}' but no encryption key is configured`}async function resolveValuesForCaller(deps,ctx,ec2){if(await runnerMayDecrypt(deps,ctx,ec2)){await decryptSecretValues(deps,ec2);return}redactExecutionContextSecrets(ec2)}async function runnerMayDecrypt(deps,ctx,ec2){let authorizeRead=deps.runnerAuthService.authorizeExecutionContextRead?.bind(deps.runnerAuthService);if(authorizeRead!==void 0){let token2=bearerToken(ctx);if(token2==="")return!1;try{return await authorizeRead(token2,ec2.spec?.executionId??"")}catch(error2){return deps.logger.warn("ExecutionContext read authorization failed \u2014 redacting secrets",{error:error2 instanceof Error?error2.message:String(error2)}),!1}}let token=bearerToken(ctx),executionId=verifyRunnerToken(deps,token,ec2);return executionId===void 0?!1:!isClockedToken(token)&&!await runIsLive(deps,executionId)?(deps.logger.debug("Run credential presented for a run that is over - redacting execution context secrets",{executionId}),!1):(deps.logger.debug("Scope-bound runner token presented - decrypting execution context secrets",{executionId}),!0)}function verifyRunnerToken(deps,token,ec2){if(token==="")return;let tokenExecutionId;try{tokenExecutionId=deps.runnerAuthService.verify(TOKEN_TYPE_EXECUTION_SCOPED,token)}catch{deps.logger.debug("Presented runner token failed verification - redacting execution context secrets");return}if(tokenExecutionId!==(ec2.spec?.executionId??"")){deps.logger.warn("Runner token is not scope-bound to this execution context - redacting secrets",{tokenExecutionId,executionId:ec2.spec?.executionId??""});return}return tokenExecutionId}async function runIsLive(deps,executionId){try{let execution=await loadBoundExecution(deps.store,executionId);return execution!==void 0&&bindsARun(execution.kind)&&execution.live}catch(error2){throw internalError(error2,"failed to load the run credential's execution")}}function bearerToken(ctx){return parseBearerToken(ctx.requestHeader.get("authorization")??"")}async function decryptSecretValues(deps,ec2){let executionId=ec2.spec?.executionId??"",data=ec2.spec?.data??{};for(let[key,value]of Object.entries(data))if(!(!value.isSecret||!deps.secretService.isEncrypted(value.value)))try{value.value=await deps.secretService.decrypt(value.value)}catch(error2){if(error2 instanceof EncryptionUnavailableError)throw internalError(error2,encryptionKeyMissingMessage(executionId,key));deps.logger.warn("Undecryptable ciphertext in execution context \u2014 dropping this value from the runner read",{key,executionId,error:error2 instanceof Error?error2.message:String(error2)}),delete data[key]}}var executionContextSearchExtractor={kind:ApiResourceKind.execution_context,schema:ExecutionContextSchema,getSearchSummary(){return""},toSearchResult(resource,score){let ec2=resource;return buildSearchResult({kind:ApiResourceKind.execution_context,metadata:ec2.metadata,summary:"",score,createdAt:ec2.status?.audit?.specAudit?.createdAt,updatedAt:ec2.status?.audit?.specAudit?.updatedAt})},getSearchIndexEntry(resource){let ec2=resource,metadata=ec2.metadata;if(metadata!==void 0)return{name:metadata.name,description:"",tags:metadata.tags.join(" "),org:metadata.org,visibility:ApiResourceVisibility[metadata.visibility]??"",createdAt:Number(ec2.status?.audit?.specAudit?.createdAt?.seconds??0n)}}};function newRejectCiphertextShapedStep(){return{name:"RejectCiphertextShapedValues",execute(ctx){let data=ctx.input.spec?.data??{};for(let[key,value]of Object.entries(data))if(isCiphertextShaped(value.value))throw invalidArgumentError(ciphertextShapedMessage(key))}}}function newEncryptSecretValuesStep2(secretService,logger2){return{name:"EncryptSecretValues",async execute(ctx){let ec2=ctx.newState,data=ec2.spec?.data;if(data===void 0||Object.keys(data).length===0)return;if(!secretService.isEnabled()){hasNonEmptySecret2(data)&&logger2.warn("Encryption disabled: execution context secret values will be stored in plaintext",{executionId:ec2.spec?.executionId??""});return}let toSeal=new Map;for(let[key,value]of Object.entries(data))!value.isSecret||value.value===""||toSeal.set(key,value.value);if(toSeal.size===0)return;let sealed;try{sealed=await secretService.encryptAllAtMostV2(toSeal,EncryptionScope.forOrganization(ec2.metadata?.org??""))}catch(error2){throw internalError(error2,ENCRYPT_BATCH_FAILURE_MESSAGE)}for(let[key,value]of Object.entries(data)){let sealedValue=sealed.get(key);sealedValue!==void 0&&(value.value=sealedValue)}}}}function hasNonEmptySecret2(data){return Object.values(data).some(v=>v.isSecret&&v.value!=="")}function newLoadByExecutionIdStep(store){return{name:"LoadByExecutionId",async execute(ctx){let input=ctx.input;if(input.executionId==="")throw invalidArgumentError("execution_id is required");let executionContext;try{executionContext=await store.findByField(ctx.apiResourceKind,"spec.executionId",input.executionId,ExecutionContextSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("execution_context",`execution_id=${input.executionId}`):internalError(error2,"failed to query execution context")}ctx.set(TARGET_RESOURCE_KEY,executionContext)}}}function newAuthorizeExecutionContextCreateStep(authorizer){return{name:"AuthorizeCreate",async execute(ctx){let caller=ctx.callerIdentity;if(isServerComposedRequest(caller))return;let decision;try{decision=await authorizer.authorize(caller,{permission:IamPermission.can_create_execution_in,resourceKind:ApiResourceKind.organization,resourceId:ctx.newState.metadata?.org??""})}catch(error2){throw internalError(error2 instanceof Error?error2:new Error(String(error2)),"execution-context create authorization could not be completed")}switch(decision.kind){case"allow":return;case"deny":case"not-found":throw new ConnectError("unauthorized to create execution context in this organization",Code.PermissionDenied);case"unavailable":throw internalError(decision.cause,"execution-context create authorization could not be completed");default:{let exhaustive=decision;throw internalError(new Error(`unknown decision ${JSON.stringify(exhaustive)}`),"execution-context create authorization could not be completed")}}}}}function registerExecutionContextServices(router,deps){router.service(ExecutionContextCommandController,{apply:(ec2,ctx)=>apply8(deps,ec2,ctx),create:(ec2,ctx)=>createExecutionContext(deps,ec2,ctx),delete:(input,ctx)=>deleteExecutionContext(deps,input,ctx)}),router.service(ExecutionContextQueryController,{get:(id,ctx)=>get14(deps,id,ctx),getByReference:(ref,ctx)=>getByReference8(deps,ref,ctx),getByExecutionId:(input,ctx)=>getByExecutionId(deps,input,ctx)})}function kindOf13(ctx){return ctx.values.get(apiResourceKindKey)}async function createExecutionContext(deps,ec2,ctx){let reqCtx=new RequestContext(ExecutionContextSchema,ec2,callerIdentityOf(ctx),kindOf13(ctx));return await newPipeline("execution-context-create",deps.logger).addStep(newAuthorizeStep(ExecutionContextCommandController.method.create,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newAuthorizeExecutionContextCreateStep(deps.authorizer)).addStep(newValidateVisibilityStep()).addStep(newRejectCiphertextShapedStep()).addStep(newResolveSlugStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store)).addStep(newEncryptSecretValuesStep2(deps.secretService,deps.logger)).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).addStep(newIndexSearchStep(deps.store,executionContextSearchExtractor,deps.logger)).build().execute(reqCtx),redactExecutionContextSecrets(reqCtx.newState),reqCtx.newState}async function apply8(deps,ec2,ctx){let reqCtx=new RequestContext(ExecutionContextSchema,ec2,callerIdentityOf(ctx),kindOf13(ctx));await newPipeline("execution-context-apply",deps.logger).addStep(newAuthorizeStep(ExecutionContextCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");if(shouldCreate)return createExecutionContext(deps,ec2,ctx);throw deps.logger.warn("ExecutionContext already exists - UPDATE not supported",{slug:ec2.metadata?.name??"",id:ec2.metadata?.id??""}),alreadyExistsError("ExecutionContext",ec2.metadata?.name??"")}async function deleteExecutionContext(deps,input,ctx){let reqCtx=new RequestContext(ExecutionContextCommandController.method.delete.input,input,callerIdentityOf(ctx),kindOf13(ctx));reqCtx.set(RESOURCE_ID_KEY,input.resourceId),await newPipeline("execution-context-delete",deps.logger).addStep(newAuthorizeStep(ExecutionContextCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingForDeleteStep(deps.store,ExecutionContextSchema)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDeleteSearchIndexStep(deps.store,deps.logger)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted execution context not found in context"),"deleted execution context not found in context");let ec2=deleted;return redactExecutionContextSecrets(ec2),ec2}async function get14(deps,id,ctx){let reqCtx=new RequestContext(ExecutionContextQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf13(ctx));await newPipeline("execution-context-get",deps.logger).addStep(newAuthorizeStep(ExecutionContextQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,ExecutionContextSchema)).build().execute(reqCtx);let ec2=reqCtx.get(TARGET_RESOURCE_KEY);return redactExecutionContextSecrets(ec2),ec2}async function getByReference8(deps,ref,ctx){let reqCtx=new RequestContext(ExecutionContextQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf13(ctx));await newPipeline("execution-context-get-by-reference",deps.logger).addStep(newAuthorizeStep(ExecutionContextQueryController.method.getByReference,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadByReferenceStep(deps.store,ExecutionContextSchema)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,loadedTargetAsMethod(ExecutionContextQueryController.method.get))).build().execute(reqCtx);let ec2=reqCtx.get(TARGET_RESOURCE_KEY);return redactExecutionContextSecrets(ec2),ec2}async function getByExecutionId(deps,input,ctx){let reqCtx=new RequestContext(ExecutionContextQueryController.method.getByExecutionId.input,input,callerIdentityOf(ctx),kindOf13(ctx));await newPipeline("execution-context-get-by-execution-id",deps.logger).addStep(newAuthorizeStep(ExecutionContextQueryController.method.getByExecutionId,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadByExecutionIdStep(deps.store)).build().execute(reqCtx);let ec2=reqCtx.get(TARGET_RESOURCE_KEY);return await resolveValuesForCaller(deps,ctx,ec2),ec2}var import_node_crypto20=require("node:crypto");var file_ai_stigmer_platform_github_v1_service=fileDesc("CithaS9zdGlnbWVyL3BsYXRmb3JtL2dpdGh1Yi92MS9zZXJ2aWNlLnByb3RvEh1haS5zdGlnbWVyLnBsYXRmb3JtLmdpdGh1Yi52MSI8ChtHZXRPQXV0aEF1dGhvcml6ZVVybFJlcXVlc3QSHQoMcmVkaXJlY3RfdXJpGAEgASgJQge6SARyAhABIkQKHEdldE9BdXRoQXV0aG9yaXplVXJsUmVzcG9uc2USFQoNYXV0aG9yaXplX3VybBgBIAEoCRINCgVzdGF0ZRgCIAEoCSJoChhFeGNoYW5nZU9BdXRoQ29kZVJlcXVlc3QSFQoEY29kZRgBIAEoCUIHukgEcgIQARIWCgVzdGF0ZRgCIAEoCUIHukgEcgIQARIdCgxyZWRpcmVjdF91cmkYAyABKAlCB7pIBHICEAEiVAoZRXhjaGFuZ2VPQXV0aENvZGVSZXNwb25zZRIUCgxhY2Nlc3NfdG9rZW4YASABKAkSEgoKdG9rZW5fdHlwZRgCIAEoCRINCgVzY29wZRgDIAEoCTK2AgoNR2l0SHViU2VydmljZRKVAQoUZ2V0T0F1dGhBdXRob3JpemVVcmwSOi5haS5zdGlnbWVyLnBsYXRmb3JtLmdpdGh1Yi52MS5HZXRPQXV0aEF1dGhvcml6ZVVybFJlcXVlc3QaOy5haS5zdGlnbWVyLnBsYXRmb3JtLmdpdGh1Yi52MS5HZXRPQXV0aEF1dGhvcml6ZVVybFJlc3BvbnNlIgTQuBgBEowBChFleGNoYW5nZU9BdXRoQ29kZRI3LmFpLnN0aWdtZXIucGxhdGZvcm0uZ2l0aHViLnYxLkV4Y2hhbmdlT0F1dGhDb2RlUmVxdWVzdBo4LmFpLnN0aWdtZXIucGxhdGZvcm0uZ2l0aHViLnYxLkV4Y2hhbmdlT0F1dGhDb2RlUmVzcG9uc2UiBNC4GAFiBnByb3RvMw",[file_ai_stigmer_commons_rpc_method_options,file_buf_validate_validate]);var GetOAuthAuthorizeUrlResponseSchema=messageDesc2(file_ai_stigmer_platform_github_v1_service,1);var ExchangeOAuthCodeResponseSchema=messageDesc2(file_ai_stigmer_platform_github_v1_service,3),GitHubService=serviceDesc(file_ai_stigmer_platform_github_v1_service,0);var GITHUB_AUTHORIZE_URL="https://github.com/login/oauth/authorize",GITHUB_TOKEN_URL="https://github.com/login/oauth/access_token",OAUTH_SCOPES="repo,read:user",HTTP_TIMEOUT_MS=1e4;function registerGitHubServices(router,deps){router.service(GitHubService,{getOAuthAuthorizeUrl:req=>getOAuthAuthorizeUrl(deps,req),exchangeOAuthCode:req=>exchangeOAuthCode(deps,req)})}function getOAuthAuthorizeUrl(deps,req){if(deps.clientId==="")throw failedPreconditionError("GitHub OAuth is not configured (STIGMER_GITHUB_CLIENT_ID not set)");let state2;try{state2=(0,import_node_crypto20.randomBytes)(16).toString("hex")}catch(error2){throw deps.logger.error("failed to generate OAuth state",{error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to generate OAuth state")}let authorizeUrl=GITHUB_AUTHORIZE_URL+"?"+goUrlValuesEncode({client_id:deps.clientId,redirect_uri:req.redirectUri,scope:OAUTH_SCOPES,state:state2});return create2(GetOAuthAuthorizeUrlResponseSchema,{authorizeUrl,state:state2})}async function exchangeOAuthCode(deps,req){if(deps.clientId===""||deps.clientSecret==="")throw failedPreconditionError("GitHub OAuth is not configured");let body=goUrlValuesEncode({client_id:deps.clientId,client_secret:deps.clientSecret,code:req.code,redirect_uri:req.redirectUri}),fetchImpl=deps.fetchImpl??fetch,response;try{response=await fetchImpl(GITHUB_TOKEN_URL,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body,signal:AbortSignal.timeout(HTTP_TIMEOUT_MS)})}catch(error2){throw deps.logger.error("GitHub token exchange failed",{error:error2 instanceof Error?error2.message:String(error2)}),unavailableError("failed to reach GitHub for token exchange")}let raw;try{raw=await response.text()}catch(error2){throw deps.logger.error("failed to read GitHub token response",{error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to read GitHub response")}let tokenResponse;try{tokenResponse=JSON.parse(raw)}catch(error2){throw deps.logger.error("failed to parse GitHub token response",{error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to parse GitHub response")}if(tokenResponse.error!==void 0&&tokenResponse.error!=="")throw deps.logger.warn("GitHub OAuth error",{error:tokenResponse.error,description:tokenResponse.error_description??""}),invalidArgumentError(`GitHub OAuth error: ${tokenResponse.error_description??""}`);return create2(ExchangeOAuthCodeResponseSchema,{accessToken:tokenResponse.access_token??"",tokenType:tokenResponse.token_type??"",scope:tokenResponse.scope??""})}var file_ai_stigmer_agentic_memory_v1_io=fileDesc("CiVhaS9zdGlnbWVyL2FnZW50aWMvbWVtb3J5L3YxL2lvLnByb3RvEhxhaS5zdGlnbWVyLmFnZW50aWMubWVtb3J5LnYxIiEKCE1lbW9yeUlkEhUKBXZhbHVlGAEgASgJQga6SAPIAQEiYAoTTGlzdE1lbW9yaWVzUmVxdWVzdBIUCgNvcmcYASABKAlCB7pIBHICEAESMwoJcGFnZV9pbmZvGAIgASgLMiAuYWkuc3RpZ21lci5jb21tb25zLnJwYy5QYWdlSW5mbyJWCgpNZW1vcnlMaXN0EhMKC3RvdGFsX2NvdW50GAEgASgFEjMKBWl0ZW1zGAIgAygLMiQuYWkuc3RpZ21lci5hZ2VudGljLm1lbW9yeS52MS5NZW1vcnliBnByb3RvMw",[file_ai_stigmer_agentic_memory_v1_api,file_ai_stigmer_commons_rpc_pagination,file_buf_validate_validate]),MemoryIdSchema=messageDesc2(file_ai_stigmer_agentic_memory_v1_io,0);var MemoryListSchema=messageDesc2(file_ai_stigmer_agentic_memory_v1_io,2);var file_ai_stigmer_agentic_memory_v1_command=fileDesc("CiphaS9zdGlnbWVyL2FnZW50aWMvbWVtb3J5L3YxL2NvbW1hbmQucHJvdG8SHGFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEypQUKF01lbW9yeUNvbW1hbmRDb250cm9sbGVyEloKBmNyZWF0ZRIkLmFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEuTWVtb3J5GiQuYWkuc3RpZ21lci5hZ2VudGljLm1lbW9yeS52MS5NZW1vcnkiBNC4GAESigEKBnVwZGF0ZRIkLmFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEuTWVtb3J5GiQuYWkuc3RpZ21lci5hZ2VudGljLm1lbW9yeS52MS5NZW1vcnkiNMK4GDAIAhA5IgttZXRhZGF0YS5pZCoddW5hdXRob3JpemVkIHRvIHVwZGF0ZSBtZW1vcnkShgEKBmRlbGV0ZRImLmFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEuTWVtb3J5SWQaJC5haS5zdGlnbWVyLmFnZW50aWMubWVtb3J5LnYxLk1lbW9yeSIuwrgYKggDEDkiBXZhbHVlKh11bmF1dGhvcml6ZWQgdG8gZGVsZXRlIG1lbW9yeRKIAQoHY29uZmlybRImLmFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEuTWVtb3J5SWQaJC5haS5zdGlnbWVyLmFnZW50aWMubWVtb3J5LnYxLk1lbW9yeSIvwrgYKwgCEDkiBXZhbHVlKh51bmF1dGhvcml6ZWQgdG8gY29uZmlybSBtZW1vcnkShgEKBnJlamVjdBImLmFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEuTWVtb3J5SWQaJC5haS5zdGlnbWVyLmFnZW50aWMubWVtb3J5LnYxLk1lbW9yeSIuwrgYKggCEDkiBXZhbHVlKh11bmF1dGhvcml6ZWQgdG8gcmVqZWN0IG1lbW9yeRoEoP8rOWIGcHJvdG8z",[file_ai_stigmer_agentic_memory_v1_api,file_ai_stigmer_agentic_memory_v1_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),MemoryCommandController=serviceDesc(file_ai_stigmer_agentic_memory_v1_command,0);var file_ai_stigmer_agentic_memory_v1_query=fileDesc("CihhaS9zdGlnbWVyL2FnZW50aWMvbWVtb3J5L3YxL3F1ZXJ5LnByb3RvEhxhaS5zdGlnbWVyLmFnZW50aWMubWVtb3J5LnYxMosCChVNZW1vcnlRdWVyeUNvbnRyb2xsZXISgAEKA2dldBImLmFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEuTWVtb3J5SWQaJC5haS5zdGlnbWVyLmFnZW50aWMubWVtb3J5LnYxLk1lbW9yeSIrwrgYJwgBEDkiBXZhbHVlKhp1bmF1dGhvcml6ZWQgdG8gZ2V0IG1lbW9yeRJpCgRsaXN0EjEuYWkuc3RpZ21lci5hZ2VudGljLm1lbW9yeS52MS5MaXN0TWVtb3JpZXNSZXF1ZXN0GiguYWkuc3RpZ21lci5hZ2VudGljLm1lbW9yeS52MS5NZW1vcnlMaXN0IgTQuBgBGgSg/ys5YgZwcm90bzM",[file_ai_stigmer_agentic_memory_v1_api,file_ai_stigmer_agentic_memory_v1_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),MemoryQueryController=serviceDesc(file_ai_stigmer_agentic_memory_v1_query,0);var MEMORY_CAPTURE_CALLER_MESSAGE="memory can only be captured for a first-party human operator",MEMORY_CAPTURE_CREDENTIAL_KEY="memoryCaptureCredential";function newGuardMemoryCaptureStep(provider){return{name:"GuardMemoryCapture",async execute(ctx){let caller=ctx.callerIdentity;if(isServerComposedRequest(caller))return;let decide=provider?.authorizeMemoryCapture;if(decide!==void 0){let org=metadataOf(ctx.newState)?.org??"",decision=await decide.call(provider,caller,org);switch(decision.verdict){case"admit":ctx.set(MEMORY_CAPTURE_CREDENTIAL_KEY,{subjectIdentityAccountId:decision.subjectIdentityAccountId,provedSessionId:decision.provedSessionId});return;case"refuse":throw new ConnectError(MEMORY_CAPTURE_CALLER_MESSAGE,Code.PermissionDenied);case"no-opinion":break;default:{let exhaustive=decision;throw new Error(`unknown memory capture decision ${JSON.stringify(exhaustive)}`)}}}if(caller.callerClass==="machine"||carriesPlatformClientClaim(caller.rawToken))throw new ConnectError(MEMORY_CAPTURE_CALLER_MESSAGE,Code.PermissionDenied)}}}function memoryCaptureCredentialOf(ctx){let payload=ctx.get(MEMORY_CAPTURE_CREDENTIAL_KEY);if(typeof payload=="object"&&payload!==null&&"subjectIdentityAccountId"in payload&&"provedSessionId"in payload)return payload}var MEMORY_FULL_MESSAGE="memory is full \u2014 review and delete existing memories";function memoryDisabledMessage(org){return`memory is not enabled for organization ${org} \u2014 an organization admin can enable it in organization preferences`}var MEMORY_ACCOUNT_DISABLED_MESSAGE="memory is not enabled for your account \u2014 enable it in account preferences",MEMORY_CONFIRM_REJECTED_MESSAGE="memory was rejected \u2014 delete it and let the agent propose it again",MEMORY_REJECT_CONFIRMED_MESSAGE="memory was confirmed \u2014 delete it to stop it from being recalled",MEMORY_SUBJECT_IMMUTABLE_MESSAGE="spec.subject_identity_account_id is immutable \u2014 it is derived from the capturing credential at create",MEMORY_PROVENANCE_IMMUTABLE_MESSAGE="spec.provenance is immutable \u2014 it records where the fact came from";var LIST_RESULT_KEY6="listResult";function newResolveMemoryDefaultsStep(personAccounts){return{name:"ResolveMemoryDefaults",async execute(ctx){let memory=ctx.newState,metadata=memory.metadata;if((metadata?.org??"")==="")throw invalidArgumentError("metadata.org is required for a memory");if(metadata===void 0)throw internalError(new Error("metadata is nil"),"metadata is nil");metadata.id===""&&(metadata.id=generateId("mem")),metadata.name===""&&metadata.slug===""&&(metadata.name=metadata.id);let spec=memory.spec;if(spec===void 0)throw internalError(new Error("memory spec is nil"),"memory spec is nil");let captureCredential=memoryCaptureCredentialOf(ctx);if(personAccounts===void 0)spec.subjectIdentityAccountId=captureCredential?.subjectIdentityAccountId??"";else{let account2=await resolveSubjectAccount(personAccounts,ctx,captureCredential?.subjectIdentityAccountId);spec.subjectIdentityAccountId=account2?.metadata?.id??"",account2!==void 0&&ctx.set(MEMORY_SUBJECT_ACCOUNT_KEY,account2)}spec.provenance!==void 0&&(spec.provenance.toolCallId=""),captureCredential!==void 0&&(spec.provenance===void 0&&(spec.provenance=create2(MemoryProvenanceSchema,{})),spec.provenance.sessionId=captureCredential.provedSessionId)}}}var MEMORY_SUBJECT_ACCOUNT_KEY="memorySubjectAccount";function memorySubjectAccountOf(ctx){let payload=ctx.get(MEMORY_SUBJECT_ACCOUNT_KEY);return isMessage2(payload,IdentityAccountSchema)?payload:void 0}async function resolveSubjectAccount(personAccounts,ctx,credentialSubject){let account2;try{account2=credentialSubject!==void 0?await accountForStamp(personAccounts,credentialSubject):await accountForCaller(personAccounts,ctx.callerIdentity)}catch(error2){throw internalError(error2,"failed to resolve the identity account a memory is about")}if(account2!==void 0&&(account2.metadata?.id??"")==="")throw internalError(new Error("identity account carries no id"),"failed to resolve the identity account a memory is about");return account2}var MEMORY_CREATE_DENIED_MESSAGE="unauthorized to capture memory in this organization";function resolveMemoryCreateTargets(ctx){return isServerComposedRequest(ctx.callerIdentity)?[]:[{permission:IamPermission.can_create_session,resourceKind:ApiResourceKind.organization,resourceId:ctx.newState.metadata?.org??"",deniedMessage:MEMORY_CREATE_DENIED_MESSAGE}]}function newCheckMemoryEnablementStep(store,personAccounts){return{name:"CheckMemoryEnablement",async execute(ctx){let orgID=ctx.newState.metadata?.org??"",org;try{org=await store.getResource(ApiResourceKind.organization,orgID,OrganizationSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("Organization",orgID):internalError(error2,"failed to load organization for memory enablement check")}if(org.spec?.preferences?.memoryEnabled!==!0)throw failedPreconditionError(memoryDisabledMessage(orgID));if(personAccounts===void 0)return;if(memorySubjectAccountOf(ctx)?.spec?.preferences?.memoryEnabled!==!0)throw failedPreconditionError(MEMORY_ACCOUNT_DISABLED_MESSAGE)}}}function newCheckMemoryCapStep(store){return{name:"CheckMemoryCap",async execute(ctx){let newState=ctx.newState,org=newState.metadata?.org??"",subject=newState.spec?.subjectIdentityAccountId??"",rows;try{rows=await store.listResources(ApiResourceKind.memory)}catch(error2){throw internalError(error2,"failed to count memories for cap check")}let count=0;for(let bytes of rows){let existing=unmarshalMemory(bytes);existing!==void 0&&(existing.metadata?.org??"")===org&&(existing.spec?.subjectIdentityAccountId??"")===subject&&count++}if(count>=100)throw failedPreconditionError(MEMORY_FULL_MESSAGE)}}}function newInitializeMemoryLifecycleStep(){return{name:"InitializeMemoryLifecycle",execute(ctx){let memory=ctx.newState;memory.status===void 0&&(memory.status=create2(MemoryStatusSchema,{})),memory.status.lifecycleState=MemoryLifecycleState.lifecycle_state_proposed,memory.status.stateChangedAt=timestampNow()}}}function newValidateMemoryUpdateStep(){return{name:"ValidateMemoryUpdate",execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)throw internalError(new Error("existing memory not found in context"),"existing memory not found in context");let newState=ctx.newState;if((newState.spec?.subjectIdentityAccountId??"")!==(existing.spec?.subjectIdentityAccountId??""))throw failedPreconditionError(MEMORY_SUBJECT_IMMUTABLE_MESSAGE);let newProvenance=newState.spec?.provenance,existingProvenance=existing.spec?.provenance;if(!(newProvenance===void 0||existingProvenance===void 0?newProvenance===existingProvenance:equals(MemoryProvenanceSchema,newProvenance,existingProvenance)))throw failedPreconditionError(MEMORY_PROVENANCE_IMMUTABLE_MESSAGE)}}}function newPersistMemoryUpdateStep(store){return{name:"PersistMemoryUpdate",async execute(ctx){let newState=ctx.newState,memoryId=newState.metadata?.id??"",live;try{live=await store.updateResource(ApiResourceKind.memory,memoryId,MemorySchema,row=>{row.apiVersion=newState.apiVersion,row.kind=newState.kind,row.metadata=newState.metadata,row.spec=newState.spec,newState.status?.audit!==void 0&&(row.status===void 0&&(row.status=create2(MemoryStatusSchema,{})),row.status.audit=newState.status.audit)})}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("Memory",memoryId):internalError(error2,"failed to persist memory update")}ctx.setNewState(live)}}}function newTransitionMemoryLifecycleStep(store,target,blockedMessage){return{name:"TransitionMemoryLifecycle",async execute(ctx){let memoryId=ctx.get(EXISTING_RESOURCE_KEY).metadata?.id??"",transitionNoOp=new Error("memory already in target state"),blocked,live;try{live=await store.updateResource(ApiResourceKind.memory,memoryId,MemorySchema,row=>{live=row;let current=row.status?.lifecycleState??MemoryLifecycleState.lifecycle_state_unspecified;if(current===target)throw transitionNoOp;if(current!==MemoryLifecycleState.lifecycle_state_proposed&&current!==MemoryLifecycleState.lifecycle_state_unspecified)throw blocked=failedPreconditionError(blockedMessage),blocked;row.status===void 0&&(row.status=create2(MemoryStatusSchema,{})),row.status.lifecycleState=target,row.status.stateChangedAt=timestampNow(),setAuditFieldsForUpdate(MemorySchema,row,"status_audit",ctx.callerIdentity)})}catch(error2){if(error2!==transitionNoOp)throw blocked!==void 0&&error2===blocked?blocked:error2 instanceof ResourceNotFoundError?notFoundError("Memory",memoryId):internalError(error2,"failed to transition memory lifecycle")}if(live===void 0)throw internalError(new Error("transition closure did not observe the row"),"failed to transition memory lifecycle");ctx.set(EXISTING_RESOURCE_KEY,live)}}}function newListMemoriesByOrgStep(store,listReadScope){return{name:"ListMemoriesByOrg",async execute(ctx){let org=ctx.input.org,rows;try{rows=await store.listResources(ApiResourceKind.memory)}catch(error2){throw internalError(error2,"failed to list memories")}let decoded=[];for(let bytes of rows){let memory=unmarshalMemory(bytes);memory!==void 0&&decoded.push(memory)}let memories=await restrictListByReadScope(listReadScope,ctx.callerIdentity,ApiResourceKind.memory,decoded.filter(memory=>(memory.metadata?.org??"")===org),"");memories.sort((a5,b7)=>compareCreatedAtDesc(a5.status?.audit?.specAudit?.createdAt,b7.status?.audit?.specAudit?.createdAt)),ctx.set(LIST_RESULT_KEY6,create2(MemoryListSchema,{totalCount:memories.length,items:memories}))}}}function unmarshalMemory(data){try{return fromBinary2(MemorySchema,data)}catch{return}}function registerMemoryServices(router,deps){router.service(MemoryCommandController,{create:(memory,ctx)=>createMemory(deps,memory,ctx),update:(memory,ctx)=>update11(deps,memory,ctx),delete:(id,ctx)=>deleteMemory(deps,id,ctx),confirm:(id,ctx)=>confirm(deps,id,ctx),reject:(id,ctx)=>reject(deps,id,ctx)}),router.service(MemoryQueryController,{get:(id,ctx)=>get15(deps,id,ctx),list:(req,ctx)=>list9(deps,req,ctx)})}function kindOf14(ctx){return ctx.values.get(apiResourceKindKey)}async function createMemory(deps,memory,ctx){let reqCtx=new RequestContext(MemorySchema,memory,callerIdentityOf(ctx),kindOf14(ctx));return await newPipeline("memory-create",deps.logger).addStep(newAuthorizeStep(MemoryCommandController.method.create,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newGuardMemoryCaptureStep(deps.runnerCredentialProvider)).addStep(newValidateVisibilityStep()).addStep(newResolveMemoryDefaultsStep(deps.personAccounts)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,resolveMemoryCreateTargets)).addStep(newCheckMemoryEnablementStep(deps.store,deps.personAccounts)).addStep(newCheckMemoryCapStep(deps.store)).addStep(newResolveSlugStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newInitializeMemoryLifecycleStep()).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function update11(deps,memory,ctx){let reqCtx=new RequestContext(MemorySchema,memory,callerIdentityOf(ctx),kindOf14(ctx));return await newPipeline("memory-update",deps.logger).addStep(newAuthorizeStep(MemoryCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingStep(deps.store)).addStep(newValidateMemoryUpdateStep()).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newPersistMemoryUpdateStep(deps.store)).build().execute(reqCtx),reqCtx.newState}async function confirm(deps,memoryId,ctx){return runTransition(deps,memoryId,ctx,"memory-confirm",MemoryCommandController.method.confirm,MemoryLifecycleState.lifecycle_state_confirmed,MEMORY_CONFIRM_REJECTED_MESSAGE)}async function reject(deps,memoryId,ctx){return runTransition(deps,memoryId,ctx,"memory-reject",MemoryCommandController.method.reject,MemoryLifecycleState.lifecycle_state_rejected,MEMORY_REJECT_CONFIRMED_MESSAGE)}async function runTransition(deps,memoryId,ctx,name,method,target,blockedMessage){let reqCtx=new RequestContext(MemoryIdSchema,memoryId,callerIdentityOf(ctx),kindOf14(ctx));await newPipeline(name,deps.logger).addStep(newAuthorizeStep(method,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newExtractResourceIdStep()).addStep(newLoadExistingForDeleteStep(deps.store,MemorySchema)).addStep(newTransitionMemoryLifecycleStep(deps.store,target,blockedMessage)).build().execute(reqCtx);let transitioned=reqCtx.get(EXISTING_RESOURCE_KEY);if(transitioned===void 0)throw internalError(new Error("transitioned memory not found in context"),"transitioned memory not found in context");return transitioned}async function deleteMemory(deps,memoryId,ctx){let reqCtx=new RequestContext(MemoryIdSchema,memoryId,callerIdentityOf(ctx),kindOf14(ctx));await newPipeline("memory-delete",deps.logger).addStep(newAuthorizeStep(MemoryCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newExtractResourceIdStep()).addStep(newLoadExistingForDeleteStep(deps.store,MemorySchema)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted memory not found in context"),"deleted memory not found in context");return deleted}async function get15(deps,memoryId,ctx){let reqCtx=new RequestContext(MemoryIdSchema,memoryId,callerIdentityOf(ctx),kindOf14(ctx));await newPipeline("memory-get",deps.logger).addStep(newAuthorizeStep(MemoryQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newExtractResourceIdStep()).addStep(newLoadTargetStep(deps.store,MemorySchema)).build().execute(reqCtx);let target=reqCtx.get(TARGET_RESOURCE_KEY);if(target===void 0)throw internalError(new Error("target memory not found in context"),"target memory not found in context");return target}async function list9(deps,req,ctx){let reqCtx=new RequestContext(MemoryQueryController.method.list.input,req,callerIdentityOf(ctx),kindOf14(ctx));await newPipeline("memory-list",deps.logger).addStep(newAuthorizeStep(MemoryQueryController.method.list,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newListMemoriesByOrgStep(deps.store,deps.listReadScope)).build().execute(reqCtx);let result=reqCtx.get(LIST_RESULT_KEY6);if(result===void 0)throw internalError(new Error("memory list not found in context"),"memory list not found in context");return result}var file_ai_stigmer_iam_oauthapp_v1_command=fileDesc("CihhaS9zdGlnbWVyL2lhbS9vYXV0aGFwcC92MS9jb21tYW5kLnByb3RvEhphaS5zdGlnbWVyLmlhbS5vYXV0aGFwcC52MTLOBAoZT0F1dGhBcHBDb21tYW5kQ29udHJvbGxlchJTCgVhcHBseRIkLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwGiQuYWkuc3RpZ21lci5pYW0ub2F1dGhhcHAudjEuT0F1dGhBcHASowEKBmNyZWF0ZRIkLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwGiQuYWkuc3RpZ21lci5pYW0ub2F1dGhhcHAudjEuT0F1dGhBcHAiTcK4GEkIFxAeIgxtZXRhZGF0YS5vcmcqNXVuYXV0aG9yaXplZCB0byBjcmVhdGUgb2F1dGggYXBwIGluIHRoaXMgb3JnYW5pemF0aW9uEo0BCgZ1cGRhdGUSJC5haS5zdGlnbWVyLmlhbS5vYXV0aGFwcC52MS5PQXV0aEFwcBokLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwIjfCuBgzCAIQFiILbWV0YWRhdGEuaWQqIHVuYXV0aG9yaXplZCB0byB1cGRhdGUgb2F1dGggYXBwEp8BCgZkZWxldGUSNi5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VEZWxldGVJbnB1dBokLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwIjfCuBgzCAMQFiILcmVzb3VyY2VfaWQqIHVuYXV0aG9yaXplZCB0byBkZWxldGUgb2F1dGggYXBwGgSg/ysWYgZwcm90bzM",[file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options,file_ai_stigmer_iam_oauthapp_v1_api]),OAuthAppCommandController=serviceDesc(file_ai_stigmer_iam_oauthapp_v1_command,0);var file_ai_stigmer_iam_oauthapp_v1_io=fileDesc("CiNhaS9zdGlnbWVyL2lhbS9vYXV0aGFwcC92MS9pby5wcm90bxIaYWkuc3RpZ21lci5pYW0ub2F1dGhhcHAudjEiJgoKT0F1dGhBcHBJZBIYCgV2YWx1ZRgBIAEoCUIJukgGcgQQARhAIkIKCU9BdXRoQXBwcxI1CgdlbnRyaWVzGAEgAygLMiQuYWkuc3RpZ21lci5pYW0ub2F1dGhhcHAudjEuT0F1dGhBcHAiLwoXTGlzdE9BdXRoQXBwc0J5T3JnSW5wdXQSFAoDb3JnGAEgASgJQge6SARyAhABYgZwcm90bzM",[file_ai_stigmer_iam_oauthapp_v1_api,file_buf_validate_validate]);var OAuthAppsSchema=messageDesc2(file_ai_stigmer_iam_oauthapp_v1_io,1);var file_ai_stigmer_iam_oauthapp_v1_query=fileDesc("CiZhaS9zdGlnbWVyL2lhbS9vYXV0aGFwcC92MS9xdWVyeS5wcm90bxIaYWkuc3RpZ21lci5pYW0ub2F1dGhhcHAudjEy0AMKF09BdXRoQXBwUXVlcnlDb250cm9sbGVyEosBCgNnZXQSLS5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VJZBokLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwIi/CuBgrCAEQFiIFdmFsdWUqHnVuYXV0aG9yaXplZCB0byB2aWV3IG9hdXRoIGFwcBJyCg5nZXRCeVJlZmVyZW5jZRI0LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVJlZmVyZW5jZRokLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwIgTQuBgBEqwBCglsaXN0QnlPcmcSMy5haS5zdGlnbWVyLmlhbS5vYXV0aGFwcC52MS5MaXN0T0F1dGhBcHBzQnlPcmdJbnB1dBolLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwcyJDwrgYPwgBEB4iA29yZyo0dW5hdXRob3JpemVkIHRvIGxpc3Qgb2F1dGggYXBwcyBpbiB0aGlzIG9yZ2FuaXphdGlvbhoEoP8rFmIGcHJvdG8z",[file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options,file_ai_stigmer_iam_oauthapp_v1_api,file_ai_stigmer_iam_oauthapp_v1_io]),OAuthAppQueryController=serviceDesc(file_ai_stigmer_iam_oauthapp_v1_query,0);var REDACTED_MARKER3="***REDACTED***",MARKER_ON_CREATE_MESSAGE="cannot use the redaction marker as client_secret on create",PRESERVE_NO_EXISTING_SECRET_MESSAGE="cannot preserve client_secret: no existing secret value found",CIPHERTEXT_SHAPED_SECRET_MESSAGE="client_secret must be plaintext \u2014 values carrying the 'enc:' encryption prefix are not accepted from clients";function deleteBlockedByMcpServerMessage(org,slug,mcpServerName){return`cannot delete OAuthApp '${org}/${slug}': referenced by MCP server '${mcpServerName}'`}async function resolveOAuthAppRef(store,ref,logger2){let slug=ref?.slug??"";if(slug==="")return;let rows=await store.listResources(ApiResourceKind.oauth_app),slugMatches=[];for(let data of rows){let app;try{app=fromBinary2(OAuthAppSchema,data)}catch{continue}if((app.metadata?.slug??"")!==slug)continue;let refOrg=ref?.org??"";if(refOrg!==""&&app.metadata?.org===refOrg)return app;slugMatches.push(app)}if(slugMatches.length!==0){if(slugMatches.length===1)return slugMatches[0];logger2.warn("oauth_app_ref is ambiguous (slug exists in several orgs, none matching the ref); refusing to pick \u2014 pin the ref's org to resolve",{oauthAppSlug:slug,refOrg:ref?.org??"",candidateOrgs:slugMatches.map(app=>app.metadata?.org??"")})}}function redactOAuthApp(app){app.spec!==void 0&&app.spec.clientSecret!==""&&(app.spec.clientSecret=REDACTED_MARKER3)}function newEncryptClientSecretForCreateStep(secretService,logger2){return newEncryptClientSecretStep(secretService,logger2,!0)}function newEncryptClientSecretForUpdateStep(secretService,logger2){return newEncryptClientSecretStep(secretService,logger2,!1)}function newEncryptClientSecretStep(secretService,logger2,isCreate){return{name:"EncryptClientSecret",async execute(ctx){let app=ctx.newState;if(app.spec===void 0)return;let clientSecret=app.spec.clientSecret;if(clientSecret!==""){if(clientSecret===REDACTED_MARKER3){preserveExistingSecret(ctx,app,isCreate,logger2);return}if(isCiphertextShaped(clientSecret))throw invalidArgumentError(CIPHERTEXT_SHAPED_SECRET_MESSAGE);if(!secretService.isEnabled()){logger2.warn("encryption disabled: client_secret will be stored in plaintext");return}try{app.spec.clientSecret=await secretService.encrypt(clientSecret,EncryptionScope.forOrganization(app.metadata?.org??""))}catch(error2){throw internalError(error2,"failed to encrypt client_secret")}}}}}function preserveExistingSecret(ctx,app,isCreate,logger2){if(isCreate)throw invalidArgumentError(MARKER_ON_CREATE_MESSAGE);let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)throw internalError(new Error("existing resource not loaded"),"cannot preserve client_secret: existing resource not loaded");let existingSecret=existing.spec?.clientSecret??"";if(existingSecret==="")throw invalidArgumentError(PRESERVE_NO_EXISTING_SECRET_MESSAGE);app.spec!==void 0&&(app.spec.clientSecret=existingSecret),logger2.debug("preserved existing encrypted client_secret",{oauthAppId:app.metadata?.id??""})}function newCheckNoReferencingMcpServersStep(store,logger2){return{name:"CheckNoReferencingMcpServers",async execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)throw internalError(new Error("existing OAuthApp missing from pipeline context"),"existing OAuthApp not loaded in delete pipeline");let resources;try{resources=await store.listResources(ApiResourceKind.mcp_server)}catch(error2){throw internalError(error2,"failed to list MCP servers for referential integrity check")}for(let data of resources){let mcp;try{mcp=fromBinary2(McpServerSchema,data)}catch(error2){logger2.warn("failed to unmarshal MCP server during referential integrity check, skipping",{error:error2 instanceof Error?error2.message:String(error2)});continue}let ref=mcp.spec?.auth?.oauthAppRef;if(ref===void 0)continue;let resolved;try{resolved=await resolveOAuthAppRef(store,ref,logger2)}catch(error2){throw internalError(error2,"failed to resolve oauth_app_ref during referential integrity check")}if(resolved!==void 0&&(resolved.metadata?.id??"")===(existing.metadata?.id??""))throw failedPreconditionError(deleteBlockedByMcpServerMessage(existing.metadata?.org??"",existing.metadata?.slug??"",mcp.metadata?.name??""))}}}}function registerOAuthAppServices(router,deps){router.service(OAuthAppCommandController,{apply:(app,ctx)=>apply9(deps,app,ctx),create:(app,ctx)=>createOAuthApp(deps,app,ctx),update:(app,ctx)=>update12(deps,app,ctx),delete:(input,ctx)=>deleteOAuthApp(deps,input,ctx)}),router.service(OAuthAppQueryController,{get:(id,ctx)=>get16(deps,id,ctx),getByReference:(ref,ctx)=>getByReference9(deps,ref,ctx),listByOrg:(req,ctx)=>listByOrg2(deps,req,ctx)})}function kindOf15(ctx){return ctx.values.get(apiResourceKindKey)}async function createOAuthApp(deps,app,ctx){let reqCtx=new RequestContext(OAuthAppSchema,app,callerIdentityOf(ctx),kindOf15(ctx));await newPipeline("oauthapp-create",deps.logger).addStep(newAuthorizeStep(OAuthAppCommandController.method.create,deps.authorizer)).addStep(newResolveSlugStep()).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newEncryptClientSecretForCreateStep(deps.secretService,deps.logger)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).build().execute(reqCtx);let result=reqCtx.newState;return redactOAuthApp(result),result}async function update12(deps,app,ctx){let reqCtx=new RequestContext(OAuthAppSchema,app,callerIdentityOf(ctx),kindOf15(ctx));await newPipeline("oauthapp-update",deps.logger).addStep(newAuthorizeStep(OAuthAppCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingStep(deps.store)).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newEncryptClientSecretForUpdateStep(deps.secretService,deps.logger)).addStep(newPersistStep(deps.store)).build().execute(reqCtx);let result=reqCtx.newState;return redactOAuthApp(result),result}async function apply9(deps,app,ctx){let reqCtx=new RequestContext(OAuthAppSchema,app,callerIdentityOf(ctx),kindOf15(ctx));await newPipeline("oauthapp-apply",deps.logger).addStep(newAuthorizeStep(OAuthAppCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");return shouldCreate?createOAuthApp(deps,app,ctx):update12(deps,withResolvedApplyId(OAuthAppSchema,app,reqCtx),ctx)}async function deleteOAuthApp(deps,input,ctx){let reqCtx=new RequestContext(OAuthAppCommandController.method.delete.input,input,callerIdentityOf(ctx),kindOf15(ctx));reqCtx.set(RESOURCE_ID_KEY,input.resourceId),await newPipeline("oauthapp-delete",deps.logger).addStep(newAuthorizeStep(OAuthAppCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingForDeleteStep(deps.store,OAuthAppSchema)).addStep(newCheckNoReferencingMcpServersStep(deps.store,deps.logger)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDestroySecretBackingStateStep(deps.secretService,deps.logger,app2=>app2.spec===void 0?[]:[app2.spec.clientSecret])).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted OAuthApp not found in context"),"deleted OAuthApp not found in context");let app=deleted;return redactOAuthApp(app),app}async function get16(deps,id,ctx){let reqCtx=new RequestContext(OAuthAppQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf15(ctx));await newPipeline("oauthapp-get",deps.logger).addStep(newAuthorizeStep(OAuthAppQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,OAuthAppSchema)).build().execute(reqCtx);let app=reqCtx.get(TARGET_RESOURCE_KEY);return redactOAuthApp(app),app}async function getByReference9(deps,ref,ctx){let reqCtx=new RequestContext(OAuthAppQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf15(ctx));await newPipeline("oauthapp-get-by-reference",deps.logger).addStep(newAuthorizeStep(OAuthAppQueryController.method.getByReference,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadByReferenceStep(deps.store,OAuthAppSchema)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,loadedTargetAsMethod(OAuthAppQueryController.method.get))).build().execute(reqCtx);let app=reqCtx.get(TARGET_RESOURCE_KEY);return redactOAuthApp(app),app}var LIST_RESULT_KEY7="listResult";async function listByOrg2(deps,req,ctx){let reqCtx=new RequestContext(OAuthAppQueryController.method.listByOrg.input,req,callerIdentityOf(ctx),kindOf15(ctx));await newPipeline("oauthapp-list-by-org",deps.logger).addStep(newAuthorizeStep(OAuthAppQueryController.method.listByOrg,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newListByOrgStep2(deps.store,deps.listReadScope,deps.logger)).build().execute(reqCtx);let list12=reqCtx.get(LIST_RESULT_KEY7);if(list12===void 0)throw internalError(new Error("list result missing from pipeline context"),"OAuthApp list not found in context");return list12}function newListByOrgStep2(store,listReadScope,logger2){return{name:"ListByOrg",async execute(ctx){let org=ctx.input.org,resources;try{resources=await store.listResources(ApiResourceKind.oauth_app)}catch(error2){throw internalError(error2,"failed to list OAuthApps")}let requested=[];for(let data of resources){let app;try{app=fromBinary2(OAuthAppSchema,data)}catch(error2){logger2.warn("failed to unmarshal OAuthApp, skipping",{error:error2 instanceof Error?error2.message:String(error2)});continue}(app.metadata?.org??"")===org&&requested.push(app)}let apps=await restrictListByReadScope(listReadScope,ctx.callerIdentity,ApiResourceKind.oauth_app,requested,"");for(let app of apps)redactOAuthApp(app);apps.sort((a5,b7)=>compareCreatedAtDesc(a5.status?.audit?.specAudit?.createdAt,b7.status?.audit?.specAudit?.createdAt)),logger2.info("listed OAuthApps by organization",{org,matchCount:apps.length}),ctx.set(LIST_RESULT_KEY7,create2(OAuthAppsSchema,{entries:apps}))}}}var file_ai_stigmer_iam_platformclient_v1_io=fileDesc("CilhaS9zdGlnbWVyL2lhbS9wbGF0Zm9ybWNsaWVudC92MS9pby5wcm90bxIgYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEiLAoQUGxhdGZvcm1DbGllbnRJZBIYCgV2YWx1ZRgBIAEoCUIJukgGcgQQARhAIlQKD1BsYXRmb3JtQ2xpZW50cxJBCgdlbnRyaWVzGAEgAygLMjAuYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuUGxhdGZvcm1DbGllbnQiNQodTGlzdFBsYXRmb3JtQ2xpZW50c0J5T3JnSW5wdXQSFAoDb3JnGAEgASgJQge6SARyAhABIoABChxQbGF0Zm9ybUNsaWVudENyZWF0ZVJlc3BvbnNlEkkKD3BsYXRmb3JtX2NsaWVudBgBIAEoCzIwLmFpLnN0aWdtZXIuaWFtLnBsYXRmb3JtY2xpZW50LnYxLlBsYXRmb3JtQ2xpZW50EhUKDWNsaWVudF9zZWNyZXQYAiABKAliBnByb3RvMw",[file_ai_stigmer_iam_platformclient_v1_api,file_buf_validate_validate]);var PlatformClientsSchema=messageDesc2(file_ai_stigmer_iam_platformclient_v1_io,1);var PlatformClientCreateResponseSchema=messageDesc2(file_ai_stigmer_iam_platformclient_v1_io,3);var file_ai_stigmer_iam_platformclient_v1_command=fileDesc("Ci5haS9zdGlnbWVyL2lhbS9wbGF0Zm9ybWNsaWVudC92MS9jb21tYW5kLnByb3RvEiBhaS5zdGlnbWVyLmlhbS5wbGF0Zm9ybWNsaWVudC52MTKgBgofUGxhdGZvcm1DbGllbnRDb21tYW5kQ29udHJvbGxlchLPAQoGY3JlYXRlEjAuYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuUGxhdGZvcm1DbGllbnQaPi5haS5zdGlnbWVyLmlhbS5wbGF0Zm9ybWNsaWVudC52MS5QbGF0Zm9ybUNsaWVudENyZWF0ZVJlc3BvbnNlIlPCuBhPCBgQHiIMbWV0YWRhdGEub3JnKjt1bmF1dGhvcml6ZWQgdG8gY3JlYXRlIHBsYXRmb3JtIGNsaWVudCBpbiB0aGlzIG9yZ2FuaXphdGlvbhKrAQoGdXBkYXRlEjAuYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuUGxhdGZvcm1DbGllbnQaMC5haS5zdGlnbWVyLmlhbS5wbGF0Zm9ybWNsaWVudC52MS5QbGF0Zm9ybUNsaWVudCI9wrgYOQgCEBciC21ldGFkYXRhLmlkKiZ1bmF1dGhvcml6ZWQgdG8gdXBkYXRlIHBsYXRmb3JtIGNsaWVudBKxAQoGZGVsZXRlEjYuYWkuc3RpZ21lci5jb21tb25zLmFwaXJlc291cmNlLkFwaVJlc291cmNlRGVsZXRlSW5wdXQaMC5haS5zdGlnbWVyLmlhbS5wbGF0Zm9ybWNsaWVudC52MS5QbGF0Zm9ybUNsaWVudCI9wrgYOQgDEBciC3Jlc291cmNlX2lkKiZ1bmF1dGhvcml6ZWQgdG8gZGVsZXRlIHBsYXRmb3JtIGNsaWVudBLCAQoMcm90YXRlU2VjcmV0EjIuYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuUGxhdGZvcm1DbGllbnRJZBo+LmFpLnN0aWdtZXIuaWFtLnBsYXRmb3JtY2xpZW50LnYxLlBsYXRmb3JtQ2xpZW50Q3JlYXRlUmVzcG9uc2UiPsK4GDoIAhAXIgV2YWx1ZSotdW5hdXRob3JpemVkIHRvIHJvdGF0ZSBwbGF0Zm9ybSBjbGllbnQgc2VjcmV0GgSg/ysXYgZwcm90bzM",[file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options,file_ai_stigmer_iam_platformclient_v1_api,file_ai_stigmer_iam_platformclient_v1_io]),PlatformClientCommandController=serviceDesc(file_ai_stigmer_iam_platformclient_v1_command,0);var file_ai_stigmer_iam_platformclient_v1_query=fileDesc("CixhaS9zdGlnbWVyL2lhbS9wbGF0Zm9ybWNsaWVudC92MS9xdWVyeS5wcm90bxIgYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEykgQKHVBsYXRmb3JtQ2xpZW50UXVlcnlDb250cm9sbGVyEp0BCgNnZXQSLS5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VJZBowLmFpLnN0aWdtZXIuaWFtLnBsYXRmb3JtY2xpZW50LnYxLlBsYXRmb3JtQ2xpZW50IjXCuBgxCAEQFyIFdmFsdWUqJHVuYXV0aG9yaXplZCB0byB2aWV3IHBsYXRmb3JtIGNsaWVudBJ+Cg5nZXRCeVJlZmVyZW5jZRI0LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVJlZmVyZW5jZRowLmFpLnN0aWdtZXIuaWFtLnBsYXRmb3JtY2xpZW50LnYxLlBsYXRmb3JtQ2xpZW50IgTQuBgBEsoBCglsaXN0QnlPcmcSPy5haS5zdGlnbWVyLmlhbS5wbGF0Zm9ybWNsaWVudC52MS5MaXN0UGxhdGZvcm1DbGllbnRzQnlPcmdJbnB1dBoxLmFpLnN0aWdtZXIuaWFtLnBsYXRmb3JtY2xpZW50LnYxLlBsYXRmb3JtQ2xpZW50cyJJwrgYRQgBEB4iA29yZyo6dW5hdXRob3JpemVkIHRvIGxpc3QgcGxhdGZvcm0gY2xpZW50cyBpbiB0aGlzIG9yZ2FuaXphdGlvbhoEoP8rF2IGcHJvdG8z",[file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options,file_ai_stigmer_iam_platformclient_v1_api,file_ai_stigmer_iam_platformclient_v1_io]),PlatformClientQueryController=serviceDesc(file_ai_stigmer_iam_platformclient_v1_query,0);var import_node_crypto21=require("node:crypto"),CLIENT_ID_PREFIX="stgm_cid_",CLIENT_SECRET_PREFIX="stgm_cs_",CLIENT_ID_BYTES=32,CLIENT_SECRET_BYTES=48,SECRET_FINGERPRINT_LENGTH=6;function generateClientId(){return CLIENT_ID_PREFIX+(0,import_node_crypto21.randomBytes)(CLIENT_ID_BYTES).toString("base64url")}function generateClientSecret(){return CLIENT_SECRET_PREFIX+(0,import_node_crypto21.randomBytes)(CLIENT_SECRET_BYTES).toString("base64url")}function hashClientSecret(secret){return(0,import_node_crypto21.createHash)("sha256").update(secret,"utf8").digest("base64url")}function secretFingerprint(secret){return secret.length<=SECRET_FINGERPRINT_LENGTH?secret:secret.slice(-SECRET_FINGERPRINT_LENGTH)}function secretMatchesHash(secret,storedHash){if(storedHash==="")return!1;let presented=Buffer.from(hashClientSecret(secret),"utf8"),stored=Buffer.from(storedHash,"utf8");return presented.length===stored.length&&(0,import_node_crypto21.timingSafeEqual)(presented,stored)}var DuplicatePlatformClientError=class extends Error{constructor(message6,options){super(message6,options),this.name="DuplicatePlatformClientError"}};var CLIENT_SECRET_PLAINTEXT_KEY="platformClientSecretPlaintext";function redactPlatformClient(client){return client.spec!==void 0&&(client.spec.clientSecretHash=""),client}function parkedClientSecret(ctx){let secret=ctx.get(CLIENT_SECRET_PLAINTEXT_KEY);if(typeof secret!="string"||secret==="")throw internalError(new Error("no client secret parked \u2014 a credential step must run first"),"platform client credentials");return secret}function newRefuseReservedSlugStep(){return{name:"RefuseReservedSlug",execute(ctx){let slug=metadataOf(ctx.newState)?.slug??"";if(RESERVED_PLATFORM_CLIENT_SLUGS.has(slug))throw invalidArgumentError(reservedSlugMessage(slug))}}}function newCheckDuplicateStep3(clients){return{name:"CheckDuplicate",async execute(ctx){let metadata=requireMetadata2(ctx,"duplicate check"),existing=await clients.findByOrgAndSlug(metadata.org,metadata.slug);if(existing!==void 0)throw alreadyExistsError(PLATFORM_CLIENT_KIND_NAME,`slug '${metadata.slug}' in org '${metadata.org}' (id: ${existing.metadata?.id??""})`)}}}function newGenerateClientCredentialsStep(){return{name:"GenerateClientCredentials",execute(ctx){let spec=specOf3(ctx.newState),secret=generateClientSecret();spec.clientId=generateClientId(),spec.clientSecretHash=hashClientSecret(secret),spec.secretFingerprint=secretFingerprint(secret),ctx.set(CLIENT_SECRET_PLAINTEXT_KEY,secret)}}}function newPersistNewClientStep(clients){return{name:"Persist",async execute(ctx){try{await clients.save(ctx.newState)}catch(error2){if(error2 instanceof DuplicatePlatformClientError){let metadata=requireMetadata2(ctx,"persist");throw alreadyExistsError(PLATFORM_CLIENT_KIND_NAME,`slug '${metadata.slug}' in org '${metadata.org}'`)}throw internalError(error2,"failed to save platform client")}}}}function newLoadExistingClientStep(clients){return{name:"LoadExisting",async execute(ctx){let metadata=requireMetadata2(ctx,"load existing"),existing;if(metadata.id!==""){if(existing=await clients.findById(metadata.id),existing===void 0)throw notFoundError(PLATFORM_CLIENT_KIND_NAME,metadata.id)}else if(metadata.slug!==""){if(existing=await clients.findByOrgAndSlug(metadata.org,metadata.slug),existing===void 0)throw notFoundError(PLATFORM_CLIENT_KIND_NAME,metadata.slug);metadata.id=existing.metadata?.id??""}else throw invalidArgumentError("resource id or slug is required for update");ctx.set(EXISTING_RESOURCE_KEY,existing)}}}function newPreserveClientCredentialsStep(){return{name:"PreserveClientCredentials",execute(ctx){let existing=storedClientOf(ctx,EXISTING_RESOURCE_KEY),spec=specOf3(ctx.newState);spec.clientId=existing.spec?.clientId??"",spec.clientSecretHash=existing.spec?.clientSecretHash??"",spec.secretFingerprint=existing.spec?.secretFingerprint??""}}}function newPersistUpdatedClientStep(clients){return{name:"Persist",async execute(ctx){try{await clients.update(ctx.newState)}catch(error2){throw internalError(error2,"failed to save platform client")}}}}function newRefuseSystemManagedStep(verb,key){return{name:"RefuseSystemManaged",execute(ctx){if(storedClientOf(ctx,key).metadata?.labels[SYSTEM_MANAGED_LABEL]===RESERVED_LABEL_TRUE)throw failedPreconditionError(systemManagedMessage(verb))}}}function newLoadTargetClientStep(clients){return{name:"LoadTarget",async execute(ctx){let id=idValueOf(ctx.input);if(id==="")throw invalidArgumentError("resource id is required");ctx.set(TARGET_RESOURCE_KEY,await readClient(clients,id))}}}function newLoadClientByReferenceStep(clients){return{name:"LoadByReference",async execute(ctx){let ref=ctx.input;if(ref.slug==="")throw invalidArgumentError("slug is required in reference");if(ref.kind!==ApiResourceKind.api_resource_kind_unknown&&ref.kind!==ApiResourceKind.platform_client)throw invalidArgumentError(`kind mismatch: expected platform_client, got ${ApiResourceKind[ref.kind]??String(ref.kind)}`);requireOrgForReference(ApiResourceKind.platform_client,ref.org);let client=await clients.findByOrgAndSlug(ref.org,ref.slug);if(client===void 0)throw new ConnectError(referenceNotFoundMessage(ref.org,ref.slug),Code.NotFound);ctx.set(TARGET_RESOURCE_KEY,client)}}}function newRotateClientCredentialsStep(){return{name:"RotateClientCredentials",execute(ctx){let client=storedClientOf(ctx,TARGET_RESOURCE_KEY),spec=specOf3(client),secret=generateClientSecret();spec.clientSecretHash=hashClientSecret(secret),spec.secretFingerprint=secretFingerprint(secret),updateAuditFields(PlatformClientSchema,client,client,ctx.callerIdentity),ctx.set(CLIENT_SECRET_PLAINTEXT_KEY,secret)}}}function newPersistTargetClientStep(clients){return{name:"Persist",async execute(ctx){try{await clients.update(storedClientOf(ctx,TARGET_RESOURCE_KEY))}catch(error2){throw internalError(error2,"failed to save platform client")}}}}function newLoadExistingClientForDeleteStep(clients){return{name:"LoadExistingForDelete",async execute(ctx){ctx.set(EXISTING_RESOURCE_KEY,await readClient(clients,requireResourceId3(ctx)))}}}function newDeleteClientStep(clients){return{name:"DeleteResource",async execute(ctx){try{await clients.deleteById(requireResourceId3(ctx))}catch(error2){throw internalError(error2,"failed to delete platform client")}}}}async function readClient(clients,id){let client=await clients.findById(id);if(client===void 0)throw notFoundError(PLATFORM_CLIENT_KIND_NAME,id);return client}function storedClientOf(ctx,key){let client=ctx.get(key);if(client===void 0)throw internalError(new Error(`no platform client under '${key}' \u2014 its load step must run first`),"platform client chain ordering");return client}function requireMetadata2(ctx,operation2){let metadata=metadataOf(ctx.newState);if(metadata===void 0)throw internalError(new Error("platform client metadata is nil"),operation2);return metadata}function specOf3(client){return client.spec===void 0&&(client.spec=create2(PlatformClientSpecSchema)),client.spec}function requireResourceId3(ctx){let id=ctx.get(RESOURCE_ID_KEY);if(typeof id!="string"||id==="")throw internalError(new Error("resource id not found in context (the delete handler sets it)"),"platform client delete ordering");return id}function registerPlatformClientServices(router,deps){router.service(PlatformClientCommandController,{create:(client,ctx)=>createClient2(deps,client,ctx),update:(client,ctx)=>updateClient(deps,client,ctx),delete:(input,ctx)=>deleteClient(deps,input,ctx),rotateSecret:(id,ctx)=>rotateSecret(deps,id,ctx)}),router.service(PlatformClientQueryController,{get:(id,ctx)=>get17(deps,id,ctx),getByReference:(ref,ctx)=>getByReference10(deps,ref,ctx),listByOrg:(input,ctx)=>listByOrg3(deps,input,ctx)})}function kindOf16(ctx){return ctx.values.get(apiResourceKindKey)}async function createClient2(deps,client,ctx){let reqCtx=new RequestContext(PlatformClientSchema,client,callerIdentityOf(ctx),kindOf16(ctx));return await newPipeline("platformclient-create",deps.logger).addStep(newAuthorizeStep(PlatformClientCommandController.method.create,deps.authorizer)).addStep(newResolveSlugStep()).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newRefuseReservedSlugStep()).addStep(newCheckDuplicateStep3(deps.clients)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store)).addStep(newGenerateClientCredentialsStep()).addStep(newPersistNewClientStep(deps.clients)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).build().execute(reqCtx),create2(PlatformClientCreateResponseSchema,{platformClient:redactPlatformClient(reqCtx.newState),clientSecret:parkedClientSecret(reqCtx)})}async function updateClient(deps,client,ctx){let reqCtx=new RequestContext(PlatformClientSchema,client,callerIdentityOf(ctx),kindOf16(ctx));return await newPipeline("platformclient-update",deps.logger).addStep(newAuthorizeStep(PlatformClientCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingClientStep(deps.clients)).addStep(newRefuseSystemManagedStep("updated",EXISTING_RESOURCE_KEY)).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store)).addStep(newPreserveClientCredentialsStep()).addStep(newPersistUpdatedClientStep(deps.clients)).build().execute(reqCtx),redactPlatformClient(reqCtx.newState)}async function deleteClient(deps,input,ctx){let reqCtx=new RequestContext(PlatformClientCommandController.method.delete.input,input,callerIdentityOf(ctx),kindOf16(ctx));return reqCtx.set(RESOURCE_ID_KEY,input.resourceId),await newPipeline("platformclient-delete",deps.logger).addStep(newAuthorizeStep(PlatformClientCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingClientForDeleteStep(deps.clients)).addStep(newRefuseSystemManagedStep("deleted",EXISTING_RESOURCE_KEY)).addStep(newDeleteClientStep(deps.clients)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).build().execute(reqCtx),redactPlatformClient(storedClientOf(reqCtx,EXISTING_RESOURCE_KEY))}async function rotateSecret(deps,id,ctx){let reqCtx=new RequestContext(PlatformClientCommandController.method.rotateSecret.input,id,callerIdentityOf(ctx),kindOf16(ctx));return await newPipeline("platformclient-rotate-secret",deps.logger).addStep(newAuthorizeStep(PlatformClientCommandController.method.rotateSecret,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetClientStep(deps.clients)).addStep(newRefuseSystemManagedStep("rotated",TARGET_RESOURCE_KEY)).addStep(newRotateClientCredentialsStep()).addStep(newPersistTargetClientStep(deps.clients)).build().execute(reqCtx),create2(PlatformClientCreateResponseSchema,{platformClient:redactPlatformClient(storedClientOf(reqCtx,TARGET_RESOURCE_KEY)),clientSecret:parkedClientSecret(reqCtx)})}async function get17(deps,id,ctx){let reqCtx=new RequestContext(PlatformClientQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf16(ctx));return await newPipeline("platformclient-get",deps.logger).addStep(newAuthorizeStep(PlatformClientQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetClientStep(deps.clients)).build().execute(reqCtx),redactPlatformClient(storedClientOf(reqCtx,TARGET_RESOURCE_KEY))}async function getByReference10(deps,ref,ctx){let reqCtx=new RequestContext(PlatformClientQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf16(ctx));return await newPipeline("platformclient-get-by-reference",deps.logger).addStep(newAuthorizeStep(PlatformClientQueryController.method.getByReference,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadClientByReferenceStep(deps.clients)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,loadedTargetAsMethod(PlatformClientQueryController.method.get))).build().execute(reqCtx),redactPlatformClient(storedClientOf(reqCtx,TARGET_RESOURCE_KEY))}async function listByOrg3(deps,input,ctx){let caller=callerIdentityOf(ctx),reqCtx=new RequestContext(PlatformClientQueryController.method.listByOrg.input,input,caller,kindOf16(ctx));await newPipeline("platformclient-list-by-org",deps.logger).addStep(newAuthorizeStep(PlatformClientQueryController.method.listByOrg,deps.authorizer)).addStep(newValidateProtoStep()).build().execute(reqCtx);let candidates;try{candidates=await deps.clients.findByOrg(input.org)}catch(error2){throw internalError(error2,"failed to list platform clients")}let entries=[...await restrictListByReadScope(deps.listReadScope,caller,ApiResourceKind.platform_client,candidates,input.org)].sort((a5,b7)=>compareCreatedAtDesc(a5.status?.audit?.specAudit?.createdAt,b7.status?.audit?.specAudit?.createdAt)).map(redactPlatformClient);return create2(PlatformClientsSchema,{entries})}var OPAQUE_ORIGIN="null";function newPlatformClientOriginGuard(deps){return{name:"platform-client-origin",async guard(caller,method,headers2){let origin=headers2.get("origin")??"";if(origin.trim()==="")return;let platformClientId=mintingClientOf(caller);if(platformClientId===void 0)return;let procedure=`/${method.parent.typeName}/${method.name}`,client=await deps.clients.findById(platformClientId);if(client===void 0)throw new ConnectError(DELETED_CLIENT_MESSAGE,Code.Unauthenticated);if(!originAllowed(origin,client.spec?.allowedOrigins??[]))throw deps.logger.warn("origin refusal: origin not in allowed_origins",{procedure,platformClientId,origin}),new ConnectError(originRefusalMessage(origin),Code.PermissionDenied)}}}function mintingClientOf(caller){let payload=decodeVerifiedPlatformTokenPayload(caller.rawToken);if(!(payload===void 0||stringClaim(payload,TOKEN_TYPE_CLAIM)!==void 0))return stringClaim(payload,USER_TOKEN_CLAIMS.platformClientId)}function originAllowed(origin,allowed){if(allowed.length===0)return!0;if(origin===OPAQUE_ORIGIN)return!1;let presented=origin.toLowerCase();return allowed.some(entry=>entry.toLowerCase()===presented)}var KIND5=ApiResourceKind.platform_client;function newResourcePlatformClientStore(store){async function readById(id){try{return await store.getResource(KIND5,id,PlatformClientSchema)}catch(error2){if(error2 instanceof ResourceNotFoundError)return;throw error2}}async function readByClientId(clientId){if(clientId!=="")try{return await store.findByField(KIND5,"spec.clientId",clientId,PlatformClientSchema)}catch(error2){if(error2 instanceof ResourceNotFoundError)return;throw error2}}async function listOrg(org){let clients=[];for(let data of await store.listResources(KIND5)){let client;try{client=fromBinary2(PlatformClientSchema,data)}catch{continue}(client.metadata?.org??"")===org&&clients.push(client)}return clients}async function readByOrgAndSlug(org,slug){if(!(org===""||slug===""))return(await listOrg(org)).find(client=>(client.metadata?.slug??"")===slug)}return{async save(client){let id=client.metadata?.id??"",org=client.metadata?.org??"",slug=client.metadata?.slug??"";if(await readById(id)!==void 0)throw new DuplicatePlatformClientError(`platform client '${id}' already exists`);if(await readByOrgAndSlug(org,slug)!==void 0)throw new DuplicatePlatformClientError(`platform client '${org}/${slug}' already exists`);if(await readByClientId(client.spec?.clientId??"")!==void 0)throw new DuplicatePlatformClientError("a platform client already holds this client_id");await store.saveResource(KIND5,id,PlatformClientSchema,client)},async update(client){let id=client.metadata?.id??"";await readById(id)!==void 0&&await store.saveResource(KIND5,id,PlatformClientSchema,client)},async modifyById(id,modify){try{return await store.updateResource(KIND5,id,PlatformClientSchema,modify)}catch(error2){if(error2 instanceof ResourceNotFoundError)return;throw error2}},async deleteById(id){await store.deleteResource(KIND5,id)},findById:readById,findByClientId:readByClientId,findByOrgAndSlug:readByOrgAndSlug,findByOrg:listOrg}}var file_ai_stigmer_iam_platformclient_v1_token=fileDesc("CixhaS9zdGlnbWVyL2lhbS9wbGF0Zm9ybWNsaWVudC92MS90b2tlbi5wcm90bxIgYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEiugEKFE1pbnRVc2VyVG9rZW5SZXF1ZXN0EhoKCWNsaWVudF9pZBgBIAEoCUIHukgEcgIQARIeCg1jbGllbnRfc2VjcmV0GAIgASgJQge6SARyAhABEhsKB3VzZXJfaWQYAyABKAlCCrpIB3IFEAEYgAISHAoKdXNlcl9lbWFpbBgEIAEoCUIIukgFcgMYwAISGwoJdXNlcl9uYW1lGAUgASgJQgi6SAVyAxiAAhIOCgZvcmdfaWQYBiABKAkiVQoVTWludFVzZXJUb2tlblJlc3BvbnNlEhQKDGFjY2Vzc190b2tlbhgBIAEoCRISCgp0b2tlbl90eXBlGAIgASgJEhIKCmV4cGlyZXNfaW4YAyABKAUiyQMKFU1pbnRHdWVzdFRva2VuUmVxdWVzdBIUCgNvcmcYASABKAlCB7pIBHICEAESFQoEc2x1ZxgCIAEoCUIHukgEcgIQARIXCg9ndWVzdF9jb29raWVfaWQYAyABKAkSywIKDGVtYmVkX29yaWdpbhgEIAEoCUK0ArpIsAK6AawCChNlbWJlZF9vcmlnaW4uZm9ybWF0EndlbWJlZF9vcmlnaW4gbXVzdCBiZSBlbXB0eSwgIm51bGwiLCBvciBhbiBleGFjdCB3ZWIgb3JpZ2luIGxpa2UgaHR0cHM6Ly9leGFtcGxlLmNvbSAobm8gcGF0aCwgcXVlcnksIG9yIHRyYWlsaW5nIHNsYXNoKRqbAXRoaXMgPT0gJycgfHwgdGhpcyA9PSAnbnVsbCcgfHwgdGhpcy5tYXRjaGVzKCdeaHR0cHM/Oi8vW0EtWmEtejAtOV0oW0EtWmEtejAtOS1dKltBLVphLXowLTldKT8oXFwuW0EtWmEtejAtOV0oW0EtWmEtejAtOS1dKltBLVphLXowLTldKT8pKig6WzAtOV17MSw1fSk/JCcpEhwKCmxpbmtfdG9rZW4YBSABKAlCCLpIBXIDGIABIm8KFk1pbnRHdWVzdFRva2VuUmVzcG9uc2USFAoMYWNjZXNzX3Rva2VuGAEgASgJEhIKCnRva2VuX3R5cGUYAiABKAkSEgoKZXhwaXJlc19pbhgDIAEoBRIXCg9ndWVzdF9jb29raWVfaWQYBCABKAkytAIKHVBsYXRmb3JtQ2xpZW50VG9rZW5Db250cm9sbGVyEoYBCg1taW50VXNlclRva2VuEjYuYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuTWludFVzZXJUb2tlblJlcXVlc3QaNy5haS5zdGlnbWVyLmlhbS5wbGF0Zm9ybWNsaWVudC52MS5NaW50VXNlclRva2VuUmVzcG9uc2UiBMi4GAESiQEKDm1pbnRHdWVzdFRva2VuEjcuYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuTWludEd1ZXN0VG9rZW5SZXF1ZXN0GjguYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuTWludEd1ZXN0VG9rZW5SZXNwb25zZSIEyLgYAWIGcHJvdG8z",[file_ai_stigmer_commons_rpc_method_options,file_buf_validate_validate]);var MintUserTokenResponseSchema=messageDesc2(file_ai_stigmer_iam_platformclient_v1_token,1);var PlatformClientTokenController=serviceDesc(file_ai_stigmer_iam_platformclient_v1_token,0);var import_node_crypto22=require("node:crypto");var PLATFORM_TOKEN_KEY_ENV_VAR="STIGMER_PLATFORM_TOKEN_KEY",PLATFORM_TOKEN_KEY_FILE_NAME="platform-token.key",DEFAULT_PLATFORM_TOKEN_TTL_SECONDS=900,MIN_RSA_MODULUS_BITS=2048;function canSign(ring){return ring.signer!==void 0}function resolvePlatformTokenKeys(input){if(input.requireAuthentication){if(input.supplied!==void 0)return input.supplied;if(input.edition!==ServerEdition.oss)throw new Error(`the ${ServerEdition[input.edition]} edition requires authentication but registers no platform-token key ring \u2014 register drivers.platformTokenKeys; only open source generates its own key`);return openSourcePlatformTokenKeyRing(input.options)}}function openSourcePlatformTokenKeyRing(options={}){let privateKey=getOrCreateKey(RSA_PRIVATE_KEY,PLATFORM_TOKEN_KEY_ENV_VAR,PLATFORM_TOKEN_KEY_FILE_NAME,options);return{signer:{key:privateKey,kid:kidOf(privateKey)},verificationKeys:[(0,import_node_crypto22.createPublicKey)(privateKey)],audience:"",ttlSeconds:DEFAULT_PLATFORM_TOKEN_TTL_SECONDS}}var RSA_PRIVATE_KEY={fromEnv(envVar,decoded){let key=parseKey2(()=>(0,import_node_crypto22.createPrivateKey)(decoded.toString("utf8")),envVar);return requireRsa(key,envVar)},fromFile(content){try{let key=(0,import_node_crypto22.createPrivateKey)(content.toString("utf8"));return isUsableRsa(key)?key:void 0}catch{return}},generate(){return(0,import_node_crypto22.generateKeyPairSync)("rsa",{modulusLength:MIN_RSA_MODULUS_BITS}).privateKey},toFile(key){return Buffer.from(key.export({format:"pem",type:"pkcs8"}))}};function kidOf(key){let publicKey=key.type==="private"?(0,import_node_crypto22.createPublicKey)(key):key;return(0,import_node_crypto22.createHash)("sha256").update(spkiOf(publicKey)).digest("base64url").slice(0,16)}function spkiOf(publicKey){return publicKey.export({format:"der",type:"spki"})}function parseKey2(parse5,what){try{return parse5()}catch(error2){throw new Error(`${what} is not a readable PEM key: ${error2 instanceof Error?error2.message:String(error2)}`)}}function requireRsa(key,what){if(!isUsableRsa(key))throw new Error(`${what} must be an RSA key of at least ${MIN_RSA_MODULUS_BITS} bits`);return key}function isUsableRsa(key){return key.asymmetricKeyType==="rsa"&&(key.asymmetricKeyDetails?.modulusLength??0)>=MIN_RSA_MODULUS_BITS}var SUBJECT_SEPARATOR="|",DEFAULT_AUTO_GRANT_ROLE=IamRole.viewer;async function mintUserToken(deps,request){let keys=deps.keys;if(keys===void 0)throw new ConnectError(MINTING_REQUIRES_AUTHENTICATION_MESSAGE,Code.FailedPrecondition);if(!canSign(keys))throw new ConnectError(MINTING_DISABLED_MESSAGE,Code.FailedPrecondition);let client=await authenticateClient(deps,request),owningOrg=client.metadata?.org??"";if(request.orgId!==""&&request.orgId!==owningOrg)throw new ConnectError(organizationMismatchMessage(owningOrg),Code.InvalidArgument);let user={externalUserId:request.userId,email:request.userEmail,name:request.userName},accountId=await resolveOrProvisionAccount(deps,client,owningOrg,user),now=deps.now(),signed=signPlatformToken(keys,{[USER_TOKEN_CLAIMS.subject]:accountId,[USER_TOKEN_CLAIMS.externalUserId]:user.externalUserId,[USER_TOKEN_CLAIMS.email]:user.email,[USER_TOKEN_CLAIMS.name]:user.name,[USER_TOKEN_CLAIMS.org]:owningOrg,[USER_TOKEN_CLAIMS.platformClientId]:client.metadata?.id??""},{now});return await recordClientUse(deps,client,now),create2(MintUserTokenResponseSchema,{accessToken:signed.token,tokenType:BEARER_TOKEN_TYPE,expiresIn:keys.ttlSeconds})}async function authenticateClient(deps,request){let client;try{client=await deps.clients.findByClientId(request.clientId)}catch(error2){throw internalError(error2,"failed to authenticate platform client")}if(client===void 0||!secretMatchesHash(request.clientSecret,client.spec?.clientSecretHash??""))throw new ConnectError(INVALID_CLIENT_CREDENTIALS_MESSAGE,Code.Unauthenticated);let spec=client.spec;if(spec?.neverExpires!==!0&&spec?.expiresAt!==void 0&&deps.now().getTime()>timestampDate(spec.expiresAt).getTime())throw new ConnectError(EXPIRED_CLIENT_SECRET_MESSAGE,Code.FailedPrecondition);return client}function recordClientUse(deps,client,now){let id=client.metadata?.id??"";return recordCredentialUse({credential:"platform client",id,lastUsedAt:client.status?.lastUsedAt,now,logger:deps.logger,write:stamp2=>deps.clients.modifyById(id,live=>{live.status??=create2(PlatformClientStatusSchema),stamp2(live.status)})})}async function resolveOrProvisionAccount(deps,client,org,user){let idpId=platformClientSubject(org,user.externalUserId),existing=await findAccount(deps,idpId);if(existing!==void 0)return platformClientAccountId(existing,user,org);let spec=client.spec;if(spec?.autoProvisionAccounts!==!0)throw new ConnectError(noAccountMessage(user.externalUserId,org),Code.FailedPrecondition);let input=accountInput(idpId,org,user),actor=serverActingFor(client.metadata?.id??"");spec.autoGrantOnOrg&&await grantAutoRole(deps,client,org,accountIdFor(idpId),actor);try{return(await deps.createAccount(input,actor)).metadata?.id??""}catch(error2){let winner=await resolveCreateRace(error2,()=>deps.accounts.findByIdpId(idpId));return platformClientAccountId(winner,user,org)}}async function findAccount(deps,idpId){try{return await deps.accounts.findByIdpId(idpId)}catch(error2){throw internalError(error2,"failed to resolve platform client user")}}function platformClientAccountId(account2,user,org){if(account2.spec?.provisioningMode!==IdentityAccountProvisioningMode.platform_client)throw new ConnectError(foreignAccountMessage(user.externalUserId,org),Code.FailedPrecondition);return account2.metadata?.id??""}function accountInput(idpId,org,user){let input={name:user.email!==""?user.email:user.externalUserId,spec:create2(IdentityAccountSpecSchema,{idpId,email:user.email,...splitName(user.name,user.email)}),provisioning:{mode:"platform_client",org}},result=validator().validate(IdentityAccountSchema,create2(IdentityAccountSchema,{apiVersion:"iam.stigmer.ai/v1",kind:"IdentityAccount",metadata:{name:input.name,org},spec:input.spec}));if(result.kind==="invalid")throw new ConnectError(result.error.message,Code.InvalidArgument);if(result.kind==="error")throw new ConnectError(`validation could not run: ${result.error.message}`,Code.Internal);return input}async function grantAutoRole(deps,client,org,accountId,actor){let configured=client.spec?.autoGrantRole??IamRole.iam_role_unspecified;if(configured===IamRole.owner)throw new ConnectError(OWNER_AUTO_GRANT_MESSAGE,Code.InvalidArgument);let role=configured===IamRole.iam_role_unspecified?DEFAULT_AUTO_GRANT_ROLE:configured;try{await deps.grantPath.grant(organizationRole(accountId,role,org),actor)}catch(error2){throw deps.logger.error("platform client auto-grant failed; nothing was provisioned",{accountId,platformClientId:client.metadata?.id??"",error:error2 instanceof Error?error2.message:String(error2)}),new ConnectError(PROVISIONING_FAILED_MESSAGE,Code.Internal)}}function platformClientSubject(org,externalUserId){return requireSubjectPart("org",org),requireSubjectPart("externalUserId",externalUserId),`${PLATFORM_CLIENT_SUBJECT_PREFIX}${org}${SUBJECT_SEPARATOR}${externalUserId}`}function requireSubjectPart(part,value){if(value.trim()==="")throw new ConnectError(blankSubjectPartMessage(part),Code.InvalidArgument);if(value.includes(SUBJECT_SEPARATOR))throw new ConnectError(subjectSeparatorMessage(part,value),Code.InvalidArgument)}function splitName(name,email){if(name!==""){let space=name.indexOf(" ");return space>0?{firstName:name.slice(0,space),lastName:name.slice(space+1)}:{firstName:name,lastName:""}}let at2=email.indexOf("@");return{firstName:at2>=0?email.slice(0,at2):email,lastName:""}}function registerPlatformClientTokenService(router,deps){router.service(PlatformClientTokenController,{mintUserToken:request=>mintUserToken(deps.mint,request),mintGuestToken:(request,ctx)=>{if(deps.guestTokenMinting===void 0)throw new ConnectError(GUEST_MINT_UNIMPLEMENTED_MESSAGE,Code.Unimplemented);return deps.guestTokenMinting.mintGuestToken(request,ctx.requestHeader)}})}function newPlatformClientTokenVerifier(deps){return{name:"platform-client",async verify(token){let result=verifyPlatformToken(deps.keys,token,deps.now?.());switch(result.outcome){case"foreign":return null;case"refused":throw platformTokenRefusalError(result.refusal);case"verified":break;default:{let exhaustive=result;throw new Error(`unknown verification ${JSON.stringify(exhaustive)}`)}}let verified=result.token;if(verified.tokenType!==void 0)return null;let platformClientId=stringClaim(verified.payload,USER_TOKEN_CLAIMS.platformClientId);if(platformClientId===void 0)throw new ConnectError(TOKEN_NAMES_NO_CLIENT_MESSAGE,Code.Unauthenticated);if(await deps.clients.findById(platformClientId)===void 0)throw new ConnectError(DELETED_CLIENT_MESSAGE,Code.Unauthenticated);let email=stringClaim(verified.payload,USER_TOKEN_CLAIMS.email),displayName=stringClaim(verified.payload,USER_TOKEN_CLAIMS.name);return{identityId:verified.subject,callerClass:"user",issuer:PLATFORM_TOKEN_ISSUER,rawToken:token,...email!==void 0?{email}:{},...displayName!==void 0?{displayName}:{},platformClientId}}}}var file_ai_stigmer_tenancy_organization_v1_io=fileDesc("CithaS9zdGlnbWVyL3RlbmFuY3kvb3JnYW5pemF0aW9uL3YxL2lvLnByb3RvEiJhaS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxIlIKDU9yZ2FuaXphdGlvbnMSQQoHZW50cmllcxgBIAMoCzIwLmFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEuT3JnYW5pemF0aW9uImoKEE9yZ2FuaXphdGlvbkxpc3QSEwoLdG90YWxfcGFnZXMYASABKAUSQQoHZW50cmllcxgCIAMoCzIwLmFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEuT3JnYW5pemF0aW9uIioKDk9yZ2FuaXphdGlvbklkEhgKBXZhbHVlGAEgASgJQgm6SAZyBBABGEAimwEKGk9yZ2FuaXphdGlvbkV4dGVybmFsTG9va3VwElsKFWlkZW50aXR5X3Byb3ZpZGVyX3JlZhgBIAEoCzI0LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVJlZmVyZW5jZUIGukgDyAEBEiAKD2V4dGVybmFsX29yZ19pZBgCIAEoCUIHukgEcgIQAWIGcHJvdG8z",[file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_tenancy_organization_v1_api,file_buf_validate_validate]),OrganizationsSchema=messageDesc2(file_ai_stigmer_tenancy_organization_v1_io,0),OrganizationListSchema=messageDesc2(file_ai_stigmer_tenancy_organization_v1_io,1);var file_ai_stigmer_tenancy_organization_v1_command=fileDesc("CjBhaS9zdGlnbWVyL3RlbmFuY3kvb3JnYW5pemF0aW9uL3YxL2NvbW1hbmQucHJvdG8SImFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEy2AQKHU9yZ2FuaXphdGlvbkNvbW1hbmRDb250cm9sbGVyEmsKBWFwcGx5EjAuYWkuc3RpZ21lci50ZW5hbmN5Lm9yZ2FuaXphdGlvbi52MS5Pcmdhbml6YXRpb24aMC5haS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxLk9yZ2FuaXphdGlvbhJyCgZjcmVhdGUSMC5haS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxLk9yZ2FuaXphdGlvbhowLmFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEuT3JnYW5pemF0aW9uIgTQuBgBEqgBCgZ1cGRhdGUSMC5haS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxLk9yZ2FuaXphdGlvbhowLmFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEuT3JnYW5pemF0aW9uIjrCuBg2CAIQHiILbWV0YWRhdGEuaWQqI3VuYXV0aG9yaXplZCB0byB1cGRhdGUgb3JnYW5pemF0aW9uEqQBCgZkZWxldGUSMi5haS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxLk9yZ2FuaXphdGlvbklkGjAuYWkuc3RpZ21lci50ZW5hbmN5Lm9yZ2FuaXphdGlvbi52MS5Pcmdhbml6YXRpb24iNMK4GDAIAxAeIgV2YWx1ZSojdW5hdXRob3JpemVkIHRvIGRlbGV0ZSBvcmdhbml6YXRpb24aBKD/Kx5iBnByb3RvMw",[file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options,file_ai_stigmer_tenancy_organization_v1_api,file_ai_stigmer_tenancy_organization_v1_io]),OrganizationCommandController=serviceDesc(file_ai_stigmer_tenancy_organization_v1_command,0);var file_ai_stigmer_tenancy_organization_v1_query=fileDesc("Ci5haS9zdGlnbWVyL3RlbmFuY3kvb3JnYW5pemF0aW9uL3YxL3F1ZXJ5LnByb3RvEiJhaS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxMrkEChtPcmdhbml6YXRpb25RdWVyeUNvbnRyb2xsZXISnwEKA2dldBIyLmFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEuT3JnYW5pemF0aW9uSWQaMC5haS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxLk9yZ2FuaXphdGlvbiIywrgYLggBEB4iBXZhbHVlKiF1bmF1dGhvcml6ZWQgdG8gdmlldyBvcmdhbml6YXRpb24SewoEZmluZBI3LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5GaW5kQXBpUmVzb3VyY2VzUmVxdWVzdBo0LmFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEuT3JnYW5pemF0aW9uTGlzdCIE0LgYARJmChNmaW5kTXlPcmdhbml6YXRpb25zEhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5GjEuYWkuc3RpZ21lci50ZW5hbmN5Lm9yZ2FuaXphdGlvbi52MS5Pcmdhbml6YXRpb25zIgTQuBgBEowBChJnZXRCeUV4dGVybmFsT3JnSWQSPi5haS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxLk9yZ2FuaXphdGlvbkV4dGVybmFsTG9va3VwGjAuYWkuc3RpZ21lci50ZW5hbmN5Lm9yZ2FuaXphdGlvbi52MS5Pcmdhbml6YXRpb24iBNC4GAEaBKD/Kx5iBnByb3RvMw",[file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options,file_ai_stigmer_tenancy_organization_v1_api,file_ai_stigmer_tenancy_organization_v1_io,file_google_protobuf_empty]),OrganizationQueryController=serviceDesc(file_ai_stigmer_tenancy_organization_v1_query,0);var organizationSearchExtractor={kind:ApiResourceKind.organization,schema:OrganizationSchema,getSearchSummary(resource){return resource.spec?.description??""},toSearchResult(resource,score){let org=resource;return buildSearchResult({kind:ApiResourceKind.organization,metadata:org.metadata,summary:org.spec?.description??"",score,createdAt:org.status?.audit?.specAudit?.createdAt,updatedAt:org.status?.audit?.specAudit?.updatedAt})},getSearchIndexEntry(resource){let org=resource,metadata=org.metadata;if(metadata!==void 0)return{name:metadata.name,description:org.spec?.description??"",tags:metadata.tags.join(" "),org:metadata.org,visibility:ApiResourceVisibility[metadata.visibility]??"",createdAt:Number(org.status?.audit?.specAudit?.createdAt?.seconds??0n)}}};var ORGANIZATION_SLUG_RESERVED="ORGANIZATION_SLUG_RESERVED",CLAIMED_SLUG_KEY="organizationSlugClaim";function organizationSlugReservedMessage(slug){return`Organization slug '${slug}' belonged to an organization that was deleted, and a slug is never reused`}function refusalForHeldSlug(entry){return entry.retiredAt!==""?alreadyExistsWithReasonError(organizationSlugReservedMessage(entry.slug),{reason:ORGANIZATION_SLUG_RESERVED,metadata:{slug:entry.slug}}):alreadyExistsError("Organization",`slug '${entry.slug}'`)}function newClaimOrganizationSlugStep(store){return{name:"ClaimOrganizationSlug",async execute(ctx){let slug=metadataOf(ctx.newState)?.slug??"";if(slug==="")throw internalError(new Error("organization slug is empty"),"failed to claim the organization slug");let claim;try{claim=await store.organizationSlugs.claim(slug)}catch(error2){throw internalError(error2,"failed to claim the organization slug")}if(!claim.claimed)throw refusalForHeldSlug(claim.entry);ctx.set(CLAIMED_SLUG_KEY,claim.entry)}}}async function releaseSlugClaimAfterFailure(store,logger2,ctx){let entry=ctx.get(CLAIMED_SLUG_KEY);if(entry!==void 0){try{await store.getResource(ApiResourceKind.organization,entry.slug,OrganizationSchema);return}catch(error2){if(!(error2 instanceof ResourceNotFoundError)){logger2.error("organization create failed and its slug claim could not be checked; the slug stays claimed",{slug:entry.slug,error:error2 instanceof Error?error2.message:String(error2)});return}}try{await store.organizationSlugs.release(entry)}catch(error2){logger2.error("organization create failed and its slug claim could not be released; the slug stays claimed",{slug:entry.slug,error:error2 instanceof Error?error2.message:String(error2)})}}}function newRetireOrganizationSlugStep(store){return{name:"RetireOrganizationSlug",async execute(ctx){let id=ctx.get(EXISTING_RESOURCE_KEY)?.metadata?.id??"";if(id==="")throw internalError(new Error("organization delete reached RetireOrganizationSlug without its loaded row"),"failed to retire the organization slug");try{await store.organizationSlugs.retire(id)}catch(error2){throw internalError(error2,"failed to retire the organization slug")}}}}function newCheckOrgDuplicateStep(store){return{name:"CheckDuplicate",async execute(ctx){let metadata=metadataOf(ctx.newState);if(metadata===void 0)throw internalError(new Error("organization metadata is nil"),"duplicate check");if(metadata.slug==="")throw internalError(new Error("organization slug is empty"),"duplicate check");let entry;try{entry=await store.organizationSlugs.find(metadata.slug)}catch(error2){throw internalError(error2,"failed to check for duplicate organization")}if(entry!==void 0)throw refusalForHeldSlug(entry);try{await store.getResource(ctx.apiResourceKind,metadata.slug,OrganizationSchema)}catch(error2){if(error2 instanceof ResourceNotFoundError)return;throw internalError(error2,"failed to check for duplicate organization")}throw alreadyExistsError("Organization",`slug '${metadata.slug}'`)}}}function newCopySlugToIdStep(){return{name:"CopySlugToId",execute(ctx){let metadata=metadataOf(ctx.newState);if(metadata===void 0)throw internalError(new Error("organization metadata is nil"),"copy slug to id");if(metadata.slug==="")throw internalError(new Error("organization slug is empty"),"copy slug to id");metadata.id=metadata.slug}}}function newRevokeOrganizationPoliciesStep(grantPath){return{name:"RevokeOrganizationPolicies",async execute(ctx){let id=ctx.get(EXISTING_RESOURCE_KEY)?.metadata?.id??"";if(id==="")throw internalError(new Error("organization delete reached RevokeOrganizationPolicies without its loaded row"),"failed to remove the organization's access policies");try{await grantPath.cleanupResource(create2(ApiResourceRefSchema,{kind:ApiResourceKind[ApiResourceKind.organization],id}))}catch(error2){throw internalError(error2,"failed to remove the organization's access policies")}}}}function registerOrganizationServices(router,deps){router.service(OrganizationCommandController,{apply:(org,ctx)=>apply10(deps,org,ctx),create:(org,ctx)=>createOrganization(deps,org,ctx),update:(org,ctx)=>update13(deps,org,ctx),delete:(orgId,ctx)=>deleteOrganization(deps,orgId,ctx)});let externalLookup=deps.organizationDirectory?.lookupExternalOrganization?.bind(deps.organizationDirectory);router.service(OrganizationQueryController,{get:(orgId,ctx)=>get18(deps,orgId,ctx),find:(req,ctx)=>find(deps,req,ctx),findMyOrganizations:(_,ctx)=>findMyOrganizations(deps,ctx),...externalLookup===void 0?{}:{getByExternalOrgId:(lookup3,ctx)=>getByExternalOrgId(deps,externalLookup,lookup3,ctx)}})}function kindOf17(ctx){return ctx.values.get(apiResourceKindKey)}async function createOrganization(deps,org,ctx){let reqCtx=new RequestContext(OrganizationSchema,org,callerIdentityOf(ctx),kindOf17(ctx)),builder2=newPipeline("organization-create",deps.logger).addStep(newAuthorizeStep(OrganizationCommandController.method.create,deps.authorizer)).addStep(newResolveSlugStep()).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newCheckOrgDuplicateStep(deps.store)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newCopySlugToIdStep());for(let step of stepsForSlot(deps.gateSteps,"org-create:pre-side-effect-gate"))builder2.addStep(step);builder2.addStep(newClaimOrganizationSlugStep(deps.store)).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger));for(let step of stepsForSlot(deps.gateSteps,"org-create:post-persist"))builder2.addStep(step);let pipeline2=builder2.addStep(newIndexSearchStep(deps.store,organizationSearchExtractor,deps.logger)).build();try{await pipeline2.execute(reqCtx)}catch(error2){throw await releaseSlugClaimAfterFailure(deps.store,deps.logger,reqCtx),error2}return reqCtx.newState}async function update13(deps,org,ctx){let reqCtx=new RequestContext(OrganizationSchema,org,callerIdentityOf(ctx),kindOf17(ctx));return await newPipeline("organization-update",deps.logger).addStep(newAuthorizeStep(OrganizationCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingStep(deps.store)).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newPersistStep(deps.store)).addStep(newIndexSearchStep(deps.store,organizationSearchExtractor,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function apply10(deps,org,ctx){let reqCtx=new RequestContext(OrganizationSchema,org,callerIdentityOf(ctx),kindOf17(ctx));await newPipeline("organization-apply",deps.logger).addStep(newAuthorizeStep(OrganizationCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");return shouldCreate?createOrganization(deps,org,ctx):update13(deps,withResolvedApplyId(OrganizationSchema,org,reqCtx),ctx)}async function deleteOrganization(deps,orgId,ctx){let reqCtx=new RequestContext(OrganizationCommandController.method.delete.input,orgId,callerIdentityOf(ctx),kindOf17(ctx)),builder2=newPipeline("organization-delete",deps.logger).addStep(newAuthorizeStep(OrganizationCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newExtractResourceIdStep()).addStep(newLoadExistingForDeleteStep(deps.store,OrganizationSchema)).addStep(newRetireOrganizationSlugStep(deps.store));for(let step of stepsForSlot(deps.gateSteps,"org-delete:pre-delete"))builder2.addStep(step);await builder2.addStep(newRevokeOrganizationPoliciesStep(deps.grantPath)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDeleteSearchIndexStep(deps.store,deps.logger)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted organization not found in context"),"delete operation lost its loaded resource");return deleted}async function get18(deps,orgId,ctx){let reqCtx=new RequestContext(OrganizationQueryController.method.get.input,orgId,callerIdentityOf(ctx),kindOf17(ctx));return await newPipeline("organization-get",deps.logger).addStep(newAuthorizeStep(OrganizationQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,OrganizationSchema)).build().execute(reqCtx),reqCtx.get(TARGET_RESOURCE_KEY)}var FIND_RESULT_KEY="findResult";async function find(deps,req,ctx){if(deps.organizationDirectory?.refusesEnumeration===!0)throw new ConnectError("ai.stigmer.tenancy.organization.v1.OrganizationQueryController.find is not implemented",Code.Unimplemented);let reqCtx=new RequestContext(OrganizationQueryController.method.find.input,req,callerIdentityOf(ctx),kindOf17(ctx));return await newPipeline("organization-find",deps.logger).addStep(newAuthorizeStep(OrganizationQueryController.method.find,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newListAllOrganizationsStep(deps.store)).build().execute(reqCtx),reqCtx.get(FIND_RESULT_KEY)}function newListAllOrganizationsStep(store){return{name:"ListAllOrganizations",async execute(ctx){let data;try{data=await store.listResources(ctx.apiResourceKind)}catch(error2){throw internalError(error2,"failed to list organizations")}let orgs=[];for(let bytes of data)try{orgs.push(fromBinary2(OrganizationSchema,bytes))}catch{continue}let req=ctx.input,pageSize=req.pageSize,pageNumber=req.pageNumber;req.page!==void 0&&(req.page.size>0&&(pageSize=req.page.size),req.page.num>0&&(pageNumber=req.page.num)),pageSize<=0&&(pageSize=20),pageSize>100&&(pageSize=100),pageNumber<=0&&(pageNumber=1);let totalPages=Math.ceil(orgs.length/pageSize),start=(pageNumber-1)*pageSize,entries=start>=orgs.length?[]:orgs.slice(start,start+pageSize);ctx.set(FIND_RESULT_KEY,create2(OrganizationListSchema,{totalPages,entries}))}}}async function findMyOrganizations(deps,ctx){let directory=deps.organizationDirectory;if(directory!==void 0){let authorized=await directory.listMyOrganizationIds(callerIdentityOf(ctx));if(authorized!=="all"){let entries2=[];for(let id of authorized)try{entries2.push(await deps.store.getResource(ApiResourceKind.organization,id,OrganizationSchema))}catch(error2){if(error2 instanceof ResourceNotFoundError)continue;throw internalError(error2,"failed to list organizations")}return create2(OrganizationsSchema,{entries:entries2})}}let data;try{data=await deps.store.listResources(ApiResourceKind.organization)}catch(error2){throw internalError(error2,"failed to list organizations")}let entries=[];for(let bytes of data)try{entries.push(fromBinary2(OrganizationSchema,bytes))}catch{continue}return create2(OrganizationsSchema,{entries})}async function getByExternalOrgId(deps,lookup3,input,ctx){let reqCtx=new RequestContext(OrganizationQueryController.method.getByExternalOrgId.input,input,callerIdentityOf(ctx),kindOf17(ctx));if(await newPipeline("organization-get-by-external-org-id",deps.logger).addStep(newAuthorizeStep(OrganizationQueryController.method.getByExternalOrgId,deps.authorizer)).addStep(newValidateProtoStep()).build().execute(reqCtx),input.externalOrgId==="")throw invalidArgumentError("external_org_id is required");let found=await lookup3({org:input.identityProviderRef?.org??"",slug:input.identityProviderRef?.slug??""},input.externalOrgId);if(found.kind==="no-identity-provider")throw notFoundError("Organization",input.externalOrgId);await authorizeResolvedResource(deps.authorizer,reqCtx.callerIdentity,{permission:IamPermission.can_view,resourceKind:ApiResourceKind.identity_provider,resourceId:found.identityProviderId},EXTERNAL_LOOKUP_DENIED_MESSAGE);let orgId=found.organizationId;if(orgId===void 0)throw notFoundError("Organization",input.externalOrgId);try{return await deps.store.getResource(ApiResourceKind.organization,orgId,OrganizationSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("Organization",input.externalOrgId):internalError(error2,"failed to load organization")}}var EXTERNAL_LOOKUP_DENIED_MESSAGE="unauthorized to view identity provider";var file_ai_stigmer_agentic_mcpserver_v1_io=fileDesc("CihhaS9zdGlnbWVyL2FnZW50aWMvbWNwc2VydmVyL3YxL2lvLnByb3RvEh9haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxIiQKC01jcFNlcnZlcklkEhUKBXZhbHVlGAEgASgJQga6SAPIAQEiggIKDENvbm5lY3RJbnB1dBIdCg1tY3Bfc2VydmVyX2lkGAEgASgJQga6SAPIAQESUgoLcnVudGltZV9lbnYYAiADKAsyPS5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLkNvbm5lY3RJbnB1dC5SdW50aW1lRW52RW50cnkSFAoDb3JnGAMgASgJQge6SARyAhABGmkKD1J1bnRpbWVFbnZFbnRyeRILCgNrZXkYASABKAkSRQoFdmFsdWUYAiABKAsyNi5haS5zdGlnbWVyLmFnZW50aWMuZXhlY3V0aW9uY29udGV4dC52MS5FeGVjdXRpb25WYWx1ZToCOAEiUAoZSW5pdGlhdGVPQXV0aENvbm5lY3RJbnB1dBIdCg1tY3Bfc2VydmVyX2lkGAEgASgJQga6SAPIAQESFAoDb3JnGAIgASgJQge6SARyAhABIm0KGkluaXRpYXRlT0F1dGhDb25uZWN0T3V0cHV0EhkKEWF1dGhvcml6YXRpb25fdXJsGAEgASgJEg0KBXN0YXRlGAIgASgJEg4KBnNjb3BlcxgDIAMoCRIVCg1wcm92aWRlcl9uYW1lGAQgASgJIncKGUNvbXBsZXRlT0F1dGhDb25uZWN0SW5wdXQSHQoNbWNwX3NlcnZlcl9pZBgBIAEoCUIGukgDyAEBEiMKEmF1dGhvcml6YXRpb25fY29kZRgCIAEoCUIHukgEcgIQARIWCgVzdGF0ZRgDIAEoCUIHukgEcgIQASJkChpDb21wbGV0ZU9BdXRoQ29ubmVjdE91dHB1dBIRCgljb25uZWN0ZWQYASABKAgSFgoOdGFyZ2V0X2Vudl92YXIYAiABKAkSGwoTdG9rZW5fbGlmZXRpbWVfaGludBgDIAEoCSJNChhHZXRPQXV0aEdyYW50U3RhdHVzSW5wdXQSGwoLcmVzb3VyY2VfaWQYASABKAlCBrpIA8gBARIUCgNvcmcYAiABKAlCB7pIBHICEAEizwEKGUdldE9BdXRoR3JhbnRTdGF0dXNPdXRwdXQSEQoJY29ubmVjdGVkGAEgASgIEh8KF2FjY2Vzc190b2tlbl9leHBpcmVzX2F0GAIgASgDEhYKDnRhcmdldF9lbnZfdmFyGAMgASgJEhMKC2F1dGhfbWV0aG9kGAQgASgJElEKEWNvbm5lY3Rpb25faGVhbHRoGAUgASgOMjYuYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5PQXV0aENvbm5lY3Rpb25IZWFsdGgiSQoURGlzY29ubmVjdE9BdXRoSW5wdXQSGwoLcmVzb3VyY2VfaWQYASABKAlCBrpIA8gBARIUCgNvcmcYAiABKAlCB7pIBHICEAEiLQoVRGlzY29ubmVjdE9BdXRoT3V0cHV0EhQKDGRpc2Nvbm5lY3RlZBgBIAEoCCKEAQoTU2V0T3JnT0F1dGhBcHBJbnB1dBIbCgtyZXNvdXJjZV9pZBgBIAEoCUIGukgDyAEBEhQKA29yZxgCIAEoCUIHukgEcgIQARIaCgljbGllbnRfaWQYAyABKAlCB7pIBHICEAESHgoNY2xpZW50X3NlY3JldBgEIAEoCUIHukgEcgIQASIsChRTZXRPcmdPQXV0aEFwcE91dHB1dBIUCgxvYXV0aF9hcHBfaWQYASABKAkiSAoTR2V0T3JnT0F1dGhBcHBJbnB1dBIbCgtyZXNvdXJjZV9pZBgBIAEoCUIGukgDyAEBEhQKA29yZxgCIAEoCUIHukgEcgIQASJVChRHZXRPcmdPQXV0aEFwcE91dHB1dBIUCgxoYXNfb3ZlcnJpZGUYASABKAgSFAoMb2F1dGhfYXBwX2lkGAIgASgJEhEKCWNsaWVudF9pZBgDIAEoCSJLChZEZWxldGVPcmdPQXV0aEFwcElucHV0EhsKC3Jlc291cmNlX2lkGAEgASgJQga6SAPIAQESFAoDb3JnGAIgASgJQge6SARyAhABIioKF0RlbGV0ZU9yZ09BdXRoQXBwT3V0cHV0Eg8KB2RlbGV0ZWQYASABKAgq7QEKFU9BdXRoQ29ubmVjdGlvbkhlYWx0aBInCiNPQVVUSF9DT05ORUNUSU9OX0hFQUxUSF9VTlNQRUNJRklFRBAAEiMKH09BVVRIX0NPTk5FQ1RJT05fSEVBTFRIX0hFQUxUSFkQARIpCiVPQVVUSF9DT05ORUNUSU9OX0hFQUxUSF9UT0tFTl9FWFBJUkVEEAISNQoxT0FVVEhfQ09OTkVDVElPTl9IRUFMVEhfVE9LRU5fRVhQSVJFRF9SRUZSRVNIQUJMRRADEiQKIE9BVVRIX0NPTk5FQ1RJT05fSEVBTFRIX05PX0dSQU5UEARiBnByb3RvMw",[file_ai_stigmer_agentic_executioncontext_v1_spec,file_buf_validate_validate]);var InitiateOAuthConnectOutputSchema=messageDesc2(file_ai_stigmer_agentic_mcpserver_v1_io,3);var CompleteOAuthConnectOutputSchema=messageDesc2(file_ai_stigmer_agentic_mcpserver_v1_io,5);var GetOAuthGrantStatusOutputSchema=messageDesc2(file_ai_stigmer_agentic_mcpserver_v1_io,7);var DisconnectOAuthOutputSchema=messageDesc2(file_ai_stigmer_agentic_mcpserver_v1_io,9);var OAuthConnectionHealth;(function(OAuthConnectionHealth2){OAuthConnectionHealth2[OAuthConnectionHealth2.OAUTH_CONNECTION_HEALTH_UNSPECIFIED=0]="OAUTH_CONNECTION_HEALTH_UNSPECIFIED",OAuthConnectionHealth2[OAuthConnectionHealth2.OAUTH_CONNECTION_HEALTH_HEALTHY=1]="OAUTH_CONNECTION_HEALTH_HEALTHY",OAuthConnectionHealth2[OAuthConnectionHealth2.OAUTH_CONNECTION_HEALTH_TOKEN_EXPIRED=2]="OAUTH_CONNECTION_HEALTH_TOKEN_EXPIRED",OAuthConnectionHealth2[OAuthConnectionHealth2.OAUTH_CONNECTION_HEALTH_TOKEN_EXPIRED_REFRESHABLE=3]="OAUTH_CONNECTION_HEALTH_TOKEN_EXPIRED_REFRESHABLE",OAuthConnectionHealth2[OAuthConnectionHealth2.OAUTH_CONNECTION_HEALTH_NO_GRANT=4]="OAUTH_CONNECTION_HEALTH_NO_GRANT"})(OAuthConnectionHealth||(OAuthConnectionHealth={}));var file_ai_stigmer_agentic_mcpserver_v1_command=fileDesc("Ci1haS9zdGlnbWVyL2FnZW50aWMvbWNwc2VydmVyL3YxL2NvbW1hbmQucHJvdG8SH2FpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEynREKGk1jcFNlcnZlckNvbW1hbmRDb250cm9sbGVyEl8KBWFwcGx5EiouYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5NY3BTZXJ2ZXIaKi5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLk1jcFNlcnZlchKwAQoGY3JlYXRlEiouYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5NY3BTZXJ2ZXIaKi5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLk1jcFNlcnZlciJOwrgYSggrEB4iDG1ldGFkYXRhLm9yZyo2dW5hdXRob3JpemVkIHRvIGNyZWF0ZSBtY3Agc2VydmVyIGluIHRoaXMgb3JnYW5pemF0aW9uEpoBCgZ1cGRhdGUSKi5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLk1jcFNlcnZlchoqLmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuTWNwU2VydmVyIjjCuBg0CAIQLCILbWV0YWRhdGEuaWQqIXVuYXV0aG9yaXplZCB0byB1cGRhdGUgbWNwIHNlcnZlchKmAQoGZGVsZXRlEjYuYWkuc3RpZ21lci5jb21tb25zLmFwaXJlc291cmNlLkFwaVJlc291cmNlRGVsZXRlSW5wdXQaKi5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLk1jcFNlcnZlciI4wrgYNAgDECwiC3Jlc291cmNlX2lkKiF1bmF1dGhvcml6ZWQgdG8gZGVsZXRlIG1jcCBzZXJ2ZXISugEKEHVwZGF0ZVZpc2liaWxpdHkSNS5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuVXBkYXRlVmlzaWJpbGl0eUlucHV0GiouYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5NY3BTZXJ2ZXIiQ8K4GD8IAhAsIgtyZXNvdXJjZV9pZCosdW5hdXRob3JpemVkIHRvIHVwZGF0ZSBtY3Agc2VydmVyIHZpc2liaWxpdHkSpAEKB2Nvbm5lY3QSLS5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLkNvbm5lY3RJbnB1dBoqLmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuTWNwU2VydmVyIj7CuBg6CBYQLCINbWNwX3NlcnZlcl9pZColdW5hdXRob3JpemVkIHRvIGNvbm5lY3QgdG8gbWNwIHNlcnZlchKpAQoMc3RhcnRDb25uZWN0Ei0uYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5Db25uZWN0SW5wdXQaKi5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLk1jcFNlcnZlciI+wrgYOggWECwiDW1jcF9zZXJ2ZXJfaWQqJXVuYXV0aG9yaXplZCB0byBjb25uZWN0IHRvIG1jcCBzZXJ2ZXIS3wEKFGluaXRpYXRlT0F1dGhDb25uZWN0EjouYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5Jbml0aWF0ZU9BdXRoQ29ubmVjdElucHV0GjsuYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5Jbml0aWF0ZU9BdXRoQ29ubmVjdE91dHB1dCJOwrgYSggWECwiDW1jcF9zZXJ2ZXJfaWQqNXVuYXV0aG9yaXplZCB0byBpbml0aWF0ZSBvYXV0aCBjb25uZWN0IGZvciBtY3Agc2VydmVyEt8BChRjb21wbGV0ZU9BdXRoQ29ubmVjdBI6LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuQ29tcGxldGVPQXV0aENvbm5lY3RJbnB1dBo7LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuQ29tcGxldGVPQXV0aENvbm5lY3RPdXRwdXQiTsK4GEoIFhAsIg1tY3Bfc2VydmVyX2lkKjV1bmF1dGhvcml6ZWQgdG8gY29tcGxldGUgb2F1dGggY29ubmVjdCBmb3IgbWNwIHNlcnZlchLIAQoPZGlzY29ubmVjdE9BdXRoEjUuYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5EaXNjb25uZWN0T0F1dGhJbnB1dBo2LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuRGlzY29ubmVjdE9BdXRoT3V0cHV0IkbCuBhCCBYQLCILcmVzb3VyY2VfaWQqL3VuYXV0aG9yaXplZCB0byBkaXNjb25uZWN0IG9hdXRoIGZvciBtY3Agc2VydmVyErgBCg5zZXRPcmdPQXV0aEFwcBI0LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuU2V0T3JnT0F1dGhBcHBJbnB1dBo1LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuU2V0T3JnT0F1dGhBcHBPdXRwdXQiOcK4GDUIFxAeIgNvcmcqKnVuYXV0aG9yaXplZCB0byBzZXQgb3JnIG9hdXRoIGFwcCBvdmVycmlkZRLEAQoRZGVsZXRlT3JnT0F1dGhBcHASNy5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLkRlbGV0ZU9yZ09BdXRoQXBwSW5wdXQaOC5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLkRlbGV0ZU9yZ09BdXRoQXBwT3V0cHV0IjzCuBg4CBcQHiIDb3JnKi11bmF1dGhvcml6ZWQgdG8gZGVsZXRlIG9yZyBvYXV0aCBhcHAgb3ZlcnJpZGUaBKD/KyxiBnByb3RvMw",[file_ai_stigmer_agentic_mcpserver_v1_api,file_ai_stigmer_agentic_mcpserver_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),McpServerCommandController=serviceDesc(file_ai_stigmer_agentic_mcpserver_v1_command,0);var file_ai_stigmer_agentic_mcpserver_v1_query=fileDesc("CithaS9zdGlnbWVyL2FnZW50aWMvbWNwc2VydmVyL3YxL3F1ZXJ5LnByb3RvEh9haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxMssFChhNY3BTZXJ2ZXJRdWVyeUNvbnRyb2xsZXISkgEKA2dldBItLmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZUlkGiouYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5NY3BTZXJ2ZXIiMMK4GCwIARAsIgV2YWx1ZSofdW5hdXRob3JpemVkIHRvIHZpZXcgbWNwIHNlcnZlchJ4Cg5nZXRCeVJlZmVyZW5jZRI0LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVJlZmVyZW5jZRoqLmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuTWNwU2VydmVyIgTQuBgBEtUBChNnZXRPQXV0aEdyYW50U3RhdHVzEjkuYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5HZXRPQXV0aEdyYW50U3RhdHVzSW5wdXQaOi5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLkdldE9BdXRoR3JhbnRTdGF0dXNPdXRwdXQiR8K4GEMIARAsIgtyZXNvdXJjZV9pZCowdW5hdXRob3JpemVkIHRvIHZpZXcgb2F1dGggc3RhdHVzIGZvciBtY3Agc2VydmVyEsEBCg5nZXRPcmdPQXV0aEFwcBI0LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuR2V0T3JnT0F1dGhBcHBJbnB1dBo1LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuR2V0T3JnT0F1dGhBcHBPdXRwdXQiQsK4GD4IARAsIgtyZXNvdXJjZV9pZCordW5hdXRob3JpemVkIHRvIHZpZXcgb3JnIG9hdXRoIGFwcCBvdmVycmlkZRoEoP8rLGIGcHJvdG8z",[file_ai_stigmer_agentic_mcpserver_v1_api,file_ai_stigmer_agentic_mcpserver_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),McpServerQueryController=serviceDesc(file_ai_stigmer_agentic_mcpserver_v1_query,0);async function completeOAuthConnect(deps,input,identity2){let mcpServerId=input.mcpServerId;if(mcpServerId==="")throw invalidArgumentError("mcp_server_id is required");let stateParam=input.state;if(stateParam==="")throw invalidArgumentError("state is required");let code=input.authorizationCode;if(code==="")throw invalidArgumentError("authorization_code is required");let pendingState;try{pendingState=await deps.pendingOAuthStates.getAndDelete(stateParam)}catch(error2){throw internalError(error2,"failed to load pending OAuth state")}if(pendingState===void 0)throw failedPreconditionError("no pending OAuth state found for the given state parameter (expired or already used)");if(pendingState.mcpServerId!==mcpServerId)throw failedPreconditionError("state parameter does not match the requested mcp_server_id");await authorizeDirect(McpServerCommandController.method.completeOAuthConnect,deps.authorizer,identity2,input,{resourceId:pendingState.mcpServerId});try{pendingState=await unsealPendingOAuthState(deps.secretService,pendingState)}catch(error2){throw deps.logger.error("Failed to decrypt pending OAuth state secrets",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to decrypt OAuth handshake secrets \u2014 please retry the connect flow")}let tokenResponse;try{tokenResponse=await exchangeCode(pendingState.tokenEndpoint,code,pendingState.redirectUri,pendingState.codeVerifier,pendingState.clientId,pendingState.clientSecret,pendingState.tokenAuthMethod,deps.outboundFetch)}catch(error2){throw unavailableError(`token exchange failed: ${error2 instanceof Error?error2.message:String(error2)}`)}let mcpServer;try{mcpServer=await deps.store.getResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("mcp_server",mcpServerId):internalError(error2,"failed to load mcp server \u2014 please retry the connect flow")}let org=pendingState.org;org===""&&(org=mcpServer.metadata?.org??"");let managedEnvId=await resolveOrCreateManagedEnvironment(deps,pendingState.identityAccountId,mcpServerId,org,mcpServer.metadata?.name??"",identity2),tokenVars={[pendingState.targetEnvVar]:create2(EnvironmentValueSchema,{value:tokenResponse.accessToken,isSecret:!0})},refreshTokenEnvVar=`${pendingState.targetEnvVar}_REFRESH_TOKEN`;tokenResponse.refreshToken!==""&&(tokenVars[refreshTokenEnvVar]=create2(EnvironmentValueSchema,{value:tokenResponse.refreshToken,isSecret:!0}));try{await deps.managedEnv.updateSecrets(managedEnvId,tokenVars)}catch(error2){throw internalError(error2,"failed to store OAuth tokens in managed environment")}let expiresAt=0;tokenResponse.expiresIn>0&&(expiresAt=Math.floor(Date.now()/1e3)+tokenResponse.expiresIn);try{await deps.oauthGrants.upsert({identityAccountId:pendingState.identityAccountId,resourceId:mcpServerId,resourceKind:"mcp_server",orgId:org,accessTokenExpiresAt:expiresAt,clientId:pendingState.clientId,authMethod:pendingState.authMethod,tokenEndpoint:pendingState.tokenEndpoint,accessTokenEnvVar:pendingState.targetEnvVar,refreshTokenEnvVar,environmentId:managedEnvId,createdAt:0,updatedAt:0})}catch(error2){throw internalError(error2,"failed to create OAuth grant record")}let auth=mcpServer.spec?.auth;return deps.logger.info("OAuth Connect completed: tokens stored in managed environment",{mcp_server_id:mcpServerId,auth_method:pendingState.authMethod,target_env_var:pendingState.targetEnvVar,managed_env_id:managedEnvId,expires_at:expiresAt,has_refresh_token:tokenResponse.refreshToken!==""}),create2(CompleteOAuthConnectOutputSchema,{connected:!0,targetEnvVar:pendingState.targetEnvVar,tokenLifetimeHint:auth?.tokenLifetimeHint??""})}async function unsealPendingOAuthState(secretService,state2){let verifier;try{verifier=await secretService.decrypt(state2.codeVerifier)}catch(error2){throw new Error(`failed to decrypt code_verifier: ${error2 instanceof Error?error2.message:String(error2)}`)}let secret;try{secret=await secretService.decrypt(state2.clientSecret)}catch(error2){throw new Error(`failed to decrypt client_secret: ${error2 instanceof Error?error2.message:String(error2)}`)}return{...state2,codeVerifier:verifier,clientSecret:secret}}async function resolveOrCreateManagedEnvironment(deps,identityAccountId,mcpServerId,org,mcpServerName,caller){let existingGrant;try{existingGrant=await deps.oauthGrants.find(identityAccountId,mcpServerId,org)}catch(error2){deps.logger.warn("Failed to look up existing OAuth grant (non-fatal, will create new managed env)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)})}if(existingGrant!==void 0&&existingGrant.environmentId!=="")return deps.logger.info("Reusing existing managed environment for OAuth re-connect",{mcp_server_id:mcpServerId,environment_id:existingGrant.environmentId}),existingGrant.environmentId;let envName=`OAuth: ${mcpServerName}`;try{return await deps.managedEnv.createManagedEnvironment(envName,org,caller)}catch(error2){throw internalError(error2,"failed to create managed environment for OAuth tokens")}}function convertToDiscoveredCapabilities(output){let capabilities=create2(DiscoveredCapabilitiesSchema,{lastDiscoveredAt:timestampNow()});for(let t of output.tools??[]){let tool=create2(DiscoveredToolSchema,{name:t.name??"",description:t.description??""});t.input_schema!==void 0&&(tool.inputSchema=t.input_schema),capabilities.tools.push(tool)}for(let rt of output.resource_templates??[])capabilities.resourceTemplates.push(create2(DiscoveredResourceTemplateSchema,{uriTemplate:rt.uri_template??"",name:rt.name??"",description:rt.description??"",mimeType:rt.mime_type??""}));return capabilities}function convertToToolApprovals(output){let approvals=[];for(let a5 of output.tool_approvals??[])a5.requires_approval!==!0||(a5.tool_name??"")===""||approvals.push(create2(ToolApprovalPolicySchema,{toolName:a5.tool_name,message:a5.message??"",fromDestructiveHint:a5.from_destructive_hint??!1}));return approvals}function setToolApprovalsFromConnect(status,output){let approvals=convertToToolApprovals(output);return approvals.length>0&&(status.toolApprovals=approvals),approvals.length}function settleConnectStatus(mcpStatus,workflowId,failure){let cs=mcpStatus.connectStatus;if(cs===void 0&&(cs=create2(ConnectStatusSchema),mcpStatus.connectStatus=cs),cs.workflowId=workflowId,cs.finishedAt=timestampNow(),cs.warning="",failure===void 0){cs.phase=ConnectPhase.succeeded,cs.failureCode="",cs.failureMessage="";return}cs.phase=ConnectPhase.failed,cs.failureCode=grpcCodeName(failure.code),cs.failureMessage=failure.rawMessage}async function persistConnectResult(store,mcpServerId,workflowId,output){let toolApprovalCount=0;return{persisted:await store.updateResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema,mcpServer=>{mcpServer.status===void 0&&(mcpServer.status=create2(McpServerStatusSchema)),mcpServer.status.discoveredCapabilities=convertToDiscoveredCapabilities(output),toolApprovalCount=setToolApprovalsFromConnect(mcpServer.status,output),settleConnectStatus(mcpServer.status,workflowId,void 0)}),toolApprovalCount}}async function persistConnectStarting(store,mcpServerId,workflowId,warning2){return store.updateResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema,mcpServer=>{mcpServer.status===void 0&&(mcpServer.status=create2(McpServerStatusSchema)),mcpServer.status.connectStatus=create2(ConnectStatusSchema,{phase:ConnectPhase.connecting,workflowId,startedAt:timestampNow(),warning:warning2})})}async function persistConnectFailure(store,logger2,mcpServerId,failure){try{await store.updateResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema,mcpServer=>{mcpServer.status===void 0&&(mcpServer.status=create2(McpServerStatusSchema)),settleConnectStatus(mcpServer.status,mcpServer.status.connectStatus?.workflowId??"",failure)})}catch(error2){if(error2 instanceof ResourceNotFoundError){logger2.info("Skipping connect failure persistence: MCP server deleted before connect settled",{mcp_server_id:mcpServerId});return}logger2.warn("Failed to record connect failure on connect_status (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)})}}var CONNECT_TIMEOUT={ms:42e4,goLabel:"7m0s"},ASYNC_CONNECT_TIMEOUT={ms:3600*1e3,goLabel:"1h0m0s"},BEST_EFFORT_CONNECT_GET_BUFFER_MS=15e3;async function connect(deps,input,identity2){let mcpServerId=input.mcpServerId;if(mcpServerId==="")throw invalidArgumentError("mcp_server_id is required");if(input.org==="")throw invalidArgumentError("org is required for connect");let mcpServer;try{mcpServer=await deps.store.getResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("mcp_server",mcpServerId):internalError(error2,"failed to load mcp server")}await authorizeDirect(McpServerCommandController.method.connect,deps.authorizer,identity2,input);let engineState=deps.engineState();if(!engineState.connected)throw failedPreconditionError("connect is not available: Temporal not configured");let prepared=await prepareConnect(deps,mcpServer,input,identity2);try{let run;try{run=await engineState.engine.startOrAttachConnect(mcpServerId,prepared.workflowInput,CONNECT_TIMEOUT.ms)}catch(error2){throw deps.logger.error("Failed to start MCP connect workflow",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to start connect workflow")}if(!run.attached)try{await persistConnectStarting(deps.store,mcpServerId,run.workflowId,"")}catch(error2){deps.logger.warn("Failed to record CONNECTING on connect_status (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)})}let outcome=await run.result(CONNECT_TIMEOUT.ms+BEST_EFFORT_CONNECT_GET_BUFFER_MS);if(!outcome.ok){let failure=mapConnectFailure(deps.logger,mcpServer,run.workflowId,outcome.failure,CONNECT_TIMEOUT);throw await persistConnectFailure(deps.store,deps.logger,mcpServerId,failure),failure}let persisted,toolApprovalCount;try{({persisted,toolApprovalCount}=await persistConnectResult(deps.store,mcpServerId,run.workflowId,outcome.output))}catch(error2){throw internalError(error2,"failed to save mcp server after connect")}return deps.logger.info("MCP server connect completed and stored",{mcp_server_id:mcpServerId,tools:persisted.status?.discoveredCapabilities?.tools.length??0,resource_templates:persisted.status?.discoveredCapabilities?.resourceTemplates.length??0,tool_approvals:toolApprovalCount}),persisted}finally{prepared.ecResourceId!==""&&await deleteConnectExecutionContext(deps,prepared.ecResourceId,prepared.executionId)}}async function prepareConnect(deps,mcpServer,input,identity2){let mcpServerId=mcpServer.metadata?.id??"",callerOrg=input.org;Object.keys(input.runtimeEnv).length===0&&await refreshOAuthTokenIfNeeded(deps,mcpServer,callerOrg);let executionId=newConnectExecutionId(mcpServerId),ecResourceId=await createConnectExecutionContext(deps,mcpServer,executionId,callerOrg,input.runtimeEnv,identity2),workflowInput={mcp_server_id:mcpServerId,...ecResourceId!==""?{execution_context_id:executionId}:{}};if(ecResourceId!==""&&deps.runnerAuth.isEnabled(TOKEN_TYPE_EXECUTION_SCOPED))try{let minted=deps.runnerAuth.mint(TOKEN_TYPE_EXECUTION_SCOPED,executionId,0);return{workflowInput:{...workflowInput,execution_context_token:minted.token},ecResourceId,executionId}}catch(error2){deps.logger.warn("Failed to mint connect EC token \u2014 discovery will read redacted credentials",{execution_id:executionId,error:error2 instanceof Error?error2.message:String(error2)})}return{workflowInput,ecResourceId,executionId}}async function createConnectExecutionContext(deps,mcpServer,executionId,callerOrg,runtimeEnv,caller){let ecData;if(Object.keys(runtimeEnv).length>0)ecData=runtimeEnv,deps.logger.info("Using runtime_env for connect ExecutionContext (one-time use)",{execution_id:executionId,runtime_env_count:Object.keys(runtimeEnv).length});else{let envDecls=mcpServer.spec?.env??{};if(Object.keys(envDecls).length===0)return deps.logger.debug("MCP server has no env declarations \u2014 skipping ExecutionContext creation",{execution_id:executionId}),"";let mcpServerId=mcpServer.metadata?.id??"",{oauthVars,remainingDecls}=await resolveOAuthVarsFromManagedEnv(deps,mcpServerId,callerOrg,envDecls),personalVars={};Object.keys(remainingDecls).length>0&&(personalVars=await resolveFromPersonalEnvironment(deps,callerOrg,remainingDecls)),ecData={...personalVars,...oauthVars},deps.logger.info("Resolved env vars for connect ExecutionContext",{execution_id:executionId,oauth_count:Object.keys(oauthVars).length,personal_count:Object.keys(personalVars).length})}if(Object.keys(ecData).length===0)return"";let created;try{created=await deps.executionContext.create(create2(ExecutionContextSchema,{apiVersion:"agentic.stigmer.ai/v1",kind:"ExecutionContext",metadata:{name:`exec-ctx-${executionId}`,org:callerOrg},spec:{executionId,data:ecData}}),caller)}catch(error2){throw internalError(error2,"failed to create connect ExecutionContext")}let resourceId=created.metadata?.id??"";return deps.logger.info("Created ephemeral ExecutionContext for MCP connect",{execution_context_id:resourceId,execution_id:executionId,data_entries:Object.keys(ecData).length}),resourceId}async function resolveOAuthVarsFromManagedEnv(deps,mcpServerId,org,envDecls){let grant;try{grant=await deps.oauthGrants.find("",mcpServerId,org)}catch{return{oauthVars:{},remainingDecls:envDecls}}if(grant===void 0||grant.environmentId==="")return{oauthVars:{},remainingDecls:envDecls};let oauthKey=grant.accessTokenEnvVar;if(!(oauthKey in envDecls))return{oauthVars:{},remainingDecls:envDecls};let tokenValue="";try{tokenValue=await deps.managedEnv.readSecretValue(grant.environmentId,oauthKey)}catch(error2){return deps.logger.warn("Failed to read OAuth token from managed environment \u2014 falling back to personal env",{mcp_server_id:mcpServerId,oauth_key:oauthKey,managed_env_id:grant.environmentId,error:error2 instanceof Error?error2.message:String(error2)}),{oauthVars:{},remainingDecls:envDecls}}if(tokenValue==="")return deps.logger.warn("Failed to read OAuth token from managed environment \u2014 falling back to personal env",{mcp_server_id:mcpServerId,oauth_key:oauthKey,managed_env_id:grant.environmentId}),{oauthVars:{},remainingDecls:envDecls};let remainingDecls={};for(let[k5,v]of Object.entries(envDecls))k5!==oauthKey&&(remainingDecls[k5]=v);return deps.logger.debug("Resolved OAuth token from managed environment",{mcp_server_id:mcpServerId,oauth_key:oauthKey,managed_env_id:grant.environmentId}),{oauthVars:{[oauthKey]:create2(ExecutionValueSchema,{value:tokenValue,isSecret:!0})},remainingDecls}}async function resolveFromPersonalEnvironment(deps,org,envDecls){let resolution=await resolveDeclaredFromPersonalEnvironment(deps.environmentReader,deps.logger,org,envDecls);if(resolution.kind==="no-personal-environment"){let requiredKeys=Object.entries(envDecls).filter(([,decl])=>!decl.optional).map(([key])=>key);if(requiredKeys.length===0)return{};throw failedPreconditionError(`personal environment not found for org '${org}'; save required credentials first: [${requiredKeys.join(" ")}]`)}if(resolution.missing.length>0)throw failedPreconditionError(`missing required credentials in personal environment: [${resolution.missing.join(" ")}]`);return{...resolution.values}}async function deleteConnectExecutionContext(deps,resourceId,executionId){try{await deps.executionContext.delete({resourceId})}catch(error2){deps.logger.warn("Failed to delete connect ExecutionContext (non-fatal)",{resource_id:resourceId,execution_id:executionId,error:error2 instanceof Error?error2.message:String(error2)});return}deps.logger.debug("Deleted ephemeral connect ExecutionContext",{resource_id:resourceId,execution_id:executionId})}function mapConnectFailure(logger2,mcpServer,workflowId,failure,budget){let mcpServerId=mcpServer.metadata?.id??"";switch(logger2.error("MCP connect workflow failed",{workflow_id:workflowId,mcp_server_id:mcpServerId,failure_kind:failure.kind}),failure.kind){case"application":return failedPreconditionError(buildConnectFailureMessage(mcpServer,failure.message));case"timeout":return new ConnectError(`connect did not complete within the ${budget.goLabel} budget for MCP server '${mcpServerId}' \u2014 if this repeats, check that your runner is running and healthy`,Code.DeadlineExceeded);case"service-not-found":return unavailableError(`connect service temporarily unavailable for MCP server '${mcpServerId}'`);case"other":return new ConnectError(buildConnectFailureMessage(mcpServer,failure.message),Code.Internal);default:{let exhaustive=failure;throw new Error(`unhandled connect failure ${String(exhaustive)}`)}}}function buildConnectFailureMessage(mcpServer,cause){let name=mcpServer.metadata?.name??"";if(cause.includes("requires OAuth"))return cause;if(mcpServer.spec?.serverType.case==="stdio"){let slug=mcpServer.metadata?.slug??"";return`connect failed for MCP server '${name}': ${cause}. This is a stdio server launched by your local runner \u2014 verify the command is installed and its arguments and environment variables are correct. Preview discovery locally with: stigmer connect mcp-server ${slug} --dry-run`}return`connect failed for MCP server '${name}': ${cause}. Check that the server URL is reachable and your credentials are valid.`}async function refreshOAuthTokenIfNeeded(deps,mcpServer,callerOrg){if(mcpServer.spec?.auth===void 0)return;let mcpServerId=mcpServer.metadata?.id??"",grant;try{grant=await deps.oauthGrants.find("",mcpServerId,callerOrg)}catch(error2){deps.logger.warn("Failed to load OAuth grant for pre-flight check (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)});return}if(grant===void 0)return;if(grant.environmentId===""){deps.logger.warn("OAuth grant has no managed environment ID \u2014 user must re-authenticate via OAuth Connect",{mcp_server_id:mcpServerId});return}let refreshTokenValue;try{refreshTokenValue=await deps.managedEnv.readSecretValue(grant.environmentId,grant.refreshTokenEnvVar)}catch(error2){deps.logger.debug("No refresh token found in managed environment (may not be OAuth-connected)",{mcp_server_id:mcpServerId,refresh_token_var:grant.refreshTokenEnvVar,managed_env_id:grant.environmentId,error:error2 instanceof Error?error2.message:String(error2)});return}let clientSecret="",tokenAuthMethod="";if(grant.authMethod==="vendor_oauth")try{({clientSecret,tokenAuthMethod}=await loadOAuthAppClientCredentials(deps,mcpServer))}catch(error2){deps.logger.warn("Failed to load OAuthApp client secret for refresh",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)})}let result;try{result=await refreshTokenIfExpired(grant,refreshTokenValue,clientSecret,tokenAuthMethod,deps.logger,deps.outboundFetch)}catch(error2){throw failedPreconditionError(error2 instanceof Error?error2.message:String(error2))}if(!result.refreshed)return;let tokenVars={[grant.accessTokenEnvVar]:create2(EnvironmentValueSchema,{value:result.newAccessToken,isSecret:!0})};result.newRefreshToken!==refreshTokenValue&&(tokenVars[grant.refreshTokenEnvVar]=create2(EnvironmentValueSchema,{value:result.newRefreshToken,isSecret:!0}));try{await deps.managedEnv.updateSecrets(grant.environmentId,tokenVars)}catch(error2){throw internalError(error2,"failed to update refreshed tokens in managed environment")}try{await deps.oauthGrants.upsert({...grant,accessTokenExpiresAt:result.newExpiresAt})}catch(error2){deps.logger.warn("Failed to update OAuth grant after refresh (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)})}}async function loadOAuthAppClientCredentials(deps,mcpServer){let ref=mcpServer.spec?.auth?.oauthAppRef;if(ref===void 0||ref.slug==="")return{clientSecret:"",tokenAuthMethod:""};let app;try{app=await resolveOAuthAppRef(deps.store,ref,deps.logger)}catch(error2){throw new Error(`failed to list oauth apps: ${error2 instanceof Error?error2.message:String(error2)}`)}if(app===void 0)throw new Error(`OAuthApp '${ref.slug}' not found`);let tokenAuthMethod=tokenAuthMethodFromSpec(app.spec?.tokenEndpointAuthMethod??TokenEndpointAuthMethod.UNSPECIFIED),secret=app.spec?.clientSecret??"";return deps.secretService.isEncrypted(secret)&&(secret=await deps.secretService.decrypt(secret)),{clientSecret:secret,tokenAuthMethod}}function tokenAuthMethodFromSpec(method){return method===TokenEndpointAuthMethod.CLIENT_SECRET_POST?TOKEN_AUTH_METHOD_POST:TOKEN_AUTH_METHOD_BASIC}async function startBestEffortConnect(deps,mcpServer){let engineState=deps.engineState();if(!engineState.connected)return;let envKeys=Object.keys(mcpServer.spec?.env??{}).length;if(envKeys>0){deps.logger.debug("Skipping best-effort auto-connect: MCP server has env declarations (requires manual connect)",{mcp_server_id:mcpServer.metadata?.id??"",env_keys:envKeys});return}let mcpServerId=mcpServer.metadata?.id??"",run;try{run=await engineState.engine.startOrAttachConnect(mcpServerId,{mcp_server_id:mcpServerId},CONNECT_TIMEOUT.ms)}catch(error2){deps.logger.warn("Failed to start best-effort connect workflow (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)});return}if(!run.attached)try{await persistConnectStarting(deps.store,mcpServerId,run.workflowId,"")}catch(error2){deps.logger.warn("Failed to record CONNECTING for best-effort connect (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)})}let outcome=await run.result(CONNECT_TIMEOUT.ms+BEST_EFFORT_CONNECT_GET_BUFFER_MS);if(!outcome.ok){let failure=mapConnectFailure(deps.logger,mcpServer,run.workflowId,outcome.failure,CONNECT_TIMEOUT);await persistConnectFailure(deps.store,deps.logger,mcpServerId,failure);return}let persisted,toolApprovalCount;try{({persisted,toolApprovalCount}=await persistConnectResult(deps.store,mcpServerId,run.workflowId,outcome.output))}catch(error2){if(error2 instanceof ResourceNotFoundError){deps.logger.info("Skipping best-effort connect persistence: MCP server deleted before connect completed",{mcp_server_id:mcpServerId});return}deps.logger.warn("Failed to persist best-effort connect result (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)});return}deps.logger.info("Best-effort auto-connect completed and stored",{workflow_id:run.workflowId,mcp_server_id:mcpServerId,tools:persisted.status?.discoveredCapabilities?.tools.length??0,resource_templates:persisted.status?.discoveredCapabilities?.resourceTemplates.length??0,tool_approvals:toolApprovalCount})}async function disconnectOAuth(deps,input,identity2){let resourceId=input.resourceId;if(resourceId==="")throw invalidArgumentError("resource_id is required");let org=input.org;if(org==="")throw invalidArgumentError("org is required");await authorizeDirect(McpServerCommandController.method.disconnectOAuth,deps.authorizer,identity2,input);let grant;try{grant=await deps.oauthGrants.find("",resourceId,org)}catch(error2){throw internalError(error2,"failed to look up OAuth grant")}if(grant===void 0)return deps.logger.debug("No OAuth grant to disconnect",{resource_id:resourceId,org}),create2(DisconnectOAuthOutputSchema,{disconnected:!1});let envId=grant.environmentId;if(envId!=="")try{await deps.managedEnv.deleteManagedEnvironment(envId)}catch(error2){deps.logger.warn("Failed to delete managed environment \u2014 may already be deleted",{resource_id:resourceId,environment_id:envId,error:error2 instanceof Error?error2.message:String(error2)})}try{await deps.oauthGrants.delete("",resourceId,org)}catch(error2){throw internalError(error2,"failed to delete OAuth grant")}return deps.logger.info("OAuth connection disconnected",{resource_id:resourceId,org,env_deleted:envId!==""}),create2(DisconnectOAuthOutputSchema,{disconnected:!0})}function isOAuthChallenge(wwwAuthenticate){let value=wwwAuthenticate.toLowerCase();return value.includes("bearer")?value.includes("oauth")||value.includes("resource_metadata"):!1}function parseResourceMetadataUrl(wwwAuthenticate){return/resource_metadata="([^"]+)"/i.exec(wwwAuthenticate)?.[1]}function protectedResourceMetadataUrls(resource){let bare=`${resource.origin}/.well-known/oauth-protected-resource`,path14=resource.pathname.replace(/\/+$/,"");return path14===""?[bare]:[`${bare}${path14}`,bare]}function authorizationServerMetadataUrls(issuer){let path14=issuer.pathname.replace(/\/+$/,""),urls=[...path14===""?[]:[`${issuer.origin}/.well-known/oauth-authorization-server${path14}`],`${issuer.origin}/.well-known/oauth-authorization-server`,...path14===""?[]:[`${issuer.origin}${path14}/.well-known/openid-configuration`],`${issuer.origin}/.well-known/openid-configuration`];return[...new Set(urls)]}async function resolveAuthorizationServers(resourceUrl,pointer,deps){let attempts=[],candidates=pointer!==void 0?[pointer]:protectedResourceMetadataUrls(new URL(resourceUrl));for(let candidate of candidates){let read3=await readJson(candidate,deps,attempts);if(read3===void 0)continue;let issuers=readStringArray(read3,"authorization_servers");if(issuers.length>0)return{issuers,attempts}}return{issuers:[],attempts}}async function readAuthorizationServerMetadata(issuer,deps){let attempts=[],parsed;try{parsed=new URL(issuer)}catch{return{kind:"not-found",attempts}}for(let metadataUrl of authorizationServerMetadataUrls(parsed)){let document2=await readJson(metadataUrl,deps,attempts);if(document2===void 0)continue;let authorizationEndpoint=readString(document2,"authorization_endpoint"),tokenEndpoint=readString(document2,"token_endpoint");if(authorizationEndpoint===""||tokenEndpoint===""){let last=attempts.pop();last!==void 0&&attempts.push({...last,missing:authorizationEndpoint===""?"authorization_endpoint":"token_endpoint"});continue}return{kind:"found",attempts,metadata:{metadataUrl,issuer:readString(document2,"issuer"),authorizationEndpoint,tokenEndpoint,registrationEndpoint:readString(document2,"registration_endpoint"),scopesSupported:readStringArray(document2,"scopes_supported"),codeChallengeMethodsSupported:readStringArray(document2,"code_challenge_methods_supported")}}}return{kind:"not-found",attempts}}async function readJson(url,deps,attempts){let response;try{response=await deps.fetchImpl(url,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(deps.timeoutMs)})}catch(error2){attempts.push({url,error:error2 instanceof Error?error2.message:String(error2)});return}if(attempts.push({url,status:response.status}),response.status!==200){await response.body?.cancel().catch(()=>{});return}try{let parsed=await response.json();return isRecord(parsed)?parsed:void 0}catch{return}}function readString(record2,key){let value=record2[key];return typeof value=="string"?value:""}function readStringArray(record2,key){let list12=record2[key];return Array.isArray(list12)?list12.filter(item=>typeof item=="string"):[]}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MCP_PROTOCOL_VERSION="2025-06-18";function baseHeaders(headers2){return{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":MCP_PROTOCOL_VERSION,...headers2??{}}}function initializeRequest(clientName,headers2){return{method:"POST",headers:baseHeaders(headers2),body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:MCP_PROTOCOL_VERSION,capabilities:{},clientInfo:{name:clientName,version:"0"}}})}}async function probeEndpointAuth(url,headers2,deps){let request=initializeRequest(deps.clientName,headers2),response;try{response=await deps.fetchImpl(url,{method:request.method,headers:{...request.headers},body:request.body,signal:AbortSignal.timeout(deps.timeoutMs)})}catch(error2){return{kind:"unreachable",error:describeError(error2)}}if(await response.body?.cancel().catch(()=>{}),response.status===401){let challenge=response.headers.get("www-authenticate")??"";return isOAuthChallenge(challenge)?{kind:"oauth",challenge,resourceMetadataUrl:parseResourceMetadataUrl(challenge)}:{kind:"challenge-not-oauth",challenge}}return response.status>=200&&response.status<300?{kind:"accepted",status:response.status}:{kind:"http-other",status:response.status}}function describeError(error2){return error2 instanceof Error?`${error2.name}: ${error2.message}`:String(error2)}var ENDPOINT_PROBE_TIMEOUT_MS=3e3,PROBE_CLIENT_NAME="stigmer-server",ACCESS_TOKEN_VAR_SUFFIX="_ACCESS_TOKEN",AUTHORIZATION_HEADER="authorization";function newCompleteEndpointAuthStep(deps){return{name:"CompleteEndpointAuth",async execute(ctx){let server=ctx.newState,spec=server.spec;if(spec===void 0)return;applyTokenPathDefault(spec,server.metadata?.slug??"");let existing=ctx.get(EXISTING_RESOURCE_KEY),derived=existing!==void 0?derivedCompletionOf(existing):void 0,url=authorShapeUrl(spec);if(url===void 0){derived!==void 0&&echoesDerived(spec,derived)?stamp(ctx,server):dropLabel(server);return}if(derived!==void 0&&derived.url===url){applyCompletion(spec,derived.variable,derived.description),stamp(ctx,server);return}if(await probe(url,spec,deps)!=="oauth"){dropLabel(server);return}let variable=accessTokenVariable(server.metadata?.slug??"");applyCompletion(spec,variable,tokenDescription(server.metadata?.slug??"")),stamp(ctx,server)}}}function authorShapeUrl(spec){if(spec.serverType.case==="http"&&spec.auth===void 0&&!(Object.keys(spec.env).length>0)){for(let[name,value]of Object.entries(spec.serverType.value.headers))if(name.toLowerCase()===AUTHORIZATION_HEADER||value.includes("${"))return;return spec.serverType.value.url}}function derivedCompletionOf(existing){if(existing.metadata?.labels[MCP_AUTH_LABEL]!==MCP_AUTH_ENDPOINT)return;let spec=existing.spec;if(spec===void 0||spec.serverType.case!=="http")return;let variable=spec.auth?.targetEnvVar??"";if(variable!=="")return{url:spec.serverType.value.url,variable,description:spec.env[variable]?.description??""}}function echoesDerived(spec,derived){if(spec.serverType.case!=="http"||spec.serverType.value.url!==derived.url)return!1;let auth=spec.auth;if(auth===void 0||auth.targetEnvVar!==derived.variable||!auth.oauthOnly||(auth.oauthAppRef?.slug??"")!==""||auth.discoveryUrl!==""||auth.scopeHints.length>0||auth.tokenLifetimeHint!=="")return!1;let envKeys=Object.keys(spec.env);if(envKeys.length!==1||envKeys[0]!==derived.variable)return!1;let declaration=spec.env[derived.variable];if(declaration===void 0||!declaration.isSecret||declaration.optional)return!1;let headers2=Object.entries(spec.serverType.value.headers),authorization=headers2.filter(([name])=>name.toLowerCase()===AUTHORIZATION_HEADER);return authorization.length!==1||authorization[0]?.[1]!==bearerHeader(derived.variable)?!1:headers2.every(([name,value])=>name.toLowerCase()===AUTHORIZATION_HEADER||!value.includes("${"))}function applyCompletion(spec,variable,description){spec.auth=create2(McpServerAuthSchema,{targetEnvVar:variable,oauthOnly:!0}),spec.env[variable]=create2(EnvVarDeclarationSchema,{isSecret:!0,optional:!1,description}),applyTokenPathDefault(spec,"")}function applyTokenPathDefault(spec,slug){let variable=spec.auth?.targetEnvVar??"";if(variable===""||(spec.env[variable]===void 0&&(spec.env[variable]=create2(EnvVarDeclarationSchema,{isSecret:!0,optional:!1,description:tokenDescription(slug)})),spec.serverType.case!=="http"))return;let headers2=spec.serverType.value.headers,reference=`\${${variable}}`;Object.values(headers2).some(value=>value.includes(reference))||(headers2.Authorization=bearerHeader(variable))}function bearerHeader(variable){return`Bearer \${${variable}}`}function accessTokenVariable(slug){let stem=slug.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"");return`${stem===""?"MCP":stem}${ACCESS_TOKEN_VAR_SUFFIX}`}function tokenDescription(slug){return`OAuth access token for the '${slug}' MCP server; Sign in fills it`}function stamp(ctx,server){server.metadata!==void 0&&(server.metadata.labels[MCP_AUTH_LABEL]=MCP_AUTH_ENDPOINT,recordServerStampedReservedLabels(ctx,MCP_AUTH_LABEL))}function dropLabel(server){server.metadata!==void 0&&delete server.metadata.labels[MCP_AUTH_LABEL]}async function probe(url,spec,deps){let headers2=spec.serverType.case==="http"?spec.serverType.value.headers:{};try{let outcome=await probeEndpointAuth(url,headers2,{fetchImpl:deps.outboundFetch,timeoutMs:ENDPOINT_PROBE_TIMEOUT_MS,clientName:PROBE_CLIENT_NAME});return outcome.kind==="unreachable"&&deps.logger.debug("MCP endpoint probe got no answer; saving the spec as sent",{url,error:outcome.error}),outcome.kind==="oauth"?"oauth":"other"}catch(error2){return deps.logger.warn("MCP endpoint probe threw; saving the spec as sent",{url,error:error2 instanceof Error?error2.message:String(error2)}),"other"}}async function getOAuthGrantStatus(deps,input,identity2){if(input.resourceId==="")throw invalidArgumentError("resource_id is required");if(input.org==="")throw invalidArgumentError("org is required");await authorizeDirect(McpServerQueryController.method.getOAuthGrantStatus,deps.authorizer,identity2,input);let grant;try{grant=await deps.oauthGrants.find("",input.resourceId,input.org)}catch(error2){throw internalError(error2,"failed to look up OAuth grant")}return grant===void 0?create2(GetOAuthGrantStatusOutputSchema,{connected:!1,connectionHealth:OAuthConnectionHealth.OAUTH_CONNECTION_HEALTH_NO_GRANT}):create2(GetOAuthGrantStatusOutputSchema,{connected:!0,accessTokenExpiresAt:BigInt(grant.accessTokenExpiresAt),targetEnvVar:grant.accessTokenEnvVar,authMethod:grant.authMethod,connectionHealth:evaluateHealth(grant)})}function evaluateHealth(grant){return grant.accessTokenExpiresAt===0?OAuthConnectionHealth.OAUTH_CONNECTION_HEALTH_HEALTHY:Math.floor(Date.now()/1e3)<grant.accessTokenExpiresAt-REFRESH_EXPIRY_BUFFER_SECONDS?OAuthConnectionHealth.OAUTH_CONNECTION_HEALTH_HEALTHY:grant.refreshTokenEnvVar!==""?OAuthConnectionHealth.OAUTH_CONNECTION_HEALTH_TOKEN_EXPIRED_REFRESHABLE:OAuthConnectionHealth.OAUTH_CONNECTION_HEALTH_TOKEN_EXPIRED}var import_node_crypto24=require("node:crypto");var import_node_crypto23=require("node:crypto");function generatePkce(){let verifier=(0,import_node_crypto23.randomBytes)(32).toString("base64url"),challenge=(0,import_node_crypto23.createHash)("sha256").update(verifier).digest().toString("base64url");return{codeVerifier:verifier,codeChallenge:challenge}}var DISCOVERY_REQUEST_TIMEOUT_MS=1e4;async function discoverForResource(mcpUrl,fetchImpl){let resource=parseDiscoveryUrl(mcpUrl),deps={fetchImpl,timeoutMs:DISCOVERY_REQUEST_TIMEOUT_MS},resolved=await resolveAuthorizationServers(resource.href,void 0,deps),issuers=resolved.issuers.length>0?resolved.issuers:[resource.origin];return readIssuers(issuers,deps)}async function discoverAtIssuer(issuerUrl,fetchImpl){let issuer=parseDiscoveryUrl(issuerUrl);return readIssuers([issuer.href],{fetchImpl,timeoutMs:DISCOVERY_REQUEST_TIMEOUT_MS})}async function readIssuers(issuers,deps){let attempts=[];for(let issuer of issuers){let read3=await readAuthorizationServerMetadata(issuer,deps);if(attempts.push(...read3.attempts),read3.kind==="found"){let metadata=toAuthServerMetadata(read3.metadata);return validateMetadata(metadata,read3.metadata.metadataUrl),metadata}}throw discoveryFailure(issuers,attempts)}function toAuthServerMetadata(m3){return{issuer:m3.issuer,authorizationEndpoint:m3.authorizationEndpoint,tokenEndpoint:m3.tokenEndpoint,registrationEndpoint:m3.registrationEndpoint,scopesSupported:[...m3.scopesSupported],codeChallengeMethodsSupported:[...m3.codeChallengeMethodsSupported]}}function discoveryFailure(issuers,attempts){let firstIssuer=issuers[0]??"",named=firstDocumentFor(firstIssuer),attempt=attempts.find(a5=>a5.url===named)??attempts[0];if(attempt?.error!==void 0)return new Error(`discovery request to ${attempt.url} failed: ${attempt.error}`);if(attempt?.missing!==void 0)return new Error(`authorization server at ${attempt.url} is missing ${attempt.missing}`);let status=attempt?.status??0;return new Error(`authorization server discovery failed: ${named} returned HTTP ${status} (expected 200). This MCP server may not support the MCP Authorization specification`)}function firstDocumentFor(issuer){try{return authorizationServerMetadataUrls(new URL(issuer))[0]??issuer}catch{return issuer}}function parseDiscoveryUrl(serverUrl){let parsed;try{parsed=new URL(serverUrl)}catch(error2){throw new Error(`invalid server URL for discovery: ${error2 instanceof Error?error2.message:String(error2)}`)}let scheme=parsed.protocol.replace(/:$/,"");if(scheme!=="http"&&scheme!=="https")throw new Error(`invalid server URL for discovery: unsupported scheme "${scheme}": only http and https are supported`);if(parsed.host==="")throw new Error("invalid server URL for discovery: server URL has no host");return parsed}function validateMetadata(m3,sourceUrl){if(m3.authorizationEndpoint==="")throw new Error(`authorization server at ${sourceUrl} is missing authorization_endpoint`);if(m3.tokenEndpoint==="")throw new Error(`authorization server at ${sourceUrl} is missing token_endpoint`);if(m3.codeChallengeMethodsSupported.length>0&&!m3.codeChallengeMethodsSupported.includes("S256"))throw new Error(`authorization server at ${sourceUrl} does not support S256 PKCE (supports: [${m3.codeChallengeMethodsSupported.join(" ")}]). S256 is required by the MCP Authorization specification`)}var DCR_REQUEST_TIMEOUT_MS=15e3;async function registerClient(registrationEndpoint,redirectUri,clientName,fetchImpl){let requestBody=JSON.stringify({redirect_uris:[redirectUri],client_name:clientName,grant_types:["authorization_code"],response_types:["code"],token_endpoint_auth_method:"none"}),response;try{response=await fetchImpl(registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:requestBody,signal:AbortSignal.timeout(DCR_REQUEST_TIMEOUT_MS)})}catch(error2){throw new Error(`DCR request to ${registrationEndpoint} failed: ${error2 instanceof Error?error2.message:String(error2)}`)}let body=await response.text();if(response.status!==201&&response.status!==200)throw new Error(`DCR at ${registrationEndpoint} returned HTTP ${response.status}: ${truncateBody(body)}`);let raw;try{raw=JSON.parse(body)}catch(error2){throw new Error(`failed to parse DCR response: ${error2 instanceof Error?error2.message:String(error2)}`)}if((raw.client_id??"")==="")throw new Error(`DCR response from ${registrationEndpoint} is missing client_id`);return{clientId:raw.client_id,clientSecret:raw.client_secret??"",clientName:raw.client_name??"",tokenEndpointAuthMethod:raw.token_endpoint_auth_method??""}}var PREFLIGHT_REQUEST_TIMEOUT_MS=4e3,PREFLIGHT_BODY_READ_CAP=4096;async function preflightAuthorize(authorizationUrl,fetchImpl){let response=await fetchImpl(authorizationUrl,{method:"GET",redirect:"manual",signal:AbortSignal.timeout(PREFLIGHT_REQUEST_TIMEOUT_MS)});if(response.status!==400){await response.text().catch(()=>"");return}let body=(await response.text()).slice(0,PREFLIGHT_BODY_READ_CAP);return{statusCode:response.status,vendorDetail:extractVendorDetail(body),bodySnippet:truncateBody(body)}}function extractVendorDetail(body){let parsed;try{parsed=JSON.parse(body)}catch{return""}return(parsed.error_description??"")!==""?parsed.error_description:parsed.error??""}async function initiateOAuthConnect(deps,input,identity2){if(deps.oauthRedirectUri==="")throw failedPreconditionError("OAuth Connect is not configured: STIGMER_OAUTH_REDIRECT_URI is not set");let mcpServerId=input.mcpServerId;if(mcpServerId==="")throw invalidArgumentError("mcp_server_id is required");let mcpServer;try{mcpServer=await deps.store.getResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("mcp_server",mcpServerId):internalError(error2,"failed to load mcp server")}await authorizeDirect(McpServerCommandController.method.initiateOAuthConnect,deps.authorizer,identity2,input);let auth=mcpServer.spec?.auth;if(auth===void 0)throw failedPreconditionError(`MCP server '${mcpServerId}' does not have an auth block configured`);let pkcePair=generatePkce(),stateParam=generateState(),oauthAppRef=auth.oauthAppRef,isDcr=oauthAppRef===void 0||oauthAppRef.slug==="",result=isDcr?await initiateDcr(deps,mcpServer,pkcePair,stateParam):await initiateVendorOAuth(deps,mcpServer,pkcePair,stateParam),authMethod=isDcr?"mcp_oauth":"vendor_oauth",pendingState={state:stateParam,codeVerifier:pkcePair.codeVerifier,clientId:result.clientId,clientSecret:result.clientSecret,tokenEndpoint:result.tokenEndpoint,mcpServerId,identityAccountId:"",targetEnvVar:auth.targetEnvVar,authMethod,tokenAuthMethod:result.tokenAuthMethod,redirectUri:deps.oauthRedirectUri,org:input.org,createdAt:0},sealed;try{sealed=await sealPendingOAuthState(deps.secretService,deps.logger,pendingState)}catch(error2){throw internalError(error2,"failed to encrypt OAuth handshake secrets")}try{await deps.pendingOAuthStates.save(sealed)}catch(error2){throw internalError(error2,"failed to save pending OAuth state")}return deps.logger.info("Initiated OAuth Connect flow",{mcp_server_id:mcpServerId,auth_method:authMethod,provider:result.providerName}),create2(InitiateOAuthConnectOutputSchema,{authorizationUrl:result.authorizationUrl,state:stateParam,scopes:result.scopes,providerName:result.providerName})}async function initiateDcr(deps,mcpServer,pkcePair,stateParam){let discoveryUrl2=mcpServer.spec?.auth?.discoveryUrl??"",serverType=mcpServer.spec?.serverType,resourceUrl=serverType?.case==="http"?serverType.value.url:"",serverUrl=discoveryUrl2!==""?discoveryUrl2:resourceUrl;if(serverUrl==="")throw failedPreconditionError(`DCR requires a discoverable URL. MCP server '${mcpServer.metadata?.id??""}' has no http.url and no auth.discovery_url. Set auth.discovery_url for stdio servers, oauth_app_ref for vendor OAuth, or switch to HTTP transport`);let metadata;try{metadata=discoveryUrl2!==""?await discoverAtIssuer(discoveryUrl2,deps.outboundFetch):await discoverForResource(resourceUrl,deps.outboundFetch)}catch(error2){throw failedPreconditionError(`OAuth authorization server discovery failed for ${serverUrl}: ${error2 instanceof Error?error2.message:String(error2)}`)}if(metadata.registrationEndpoint==="")throw failedPreconditionError(`MCP server at ${serverUrl} does not advertise a registration_endpoint for DCR: ${loginServerHost(metadata,serverUrl)} does not allow automatic client registration, so this server needs an OAuth app registered with the vendor and referenced from its definition (auth.oauth_app_ref)`);let clientName=`Stigmer (${mcpServer.metadata?.name??""})`,dcrResponse;try{dcrResponse=await registerClient(metadata.registrationEndpoint,deps.oauthRedirectUri,clientName,deps.outboundFetch)}catch(error2){throw failedPreconditionError(`DCR registration failed: ${error2 instanceof Error?error2.message:String(error2)}`)}let scopes=mcpServer.spec?.auth?.scopeHints??[];scopes.length===0&&metadata.scopesSupported.length>0&&(scopes=metadata.scopesSupported);let authUrl=buildAuthorizationUrl(metadata.authorizationEndpoint,dcrResponse.clientId,deps.oauthRedirectUri,pkcePair.codeChallenge,stateParam,scopes,"scope"),rejection;try{rejection=await preflightAuthorize(authUrl,deps.outboundFetch)}catch(probeError){deps.logger.debug("authorize pre-flight probe inconclusive; proceeding",{mcp_server_id:mcpServer.metadata?.id??"",error:probeError instanceof Error?probeError.message:String(probeError)})}if(rejection!==void 0)throw deps.logger.warn("authorization endpoint rejected the sign-in request pre-flight",{status_code:rejection.statusCode,mcp_server_id:mcpServer.metadata?.id??"",body_snippet:rejection.bodySnippet}),failedPreconditionError(dcrRejectionMessage(mcpServer.metadata?.name??"",deps.oauthRedirectUri,rejection));return{authorizationUrl:authUrl,providerName:mcpServer.metadata?.name??"",scopes,clientId:dcrResponse.clientId,clientSecret:"",tokenEndpoint:metadata.tokenEndpoint,tokenAuthMethod:""}}function loginServerHost(metadata,serverUrl){for(let candidate of[metadata.issuer,metadata.authorizationEndpoint,serverUrl])try{let host=new URL(candidate).host;if(host!=="")return host}catch{}return serverUrl}async function initiateVendorOAuth(deps,mcpServer,pkcePair,stateParam){let ref=mcpServer.spec?.auth?.oauthAppRef,oauthApp;try{oauthApp=await resolveOAuthAppRef(deps.store,ref,deps.logger)}catch(error2){throw internalError(error2,"failed to list oauth apps")}if(oauthApp===void 0)throw notFoundError("oauth_app",ref?.slug??"");let approvalStatus=oauthApp.spec?.vendorApprovalStatus;if(approvalStatus===VendorApprovalStatus.PENDING||approvalStatus===VendorApprovalStatus.REJECTED){let statusLabel=approvalStatus===VendorApprovalStatus.REJECTED?"rejected":"pending approval",alternative=mcpServer.spec?.auth?.oauthOnly?"This server only accepts OAuth sign-in; an org admin can configure your own OAuth app instead.":"Please enter a token manually instead.";throw failedPreconditionError(`OAuth sign-in is unavailable: the platform's OAuth app for '${oauthApp.spec?.provider??""}' is ${statusLabel} by the vendor. ${alternative}`)}let clientSecret=oauthApp.spec?.clientSecret??"";if(deps.secretService.isEncrypted(clientSecret))try{clientSecret=await deps.secretService.decrypt(clientSecret)}catch(error2){throw internalError(error2,"failed to decrypt OAuthApp client secret")}let scopes=oauthApp.spec?.scopes??[];return{authorizationUrl:buildAuthorizationUrl(oauthApp.spec?.authorizationUrl??"",oauthApp.spec?.clientId??"",deps.oauthRedirectUri,pkcePair.codeChallenge,stateParam,scopes,oauthApp.spec?.scopeParameterName??""),providerName:oauthApp.spec?.provider??"",scopes,clientId:oauthApp.spec?.clientId??"",clientSecret,tokenEndpoint:oauthApp.spec?.tokenUrl??"",tokenAuthMethod:tokenAuthMethodFromSpec(oauthApp.spec?.tokenEndpointAuthMethod??TokenEndpointAuthMethod.UNSPECIFIED)}}function buildAuthorizationUrl(authEndpoint,clientId,redirectUri,codeChallenge,state2,scopes,scopeParamName){let scopeParam=scopeParamName===""?"scope":scopeParamName,params=new URLSearchParams({response_type:"code",client_id:clientId,redirect_uri:redirectUri,code_challenge:codeChallenge,code_challenge_method:"S256",state:state2});scopes.length>0&&params.set(scopeParam,scopes.join(" ")),params.sort();let separator=authEndpoint.includes("?")?"&":"?";return authEndpoint+separator+params.toString()}function dcrRejectionMessage(providerName,redirectUri,rejection){let callbackHost=redirectUri;try{let parsed=new URL(redirectUri);parsed.host!==""&&(callbackHost=parsed.host)}catch{}let message6=`${providerName} rejected the sign-in request before showing a login page (HTTP ${rejection.statusCode}). The most common cause is a redirect-host allowlist: this deployment's OAuth callback host (${callbackHost}) is not on the provider's approved list. Self-hosted deployments with a localhost callback are typically unaffected.`;return rejection.vendorDetail!==""&&(message6+=" Provider detail: "+rejection.vendorDetail),message6}function generateState(){return(0,import_node_crypto24.randomBytes)(32).toString("base64url")}async function sealPendingOAuthState(secretService,logger2,state2){if(!secretService.isEnabled())return logger2.warn("Encryption disabled: pending OAuth state secrets will be stored in plaintext"),state2;let scope=EncryptionScope.forOrganization(state2.org),sealedVerifier;try{sealedVerifier=await secretService.encrypt(state2.codeVerifier,scope)}catch(error2){throw new Error(`failed to encrypt code_verifier: ${error2 instanceof Error?error2.message:String(error2)}`)}let sealedSecret=state2.clientSecret;if(state2.clientSecret!=="")try{sealedSecret=await secretService.encrypt(state2.clientSecret,scope)}catch(error2){throw new Error(`failed to encrypt client_secret: ${error2 instanceof Error?error2.message:String(error2)}`)}return{...state2,codeVerifier:sealedVerifier,clientSecret:sealedSecret}}var mcpServerSearchExtractor={kind:ApiResourceKind.mcp_server,schema:McpServerSchema,getSearchSummary(resource){return resource.spec?.description??""},toSearchResult(resource,score){let mcpServer=resource;return buildSearchResult({kind:ApiResourceKind.mcp_server,metadata:mcpServer.metadata,summary:mcpServer.spec?.description??"",score,createdAt:mcpServer.status?.audit?.specAudit?.createdAt,updatedAt:mcpServer.status?.audit?.specAudit?.updatedAt,iconUrl:mcpServer.spec?.iconUrl??""})},getSearchIndexEntry(resource){let mcpServer=resource,metadata=mcpServer.metadata;if(metadata!==void 0)return{name:metadata.name,description:mcpServer.spec?.description??"",tags:metadata.tags.join(" "),org:metadata.org,visibility:ApiResourceVisibility[metadata.visibility]??"",createdAt:Number(mcpServer.status?.audit?.specAudit?.createdAt?.seconds??0n)}}};var RUNNER_QUEUE_WARNING="no runner appears to be polling the task queue \u2014 the connect will wait for one to come up (start your local runner if it is not running)";async function startConnect(deps,input,identity2){let mcpServerId=input.mcpServerId;if(mcpServerId==="")throw invalidArgumentError("mcp_server_id is required");if(input.org==="")throw invalidArgumentError("org is required for connect");let mcpServer;try{mcpServer=await deps.store.getResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("mcp_server",mcpServerId):internalError(error2,"failed to load mcp server")}await authorizeDirect(McpServerCommandController.method.startConnect,deps.authorizer,identity2,input);let engineState=deps.engineState();if(!engineState.connected)throw failedPreconditionError("connect is not available: Temporal not configured");let connectStatus=mcpServer.status?.connectStatus;if(connectStatus?.phase===ConnectPhase.connecting&&await engineState.engine.isConnectRunRunning(connectStatus.workflowId))return deps.logger.info("StartConnect attached to in-flight connect operation",{mcp_server_id:mcpServerId,workflow_id:connectStatus.workflowId}),mcpServer;let prepared=await prepareConnect(deps,mcpServer,input,identity2),warning2=await runnerQueueWarning(engineState.engine),run;try{run=await engineState.engine.startOrAttachConnect(mcpServerId,prepared.workflowInput,ASYNC_CONNECT_TIMEOUT.ms)}catch(error2){throw prepared.ecResourceId!==""&&await deleteConnectExecutionContext(deps,prepared.ecResourceId,prepared.executionId),deps.logger.error("Failed to start MCP connect workflow",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to start connect workflow")}if(run.attached){prepared.ecResourceId!==""&&await deleteConnectExecutionContext(deps,prepared.ecResourceId,prepared.executionId);try{return await deps.store.getResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("mcp_server",mcpServerId):internalError(error2,"failed to load mcp server")}}let persisted;try{persisted=await persistConnectStarting(deps.store,mcpServerId,run.workflowId,warning2)}catch(error2){throw detachSettle(deps,mcpServer,run,prepared),internalError(error2,"failed to record connect operation")}return detachSettle(deps,mcpServer,run,prepared),persisted}function detachSettle(deps,mcpServer,run,prepared){settleConnectAsync(deps,mcpServer,run,prepared.ecResourceId,prepared.executionId).catch(error2=>{deps.logger.warn("Async connect settle task failed unexpectedly",{mcp_server_id:mcpServer.metadata?.id??"",error:error2 instanceof Error?error2.message:String(error2)})})}async function settleConnectAsync(deps,mcpServer,run,ecResourceId,executionId){let mcpServerId=mcpServer.metadata?.id??"";try{let outcome=await run.result(ASYNC_CONNECT_TIMEOUT.ms+BEST_EFFORT_CONNECT_GET_BUFFER_MS);if(!outcome.ok){let failure=mapConnectFailure(deps.logger,mcpServer,run.workflowId,outcome.failure,ASYNC_CONNECT_TIMEOUT);await persistConnectFailure(deps.store,deps.logger,mcpServerId,failure);return}let persisted,toolApprovalCount;try{({persisted,toolApprovalCount}=await persistConnectResult(deps.store,mcpServerId,run.workflowId,outcome.output))}catch(error2){if(error2 instanceof ResourceNotFoundError){deps.logger.info("Skipping async connect persistence: MCP server deleted before connect completed",{mcp_server_id:mcpServerId});return}deps.logger.warn("Failed to persist async connect result",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)});return}deps.logger.info("Async MCP server connect completed and stored",{workflow_id:run.workflowId,mcp_server_id:mcpServerId,tools:persisted.status?.discoveredCapabilities?.tools.length??0,resource_templates:persisted.status?.discoveredCapabilities?.resourceTemplates.length??0,tool_approvals:toolApprovalCount})}finally{ecResourceId!==""&&await deleteConnectExecutionContext(deps,ecResourceId,executionId)}}async function runnerQueueWarning(engine){let hasPollers=await engine.hasRunnerQueuePollers();return hasPollers===void 0||hasPollers?"":RUNNER_QUEUE_WARNING}function newValidateDefaultEnabledToolsStep(){return{name:"ValidateDefaultEnabledTools",execute(ctx){let mcpServer=ctx.newState,requested=mcpServer.spec?.defaultEnabledTools??[];if(requested.length===0)return;let caps=mcpServer.status?.discoveredCapabilities;if(caps===void 0)return;let classification=classify(caps,requested);if(isValidClassification(classification))return;let problems=[];throw classification.unknown.length>0&&problems.push(`default_enabled_tools names tool(s) this server does not expose: ${quoteJoin(classification.unknown)}`),classification.resourceTemplates.length>0&&problems.push(`default_enabled_tools names resource template(s): ${quoteJoin(classification.resourceTemplates)} \u2014 resource templates are read-only data endpoints, not callable tools, and must not appear in default_enabled_tools`),invalidArgumentError(`MCP server '${mcpServer.metadata?.slug??""}': ${problems.join("; ")}. Discovered tools: ${quoteJoin(toolNames(caps))}. If the server's toolset changed, run 'stigmer connect' on it to refresh discovered capabilities.`)}}}function newEnrichOAuthStatusStep(store,logger2){return{name:"EnrichOAuthStatus",async execute(ctx){let mcpServer=ctx.get(TARGET_RESOURCE_KEY);if(mcpServer===void 0)return;let ref=mcpServer.spec?.auth?.oauthAppRef;if((ref?.slug??"")==="")return;let oauthApp;try{oauthApp=await resolveOAuthAppRef(store,ref,logger2)}catch(error2){logger2.warn("OAuthApp lookup failed; returning MCP server without oauth_status enrichment",{mcpServerId:mcpServer.metadata?.id??"",oauthAppSlug:ref?.slug??"",error:error2 instanceof Error?error2.message:String(error2)});return}if(oauthApp===void 0){logger2.debug("OAuthApp not found for ref; skipping oauth_status enrichment",{mcpServerId:mcpServer.metadata?.id??"",oauthAppSlug:ref?.slug??""});return}let approvalStatus=oauthApp.spec?.vendorApprovalStatus??VendorApprovalStatus.UNSPECIFIED,docsUrl=oauthApp.spec?.vendorApprovalDocsUrl??"";approvalStatus===VendorApprovalStatus.UNSPECIFIED&&docsUrl===""||(mcpServer.status??=create2(McpServerStatusSchema,{}),mcpServer.status.oauthStatus=create2(OAuthStatusSchema,{vendorApprovalStatus:approvalStatus,vendorApprovalDocsUrl:docsUrl}))}}}function registerMcpServerServices(router,deps){router.service(McpServerCommandController,{apply:(server,ctx)=>apply11(deps,server,ctx),create:(server,ctx)=>createMcpServer(deps,server,ctx),update:(server,ctx)=>update14(deps,server,ctx),updateVisibility:(input,ctx)=>updateVisibility4(deps,input,ctx),delete:(input,ctx)=>deleteMcpServer(deps,input,ctx),connect:(input,ctx)=>connect(deps.connect,input,callerIdentityOf(ctx)),startConnect:(input,ctx)=>startConnect(deps.connect,input,callerIdentityOf(ctx)),initiateOAuthConnect:(input,ctx)=>initiateOAuthConnect(deps.connect,input,callerIdentityOf(ctx)),completeOAuthConnect:(input,ctx)=>completeOAuthConnect(deps.connect,input,callerIdentityOf(ctx)),disconnectOAuth:(input,ctx)=>disconnectOAuth(deps.connect,input,callerIdentityOf(ctx)),setOrgOAuthApp:()=>{throw orgOAuthAppUnimplemented("SetOrgOAuthApp")},deleteOrgOAuthApp:()=>{throw orgOAuthAppUnimplemented("DeleteOrgOAuthApp")}}),router.service(McpServerQueryController,{get:(id,ctx)=>get19(deps,id,ctx),getByReference:(ref,ctx)=>getByReference11(deps,ref,ctx),getOAuthGrantStatus:(input,ctx)=>getOAuthGrantStatus(deps.connect,input,callerIdentityOf(ctx)),getOrgOAuthApp:()=>{throw orgOAuthAppUnimplemented("GetOrgOAuthApp")}})}function orgOAuthAppUnimplemented(method){return new ConnectError(`method ${method} not implemented`,Code.Unimplemented)}function kindOf18(ctx){return ctx.values.get(apiResourceKindKey)}function endpointAuthDeps(deps){return{outboundFetch:deps.connect.outboundFetch,logger:deps.logger}}async function createMcpServer(deps,server,ctx){let reqCtx=new RequestContext(McpServerSchema,server,callerIdentityOf(ctx),kindOf18(ctx));return await newPipeline("mcpserver-create",deps.logger).addStep(newAuthorizeStep(McpServerCommandController.method.create,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newResolveSlugStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newBuildNewStateStep()).addStep(newCompleteEndpointAuthStep(endpointAuthDeps(deps))).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store)).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).addStep(newIndexSearchStep(deps.store,mcpServerSearchExtractor,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function update14(deps,server,ctx){let reqCtx=new RequestContext(McpServerSchema,server,callerIdentityOf(ctx),kindOf18(ctx));return await newPipeline("mcpserver-update",deps.logger).addStep(newAuthorizeStep(McpServerCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingStep(deps.store)).addStep(newGuardPluginManagedStep(deps.store)).addStep(newBuildUpdateStateStep()).addStep(newCompleteEndpointAuthStep(endpointAuthDeps(deps))).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newValidateDefaultEnabledToolsStep()).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store)).addStep(newPersistStep(deps.store)).addStep(newIndexSearchStep(deps.store,mcpServerSearchExtractor,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function apply11(deps,server,ctx){let reqCtx=new RequestContext(McpServerSchema,server,callerIdentityOf(ctx),kindOf18(ctx));await newPipeline("mcpserver-apply",deps.logger).addStep(newAuthorizeStep(McpServerCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");let result=shouldCreate?await createMcpServer(deps,server,ctx):await update14(deps,withResolvedApplyId(McpServerSchema,server,reqCtx),ctx);return startBestEffortConnect(deps.connect,result).catch(error2=>{deps.logger.warn("Best-effort connect task failed unexpectedly",{mcp_server_id:result.metadata?.id??"",error:error2 instanceof Error?error2.message:String(error2)})}),result}async function deleteMcpServer(deps,input,ctx){let reqCtx=new RequestContext(McpServerCommandController.method.delete.input,input,callerIdentityOf(ctx),kindOf18(ctx));reqCtx.set(RESOURCE_ID_KEY,input.resourceId),await newPipeline("mcpserver-delete",deps.logger).addStep(newAuthorizeStep(McpServerCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingForDeleteStep(deps.store,McpServerSchema)).addStep(newGuardPluginManagedStep(deps.store)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDeleteSearchIndexStep(deps.store,deps.logger)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted mcp server not found in context"),"deleted mcp server not found in context");return deleted}var UPDATE_VISIBILITY_MCP_SERVER_KEY="updateVisibilityMcpServer";async function updateVisibility4(deps,input,ctx){let reqCtx=new RequestContext(McpServerCommandController.method.updateVisibility.input,input,callerIdentityOf(ctx),kindOf18(ctx));return await newPipeline("mcpserver-update-visibility",deps.logger).addStep(newAuthorizeStep(McpServerCommandController.method.updateVisibility,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadMcpServerForVisibilityUpdateStep(deps.store)).addStep(newGuardPluginManagedStep(deps.store,{existingKey:UPDATE_VISIBILITY_MCP_SERVER_KEY})).addStep(newRecordVisibilityBeforeUpdateStep(UPDATE_VISIBILITY_MCP_SERVER_KEY)).addStep(newValidateVisibilityUpdateStep()).addStep(newSetMcpServerVisibilityStep()).addStep(newPersistMcpServerForVisibilityUpdateStep(deps.store)).addStep(newUpdateVisibilityTuplesStep(deps.authorizationLifecycle,UPDATE_VISIBILITY_MCP_SERVER_KEY)).addStep(newIndexMcpServerAfterVisibilityUpdateStep(deps.store,deps.logger)).build().execute(reqCtx),reqCtx.get(UPDATE_VISIBILITY_MCP_SERVER_KEY)}function newLoadMcpServerForVisibilityUpdateStep(store){return{name:"LoadMcpServerForVisibilityUpdate",async execute(ctx){let input=ctx.input,mcpServer;try{mcpServer=await store.getResource(ctx.apiResourceKind,input.resourceId,McpServerSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("mcp_server",input.resourceId):internalError(error2,"failed to load mcp server")}ctx.set(UPDATE_VISIBILITY_MCP_SERVER_KEY,mcpServer)}}}function newSetMcpServerVisibilityStep(){return{name:"SetMcpServerVisibility",execute(ctx){let mcpServer=ctx.get(UPDATE_VISIBILITY_MCP_SERVER_KEY);mcpServer.metadata!==void 0&&(mcpServer.metadata.visibility=ctx.input.visibility),setAuditFieldsForUpdate(McpServerSchema,mcpServer,"status_audit",ctx.callerIdentity)}}}function newPersistMcpServerForVisibilityUpdateStep(store){return{name:"PersistMcpServerForVisibilityUpdate",async execute(ctx){let mcpServer=ctx.get(UPDATE_VISIBILITY_MCP_SERVER_KEY);try{await store.saveResource(ctx.apiResourceKind,mcpServer.metadata?.id??"",McpServerSchema,mcpServer)}catch(error2){throw internalError(error2,"failed to save mcp server")}}}}function newIndexMcpServerAfterVisibilityUpdateStep(store,logger2){return{name:"IndexMcpServerAfterVisibilityUpdate",async execute(ctx){let mcpServer=ctx.get(UPDATE_VISIBILITY_MCP_SERVER_KEY),entry=mcpServerSearchExtractor.getSearchIndexEntry(mcpServer);if(entry===void 0){logger2.warn("IndexMcpServerAfterVisibilityUpdate: extractor returned nil, skipping",{id:mcpServer.metadata?.id??""});return}try{await store.upsertSearchIndex(ctx.apiResourceKind,mcpServer.metadata?.id??"",entry)}catch(error2){logger2.warn("IndexMcpServerAfterVisibilityUpdate: failed (best-effort)",{id:mcpServer.metadata?.id??"",error:error2 instanceof Error?error2.message:String(error2)})}}}}async function get19(deps,id,ctx){let reqCtx=new RequestContext(McpServerQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf18(ctx));return await newPipeline("mcpserver-get",deps.logger).addStep(newAuthorizeStep(McpServerQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,McpServerSchema)).addStep(newEnrichOAuthStatusStep(deps.store,deps.logger)).build().execute(reqCtx),reqCtx.get(TARGET_RESOURCE_KEY)}async function getByReference11(deps,ref,ctx){let reqCtx=new RequestContext(McpServerQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf18(ctx));return await newPipeline("mcpserver-get-by-reference",deps.logger).addStep(newAuthorizeStep(McpServerQueryController.method.getByReference,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadByReferenceStep(deps.store,McpServerSchema)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,loadedTargetAsMethod(McpServerQueryController.method.get))).addStep(newEnrichOAuthStatusStep(deps.store,deps.logger)).build().execute(reqCtx),reqCtx.get(TARGET_RESOURCE_KEY)}function registerPlatformServices(router,deps){router.service(PlatformQueryController,{getServerInfo:()=>getServerInfo(deps),getLicenseStatus:()=>getLicenseStatus(deps),getRunnerBootstrapConfig:(_input,ctx)=>getRunnerBootstrapConfig(deps,ctx),getRunnerScopedToken:(input,ctx)=>getRunnerScopedToken(deps,input,ctx)})}function getServerInfo(deps){return create2(GetServerInfoOutputSchema,{edition:deps.edition,version:deps.version,authenticationRequired:deps.authenticationRequired})}async function getLicenseStatus(deps){let now=deps.now(),report=await deps.licenseStatus.status(now),output=create2(GetLicenseStatusOutputSchema,{state:report.state,checkedAt:timestampFromDate(now)});switch(report.state){case LicenseState.absent:return output;case LicenseState.invalid:return output.keyId=report.keyId,output;case LicenseState.valid:case LicenseState.expiring:case LicenseState.grace:case LicenseState.expired:return output.keyId=report.keyId,output.claims=report.claims,output;default:{let exhaustive=report;throw new Error(`unhandled license report: ${JSON.stringify(exhaustive)}`)}}}async function getRunnerBootstrapConfig(deps,ctx){let output=create2(GetRunnerBootstrapConfigOutputSchema,{temporalAddress:deps.runnerBootstrapTemporalAddress,temporalNamespace:deps.temporalNamespace}),bootstrapCredentials=deps.runnerAuthService.bootstrapCredentials?.bind(deps.runnerAuthService);if(bootstrapCredentials===void 0)return output;try{let credentials=await bootstrapCredentials(callerIdentityOf(ctx));credentials.accessToken!==void 0&&(output.runnerAccessToken=credentials.accessToken.token,output.tokenType="Bearer",output.runnerAccessTokenExpiresInSeconds=credentials.accessToken.expiresInSeconds),credentials.payloadKeys!==void 0&&(output.payloadEncryptionKey=credentials.payloadKeys.keyBase64,output.payloadEncryptionKeyId=credentials.payloadKeys.keyId,output.payloadEncryptionSecondaryKey=credentials.payloadKeys.secondaryKeyBase64??"",output.payloadEncryptionSecondaryKeyId=credentials.payloadKeys.secondaryKeyId??"")}catch(error2){deps.logger.warn("Bootstrap credentials unavailable \u2014 answering coordinates without them",{error:error2 instanceof Error?error2.message:String(error2)})}return output}async function getRunnerScopedToken(deps,input,ctx){let exchange=deps.runnerAuthService.exchangeScopedToken?.bind(deps.runnerAuthService);if(exchange!==void 0){let minted=await exchange(exchangeRequestOf(input),callerIdentityOf(ctx));return minted.minted?create2(GetRunnerScopedTokenOutputSchema,{runnerScopedToken:minted.token,tokenType:"Bearer",expiresInSeconds:minted.expiresInSeconds}):create2(GetRunnerScopedTokenOutputSchema)}let executionId;switch(input.scope.case){case"agentExecutionId":executionId=input.scope.value;break;case"workflowExecutionId":executionId=input.scope.value;break;case"poolClaim":case"renewal":case void 0:return create2(GetRunnerScopedTokenOutputSchema);default:{let exhaustive=input.scope;throw new Error(`unhandled scope arm: ${JSON.stringify(exhaustive)}`)}}if(executionId===""||!deps.runnerAuthService.isEnabled(TOKEN_TYPE_EXECUTION_SCOPED))return create2(GetRunnerScopedTokenOutputSchema);try{let minted=deps.runnerAuthService.mint(TOKEN_TYPE_EXECUTION_SCOPED,executionId,0);return create2(GetRunnerScopedTokenOutputSchema,{runnerScopedToken:minted.token,tokenType:"Bearer",expiresInSeconds:minted.ttlSeconds})}catch(error2){return deps.logger.warn("failed to mint runner scoped token \u2014 answering not-minted",{executionId,error:error2 instanceof Error?error2.message:String(error2)}),create2(GetRunnerScopedTokenOutputSchema)}}function exchangeRequestOf(input){switch(input.scope.case){case"agentExecutionId":return{arm:"agent-execution",executionId:input.scope.value};case"workflowExecutionId":return{arm:"workflow-execution",executionId:input.scope.value};case"poolClaim":return{arm:"pool-claim",sessionId:input.scope.value.sessionId};case"renewal":return{arm:"renewal"};case void 0:return{arm:"unset"};default:{let exhaustive=input.scope;throw new Error(`unhandled scope arm: ${JSON.stringify(exhaustive)}`)}}}var SERVER_VERSION="3.40.0";var file_ai_stigmer_agentic_session_v1_io=fileDesc("CiZhaS9zdGlnbWVyL2FnZW50aWMvc2Vzc2lvbi92MS9pby5wcm90bxIdYWkuc3RpZ21lci5hZ2VudGljLnNlc3Npb24udjEiIgoJU2Vzc2lvbklkEhUKBXZhbHVlGAEgASgJQga6SAPIAQEiIAoHQWdlbnRJZBIVCgV2YWx1ZRgBIAEoCUIGukgDyAEBInQKC1Nlc3Npb25MaXN0EhMKC3RvdGFsX3BhZ2VzGAEgASgFEjcKB2VudHJpZXMYAiADKAsyJi5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5TZXNzaW9uEhcKD25leHRfcGFnZV90b2tlbhgDIAEoCSJgChNMaXN0U2Vzc2lvbnNSZXF1ZXN0EhoKCXBhZ2Vfc2l6ZRgBIAEoBUIHukgEGgIoABISCgpwYWdlX3Rva2VuGAIgASgJEgwKBHRhZ3MYAyADKAkSCwoDb3JnGAQgASgJIncKIkxpc3RTZXNzaW9uc0J5QWdlbnRJbnN0YW5jZVJlcXVlc3QSIQoRYWdlbnRfaW5zdGFuY2VfaWQYASABKAlCBrpIA8gBARIaCglwYWdlX3NpemUYAiABKAVCB7pIBBoCKAASEgoKcGFnZV90b2tlbhgDIAEoCSJqChxMaXN0U2Vzc2lvbnNCeUNoYW5uZWxSZXF1ZXN0EhoKCmNoYW5uZWxfaWQYASABKAlCBrpIA8gBARIaCglwYWdlX3NpemUYAiABKAVCB7pIBBoCKAASEgoKcGFnZV90b2tlbhgDIAEoCSJCChtVcGRhdGVTZXNzaW9uU3ViamVjdFJlcXVlc3QSEgoCaWQYASABKAlCBrpIA8gBARIPCgdzdWJqZWN0GAIgASgJYgZwcm90bzM",[file_ai_stigmer_agentic_session_v1_api,file_buf_validate_validate]),SessionIdSchema=messageDesc2(file_ai_stigmer_agentic_session_v1_io,0);var SessionListSchema=messageDesc2(file_ai_stigmer_agentic_session_v1_io,2);var file_ai_stigmer_agentic_session_v1_command=fileDesc("CithaS9zdGlnbWVyL2FnZW50aWMvc2Vzc2lvbi92MS9jb21tYW5kLnByb3RvEh1haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MTLtBQoYU2Vzc2lvbkNvbW1hbmRDb250cm9sbGVyElcKBWFwcGx5EiYuYWkuc3RpZ21lci5hZ2VudGljLnNlc3Npb24udjEuU2Vzc2lvbhomLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb24SpQEKBmNyZWF0ZRImLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb24aJi5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5TZXNzaW9uIkvCuBhHCAgQHiIMbWV0YWRhdGEub3JnKjN1bmF1dGhvcml6ZWQgdG8gY3JlYXRlIHNlc3Npb24gaW4gdGhpcyBvcmdhbml6YXRpb24SjwEKBnVwZGF0ZRImLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb24aJi5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5TZXNzaW9uIjXCuBgxCAIQKiILbWV0YWRhdGEuaWQqHnVuYXV0aG9yaXplZCB0byB1cGRhdGUgc2Vzc2lvbhKpAQoNdXBkYXRlU3ViamVjdBI6LmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlVwZGF0ZVNlc3Npb25TdWJqZWN0UmVxdWVzdBomLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb24iNMK4GDAIAhAqIgJpZComdW5hdXRob3JpemVkIHRvIHVwZGF0ZSBzZXNzaW9uIHN1YmplY3QSiwEKBmRlbGV0ZRIoLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb25JZBomLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb24iL8K4GCsIAxAqIgV2YWx1ZSoedW5hdXRob3JpemVkIHRvIGRlbGV0ZSBzZXNzaW9uGgSg/ysqYgZwcm90bzM",[file_ai_stigmer_agentic_session_v1_api,file_ai_stigmer_agentic_session_v1_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),SessionCommandController=serviceDesc(file_ai_stigmer_agentic_session_v1_command,0);var file_ai_stigmer_agentic_session_v1_query=fileDesc("CilhaS9zdGlnbWVyL2FnZW50aWMvc2Vzc2lvbi92MS9xdWVyeS5wcm90bxIdYWkuc3RpZ21lci5hZ2VudGljLnNlc3Npb24udjEyoQQKFlNlc3Npb25RdWVyeUNvbnRyb2xsZXIShQEKA2dldBIoLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb25JZBomLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb24iLMK4GCgIARAqIgV2YWx1ZSobdW5hdXRob3JpemVkIHRvIGdldCBzZXNzaW9uEmwKBGxpc3QSMi5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5MaXN0U2Vzc2lvbnNSZXF1ZXN0GiouYWkuc3RpZ21lci5hZ2VudGljLnNlc3Npb24udjEuU2Vzc2lvbkxpc3QiBNC4GAESigEKE2xpc3RCeUFnZW50SW5zdGFuY2USQS5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5MaXN0U2Vzc2lvbnNCeUFnZW50SW5zdGFuY2VSZXF1ZXN0GiouYWkuc3RpZ21lci5hZ2VudGljLnNlc3Npb24udjEuU2Vzc2lvbkxpc3QiBNC4GAESfgoNbGlzdEJ5Q2hhbm5lbBI7LmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLkxpc3RTZXNzaW9uc0J5Q2hhbm5lbFJlcXVlc3QaKi5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5TZXNzaW9uTGlzdCIE0LgYARoEoP8rKmIGcHJvdG8z",[file_ai_stigmer_agentic_session_v1_api,file_ai_stigmer_agentic_session_v1_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),SessionQueryController=serviceDesc(file_ai_stigmer_agentic_session_v1_query,0);function runAgentInstanceDeniedMessage2(agentInstanceId){return`unauthorized to run agent instance '${agentInstanceId}'`}function sessionRunTarget(session){let agentInstanceId=session.spec?.agentInstanceId??"";if(agentInstanceId!=="")return{...RUN_GATE_CHECKS.agentInstance,resourceId:agentInstanceId,deniedMessage:runAgentInstanceDeniedMessage2(agentInstanceId)}}var sessionSearchExtractor={kind:ApiResourceKind.session,schema:SessionSchema,getSearchSummary(resource){return resource.spec?.subject??""},toSearchResult(resource,score){let session=resource;return buildSearchResult({kind:ApiResourceKind.session,metadata:session.metadata,summary:session.spec?.subject??"",score,createdAt:session.status?.audit?.specAudit?.createdAt,updatedAt:session.status?.audit?.specAudit?.updatedAt})},getSearchIndexEntry(resource){let session=resource,metadata=session.metadata;if(metadata!==void 0)return{name:metadata.name,description:session.spec?.subject??"",tags:metadata.tags.join(" "),org:metadata.org,visibility:ApiResourceVisibility[metadata.visibility]??"",createdAt:Number(session.status?.audit?.specAudit?.createdAt?.seconds??0n)}}};var SESSION_CHANNEL_ID_LABEL="stigmer.ai/channel-id",sessionListIndex=declareListIndex({kind:ApiResourceKind.session,schema:SessionSchema,revision:1,keys:{agent_instance:field2("spec.agent_instance_id"),channel:label(SESSION_CHANNEL_ID_LABEL)}});var LIST_RESULT_KEY8="listResult";function newValidateHarnessImmutabilityStep(){return{name:"ValidateHarnessImmutability",execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)return;let existingSpec=existing.spec;if(existingSpec===void 0||existingSpec.harnessStateId==="")return;let inputSpec=ctx.input.spec;if(inputSpec===void 0)return;let existingHarness=existingSpec.harness,inputHarness=inputSpec.harness;if(existingHarness===Harness.UNSPECIFIED&&(existingHarness=Harness.NATIVE),inputHarness===Harness.UNSPECIFIED&&(inputHarness=Harness.NATIVE),inputHarness!==existingHarness)throw failedPreconditionError("session harness cannot be changed after the first execution \u2014 each harness owns its conversation state independently")}}}var EXECUTION_TARGET_GO_NAMES={[ExecutionTarget.UNSPECIFIED]:"EXECUTION_TARGET_UNSPECIFIED",[ExecutionTarget.LOCAL]:"EXECUTION_TARGET_LOCAL",[ExecutionTarget.CLOUD]:"EXECUTION_TARGET_CLOUD"};function newValidateExecutionTargetImmutabilityStep(temporalConfig){return{name:"ValidateExecutionTargetImmutability",execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)return;let existingSpec=existing.spec;if(existingSpec===void 0||existingSpec.harnessStateId==="")return;let inputSpec=ctx.input.spec;if(inputSpec===void 0)return;let existingTarget=temporalConfig.resolveExecutionTarget(existingSpec.executionTarget),inputTarget=temporalConfig.resolveExecutionTarget(inputSpec.executionTarget);if(inputTarget!==existingTarget)throw failedPreconditionError(`session execution_target cannot be changed after the first execution (${EXECUTION_TARGET_GO_NAMES[existingTarget]} \u2192 ${EXECUTION_TARGET_GO_NAMES[inputTarget]}; unset resolves to the deployment default, ${temporalConfig.defaultExecutionTarget}) \u2014 workspace state may not be portable between local and cloud environments`)}}}function newRecordHarnessStateHistoryStep(){return{name:"RecordHarnessStateHistory",execute(ctx){let mergedSpec=ctx.newState.spec;if(mergedSpec===void 0)return;let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0||existing.spec===void 0)return;let existingSpec=existing.spec,history=[...existingSpec.harnessStateIdHistory],previousId=existingSpec.harnessStateId;previousId!==""&&previousId!==mergedSpec.harnessStateId&&!history.includes(previousId)&&history.push(previousId),mergedSpec.harnessStateIdHistory=history}}}function isActiveExecutionPhase(phase){switch(phase){case ExecutionPhase.EXECUTION_PENDING:case ExecutionPhase.EXECUTION_IN_PROGRESS:case ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL:case ExecutionPhase.EXECUTION_PAUSED:return!0;default:return!1}}async function listExecutionsBySession(store,logger2,sessionId){let rows;try{rows=await store.queryResources(agentExecutionListIndex,{anyKey:[{name:"session",value:sessionId}]})}catch(error2){throw internalError(error2,"failed to list agent executions")}let executions=[];for(let row of rows)try{executions.push(fromBinary2(AgentExecutionSchema,row.data))}catch(error2){logger2.warn("Failed to unmarshal execution, skipping",{error:error2 instanceof Error?error2.message:String(error2)})}return executions}function newRejectDeleteWithActiveExecutionsStep(store,logger2){return{name:"RejectDeleteWithActiveExecutions",async execute(ctx){let sessionId=requireSessionId(ctx),executions=await listExecutionsBySession(store,logger2,sessionId),activeCount=0;for(let execution of executions)isActiveExecutionPhase(execution.status?.phase??ExecutionPhase.EXECUTION_PHASE_UNSPECIFIED)&&activeCount++;if(activeCount>0)throw failedPreconditionError(`session has ${activeCount} active execution(s); cancel them or wait for completion before deleting`)}}}function newCascadeDeleteAgentExecutionsStep(store,logger2){return{name:"CascadeDeleteAgentExecutions",async execute(ctx){let sessionId=requireSessionId(ctx),executions=await listExecutionsBySession(store,logger2,sessionId);if(executions.length!==0){for(let execution of executions){let executionId=execution.metadata?.id??"";try{await store.deleteResource(ApiResourceKind.agent_execution,executionId)}catch(error2){throw internalError(error2,`failed to cascade-delete execution ${executionId} of session ${sessionId}`)}try{await store.deleteSearchIndex(ApiResourceKind.agent_execution,executionId)}catch(error2){logger2.warn("CascadeDeleteAgentExecutions: failed to remove search index entry (best-effort)",{executionId,error:error2 instanceof Error?error2.message:String(error2)})}}logger2.info("Cascade-deleted executions of session",{sessionId,count:executions.length})}}}}function requireSessionId(ctx){let sessionId=ctx.get(RESOURCE_ID_KEY);if(typeof sessionId!="string"||sessionId==="")throw internalError(new Error("session id not found in context (ExtractResourceId must run first)"),"session id not found in context (ExtractResourceId must run first)");return sessionId}function newListAllSessionsStep(store,logger2,listReadScope){return{name:"ListAllSessions",async execute(ctx){let input=ctx.input,page=await readSessionPage(store,logger2,listReadScope,ctx.callerIdentity,ctx.input,{query:{org:input.org},fingerprint:{lane:"session.list",org:input.org,tags:input.tags}});ctx.set(LIST_RESULT_KEY8,page)}}}function newFilterByAgentInstanceStep(store,logger2,listReadScope){return{name:"FilterByAgentInstance",async execute(ctx){let agentInstanceId=ctx.input.agentInstanceId;if(agentInstanceId==="")throw invalidArgumentError("agent_instance_id is required");let page=await readSessionPage(store,logger2,listReadScope,ctx.callerIdentity,ctx.input,{query:{anyKey:[{name:"agent_instance",value:agentInstanceId}]},fingerprint:{lane:"session.listByAgentInstance",agentInstanceId}});ctx.set(LIST_RESULT_KEY8,page)}}}function newAuthorizeChannelAccessStep(authorizer){return newAuthorizeResolvedTargetStep(authorizer,({input})=>input.channelId===""?[]:[{permission:IamPermission.can_view,resourceKind:ApiResourceKind.agent_channel,resourceId:input.channelId,deniedMessage:"unauthorized to list channel conversations"}],"AuthorizeChannelAccess")}function newFilterByChannelStep(store,logger2,listReadScope){return{name:"FilterByChannel",async execute(ctx){let channelId=ctx.input.channelId;if(channelId==="")throw invalidArgumentError("channel_id is required");let page=await readSessionPage(store,logger2,listReadScope,ctx.callerIdentity,ctx.input,{query:{anyKey:[{name:"channel",value:channelId}]},fingerprint:{lane:"session.listByChannel",channelId}});ctx.set(LIST_RESULT_KEY8,page)}}}async function readSessionPage(store,logger2,listReadScope,caller,request,lane){let page=await readListPage({store,declaration:sessionListIndex,query:lane.query,request,fingerprint:listPageFingerprint(lane.fingerprint),decode:data=>{try{return fromBinary2(SessionSchema,data)}catch(error2){logger2.warn("Failed to unmarshal session, skipping",{error:error2 instanceof Error?error2.message:String(error2)});return}},scope:sessions=>restrictListByReadScope(listReadScope,caller,ApiResourceKind.session,sessions,""),failure:"failed to list sessions"});return create2(SessionListSchema,{entries:page.entries,nextPageToken:page.nextPageToken,totalPages:page.nextPageToken===""?1:0})}function registerSessionServices(router,deps){router.service(SessionCommandController,{apply:(session,ctx)=>apply12(deps,session,ctx),create:(session,ctx)=>createSession(deps,session,ctx),update:(session,ctx)=>update15(deps,session,ctx),updateSubject:(req,ctx)=>updateSubject(deps,req,callerIdentityOf(ctx)),delete:(id,ctx)=>deleteSession(deps,id,ctx)}),router.service(SessionQueryController,{get:(id,ctx)=>get20(deps,id,ctx),list:(req,ctx)=>list10(deps,req,ctx),listByAgentInstance:(req,ctx)=>listByAgentInstance(deps,req,ctx),listByChannel:(req,ctx)=>listByChannel(deps,req,ctx)})}function kindOf19(ctx){return ctx.values.get(apiResourceKindKey)}async function createSession(deps,session,ctx){let reqCtx=new RequestContext(SessionSchema,session,callerIdentityOf(ctx),kindOf19(ctx)),builder2=newPipeline("session-create",deps.logger).addStep(newAuthorizeStep(SessionCommandController.method.create,deps.authorizer)).addStep(newAuthorizeRunTargetStep(deps.authorizer,sessionRunTarget)).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newResolveSlugStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store));for(let step of stepsForSlot(deps.gateSteps,"session-create:pre-side-effect-gate"))builder2.addStep(step);return await builder2.addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).addStep(newIndexSearchStep(deps.store,sessionSearchExtractor,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function update15(deps,session,ctx){let reqCtx=new RequestContext(SessionSchema,session,callerIdentityOf(ctx),kindOf19(ctx));return await newPipeline("session-update",deps.logger).addStep(newAuthorizeStep(SessionCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingStep(deps.store)).addStep(newValidateHarnessImmutabilityStep()).addStep(newValidateExecutionTargetImmutabilityStep(deps.temporalConfig)).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newRecordHarnessStateHistoryStep()).addStep(newPersistStep(deps.store)).addStep(newIndexSearchStep(deps.store,sessionSearchExtractor,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function apply12(deps,session,ctx){let reqCtx=new RequestContext(SessionSchema,session,callerIdentityOf(ctx),kindOf19(ctx));await newPipeline("session-apply",deps.logger).addStep(newAuthorizeStep(SessionCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");return shouldCreate?createSession(deps,session,ctx):update15(deps,withResolvedApplyId(SessionSchema,session,reqCtx),ctx)}async function deleteSession(deps,sessionId,ctx){let reqCtx=new RequestContext(SessionCommandController.method.delete.input,sessionId,callerIdentityOf(ctx),kindOf19(ctx));await newPipeline("session-delete",deps.logger).addStep(newAuthorizeStep(SessionCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newExtractResourceIdStep()).addStep(newLoadExistingForDeleteStep(deps.store,SessionSchema)).addStep(newRejectDeleteWithActiveExecutionsStep(deps.store,deps.logger)).addStep(newCascadeDeleteAgentExecutionsStep(deps.store,deps.logger)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDeleteSearchIndexStep(deps.store,deps.logger)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted session not found in context"),"deleted session not found in context");return await deprovisionSessionSandboxBestEffort(deps.sandboxLane,deps.logger,deleted.metadata?.id??""),deleted}async function updateSubject(deps,req,identity2){if(req.id==="")throw invalidArgumentError("id is required");let kind=ApiResourceKind.session,session;try{session=await deps.store.getResource(kind,req.id,SessionSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("session",req.id):internalError(error2,"failed to load session")}await authorizeDirect(SessionCommandController.method.updateSubject,deps.authorizer,identity2,req),session.spec===void 0&&(session.spec=create2(SessionSpecSchema,{})),session.spec.subject=req.subject,setAuditFieldsForUpdate(SessionSchema,session,"spec_audit",identity2);try{await deps.store.saveResource(kind,req.id,SessionSchema,session)}catch(error2){throw internalError(error2,"failed to persist session")}return await indexSessionSearch(deps,kind,session),session}async function indexSessionSearch(deps,kind,session){let entry=sessionSearchExtractor.getSearchIndexEntry(session);if(entry!==void 0)try{await deps.store.upsertSearchIndex(kind,session.metadata?.id??"",entry)}catch(error2){deps.logger.warn("UpdateSubject: failed to update search index (best-effort)",{id:session.metadata?.id??"",error:error2 instanceof Error?error2.message:String(error2)})}}async function get20(deps,id,ctx){let reqCtx=new RequestContext(SessionQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf19(ctx));return await newPipeline("session-get",deps.logger).addStep(newAuthorizeStep(SessionQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,SessionSchema)).build().execute(reqCtx),reqCtx.get(TARGET_RESOURCE_KEY)}async function list10(deps,req,ctx){let reqCtx=new RequestContext(SessionQueryController.method.list.input,req,callerIdentityOf(ctx),kindOf19(ctx));return await newPipeline("session-list",deps.logger).addStep(newAuthorizeStep(SessionQueryController.method.list,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newListAllSessionsStep(deps.store,deps.logger,deps.listReadScope)).build().execute(reqCtx),requireListResult2(reqCtx.get(LIST_RESULT_KEY8))}async function listByAgentInstance(deps,req,ctx){let reqCtx=new RequestContext(SessionQueryController.method.listByAgentInstance.input,req,callerIdentityOf(ctx),kindOf19(ctx));return await newPipeline("session-list-by-agent-instance",deps.logger).addStep(newAuthorizeStep(SessionQueryController.method.listByAgentInstance,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newFilterByAgentInstanceStep(deps.store,deps.logger,deps.listReadScope)).build().execute(reqCtx),requireListResult2(reqCtx.get(LIST_RESULT_KEY8))}async function listByChannel(deps,req,ctx){let reqCtx=new RequestContext(SessionQueryController.method.listByChannel.input,req,callerIdentityOf(ctx),kindOf19(ctx));return await newPipeline("session-list-by-channel",deps.logger).addStep(newAuthorizeStep(SessionQueryController.method.listByChannel,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newAuthorizeChannelAccessStep(deps.authorizer)).addStep(newFilterByChannelStep(deps.store,deps.logger,deps.listReadScope)).build().execute(reqCtx),requireListResult2(reqCtx.get(LIST_RESULT_KEY8))}function requireListResult2(result){if(result===void 0)throw internalError(new Error("session list not found in context"),"session list not found in context");return result}var file_ai_stigmer_agentic_plugin_v1_io=fileDesc("CiVhaS9zdGlnbWVyL2FnZW50aWMvcGx1Z2luL3YxL2lvLnByb3RvEhxhaS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxIiEKCFBsdWdpbklkEhUKBXZhbHVlGAEgASgJQga6SAPIAQEi9wIKEVB1c2hQbHVnaW5SZXF1ZXN0EhMKA29yZxgBIAEoCUIGukgDyAEBEhAKCGFydGlmYWN0GAIgASgMEhsKE2FydGlmYWN0X3VwbG9hZF9yZWYYAyABKAkSUwoKdmlzaWJpbGl0eRgEIAEoDjI1LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVZpc2liaWxpdHlCCLpIBYIBAhABEg8KB21lc3NhZ2UYBSABKAk6twG6SLMBGrABCiNwdXNoX3BsdWdpbl9yZXF1ZXN0LmFydGlmYWN0X3NvdXJjZRJJZXhhY3RseSBvbmUgb2YgYXJ0aWZhY3QgKGlubGluZSBieXRlcykgb3IgYXJ0aWZhY3RfdXBsb2FkX3JlZiBtdXN0IGJlIHNldBo+KHRoaXMuYXJ0aWZhY3Quc2l6ZSgpID4gMCkgIT0gKHRoaXMuYXJ0aWZhY3RfdXBsb2FkX3JlZiAhPSAnJykiWAokQ3JlYXRlUGx1Z2luQXJ0aWZhY3RVcGxvYWRVcmxSZXF1ZXN0EhMKA29yZxgBIAEoCUIGukgDyAEBEhsKCnNpemVfYnl0ZXMYAiABKANCB7pIBCICIAAiWAoXUGx1Z2luQXJ0aWZhY3RVcGxvYWRVcmwSCwoDdXJsGAEgASgJEhsKE2FydGlmYWN0X3VwbG9hZF9yZWYYAiABKAkSEwoLdHRsX3NlY29uZHMYAyABKAUihQEKDFBsdWdpbk1lbWJlchJNCgRraW5kGAEgASgOMj8uYWkuc3RpZ21lci5jb21tb25zLmFwaXJlc291cmNlLmFwaXJlc291cmNla2luZC5BcGlSZXNvdXJjZUtpbmQSCgoCaWQYAiABKAkSDAoEc2x1ZxgDIAEoCRIMCgRuYW1lGAQgASgJIlgKGUxpc3RQbHVnaW5NZW1iZXJzUmVzcG9uc2USOwoHbWVtYmVycxgBIAMoCzIqLmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuUGx1Z2luTWVtYmVyImsKF0xpc3RQbHVnaW5WZXJzaW9uc0lucHV0EhMKA29yZxgBIAEoCUIGukgDyAEBEhQKBHNsdWcYAiABKAlCBrpIA8gBARISCgpwYWdlX3Rva2VuGAMgASgJEhEKCXBhZ2Vfc2l6ZRgEIAEoBSLtAQoSUGx1Z2luVmVyc2lvbkVudHJ5Eg4KBmRpZ2VzdBgBIAEoCRItCglwdXNoZWRfYXQYAiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEkgKCXB1c2hlZF9ieRgDIAEoCzI1LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZUF1ZGl0QWN0b3ISCwoDdGFnGAQgASgJEhIKCmlzX2N1cnJlbnQYBSABKAgSDwoHbWVzc2FnZRgGIAEoCRIcChRhcnRpZmFjdF9zdG9yYWdlX2tleRgHIAEoCSKOAQoaTGlzdFBsdWdpblZlcnNpb25zUmVzcG9uc2USQgoIdmVyc2lvbnMYASADKAsyMC5haS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxLlBsdWdpblZlcnNpb25FbnRyeRIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkSEwoLdG90YWxfY291bnQYAyABKAViBnByb3RvMw",[file_ai_stigmer_commons_apiresource_apiresourcekind_api_resource_kind,file_ai_stigmer_commons_apiresource_enum,file_ai_stigmer_commons_apiresource_status,file_buf_validate_validate,file_google_protobuf_timestamp]);var PushPluginRequestSchema=messageDesc2(file_ai_stigmer_agentic_plugin_v1_io,1);var PluginArtifactUploadUrlSchema=messageDesc2(file_ai_stigmer_agentic_plugin_v1_io,3),PluginMemberSchema=messageDesc2(file_ai_stigmer_agentic_plugin_v1_io,4),ListPluginMembersResponseSchema=messageDesc2(file_ai_stigmer_agentic_plugin_v1_io,5);var PluginVersionEntrySchema=messageDesc2(file_ai_stigmer_agentic_plugin_v1_io,7),ListPluginVersionsResponseSchema=messageDesc2(file_ai_stigmer_agentic_plugin_v1_io,8);var file_ai_stigmer_agentic_plugin_v1_command=fileDesc("CiphaS9zdGlnbWVyL2FnZW50aWMvcGx1Z2luL3YxL2NvbW1hbmQucHJvdG8SHGFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEy2gUKF1BsdWdpbkNvbW1hbmRDb250cm9sbGVyEqEBCgRwdXNoEi8uYWkuc3RpZ21lci5hZ2VudGljLnBsdWdpbi52MS5QdXNoUGx1Z2luUmVxdWVzdBokLmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuUGx1Z2luIkLCuBg+CCgQHiIDb3JnKjN1bmF1dGhvcml6ZWQgdG8gaW5zdGFsbCBwbHVnaW4gaW4gdGhpcyBvcmdhbml6YXRpb24S2AEKF2NyZWF0ZUFydGlmYWN0VXBsb2FkVXJsEkIuYWkuc3RpZ21lci5hZ2VudGljLnBsdWdpbi52MS5DcmVhdGVQbHVnaW5BcnRpZmFjdFVwbG9hZFVybFJlcXVlc3QaNS5haS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxLlBsdWdpbkFydGlmYWN0VXBsb2FkVXJsIkLCuBg+CCgQHiIDb3JnKjN1bmF1dGhvcml6ZWQgdG8gaW5zdGFsbCBwbHVnaW4gaW4gdGhpcyBvcmdhbml6YXRpb24SsAEKEHVwZGF0ZVZpc2liaWxpdHkSNS5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuVXBkYXRlVmlzaWJpbGl0eUlucHV0GiQuYWkuc3RpZ21lci5hZ2VudGljLnBsdWdpbi52MS5QbHVnaW4iP8K4GDsIAhA6IgtyZXNvdXJjZV9pZCoodW5hdXRob3JpemVkIHRvIHVwZGF0ZSBwbHVnaW4gdmlzaWJpbGl0eRKGAQoGZGVsZXRlEiYuYWkuc3RpZ21lci5hZ2VudGljLnBsdWdpbi52MS5QbHVnaW5JZBokLmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuUGx1Z2luIi7CuBgqCAMQOiIFdmFsdWUqHXVuYXV0aG9yaXplZCB0byBkZWxldGUgcGx1Z2luGgSg/ys6YgZwcm90bzM",[file_ai_stigmer_agentic_plugin_v1_api,file_ai_stigmer_agentic_plugin_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),PluginCommandController=serviceDesc(file_ai_stigmer_agentic_plugin_v1_command,0);var file_ai_stigmer_agentic_plugin_v1_query=fileDesc("CihhaS9zdGlnbWVyL2FnZW50aWMvcGx1Z2luL3YxL3F1ZXJ5LnByb3RvEhxhaS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxMsMEChVQbHVnaW5RdWVyeUNvbnRyb2xsZXISgAEKA2dldBImLmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuUGx1Z2luSWQaJC5haS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxLlBsdWdpbiIrwrgYJwgBEDoiBXZhbHVlKhp1bmF1dGhvcml6ZWQgdG8gZ2V0IHBsdWdpbhJyCg5nZXRCeVJlZmVyZW5jZRI0LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVJlZmVyZW5jZRokLmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuUGx1Z2luIgTQuBgBEqQBCgtsaXN0TWVtYmVycxImLmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuUGx1Z2luSWQaNy5haS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxLkxpc3RQbHVnaW5NZW1iZXJzUmVzcG9uc2UiNMK4GDAIARA6IgV2YWx1ZSojdW5hdXRob3JpemVkIHRvIGxpc3QgcGx1Z2luIG1lbWJlcnMShQEKDGxpc3RWZXJzaW9ucxI1LmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuTGlzdFBsdWdpblZlcnNpb25zSW5wdXQaOC5haS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxLkxpc3RQbHVnaW5WZXJzaW9uc1Jlc3BvbnNlIgTQuBgBGgSg/ys6YgZwcm90bzM",[file_ai_stigmer_agentic_plugin_v1_api,file_ai_stigmer_agentic_plugin_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),PluginQueryController=serviceDesc(file_ai_stigmer_agentic_plugin_v1_query,0);var PLATFORM_ARCHIVE_LIMITS={maxFiles:1e4,maxUncompressedSize:524288e3,maxCompressionRatio:100};var import_node_fs8=__toESM(require("node:fs"),1),import_node_path11=__toESM(require("node:path"),1),import_promises6=require("node:stream/promises"),SlotUnknownError=class extends Error{constructor(){super("upload reference unknown or expired"),this.name="SlotUnknownError"}},SlotConsumedError=class extends Error{constructor(){super("upload reference already carries an upload"),this.name="SlotConsumedError"}},SizeMismatchError=class extends Error{constructor(received,declared){super(`upload size mismatch: received ${received} bytes, declared ${declared}`),this.name="SizeMismatchError"}},STAGED_FILE_NAME=/^[0-9a-f]+\.zip$/,UploadSlots=class{root;stagingPrefix;ttlMs;maxSize;slots=new Map;stagingDir;now;constructor(root5,stagingPrefix,ttlMs,maxSize,now=Date.now){this.root=root5,this.stagingPrefix=stagingPrefix,this.ttlMs=ttlMs,this.maxSize=maxSize,this.stagingDir=import_node_path11.default.join(root5,stagingPrefix),import_node_fs8.default.rmSync(this.stagingDir,{recursive:!0,force:!0}),import_node_fs8.default.mkdirSync(this.stagingDir,{recursive:!0,mode:448}),this.now=now}reserve(key,declaredSize){if(declaredSize<=0||declaredSize>this.maxSize)throw new Error(`declared size ${declaredSize} outside (0, ${this.maxSize}]`);if(this.stagePath(key),this.slots.has(key))throw new Error(`staging key ${key} is already reserved`);return this.sweep(),this.slots.set(key,{declaredSize,expiresAtMs:this.now()+this.ttlMs,uploaded:!1}),{ttlMs:this.ttlMs}}async receive(key,body){let slot=this.slots.get(key);if(slot===void 0||this.now()>slot.expiresAtMs)throw new SlotUnknownError;if(slot.uploaded)throw new SlotConsumedError;let declared=slot.declaredSize,filePath=this.stagePath(key),written=0;try{await import_node_fs8.default.promises.mkdir(import_node_path11.default.dirname(filePath),{recursive:!0,mode:448}),await(0,import_promises6.pipeline)(body,limitBytes(declared+1,n3=>{written+=n3}),import_node_fs8.default.createWriteStream(filePath,{flags:"w",mode:384}))}catch(error2){throw await import_node_fs8.default.promises.rm(filePath,{force:!0}),new Error(`failed to receive upload: ${error2 instanceof Error?error2.message:String(error2)}`)}if(written!==declared)throw await import_node_fs8.default.promises.rm(filePath,{force:!0}),new SizeMismatchError(written,declared);let current=this.slots.get(key);if(current===void 0||this.now()>current.expiresAtMs)throw await import_node_fs8.default.promises.rm(filePath,{force:!0}),new SlotUnknownError;current.uploaded=!0}sweep(){let nowMs=this.now();for(let[key,slot]of this.slots)nowMs>slot.expiresAtMs&&(this.slots.delete(key),import_node_fs8.default.rmSync(this.stagePath(key),{force:!0}))}stagePath(key){if(!key.startsWith(this.stagingPrefix))throw new Error(`staging key ${key} is outside ${this.stagingPrefix}`);let fileName=key.slice(this.stagingPrefix.length);if(!STAGED_FILE_NAME.test(fileName))throw new Error(`staging key ${key} does not name a staged archive`);return import_node_path11.default.join(this.root,key)}};function limitBytes(limit,onBytes){return async function*(source){let remaining=limit;for await(let chunk of source){if(remaining<=0)return;let slice=chunk.length<=remaining?chunk:chunk.subarray(0,remaining);remaining-=slice.length,onBytes(slice.length),yield slice}}}var ARTIFACT_BYTES_KEY="pushArtifactBytes";function newResolveArtifactSourceStep(staging,binding){return{name:"ResolveArtifactSource",async execute(ctx){let{artifact,artifactUploadRef}=binding.source(ctx.input);if(artifactUploadRef===""){ctx.set(ARTIFACT_BYTES_KEY,artifact);return}if(staging===void 0)throw failedPreconditionError(binding.laneNotConfigured);let data;try{data=await staging.consume(artifactUploadRef)}catch(error2){throw error2 instanceof SlotUnknownError?invalidArgumentError(`artifact_upload_ref not usable: ${error2.message} \u2014 request a new upload URL via createArtifactUploadUrl`):error2}ctx.set(ARTIFACT_BYTES_KEY,data)}}}function newArchiveCurrentVersionStep(store,logger2,binding){return{name:binding.stepName,async execute(ctx){let resource=ctx.get(binding.resourceKey),versionHash=binding.headHashOf(resource);if(versionHash==="")return;let tag2=binding.liveTagOf(resource),resourceId=metadataOf(resource)?.id??"",idField=`${binding.noun}Id`,alreadyArchived=!1;try{await store.getAuditByHash(ctx.apiResourceKind,resourceId,versionHash,binding.schema),alreadyArchived=!0}catch(error2){error2 instanceof AuditNotFoundError||logger2.warn(`Could not check for an existing archived ${binding.noun} version \u2014 archiving anyway`,{[idField]:resourceId,versionHash,error:error2 instanceof Error?error2.message:String(error2)})}if(!alreadyArchived)try{await store.saveAudit(ctx.apiResourceKind,resourceId,binding.schema,resource,versionHash,"")}catch(error2){logger2.error(`Failed to archive ${binding.noun} version \u2014 reverting the version hash to maintain the audit-resolvability invariant`,{[idField]:resourceId,versionHash,error:error2 instanceof Error?error2.message:String(error2)}),binding.clearHeadHash(resource);return}if(tag2!=="")try{await store.setAuditTag(ctx.apiResourceKind,resourceId,versionHash,tag2)}catch(error2){logger2.error(`Archived ${binding.noun} version but failed to assign its tag \u2014 clearing the live tag to stay consistent with the audit column`,{[idField]:resourceId,versionHash,tag:tag2,error:error2 instanceof Error?error2.message:String(error2)}),binding.clearLiveTag(resource)}alreadyArchived?logger2.info(`${capitalize(binding.noun)} version content already archived \u2014 repointed head without a new history row`,{[idField]:resourceId,versionHash,tag:tag2}):logger2.info(`Archived ${binding.noun} version to audit history`,{[idField]:resourceId,versionHash,tag:tag2})}}}function newDeleteVersionArchivesStep(store,logger2,binding){return{name:binding.stepName,async execute(ctx){let resourceId=ctx.get(RESOURCE_ID_KEY);if(typeof resourceId!="string")throw new Error("resource id not found in context (ExtractResourceIdStep must run first)");let idField=`${binding.noun}Id`;try{let deletedCount=await store.deleteAuditByResourceId(ctx.apiResourceKind,resourceId);deletedCount>0&&logger2.info(`Deleted archive records for ${binding.noun}`,{[idField]:resourceId,count:deletedCount})}catch(error2){logger2.warn(`failed to delete ${binding.noun} archives (best-effort)`,{[idField]:resourceId,error:error2 instanceof Error?error2.message:String(error2)})}}}}function capitalize(word){return word.charAt(0).toUpperCase()+word.slice(1)}var HASH_PATTERN=/^[a-f0-9]{64}$/;function isVersionHash(version){return HASH_PATTERN.test(version)}function newLoadByReferenceWithVersionStep(store,binding,stepName){return{name:stepName,async execute(ctx){let ref=ctx.input;if(ref.slug==="")throw invalidArgumentError("slug is required in reference");if(requireOrgForReference(ctx.apiResourceKind,ref.org),ref.kind!==ApiResourceKind.api_resource_kind_unknown&&ref.kind!==binding.kind)throw invalidArgumentError(`kind mismatch: expected ${ApiResourceKind[binding.kind]}, got ${ApiResourceKind[ref.kind]}`);let head;try{head=await findResourceBySlug(store,ctx.apiResourceKind,binding.schema,ref.slug,ref.org)}catch(error2){throw internalError(error2,`failed to list ${binding.noun}s`)}if(head===void 0)throw notFoundError(binding.noun,ref.slug);let version=ref.version.trim();if(version===""||version==="latest"){ctx.set(TARGET_RESOURCE_KEY,head);return}if(headMatchesVersion(binding,head,version)){ctx.set(TARGET_RESOURCE_KEY,head);return}let archived=await findAuditByVersion(store,ctx.apiResourceKind,binding.schema,idOf(head),version);if(archived===void 0)throw notFoundError(`${binding.noun} version`,`${ref.slug}:${version}`);ctx.set(TARGET_RESOURCE_KEY,archived)}}}function headMatchesVersion(binding,head,version){if(isVersionHash(version))return binding.headHashOf(head)===version;let liveTag=binding.liveTagOf(head);return liveTag!==""&&liveTag===version}async function findAuditByVersion(store,kind,schema2,resourceId,version){if(isVersionHash(version))try{return await store.getAuditByHash(kind,resourceId,version,schema2)}catch(error2){if(error2 instanceof AuditNotFoundError)return;throw internalError(error2,"failed to query audit by hash")}try{return await store.getAuditByTag(kind,resourceId,version,schema2)}catch(error2){if(error2 instanceof AuditNotFoundError)return;throw internalError(error2,"failed to query audit by tag")}}var DEFAULT_PAGE_SIZE=50,MAX_PAGE_SIZE=100,LIST_VERSIONS_RESOURCE_ID_KEY="listVersionsResourceId",LIST_VERSIONS_HEAD_HASH_KEY="listVersionsHeadHash",LIST_VERSIONS_RESPONSE_KEY="listVersionsResponse";function versionHistoryTarget(kind,deniedMessage,idKey=LIST_VERSIONS_RESOURCE_ID_KEY){return ctx=>{let resourceId=ctx.get(idKey);if(typeof resourceId!="string"||resourceId==="")throw new Error(`ListVersions: no resolved resource id under ${idKey}; the slug resolver must run first`);return[{permission:IamPermission.can_view,resourceKind:kind,resourceId,deniedMessage}]}}function newResolveBySlugForVersionsStep(store,binding,stepName){return{name:stepName,async execute(ctx){let req=binding.input(ctx.input),head;try{head=await findResourceBySlug(store,ctx.apiResourceKind,binding.schema,req.slug,req.org)}catch(error2){throw internalError(error2,`failed to search for ${binding.noun}`)}if(head===void 0)throw notFoundError(binding.noun,`${req.slug} (org: ${req.org})`);ctx.set(LIST_VERSIONS_RESOURCE_ID_KEY,idOf(head)),ctx.set(LIST_VERSIONS_HEAD_HASH_KEY,binding.headHashOf(head))}}}function newLoadAndMapVersionsStep(store,binding,stepName){return{name:stepName,async execute(ctx){let req=binding.input(ctx.input),resourceId=ctx.get(LIST_VERSIONS_RESOURCE_ID_KEY),records;try{records=await store.listAuditRecords(ctx.apiResourceKind,resourceId)}catch(error2){throw internalError(error2,"failed to load version history")}let headHash=ctx.get(LIST_VERSIONS_HEAD_HASH_KEY),currentMarked=!1,entries=[];for(let record2 of records){let snapshot;try{snapshot=fromBinary2(binding.schema,record2.data)}catch{continue}let isCurrent=!currentMarked&&headHash!==""&&binding.headHashOf(snapshot)===headHash;currentMarked=currentMarked||isCurrent,entries.push(binding.mapEntry(snapshot,isCurrent,record2.tag))}let pageSize=req.pageSize;pageSize<=0&&(pageSize=DEFAULT_PAGE_SIZE),pageSize>MAX_PAGE_SIZE&&(pageSize=MAX_PAGE_SIZE);let startIndex=0;req.pageToken!==""&&(startIndex=decodePageToken(req.pageToken));let pageEntries=[],nextPageToken="";if(startIndex<entries.length){let end=Math.min(startIndex+pageSize,entries.length);pageEntries=entries.slice(startIndex,end),end<entries.length&&(nextPageToken=Buffer.from(String(end)).toString("base64"))}ctx.set(LIST_VERSIONS_RESPONSE_KEY,binding.response(pageEntries,nextPageToken,entries.length))}}}function decodePageToken(token){let decoded=Buffer.from(token,"base64");if(decoded.toString("base64")!==token)throw invalidArgumentError("invalid page_token");let text2=decoded.toString("utf8"),index2=Number.parseInt(text2,10);if(!Number.isSafeInteger(index2)||String(index2)!==text2||index2<0)throw invalidArgumentError("invalid page_token");return index2}function idOf(resource){return metadataOf(resource)?.id??""}var PLUGIN_ARTIFACT_KEY_PREFIX="plugins/",VERSION_TAG_PATTERN=/^[a-zA-Z0-9._-]+$/,BUILT_IN_SUB_AGENT_NAMES=new Set(["explore","shell","general-purpose"]);var TRANSFER_LANE_NOT_CONFIGURED="plugin artifact transfer lane is not configured on this server",SERVER_WARNING_KINDS={componentIgnored:"component-ignored",memberAdopted:"member-adopted",modelHintUnresolved:"model-hint-unresolved",subAgentNameBuiltin:"sub-agent-name-builtin",versionNotTaggable:"version-not-taggable"};var MEMBER_KINDS=[{kind:ApiResourceKind.skill,schema:SkillSchema},{kind:ApiResourceKind.mcp_server,schema:McpServerSchema},{kind:ApiResourceKind.agent,schema:AgentSchema},{kind:ApiResourceKind.workflow,schema:WorkflowSchema}];function memberOf(kind,metadata){return{kind,id:metadata.id,slug:metadata.slug,name:metadata.name,version:metadata.labels[PLUGIN_VERSION_LABEL]??"",system:isSystemContent(metadata)}}async function findMembers(store,pluginId,org){let members=[];for(let{kind,schema:schema2}of MEMBER_KINDS){let raws=await store.findAllByLabel(kind,PLUGIN_LABEL,pluginId,schema2);for(let raw of raws){let metadata=metadataOf(fromBinary2(schema2,raw));metadata!==void 0&&metadata.org===org&&members.push(memberOf(kind,metadata))}}return members}async function slugHolder(store,planned,org){let entry=MEMBER_KINDS.find(candidate=>candidate.kind===planned.kind);if(entry===void 0)throw new Error(`kind ${ApiResourceKind[planned.kind]} is not a plugin member kind`);let existing=await findResourceBySlug(store,planned.kind,entry.schema,planned.slug,org),metadata=existing===void 0?void 0:metadataOf(existing);return metadata===void 0?{held:!1}:{held:!0,byPlugin:pluginIdOf(metadata),holder:memberOf(planned.kind,metadata)}}function judgeSlug(holder,planned,pluginId){return holder.held?holder.byPlugin===pluginId?{kind:"ours",holder:holder.holder}:holder.byPlugin!==void 0?{kind:"held-by-plugin",holder:holder.holder,pluginId:holder.byPlugin}:holder.holder.system&&planned.system?{kind:"adopt",holder:holder.holder}:{kind:"held-unmanaged",holder:holder.holder}:{kind:"free"}}function membersConverge(existing,planned,digest3){if(existing.length!==planned.length)return!1;let byKey=new Map(existing.map(member2=>[`${member2.kind}:${member2.slug}`,member2]));return planned.every(member2=>{let found=byKey.get(`${member2.kind}:${member2.slug}`);return found!==void 0&&found.version===digest3})}function droppedMembers(existing,planned){let keep=new Set(planned.map(member2=>`${member2.kind}:${member2.slug}`));return existing.filter(member2=>!keep.has(`${member2.kind}:${member2.slug}`))}var PLUGIN_DOCUMENT_LIMITS={manifest:262144,mcpConfig:262144,skillMd:1048576,subAgent:1048576,overlay:1048576,logo:1048576,marketplace:1048576},encoder5=new TextEncoder,decoder3=new TextDecoder("utf-8",{fatal:!1});function comparePaths(a5,b7){return a5<b7?-1:a5>b7?1:0}function decodeUtf8(bytes){let text2=decoder3.decode(bytes);return text2.charCodeAt(0)===65279?text2.slice(1):text2}function isContainedPath(path14){return path14===""||path14.startsWith("/")||path14.includes("\\")?!1:path14.split("/").every(segment=>segment!==""&&segment!=="."&&segment!=="..")}var GLOB_CHARACTERS=/[*?[\]{}]/;function resolveDeclaredPath(value){if(GLOB_CHARACTERS.test(value))return{ok:!1,kind:"path-glob-unsupported"};if(value==="."||value==="./")return{ok:!0,path:""};if(!value.startsWith("./"))return{ok:!1,kind:"path-not-relative"};let trimmed=value.slice(2).replace(/\/+$/,"");return trimmed===""?{ok:!0,path:""}:isContainedPath(trimmed)?{ok:!0,path:trimmed}:{ok:!1,kind:"path-escapes-root"}}function joinPath(dir,name){return dir===""?name:`${dir}/${name}`}function basename(path14){let slash=path14.lastIndexOf("/");return slash===-1?path14:path14.slice(slash+1)}function dirname(path14){let slash=path14.lastIndexOf("/");return slash===-1?"":path14.slice(0,slash)}var PluginFileIndex=class{files;byPath;constructor(files){this.files=files,this.byPath=new Map(files.entries.map(entry=>[entry.path,entry]))}has(path14){return this.byPath.has(path14)}entry(path14){return this.byPath.get(path14)}filesUnder(dir){if(dir==="")return this.files.entries.map(entry=>entry.path);let prefix=`${dir}/`;return this.files.entries.filter(entry=>entry.path.startsWith(prefix)).map(entry=>entry.path)}isDirectory(dir){if(dir==="")return this.files.entries.length>0;let prefix=`${dir}/`;return this.files.entries.some(entry=>entry.path.startsWith(prefix))}childDirectories(dir){let prefix=dir===""?"":`${dir}/`,names=new Set;for(let entry of this.files.entries){if(!entry.path.startsWith(prefix))continue;let rest=entry.path.slice(prefix.length),slash=rest.indexOf("/");slash!==-1&&names.add(rest.slice(0,slash))}return[...names].sort(comparePaths)}childFiles(dir){let prefix=dir===""?"":`${dir}/`,names=[];for(let entry of this.files.entries){if(!entry.path.startsWith(prefix))continue;let rest=entry.path.slice(prefix.length);rest.includes("/")||names.push(rest)}return names.sort(comparePaths)}};function readText(index2,path14,cls,findings){let bytes=readBytes(index2,path14,cls,findings);return bytes===void 0?void 0:decodeUtf8(bytes)}function readBytes(index2,path14,cls,findings){let limit=PLUGIN_DOCUMENT_LIMITS[cls],entry=index2.entry(path14);if(entry===void 0)throw new Error(`plugin file '${path14}' is not listed`);if(entry.size>limit){findings.error("document-too-large",{path:path14,subject:String(entry.size),detail:String(limit)});return}let bytes=index2.files.read(path14);if(bytes.length>limit){findings.error("document-too-large",{path:path14,subject:String(bytes.length),detail:String(limit)});return}return bytes}function parseJsonObject2(text2,path14,kind,findings){let value;try{value=JSON.parse(text2)}catch(error2){findings.error(kind,{path:path14,detail:error2 instanceof Error?error2.message:String(error2)});return}if(!isJsonObject2(value)){findings.error(kind,{path:path14,detail:"the document is not a JSON object"});return}return value}function isJsonObject2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStringArray(value){return Array.isArray(value)&&value.every(item=>typeof item=="string")}function isStringRecord(value){return isJsonObject2(value)&&Object.values(value).every(item=>typeof item=="string")}function describeValue(value){return typeof value=="string"?value:JSON.stringify(value)}function fields(object){return Object.entries(object)}function optionalString(object,field3,path14,findings){let value=object[field3];if(value!==void 0){if(typeof value!="string"){findings.error("manifest-field-type",{path:path14,subject:field3,detail:"a string"});return}return value}}function optionalStringArray(object,field3,path14,findings){let value=object[field3];if(value!==void 0){if(!isStringArray(value)){findings.error("manifest-field-type",{path:path14,subject:field3,detail:"an array of strings"});return}return value}}function stringOrStringArray(object,field3,path14,findings){let value=object[field3];if(value!==void 0){if(typeof value=="string")return[value];if(isStringArray(value))return value;findings.error("manifest-field-type",{path:path14,subject:field3,detail:"a string or an array of strings"})}}function warnUnknownFields(object,known,path14,findings){for(let[name]of fields(object))known.has(name)||findings.warn("manifest-field-unknown",{path:path14,subject:name})}function readIdentity(object,path14,findings){let identity2={},name=optionalString(object,"name",path14,findings);name!==void 0&&(identity2.name=name);let version=optionalString(object,"version",path14,findings);version!==void 0&&(identity2.version=version);let description=optionalString(object,"description",path14,findings);description!==void 0&&(identity2.description=description);let homepage=optionalString(object,"homepage",path14,findings);homepage!==void 0&&(identity2.homepage=homepage);let repository=optionalString(object,"repository",path14,findings);repository!==void 0&&(identity2.repository=repository);let license=optionalString(object,"license",path14,findings);license!==void 0&&(identity2.license=license);let keywords=optionalStringArray(object,"keywords",path14,findings);keywords!==void 0&&(identity2.keywords=keywords);let author=readAuthor(object,path14,findings);return author!==void 0&&(identity2.author=author),identity2}function readAuthor(object,path14,findings){let value=object.author;if(value===void 0)return;if(!isJsonObject2(value)){findings.error("manifest-field-type",{path:path14,subject:"author",detail:"an object"});return}let author={},name=optionalString(value,"name",path14,findings);name!==void 0&&(author.name=name);let email=optionalString(value,"email",path14,findings);email!==void 0&&(author.email=email);let url=optionalString(value,"url",path14,findings);return url!==void 0&&(author.url=url),author}function readDeclaredPaths(object,field3,path14,findings){let values=stringOrStringArray(object,field3,path14,findings);if(values===void 0)return;let declared=[];for(let value of values){let resolved=resolveDeclaredPath(value);if(!resolved.ok){findings.error(resolved.kind,{path:path14,subject:value});continue}declared.push({path:resolved.path,manifest:path14})}return declared}function readMcpSources(object,field3,path14,dialect,findings){let value=object[field3];if(value===void 0)return[];let items=Array.isArray(value)?value:[value],sources=[];for(let item of items)if(typeof item=="string"){let resolved=resolveDeclaredPath(item);if(!resolved.ok){findings.error(resolved.kind,{path:path14,subject:item});continue}sources.push({kind:"file",path:resolved.path,dialect,manifest:path14})}else isJsonObject2(item)?sources.push({kind:"inline",manifest:path14,servers:item,dialect}):findings.error("manifest-field-type",{path:path14,subject:field3,detail:"a path, an object, or an array of either"});return sources}var IGNORED_FIELD_KINDS={hooks:"hooks",rules:"rules",commands:"commands",workflows:"workflows",outputStyles:"output-styles",lspServers:"lsp-servers",channels:"channels",dependencies:"dependencies",defaultEnabled:"default-enabled",minClientVersions:"min-client-versions",logo:"logo",apps:"apps"};function ignoredFieldComponents(object,path14){let ignored=[];for(let[name,value]of fields(object)){let kind=IGNORED_FIELD_KINDS[name];if(kind!==void 0&&ignored.push({kind,path:`${path14}#${name}`}),name==="experimental"&&isJsonObject2(value))for(let[sub]of fields(value)){let subKind=EXPERIMENTAL_KINDS[sub];subKind!==void 0&&ignored.push({kind:subKind,path:`${path14}#experimental.${sub}`})}}return ignored}var EXPERIMENTAL_KINDS={themes:"themes",monitors:"monitors",evals:"evals"},STIGMER_EXTENSION_NAMESPACE="ai.stigmer",STIGMER_EXTENSION_FIELDS=new Set(["displayName","logo","category"]);function extensionComponents(object,path14,findings){let value=object.extensions;if(value===void 0)return[];if(!isJsonObject2(value))return findings.warn("manifest-extensions-invalid",{path:path14}),[];let ignored=[];for(let[namespace,content]of fields(value)){if(isJsonObject2(content)&&fields(content).length===0)continue;let at2=`${path14}#extensions.${namespace}`;if(namespace===STIGMER_EXTENSION_NAMESPACE&&isJsonObject2(content)){content.logo!==void 0&&ignored.push({kind:"logo",path:`${at2}.logo`}),fields(content).some(([name])=>!STIGMER_EXTENSION_FIELDS.has(name))&&ignored.push({kind:"extension",path:at2});continue}ignored.push({kind:"extension",path:at2})}return ignored}var CLAUDE_KNOWN_FIELDS=new Set(["name","version","description","author","homepage","repository","license","keywords","skills","commands","agents","workflows","hooks","mcpServers","outputStyles","lspServers","experimental","userConfig","channels","dependencies","defaultEnabled"]),CLAUDE_DEFAULT_MCP_CONFIG=".mcp.json";function readClaudeManifest(object,path14,findings){return readClaudeShapedManifest(object,path14,"claude",CLAUDE_KNOWN_FIELDS,findings)}function readClaudeShapedManifest(object,path14,dialect,known,findings){warnUnknownFields(object,known,path14,findings);let identity2=readIdentity(object,path14,findings),skillPaths=readDeclaredPaths(object,"skills",path14,findings)??[],agentPaths=readDeclaredPaths(object,"agents",path14,findings),declaredMcp=readMcpSources(object,"mcpServers",path14,dialect,findings),manifest={dialect,path:path14,identity:identity2,skillPaths,mcpConfigs:declaredMcp,ignored:ignoredFieldComponents(object,path14)};return agentPaths!==void 0&&(manifest.agentPaths=agentPaths),object.userConfig!==void 0&&(manifest.variables={dialect:"claude",value:object.userConfig,manifest:path14}),manifest}var KNOWN_FIELDS=new Set([...CLAUDE_KNOWN_FIELDS,"apps","interface"]);function readCodexManifest(object,path14,findings){return readClaudeShapedManifest(object,path14,"codex",KNOWN_FIELDS,findings)}var KNOWN_FIELDS2=new Set(["name","displayName","description","version","minClientVersions","author","publisher","homepage","repository","license","logo","keywords","category","tags","commands","agents","skills","rules","hooks","variables","mcpServers"]);function readCursorManifest(object,path14,findings){warnUnknownFields(object,KNOWN_FIELDS2,path14,findings);let identity2=readIdentity(object,path14,findings),skillPaths=readDeclaredPaths(object,"skills",path14,findings)??[],agentPaths=readDeclaredPaths(object,"agents",path14,findings),manifest={dialect:"cursor",path:path14,identity:identity2,skillPaths,mcpConfigs:readMcpSources(object,"mcpServers",path14,"cursor",findings),ignored:ignoredFieldComponents(object,path14)};return agentPaths!==void 0&&(manifest.agentPaths=agentPaths),object.variables!==void 0&&(manifest.variables={dialect:"cursor",value:object.variables,manifest:path14}),manifest}var AGENT_PLUGINS_MANIFEST_SCHEMA="https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",AGENT_PLUGINS_MCP_SCHEMA="https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",MANIFEST_LOCATIONS={"agent-plugins":"plugin.json",claude:".claude-plugin/plugin.json",cursor:".cursor-plugin/plugin.json",codex:".codex-plugin/plugin.json"},q3=value=>`'${value??""}'`,at=path14=>path14===void 0?"":` in ${q3(path14)}`,ERROR_MESSAGES={"no-manifest":()=>`no plugin manifest found: expected one of ${Object.values(MANIFEST_LOCATIONS).map(p3=>q3(p3)).join(", ")}`,"manifest-unreadable":c5=>`manifest ${q3(c5.path)} is not valid JSON: ${c5.detail??"parse error"}`,"manifest-schema-missing":c5=>`manifest ${q3(c5.path)} is missing the required '$schema' field; an Agent Plugins manifest declares ${q3(AGENT_PLUGINS_MANIFEST_SCHEMA)}`,"manifest-schema-unsupported":c5=>`manifest ${q3(c5.path)} declares an unsupported '$schema' ${q3(c5.detail)}; this reader supports ${q3(AGENT_PLUGINS_MANIFEST_SCHEMA)}`,"manifest-name-missing":c5=>`manifest ${q3(c5.path)} is missing the required 'name' field`,"manifest-name-invalid":c5=>`plugin name ${q3(c5.subject)}${at(c5.path)} is invalid: 1 to 64 characters of lowercase letters, digits, hyphens and periods, starting and ending alphanumeric, with no '--' or '..'`,"manifest-name-conflict":c5=>`manifests disagree on the plugin name: ${q3(c5.subject)} in ${q3(c5.path)} versus ${c5.detail??"another manifest"}`,"manifest-field-type":c5=>`field ${q3(c5.subject)}${at(c5.path)} has the wrong type: expected ${c5.detail??"a different type"}`,"path-not-relative":c5=>`path ${q3(c5.subject)}${at(c5.path)} must be plugin-relative and begin with './'`,"path-escapes-root":c5=>`path ${q3(c5.subject)}${at(c5.path)} escapes the plugin root`,"path-glob-unsupported":c5=>`path ${q3(c5.subject)}${at(c5.path)} is a glob pattern; declare directories and files by path`,"path-uncontained":c5=>`the reader listed a path outside the plugin root: ${q3(c5.path)}`,"document-too-large":c5=>`${q3(c5.path)} is ${c5.subject??"too many"} bytes, over the ${c5.detail??""}-byte limit for this kind of document`,"skill-frontmatter-missing":c5=>`${q3(c5.path)} must start with YAML frontmatter ('---')`,"skill-frontmatter-unclosed":c5=>`${q3(c5.path)} frontmatter is not closed (missing the closing '---')`,"skill-frontmatter-unreadable":c5=>`${q3(c5.path)} frontmatter is not valid YAML: ${c5.detail??"parse error"}`,"skill-name-invalid":c5=>`skill name ${q3(c5.subject)}${at(c5.path)} is invalid: lowercase letters, digits and hyphens, optionally dot-scoped, with every segment alphanumeric`,"skill-name-duplicate":c5=>`skill name ${q3(c5.subject)} appears more than once (again${at(c5.path)})`,"mcp-config-unreadable":c5=>`MCP configuration ${q3(c5.path)} is not valid JSON: ${c5.detail??"parse error"}`,"mcp-config-shape":c5=>`MCP configuration ${q3(c5.path)} must be an object with an 'mcpServers' object`,"mcp-config-schema-missing":c5=>`MCP configuration ${q3(c5.path)} is missing the required '$schema' field; an Agent Plugins configuration declares ${q3(AGENT_PLUGINS_MCP_SCHEMA)}`,"mcp-config-schema-unsupported":c5=>`MCP configuration ${q3(c5.path)} declares an unsupported '$schema' ${q3(c5.detail)}; this reader supports ${q3(AGENT_PLUGINS_MCP_SCHEMA)}`,"mcp-config-field-unknown":c5=>`MCP configuration ${q3(c5.path)} has an unexpected top-level field ${q3(c5.subject)}; only '$schema' and 'mcpServers' are allowed`,"mcp-server-shape":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} must be an object`,"mcp-server-type-missing":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} is missing the 'type' field the Agent Plugins format requires ('stdio', 'streamable-http' or 'sse')`,"mcp-server-transport-unknown":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has no 'type' and neither a 'command' nor a 'url' to infer it from`,"mcp-server-type-ambiguous":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} declares both 'command' and 'url'; a server is either stdio or HTTP`,"mcp-server-type-unknown":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has an unknown 'type' ${q3(c5.detail)}; expected 'stdio', 'http', 'streamable-http' or 'sse'`,"mcp-server-field-unknown":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has a field ${q3(c5.detail)} that its transport does not define`,"mcp-server-field-type":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} field ${q3(c5.detail)} has the wrong type`,"mcp-server-url-missing":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} is missing the 'url' its HTTP transport requires`,"mcp-server-url-invalid":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has an invalid 'url' ${q3(c5.detail)}: expected an absolute HTTPS URL (HTTP only for localhost) with no user information or fragment`,"mcp-server-url-variable":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has a variable in its 'url'; Stigmer sends the URL as written, so write the URL out and put variables in 'headers'`,"mcp-server-command-missing":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} is missing the 'command' its stdio transport requires`,"mcp-server-command-invalid":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has a 'command' that is not a single executable name; put arguments in 'args'`,"mcp-server-command-relative":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} runs a command bundled in the plugin ${q3(c5.detail)}; Stigmer runs only commands on the runner's PATH (for example 'npx' or 'uvx')`,"mcp-server-plugin-root-reference":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} references the plugin's own files through ${q3(c5.detail)}; Stigmer does not mount plugin files into the runner`,"mcp-server-cwd-unsupported":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} sets a working directory; Stigmer does not mount plugin files, so a bundled directory cannot be reached`,"mcp-server-env-literal":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} sets environment variable ${q3(c5.detail)} to a literal value; Stigmer passes declared variables by name, so write ${q3(`${c5.detail??"KEY"}: "\${${c5.detail??"KEY"}}"`)} and declare the variable`,"mcp-server-env-rename":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} maps environment variable ${q3(c5.detail)} to a differently named variable; Stigmer passes declared variables by name, so use the same name on both sides`,"mcp-server-name-duplicate":c5=>`MCP server name ${q3(c5.subject)} appears more than once (again${at(c5.path)})`,"mcp-server-header-duplicate":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} declares header ${q3(c5.detail)} more than once (header names are case-insensitive)`,"mcp-server-header-invalid":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has an invalid header name ${q3(c5.detail)}`,"sub-agent-frontmatter-unreadable":c5=>`${q3(c5.path)} frontmatter is not valid YAML: ${c5.detail??"parse error"}`,"sub-agent-instructions-short":c5=>`sub-agent ${q3(c5.subject)}${at(c5.path)} has instructions under ${c5.detail??""} characters; the body of the file is the sub-agent's prompt`,"sub-agent-name-duplicate":c5=>`sub-agent name ${q3(c5.subject)} appears more than once (again${at(c5.path)})`,"variable-name-invalid":c5=>`variable name ${q3(c5.subject)}${at(c5.path)} is invalid: an environment variable name is letters, digits and underscores, not starting with a digit`,"overlay-server-unknown":c5=>`${q3(c5.path)} overlays MCP server ${q3(c5.subject)}, which the plugin does not declare`,"overlay-document-unknown":c5=>`${q3(c5.path)} is not a document Stigmer reads; the 'ai.stigmer/' folder holds 'agent.yaml', 'workflows/<name>.yaml' and 'mcp-servers/<server>.yaml'`},WARNING_MESSAGES={"manifest-field-unknown":c5=>`manifest ${q3(c5.path)} has an unknown field ${q3(c5.subject)}, ignored`,"manifest-extensions-invalid":c5=>`manifest ${q3(c5.path)} has an 'extensions' field that is not an object, ignored`,"path-missing":c5=>`path ${q3(c5.subject)} declared${at(c5.path)} does not exist in the plugin`,"skill-name-defaulted":c5=>`${q3(c5.path)} has no 'name' in its frontmatter; the skill is named after its directory, ${q3(c5.subject)}`,"skill-name-differs-from-directory":c5=>`skill ${q3(c5.subject)}${at(c5.path)} is named differently from its directory ${q3(c5.detail)}`,"skill-description-missing":c5=>`skill ${q3(c5.subject)}${at(c5.path)} has no 'description'`,"mcp-config-field-ignored":c5=>`MCP configuration ${q3(c5.path)} has a top-level field ${q3(c5.subject)} Stigmer does not read, ignored`,"mcp-server-sse-mapped":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} declares the legacy 'sse' transport; Stigmer connects over Streamable HTTP and falls back to SSE only when the server rejects it`,"mcp-server-field-ignored":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has a field ${q3(c5.detail)} Stigmer does not read, ignored`,"mcp-server-auth-ignored":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has an 'auth' block Stigmer does not read; OAuth for a server is declared in 'ai.stigmer/mcp-servers/${c5.subject??"<server>"}.yaml'`,"variable-inferred":c5=>`variable ${q3(c5.subject)} is referenced by MCP server ${q3(c5.detail)} but not declared; it is declared as a required secret`,"variable-unreferenced":c5=>`variable ${q3(c5.subject)}${at(c5.path)} is declared but no MCP server references it`,"variable-default-dropped":c5=>`variable ${q3(c5.subject)}${at(c5.path)} has a default value, which Stigmer does not carry; the user supplies the value`,"variable-type-narrowed":c5=>`variable ${q3(c5.subject)}${at(c5.path)} is typed ${q3(c5.detail)}; Stigmer variables are strings`,"variable-option-dropped":c5=>`variable ${q3(c5.subject)}${at(c5.path)} has a ${q3(c5.detail)} constraint, which Stigmer does not carry`,"sub-agent-name-defaulted":c5=>`${q3(c5.path)} has no 'name' in its frontmatter; the sub-agent is named after the file, ${q3(c5.subject)}`,"sub-agent-skill-unknown":c5=>`sub-agent ${q3(c5.subject)}${at(c5.path)} asks for skill ${q3(c5.detail)}, which the plugin does not ship`,"sub-agent-model-unknown":c5=>`sub-agent ${q3(c5.subject)}${at(c5.path)} names model ${q3(c5.detail)}, which Stigmer cannot map; the sub-agent runs on the session's model`,"sub-agent-field-ignored":c5=>`sub-agent ${q3(c5.subject)}${at(c5.path)} has a field ${q3(c5.detail)} Stigmer does not read, ignored`};var FindingCollector=class{errorSentences;warningSentences;errors=[];warnings=[];constructor(errorSentences,warningSentences){this.errorSentences=errorSentences,this.warningSentences=warningSentences}error(kind,ctx={}){this.errors.push(compose(kind,ctx,this.errorSentences[kind](ctx)))}warn(kind,ctx={}){this.warnings.push(compose(kind,ctx,this.warningSentences[kind](ctx)))}},Findings=class extends FindingCollector{constructor(){super(ERROR_MESSAGES,WARNING_MESSAGES)}};function compose(kind,ctx,message6){return{kind,...ctx.path!==void 0&&{path:ctx.path},...ctx.subject!==void 0&&{subject:ctx.subject},...ctx.detail!==void 0&&{detail:ctx.detail},message:message6}}var KNOWN_FIELDS3=new Set(["$schema","name","version","description","author","homepage","repository","license","keywords","extensions"]);function readOpenManifest(object,path14,findings){let schema2=object.$schema;return schema2===void 0?findings.error("manifest-schema-missing",{path:path14}):schema2!==AGENT_PLUGINS_MANIFEST_SCHEMA&&findings.error("manifest-schema-unsupported",{path:path14,detail:describeValue(schema2)}),warnUnknownFields(object,KNOWN_FIELDS3,path14,findings),{dialect:"agent-plugins",path:path14,identity:readIdentity(object,path14,findings),skillPaths:[],mcpConfigs:[],ignored:extensionComponents(object,path14,findings)}}var OPEN_MCP_CONFIG="mcp.json",VENDOR_PRECEDENCE=["claude","cursor","codex"],MANIFEST_PRECEDENCE=["agent-plugins",...VENDOR_PRECEDENCE],NAME_MAX_LENGTH=64,NAME_PATTERN=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/;function detectManifests(index2,findings){let manifests=[],present=dialect=>{let path14=MANIFEST_LOCATIONS[dialect];if(!index2.has(path14))return;let object=readManifestObject(index2,path14,findings),manifest=object===void 0?emptyManifest(dialect,path14):readDialect(dialect,object,path14,findings);return manifests.push(manifest),manifest},root5=present("agent-plugins"),vendors=VENDOR_PRECEDENCE.map(present).filter(m3=>m3!==void 0);if(manifests.length===0){findings.error("no-manifest");return}let identity2=root5??vendors[0];if(identity2===void 0)throw new Error("manifest set without an identity manifest");let ordered=[identity2,...manifests.filter(m3=>m3!==identity2)],name=resolveName(identity2,ordered,findings);return{dialect:identity2.dialect,manifests:ordered,name,readsAgents:vendors.length>0,mcpSources:resolveMcpSources(index2,root5,vendors)}}function readManifestObject(index2,path14,findings){let text2=readText(index2,path14,"manifest",findings);return text2===void 0?void 0:parseJsonObject2(text2,path14,"manifest-unreadable",findings)}function readDialect(dialect,object,path14,findings){switch(dialect){case"agent-plugins":return readOpenManifest(object,path14,findings);case"claude":return readClaudeManifest(object,path14,findings);case"cursor":return readCursorManifest(object,path14,findings);case"codex":return readCodexManifest(object,path14,findings);default:{let exhaustive=dialect;throw new Error(`unknown dialect ${String(exhaustive)}`)}}}function emptyManifest(dialect,path14){return{dialect,path:path14,identity:{},skillPaths:[],mcpConfigs:[],ignored:[]}}function resolveName(identity2,all,findings){let name=identity2.identity.name;if(name===void 0){if(findings.errors.some(f5=>f5.kind==="manifest-unreadable"&&f5.path===identity2.path))return;findings.error("manifest-name-missing",{path:identity2.path});return}let valid=!0;isValidPluginName(name)||(findings.error("manifest-name-invalid",{path:identity2.path,subject:name}),valid=!1);for(let other of all){if(other===identity2)continue;let otherName=other.identity.name;otherName!==void 0&&otherName!==name&&(findings.error("manifest-name-conflict",{path:identity2.path,subject:name,detail:`'${otherName}' in '${other.path}'`}),valid=!1)}return valid?name:void 0}function isValidPluginName(name){return name.length<=NAME_MAX_LENGTH&&NAME_PATTERN.test(name)&&!name.includes("--")&&!name.includes("..")}function resolveMcpSources(index2,root5,vendors){let sources=[];root5!==void 0&&index2.has(OPEN_MCP_CONFIG)&&sources.push({kind:"file",path:OPEN_MCP_CONFIG,dialect:"agent-plugins",manifest:root5.path});for(let vendor of vendors)vendor.mcpConfigs.length>0?sources.push(...vendor.mcpConfigs):vendor.dialect!=="cursor"&&index2.has(CLAUDE_DEFAULT_MCP_CONFIG)&&sources.push({kind:"file",path:CLAUDE_DEFAULT_MCP_CONFIG,dialect:vendor.dialect,manifest:vendor.path});let seen=new Set;return sources.filter(source=>source.kind==="inline"?!0:seen.has(source.path)?!1:(seen.add(source.path),!0))}var import_yaml=__toESM(require_dist2(),1);var SKILL_NAME_PATTERN=/^[a-z0-9]+([.-][a-z0-9]+)*$/;function extractFrontmatter(content){let lines=content.split(/\r?\n/);if(lines.length===0||lines[0]?.trim()!=="---")return{ok:!1,reason:"missing"};for(let i6=1;i6<lines.length;i6++)if(lines[i6]?.trim()==="---")return{ok:!0,yaml:lines.slice(1,i6).join(`
488
+ `);return}let headers2={"Content-Length":String(info.size)},downloadName=url.searchParams.get(LOCAL_DOWNLOAD_QUERY_PARAM)??"";if(downloadName!==""&&(headers2["Content-Disposition"]=contentDispositionAttachment(downloadName)),res.writeHead(200,headers2),req.method==="HEAD"){res.end();return}let stream=(0,import_node_fs7.createReadStream)(filePath);stream.on("error",error2=>{logger2.error("artifact file stream failed",{key,error:error2.message}),res.destroy()}),stream.pipe(res)}catch(error2){logger2.error("artifact file server request failed",{error:error2 instanceof Error?error2.message:String(error2)}),res.headersSent||res.writeHead(500),res.end()}}async function warnOnLegacyArtifactLayout(basePath,logger2){for(let sub of["attachments","artifacts"]){let legacy=import_node_path10.default.join(basePath,"artifacts",sub);try{if((await(0,import_promises5.stat)(legacy)).isDirectory()){logger2.warn("Detected artifacts under a pre-#285 layout at <base>/artifacts/*. The artifact root is now <base> itself. Move <base>/artifacts/* up into <base> (or set ARTIFACT_LOCAL_BASE_PATH to the old <base>/artifacts) so existing artifacts remain reachable.",{legacyDir:import_node_path10.default.join(basePath,"artifacts"),artifactRoot:basePath});return}}catch{}}}var file_ai_stigmer_agentic_channelapp_v1_command=fileDesc("Ci5haS9zdGlnbWVyL2FnZW50aWMvY2hhbm5lbGFwcC92MS9jb21tYW5kLnByb3RvEiBhaS5zdGlnbWVyLmFnZW50aWMuY2hhbm5lbGFwcC52MTKOBQobQ2hhbm5lbEFwcENvbW1hbmRDb250cm9sbGVyEmMKBWFwcGx5EiwuYWkuc3RpZ21lci5hZ2VudGljLmNoYW5uZWxhcHAudjEuQ2hhbm5lbEFwcBosLmFpLnN0aWdtZXIuYWdlbnRpYy5jaGFubmVsYXBwLnYxLkNoYW5uZWxBcHAStQEKBmNyZWF0ZRIsLmFpLnN0aWdtZXIuYWdlbnRpYy5jaGFubmVsYXBwLnYxLkNoYW5uZWxBcHAaLC5haS5zdGlnbWVyLmFnZW50aWMuY2hhbm5lbGFwcC52MS5DaGFubmVsQXBwIk/CuBhLCB8QHiIMbWV0YWRhdGEub3JnKjd1bmF1dGhvcml6ZWQgdG8gY3JlYXRlIGNoYW5uZWwgYXBwIGluIHRoaXMgb3JnYW5pemF0aW9uEp8BCgZ1cGRhdGUSLC5haS5zdGlnbWVyLmFnZW50aWMuY2hhbm5lbGFwcC52MS5DaGFubmVsQXBwGiwuYWkuc3RpZ21lci5hZ2VudGljLmNoYW5uZWxhcHAudjEuQ2hhbm5lbEFwcCI5wrgYNQgCEDAiC21ldGFkYXRhLmlkKiJ1bmF1dGhvcml6ZWQgdG8gdXBkYXRlIGNoYW5uZWwgYXBwEqkBCgZkZWxldGUSNi5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VEZWxldGVJbnB1dBosLmFpLnN0aWdtZXIuYWdlbnRpYy5jaGFubmVsYXBwLnYxLkNoYW5uZWxBcHAiOcK4GDUIAxAwIgtyZXNvdXJjZV9pZCoidW5hdXRob3JpemVkIHRvIGRlbGV0ZSBjaGFubmVsIGFwcBoEoP8rMGIGcHJvdG8z",[file_ai_stigmer_agentic_channelapp_v1_api,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),ChannelAppCommandController=serviceDesc(file_ai_stigmer_agentic_channelapp_v1_command,0);var file_ai_stigmer_agentic_channelapp_v1_io=fileDesc("CilhaS9zdGlnbWVyL2FnZW50aWMvY2hhbm5lbGFwcC92MS9pby5wcm90bxIgYWkuc3RpZ21lci5hZ2VudGljLmNoYW5uZWxhcHAudjEiTAoLQ2hhbm5lbEFwcHMSPQoHZW50cmllcxgBIAMoCzIsLmFpLnN0aWdtZXIuYWdlbnRpYy5jaGFubmVsYXBwLnYxLkNoYW5uZWxBcHAiMQoZTGlzdENoYW5uZWxBcHBzQnlPcmdJbnB1dBIUCgNvcmcYASABKAlCB7pIBHICEAFiBnByb3RvMw",[file_ai_stigmer_agentic_channelapp_v1_api,file_buf_validate_validate]),ChannelAppsSchema=messageDesc2(file_ai_stigmer_agentic_channelapp_v1_io,0);var file_ai_stigmer_agentic_channelapp_v1_query=fileDesc("CixhaS9zdGlnbWVyL2FnZW50aWMvY2hhbm5lbGFwcC92MS9xdWVyeS5wcm90bxIgYWkuc3RpZ21lci5hZ2VudGljLmNoYW5uZWxhcHAudjEy9gMKGUNoYW5uZWxBcHBRdWVyeUNvbnRyb2xsZXISlQEKA2dldBItLmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZUlkGiwuYWkuc3RpZ21lci5hZ2VudGljLmNoYW5uZWxhcHAudjEuQ2hhbm5lbEFwcCIxwrgYLQgBEDAiBXZhbHVlKiB1bmF1dGhvcml6ZWQgdG8gdmlldyBjaGFubmVsIGFwcBJ6Cg5nZXRCeVJlZmVyZW5jZRI0LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVJlZmVyZW5jZRosLmFpLnN0aWdtZXIuYWdlbnRpYy5jaGFubmVsYXBwLnYxLkNoYW5uZWxBcHAiBNC4GAESvgEKCWxpc3RCeU9yZxI7LmFpLnN0aWdtZXIuYWdlbnRpYy5jaGFubmVsYXBwLnYxLkxpc3RDaGFubmVsQXBwc0J5T3JnSW5wdXQaLS5haS5zdGlnbWVyLmFnZW50aWMuY2hhbm5lbGFwcC52MS5DaGFubmVsQXBwcyJFwrgYQQgBEB4iA29yZyo2dW5hdXRob3JpemVkIHRvIGxpc3QgY2hhbm5lbCBhcHBzIGluIHRoaXMgb3JnYW5pemF0aW9uGgSg/yswYgZwcm90bzM",[file_ai_stigmer_agentic_channelapp_v1_api,file_ai_stigmer_agentic_channelapp_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),ChannelAppQueryController=serviceDesc(file_ai_stigmer_agentic_channelapp_v1_query,0);async function destroySecretBackingState(secretService,logger2,fields2,storedValues){for(let storedValue of storedValues)if(storedValue!=="")try{await secretService.delete(storedValue)}catch(error2){logger2.error("secret backing-state destruction failed after persist \u2014 external state may be orphaned",{...fields2,error:error2 instanceof Error?error2.message:String(error2)})}}function newDestroySecretBackingStateStep(secretService,logger2,extractSecretValues){return{name:"DestroySecretBackingState",async execute(ctx){let deleted=ctx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)return;let metadata=deleted.metadata;await destroySecretBackingState(secretService,logger2,{kind:getKindName(ctx.apiResourceKind),resourceId:metadata?.id??""},extractSecretValues(deleted))}}}var REDACTED_MARKER2="***REDACTED***";function plaintextRequiredMessage(fieldName){return`${fieldName} must be plaintext \u2014 values carrying the 'enc:' encryption prefix are not accepted from clients`}function markerOnCreateMessage(fieldName){return`cannot use the redaction marker as ${fieldName} on create`}function noExistingSecretMessage(fieldName){return`cannot preserve ${fieldName}: no existing secret value found`}var PROVIDER_IMMUTABLE_MESSAGE="the provider of a channel app cannot be changed";function deleteBlockedByChannelMessage(org,slug,channelName){return`cannot delete ChannelApp '${org}/${slug}': referenced by agent channel '${channelName}'`}function redactChannelApp(app){let provider=app.spec?.providerConfig;switch(provider?.case){case"slack":redactSlack(provider.value);return;case"whatsapp":redactWhatsApp(provider.value);return;case void 0:return;default:{let exhaustive=provider;throw new Error(`unhandled provider arm: ${String(exhaustive)}`)}}}function redactSlack(slack){slack.clientSecret!==""&&(slack.clientSecret=REDACTED_MARKER2),slack.signingSecret!==""&&(slack.signingSecret=REDACTED_MARKER2)}function redactWhatsApp(whatsapp){whatsapp.appSecret!==""&&(whatsapp.appSecret=REDACTED_MARKER2),whatsapp.accessToken!==""&&(whatsapp.accessToken=REDACTED_MARKER2),whatsapp.verifyToken!==""&&(whatsapp.verifyToken=REDACTED_MARKER2)}function secretValuesOfChannelApp(app){let provider=app.spec?.providerConfig;switch(provider?.case){case"slack":return[provider.value.clientSecret,provider.value.signingSecret];case"whatsapp":return[provider.value.appSecret,provider.value.accessToken,provider.value.verifyToken];case void 0:return[];default:{let exhaustive=provider;throw new Error(`unhandled provider arm: ${String(exhaustive)}`)}}}function newEncryptChannelAppSecretsForCreateStep(secretService,logger2){return newEncryptChannelAppSecretsStep(secretService,logger2,!0)}function newEncryptChannelAppSecretsForUpdateStep(secretService,logger2){return newEncryptChannelAppSecretsStep(secretService,logger2,!1)}function newEncryptChannelAppSecretsStep(secretService,logger2,isCreate){async function resolveSecret(ctx,fieldName,requestValue,readExisting){if(requestValue==="")return requestValue;if(requestValue===REDACTED_MARKER2)return preserveExistingSecret2(ctx,fieldName,readExisting);if(isCiphertextShaped(requestValue))throw invalidArgumentError(plaintextRequiredMessage(fieldName));if(!secretService.isEnabled())return logger2.warn(`Encryption disabled: ${fieldName} will be stored in plaintext`),requestValue;try{return await secretService.encrypt(requestValue,EncryptionScope.forOrganization(ctx.newState.metadata?.org??""))}catch(error2){throw internalError(error2,`failed to encrypt ${fieldName}`)}}function preserveExistingSecret2(ctx,fieldName,readExisting){if(isCreate)throw invalidArgumentError(markerOnCreateMessage(fieldName));let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)throw internalError(new Error("existing resource not loaded"),`cannot preserve ${fieldName}: existing resource not loaded`);let existingSecret=readExisting(existing);if(existingSecret==="")throw invalidArgumentError(noExistingSecretMessage(fieldName));return existingSecret}return{name:"EncryptChannelAppSecrets",async execute(ctx){let provider=ctx.newState.spec?.providerConfig;switch(provider?.case){case"slack":{let slack=provider.value;slack.clientSecret=await resolveSecret(ctx,"client_secret",slack.clientSecret,existing=>existing.spec?.providerConfig.case==="slack"?existing.spec.providerConfig.value.clientSecret:""),slack.signingSecret=await resolveSecret(ctx,"signing_secret",slack.signingSecret,existing=>existing.spec?.providerConfig.case==="slack"?existing.spec.providerConfig.value.signingSecret:"");return}case"whatsapp":{let whatsapp=provider.value;whatsapp.appSecret=await resolveSecret(ctx,"app_secret",whatsapp.appSecret,existing=>existing.spec?.providerConfig.case==="whatsapp"?existing.spec.providerConfig.value.appSecret:""),whatsapp.accessToken=await resolveSecret(ctx,"access_token",whatsapp.accessToken,existing=>existing.spec?.providerConfig.case==="whatsapp"?existing.spec.providerConfig.value.accessToken:""),whatsapp.verifyToken=await resolveSecret(ctx,"verify_token",whatsapp.verifyToken,existing=>existing.spec?.providerConfig.case==="whatsapp"?existing.spec.providerConfig.value.verifyToken:"");return}case void 0:return;default:{let exhaustive=provider;throw new Error(`unhandled provider arm: ${String(exhaustive)}`)}}}}}function newValidateProviderImmutableStep(){return{name:"ValidateProviderImmutable",execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)throw internalError(new Error("existing channel app not found in context"),"existing channel app not found in context");let existingCase=existing.spec?.providerConfig.case,inputCase=ctx.input.spec?.providerConfig.case;if(existingCase!==inputCase)throw invalidArgumentError(PROVIDER_IMMUTABLE_MESSAGE)}}}function newCheckNoReferencingChannelsStep(store,logger2){return{name:"CheckNoReferencingChannels",async execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)throw internalError(new Error("existing ChannelApp not loaded in delete pipeline"),"existing ChannelApp not loaded in delete pipeline");let org=existing.metadata?.org??"",slug=existing.metadata?.slug??"",rows;try{rows=await store.listResources(ApiResourceKind.agent_channel)}catch(error2){throw internalError(error2,"failed to list agent channels for referential integrity check")}for(let bytes of rows){let channel;try{channel=fromBinary2(AgentChannelSchema,bytes)}catch{logger2.warn("Failed to unmarshal agent channel during referential integrity check, skipping");continue}let ref=channel.spec?.appRef;if(ref===void 0||ref.slug==="")continue;if((ref.org!==""?ref.org:channel.metadata?.org??"")===org&&ref.slug===slug)throw failedPreconditionError(deleteBlockedByChannelMessage(org,slug,channel.metadata?.name??""))}}}}function registerChannelAppServices(router,deps){router.service(ChannelAppCommandController,{apply:(app,ctx)=>apply6(deps,app,ctx),create:(app,ctx)=>createChannelApp(deps,app,ctx),update:(app,ctx)=>update9(deps,app,ctx),delete:(input,ctx)=>deleteChannelApp(deps,input,ctx)}),router.service(ChannelAppQueryController,{get:(id,ctx)=>get12(deps,id,ctx),getByReference:(ref,ctx)=>getByReference6(deps,ref,ctx),listByOrg:(req,ctx)=>listByOrg(deps,req,ctx)})}function kindOf11(ctx){return ctx.values.get(apiResourceKindKey)}async function createChannelApp(deps,app,ctx){let reqCtx=new RequestContext(ChannelAppSchema,app,callerIdentityOf(ctx),kindOf11(ctx));return await newPipeline("channelapp-create",deps.logger).addStep(newAuthorizeStep(ChannelAppCommandController.method.create,deps.authorizer)).addStep(newResolveSlugStep()).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newEncryptChannelAppSecretsForCreateStep(deps.secretService,deps.logger)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).build().execute(reqCtx),redactChannelApp(reqCtx.newState),reqCtx.newState}async function update9(deps,app,ctx){let reqCtx=new RequestContext(ChannelAppSchema,app,callerIdentityOf(ctx),kindOf11(ctx));return await newPipeline("channelapp-update",deps.logger).addStep(newAuthorizeStep(ChannelAppCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingStep(deps.store)).addStep(newValidateProviderImmutableStep()).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newEncryptChannelAppSecretsForUpdateStep(deps.secretService,deps.logger)).addStep(newPersistStep(deps.store)).build().execute(reqCtx),redactChannelApp(reqCtx.newState),reqCtx.newState}async function apply6(deps,app,ctx){let reqCtx=new RequestContext(ChannelAppSchema,app,callerIdentityOf(ctx),kindOf11(ctx));await newPipeline("channelapp-apply",deps.logger).addStep(newAuthorizeStep(ChannelAppCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");return shouldCreate?createChannelApp(deps,app,ctx):update9(deps,withResolvedApplyId(ChannelAppSchema,app,reqCtx),ctx)}async function deleteChannelApp(deps,input,ctx){let reqCtx=new RequestContext(ChannelAppCommandController.method.delete.input,input,callerIdentityOf(ctx),kindOf11(ctx));reqCtx.set(RESOURCE_ID_KEY,input.resourceId),await newPipeline("channelapp-delete",deps.logger).addStep(newAuthorizeStep(ChannelAppCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingForDeleteStep(deps.store,ChannelAppSchema)).addStep(newCheckNoReferencingChannelsStep(deps.store,deps.logger)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDestroySecretBackingStateStep(deps.secretService,deps.logger,secretValuesOfChannelApp)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted ChannelApp not found in context"),"deleted ChannelApp not found in context");let app=deleted;return redactChannelApp(app),app}async function get12(deps,id,ctx){let reqCtx=new RequestContext(ChannelAppQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf11(ctx));await newPipeline("channelapp-get",deps.logger).addStep(newAuthorizeStep(ChannelAppQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,ChannelAppSchema)).build().execute(reqCtx);let app=reqCtx.get(TARGET_RESOURCE_KEY);return redactChannelApp(app),app}async function getByReference6(deps,ref,ctx){let reqCtx=new RequestContext(ChannelAppQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf11(ctx));await newPipeline("channelapp-get-by-reference",deps.logger).addStep(newAuthorizeStep(ChannelAppQueryController.method.getByReference,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadByReferenceStep(deps.store,ChannelAppSchema)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,loadedTargetAsMethod(ChannelAppQueryController.method.get))).build().execute(reqCtx);let app=reqCtx.get(TARGET_RESOURCE_KEY);return redactChannelApp(app),app}var LIST_RESULT_KEY4="listResult";async function listByOrg(deps,req,ctx){let reqCtx=new RequestContext(ChannelAppQueryController.method.listByOrg.input,req,callerIdentityOf(ctx),kindOf11(ctx));await newPipeline("channelapp-list-by-org",deps.logger).addStep(newAuthorizeStep(ChannelAppQueryController.method.listByOrg,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newListByOrgStep(deps.store,deps.listReadScope,deps.logger)).build().execute(reqCtx);let result=reqCtx.get(LIST_RESULT_KEY4);if(result===void 0)throw internalError(new Error("ChannelApp list not found in context"),"ChannelApp list not found in context");return result}function newListByOrgStep(store,listReadScope,logger2){return{name:"ListByOrg",async execute(ctx){let org=ctx.input.org,rows;try{rows=await store.listResources(ApiResourceKind.channel_app)}catch(error2){throw internalError(error2,"failed to list ChannelApps")}let requested=[];for(let bytes of rows){let app;try{app=fromBinary2(ChannelAppSchema,bytes)}catch{logger2.warn("Failed to unmarshal ChannelApp, skipping");continue}(app.metadata?.org??"")===org&&requested.push(app)}let apps=await restrictListByReadScope(listReadScope,ctx.callerIdentity,ApiResourceKind.channel_app,requested,"");for(let app of apps)redactChannelApp(app);apps.sort((a5,b7)=>compareCreatedAtDesc(a5.status?.audit?.specAudit?.createdAt,b7.status?.audit?.specAudit?.createdAt)),ctx.set(LIST_RESULT_KEY4,create2(ChannelAppsSchema,{entries:apps}))}}}var file_ai_stigmer_agentic_environment_v1_command=fileDesc("Ci9haS9zdGlnbWVyL2FnZW50aWMvZW52aXJvbm1lbnQvdjEvY29tbWFuZC5wcm90bxIhYWkuc3RpZ21lci5hZ2VudGljLmVudmlyb25tZW50LnYxMoMKChxFbnZpcm9ubWVudENvbW1hbmRDb250cm9sbGVyEmcKBWFwcGx5Ei4uYWkuc3RpZ21lci5hZ2VudGljLmVudmlyb25tZW50LnYxLkVudmlyb25tZW50Gi4uYWkuc3RpZ21lci5hZ2VudGljLmVudmlyb25tZW50LnYxLkVudmlyb25tZW50ErkBCgZjcmVhdGUSLi5haS5zdGlnbWVyLmFnZW50aWMuZW52aXJvbm1lbnQudjEuRW52aXJvbm1lbnQaLi5haS5zdGlnbWVyLmFnZW50aWMuZW52aXJvbm1lbnQudjEuRW52aXJvbm1lbnQiT8K4GEsIDBAeIgxtZXRhZGF0YS5vcmcqN3VuYXV0aG9yaXplZCB0byBjcmVhdGUgZW52aXJvbm1lbnQgaW4gdGhpcyBvcmdhbml6YXRpb24SowEKBnVwZGF0ZRIuLmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5FbnZpcm9ubWVudBouLmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5FbnZpcm9ubWVudCI5wrgYNQgCEDUiC21ldGFkYXRhLmlkKiJ1bmF1dGhvcml6ZWQgdG8gdXBkYXRlIGVudmlyb25tZW50Er8BChB1cGRhdGVWaXNpYmlsaXR5EjUuYWkuc3RpZ21lci5jb21tb25zLmFwaXJlc291cmNlLlVwZGF0ZVZpc2liaWxpdHlJbnB1dBouLmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5FbnZpcm9ubWVudCJEwrgYQAgCEDUiC3Jlc291cmNlX2lkKi11bmF1dGhvcml6ZWQgdG8gdXBkYXRlIGVudmlyb25tZW50IHZpc2liaWxpdHkSqwEKBmRlbGV0ZRI2LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZURlbGV0ZUlucHV0Gi4uYWkuc3RpZ21lci5hZ2VudGljLmVudmlyb25tZW50LnYxLkVudmlyb25tZW50IjnCuBg1CAIQNSILcmVzb3VyY2VfaWQqInVuYXV0aG9yaXplZCB0byBkZWxldGUgZW52aXJvbm1lbnQSzwEKD3VwZGF0ZVZhcmlhYmxlcxJELmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5VcGRhdGVFbnZpcm9ubWVudFZhcmlhYmxlc1JlcXVlc3QaLi5haS5zdGlnbWVyLmFnZW50aWMuZW52aXJvbm1lbnQudjEuRW52aXJvbm1lbnQiRsK4GEIIAhA1Ig5lbnZpcm9ubWVudF9pZCosdW5hdXRob3JpemVkIHRvIHVwZGF0ZSBlbnZpcm9ubWVudCB2YXJpYWJsZXMSzwEKD3JlbW92ZVZhcmlhYmxlcxJELmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5SZW1vdmVFbnZpcm9ubWVudFZhcmlhYmxlc1JlcXVlc3QaLi5haS5zdGlnbWVyLmFnZW50aWMuZW52aXJvbm1lbnQudjEuRW52aXJvbm1lbnQiRsK4GEIIAhA1Ig5lbnZpcm9ubWVudF9pZCosdW5hdXRob3JpemVkIHRvIHJlbW92ZSBlbnZpcm9ubWVudCB2YXJpYWJsZXMaBKD/KzViBnByb3RvMw",[file_ai_stigmer_agentic_environment_v1_api,file_ai_stigmer_agentic_environment_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),EnvironmentCommandController=serviceDesc(file_ai_stigmer_agentic_environment_v1_command,0);var file_ai_stigmer_agentic_environment_v1_query=fileDesc("Ci1haS9zdGlnbWVyL2FnZW50aWMvZW52aXJvbm1lbnQvdjEvcXVlcnkucHJvdG8SIWFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MTKMBQoaRW52aXJvbm1lbnRRdWVyeUNvbnRyb2xsZXISlgEKA2dldBItLmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZUlkGi4uYWkuc3RpZ21lci5hZ2VudGljLmVudmlyb25tZW50LnYxLkVudmlyb25tZW50IjDCuBgsCAEQNSIFdmFsdWUqH3VuYXV0aG9yaXplZCB0byBnZXQgZW52aXJvbm1lbnQSfAoOZ2V0QnlSZWZlcmVuY2USNC5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VSZWZlcmVuY2UaLi5haS5zdGlnbWVyLmFnZW50aWMuZW52aXJvbm1lbnQudjEuRW52aXJvbm1lbnQiBNC4GAES0gEKDmdldFNlY3JldFZhbHVlEj4uYWkuc3RpZ21lci5hZ2VudGljLmVudmlyb25tZW50LnYxLkVudmlyb25tZW50U2VjcmV0VmFsdWVJbnB1dBozLmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5FbnZpcm9ubWVudFZhbHVlIkvCuBhHCBAQNSIOZW52aXJvbm1lbnRfaWQqMXVuYXV0aG9yaXplZCB0byByZWFkIHNlY3JldCB2YWx1ZXMgKGNyZWF0b3Itb25seSkSfAoEbGlzdBI6LmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5MaXN0RW52aXJvbm1lbnRzUmVxdWVzdBoyLmFpLnN0aWdtZXIuYWdlbnRpYy5lbnZpcm9ubWVudC52MS5FbnZpcm9ubWVudExpc3QiBNC4GAEaBKD/KzViBnByb3RvMw",[file_ai_stigmer_agentic_environment_v1_api,file_ai_stigmer_agentic_environment_v1_io,file_ai_stigmer_agentic_environment_v1_spec,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),EnvironmentQueryController=serviceDesc(file_ai_stigmer_agentic_environment_v1_query,0);function redactEnvironmentSecrets(env2){let data=env2?.spec?.data;if(data!==void 0)for(let value of Object.values(data))value.isSecret&&value.value!==""&&(value.value=REDACTED_MARKER)}function shareRestrictionReason(metadata){let labels=metadata?.labels??{};return labels[PERSONAL_LABEL_KEY]===PERSONAL_LABEL_VALUE?PERSONAL_SHARE_RESTRICTION:labels[MANAGED_LABEL_KEY]===MANAGED_LABEL_VALUE?MANAGED_SHARE_RESTRICTION:""}var environmentSearchExtractor={kind:ApiResourceKind.environment,schema:EnvironmentSchema,getSearchSummary(resource){return resource.spec?.description??""},toSearchResult(resource,score){let env2=resource;return buildSearchResult({kind:ApiResourceKind.environment,metadata:env2.metadata,summary:env2.spec?.description??"",score,createdAt:env2.status?.audit?.specAudit?.createdAt,updatedAt:env2.status?.audit?.specAudit?.updatedAt})},getSearchIndexEntry(resource){let env2=resource,metadata=env2.metadata;if(metadata!==void 0)return{name:metadata.name,description:env2.spec?.description??"",tags:metadata.tags.join(" "),org:metadata.org,visibility:ApiResourceVisibility[metadata.visibility]??"",createdAt:Number(env2.status?.audit?.specAudit?.createdAt?.seconds??0n)}}};var SECRET_VALUE_KEY="secretValue",UPDATED_ENVIRONMENT_KEY="updatedEnvironment";function newPreserveRedactedSecretsStep(){return{name:"PreserveRedactedSecrets",execute(ctx){let data=ctx.newState.spec?.data;if(data===void 0||Object.keys(data).length===0)return;let existingData=ctx.get(EXISTING_RESOURCE_KEY)?.spec?.data??{};for(let[key,value]of Object.entries(data))if(value.isSecret){if(value.value===REDACTED_MARKER){let existingEntry=existingData[key];if(existingEntry!==void 0&&existingEntry.isSecret){data[key]=existingEntry;continue}throw invalidArgumentError(markerRejectionMessage(key))}if(isCiphertextShaped(value.value))throw invalidArgumentError(forgedCiphertextMessage(key))}}}}function newEncryptSecretValuesStep(secretService,logger2){return{name:"EncryptSecretValues",async execute(ctx){let env2=ctx.newState,data=env2.spec?.data;if(!(data===void 0||Object.keys(data).length===0)){if(!secretService.isEnabled()){hasNonEmptySecret(data)&&logger2.warn("Encryption disabled: environment secret values will be stored in plaintext",{environmentId:env2.metadata?.id??""});return}for(let[key,value]of Object.entries(data))if(!(!value.isSecret||value.value===""))try{value.value=await secretService.encrypt(value.value,EncryptionScope.forOrganization(env2.metadata?.org??""))}catch(error2){throw internalError(error2,`failed to encrypt secret value for variable '${key}'`)}}}}}function hasNonEmptySecret(data){return Object.values(data).some(v=>v.isSecret&&v.value!=="")}function newEnforcePersonalUniquenessStep(store){return{name:"EnforcePersonalEnvUniqueness",async execute(ctx){let metadata=ctx.newState.metadata;if(metadata===void 0||metadata.labels[PERSONAL_LABEL_KEY]!==PERSONAL_LABEL_VALUE)return;let existing;try{existing=await findResourceByLabelAndOrg(store,ctx.apiResourceKind,EnvironmentSchema,PERSONAL_LABEL_KEY,PERSONAL_LABEL_VALUE,metadata.org)}catch(error2){throw internalError(error2,"failed to check personal environment uniqueness")}if(existing!==void 0)throw new ConnectError(personalEnvironmentExistsMessage(existing.metadata?.id??""),Code.AlreadyExists)}}}function newLoadEnvironmentByIdStep(store){return{name:"LoadEnvironmentByID",async execute(ctx){let environmentId=ctx.input.environmentId;if(typeof environmentId!="string"||environmentId==="")throw invalidArgumentError("environment_id is required");let env2;try{env2=await store.getResource(ctx.apiResourceKind,environmentId,EnvironmentSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("environment",environmentId):internalError(error2,"failed to load environment")}ctx.set(TARGET_RESOURCE_KEY,env2)}}}function newExtractAndDecryptSingleKeyStep(secretService,logger2){return{name:"ExtractAndDecryptSingleKey",async execute(ctx){let key=ctx.input.key,env2=ctx.get(TARGET_RESOURCE_KEY);if(env2===void 0)throw internalError(new Error("targetResource missing or wrong type"),"environment not loaded in context");let envValue=env2.spec?.data[key];if(envValue===void 0)throw notFoundError("environment key",key);if(envValue.isSecret&&envValue.value!==""){let decrypted;try{decrypted=await secretService.decrypt(envValue.value)}catch(error2){throw logger2.error("Failed to decrypt secret value",{key,error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to decrypt secret value")}ctx.set(SECRET_VALUE_KEY,create2(EnvironmentValueSchema,{value:decrypted,isSecret:!0,description:envValue.description}));return}ctx.set(SECRET_VALUE_KEY,envValue)}}}function newMergeVariablesAndPersistStep(store,secretService,logger2){return{name:"MergeVariablesAndPersist",async execute(ctx){let env2=ctx.get(TARGET_RESOURCE_KEY);if(env2===void 0)throw internalError(new Error("targetResource missing or wrong type"),"environment not loaded in context");env2.spec===void 0&&(env2.spec=create2(EnvironmentSpecSchema,{}));let incoming=ctx.input.variables;for(let[key,incomingValue]of Object.entries(incoming)){let value=incomingValue;if(value.isSecret&&value.value===REDACTED_MARKER){let existing=env2.spec.data[key];if(existing!==void 0&&existing.isSecret)continue;throw invalidArgumentError(markerRejectionMessage(key))}if(value.isSecret&&isCiphertextShaped(value.value))throw invalidArgumentError(forgedCiphertextMessage(key));if(value.isSecret&&value.value!=="")if(!secretService.isEnabled())logger2.warn("Encryption disabled: environment secret value will be stored in plaintext",{key});else{let encrypted;try{encrypted=await secretService.encrypt(value.value,EncryptionScope.forOrganization(env2.metadata?.org??""))}catch(error2){throw internalError(error2,`failed to encrypt secret value for variable '${key}'`)}value=create2(EnvironmentValueSchema,{value:encrypted,isSecret:!0,description:value.description})}env2.spec.data[key]=value}try{setAuditFieldsForUpdate(EnvironmentSchema,env2,"spec_audit",ctx.callerIdentity)}catch(error2){throw internalError(error2,"failed to set audit fields")}try{await store.saveResource(ctx.apiResourceKind,env2.metadata?.id??"",EnvironmentSchema,env2)}catch(error2){throw internalError(error2,"failed to persist environment after merging variables")}ctx.set(UPDATED_ENVIRONMENT_KEY,env2)}}}function newRemoveVariableKeysAndPersistStep(store,secretService,logger2){return{name:"RemoveVariableKeysAndPersist",async execute(ctx){let env2=ctx.get(TARGET_RESOURCE_KEY);if(env2===void 0)throw internalError(new Error("targetResource missing or wrong type"),"environment not loaded in context");let keys=ctx.input.keys,removedSecretValues=[];if(env2.spec?.data!==void 0)for(let key of keys){let removed=env2.spec.data[key];removed!==void 0&&removed.isSecret&&removedSecretValues.push(removed.value),delete env2.spec.data[key]}try{setAuditFieldsForUpdate(EnvironmentSchema,env2,"spec_audit",ctx.callerIdentity)}catch(error2){throw internalError(error2,"failed to set audit fields")}try{await store.saveResource(ctx.apiResourceKind,env2.metadata?.id??"",EnvironmentSchema,env2)}catch(error2){throw internalError(error2,"failed to persist environment after removing variables")}await destroySecretBackingState(secretService,logger2,{kind:"environment",resourceId:env2.metadata?.id??"",operation:"removeVariables"},removedSecretValues),ctx.set(UPDATED_ENVIRONMENT_KEY,env2)}}}function newDestroyDroppedEnvironmentSecretsStep(secretService,logger2){return{name:"DestroyDroppedEnvironmentSecrets",async execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY),oldData=existing?.spec?.data;if(oldData===void 0)return;let newData=ctx.newState.spec?.data??{},droppedSecretValues=Object.entries(oldData).filter(([key,value])=>value.isSecret&&newData[key]===void 0).map(([,value])=>value.value);await destroySecretBackingState(secretService,logger2,{kind:"environment",resourceId:existing?.metadata?.id??"",operation:"update"},droppedSecretValues)}}}function secretValuesOfEnvironment(env2){return Object.values(env2.spec?.data??{}).filter(value=>value.isSecret).map(value=>value.value)}function registerEnvironmentServices(router,deps){router.service(EnvironmentCommandController,{apply:(env2,ctx)=>apply7(deps,env2,ctx),create:(env2,ctx)=>createEnvironment(deps,env2,ctx),update:(env2,ctx)=>update10(deps,env2,ctx),updateVisibility:(input,ctx)=>updateVisibility3(deps,input,ctx),delete:(input,ctx)=>deleteEnvironment(deps,input,ctx),updateVariables:(req,ctx)=>updateVariables(deps,req,ctx),removeVariables:(req,ctx)=>removeVariables(deps,req,ctx)}),router.service(EnvironmentQueryController,{get:(id,ctx)=>get13(deps,id,ctx),getByReference:(ref,ctx)=>getByReference7(deps,ref,ctx),getSecretValue:(input,ctx)=>getSecretValue(deps,input,ctx),list:(req,ctx)=>list8(deps,req,ctx)})}function kindOf12(ctx){return ctx.values.get(apiResourceKindKey)}async function createEnvironment(deps,env2,ctx){let reqCtx=new RequestContext(EnvironmentSchema,env2,callerIdentityOf(ctx),kindOf12(ctx));return await newPipeline("environment-create",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.create,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newResolveSlugStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newEnforcePersonalUniquenessStep(deps.store)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newPreserveRedactedSecretsStep()).addStep(newEncryptSecretValuesStep(deps.secretService,deps.logger)).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).addStep(newIndexSearchStep(deps.store,environmentSearchExtractor,deps.logger)).build().execute(reqCtx),redactEnvironmentSecrets(reqCtx.newState),reqCtx.newState}async function update10(deps,env2,ctx){let reqCtx=new RequestContext(EnvironmentSchema,env2,callerIdentityOf(ctx),kindOf12(ctx));return await newPipeline("environment-update",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingStep(deps.store)).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newPreserveRedactedSecretsStep()).addStep(newEncryptSecretValuesStep(deps.secretService,deps.logger)).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store)).addStep(newPersistStep(deps.store)).addStep(newDestroyDroppedEnvironmentSecretsStep(deps.secretService,deps.logger)).addStep(newIndexSearchStep(deps.store,environmentSearchExtractor,deps.logger)).build().execute(reqCtx),redactEnvironmentSecrets(reqCtx.newState),reqCtx.newState}async function apply7(deps,env2,ctx){let reqCtx=new RequestContext(EnvironmentSchema,env2,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-apply",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");return shouldCreate?createEnvironment(deps,env2,ctx):update10(deps,withResolvedApplyId(EnvironmentSchema,env2,reqCtx),ctx)}async function deleteEnvironment(deps,input,ctx){let reqCtx=new RequestContext(EnvironmentCommandController.method.delete.input,input,callerIdentityOf(ctx),kindOf12(ctx));reqCtx.set(RESOURCE_ID_KEY,input.resourceId),await newPipeline("environment-delete",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingForDeleteStep(deps.store,EnvironmentSchema)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDestroySecretBackingStateStep(deps.secretService,deps.logger,secretValuesOfEnvironment)).addStep(newDeleteSearchIndexStep(deps.store,deps.logger)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted environment not found in context"),"deleted environment not found in context");let env2=deleted;return redactEnvironmentSecrets(env2),env2}var UPDATE_VISIBILITY_ENVIRONMENT_KEY="updateVisibilityEnvironment";async function updateVisibility3(deps,input,ctx){let reqCtx=new RequestContext(EnvironmentCommandController.method.updateVisibility.input,input,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-update-visibility",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.updateVisibility,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadEnvironmentForVisibilityUpdateStep(deps.store)).addStep(newRecordVisibilityBeforeUpdateStep(UPDATE_VISIBILITY_ENVIRONMENT_KEY)).addStep(newValidateVisibilityUpdateStep()).addStep(newValidateEnvironmentShareRestrictionStep()).addStep(newSetEnvironmentVisibilityStep()).addStep(newPersistEnvironmentForVisibilityUpdateStep(deps.store)).addStep(newUpdateVisibilityTuplesStep(deps.authorizationLifecycle,UPDATE_VISIBILITY_ENVIRONMENT_KEY)).addStep(newIndexEnvironmentAfterVisibilityUpdateStep(deps.store,deps.logger)).build().execute(reqCtx);let env2=reqCtx.get(UPDATE_VISIBILITY_ENVIRONMENT_KEY);return redactEnvironmentSecrets(env2),env2}function newLoadEnvironmentForVisibilityUpdateStep(store){return{name:"LoadEnvironmentForVisibilityUpdate",async execute(ctx){let input=ctx.input,env2;try{env2=await store.getResource(ctx.apiResourceKind,input.resourceId,EnvironmentSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("environment",input.resourceId):internalError(error2,"failed to load environment")}ctx.set(UPDATE_VISIBILITY_ENVIRONMENT_KEY,env2)}}}function newValidateEnvironmentShareRestrictionStep(){return{name:"ValidateEnvironmentShareRestriction",execute(ctx){if(ctx.input.visibility!==ApiResourceVisibility.visibility_org)return;let env2=ctx.get(UPDATE_VISIBILITY_ENVIRONMENT_KEY),reason=shareRestrictionReason(env2.metadata);if(reason!=="")throw failedPreconditionError(reason)}}}function newSetEnvironmentVisibilityStep(){return{name:"SetVisibility",execute(ctx){let env2=ctx.get(UPDATE_VISIBILITY_ENVIRONMENT_KEY);env2.metadata!==void 0&&(env2.metadata.visibility=ctx.input.visibility),setAuditFieldsForUpdate(EnvironmentSchema,env2,"status_audit",ctx.callerIdentity)}}}function newPersistEnvironmentForVisibilityUpdateStep(store){return{name:"PersistEnvironmentForVisibilityUpdate",async execute(ctx){let env2=ctx.get(UPDATE_VISIBILITY_ENVIRONMENT_KEY);try{await store.saveResource(ctx.apiResourceKind,env2.metadata?.id??"",EnvironmentSchema,env2)}catch(error2){throw internalError(error2,"failed to save environment")}}}}function newIndexEnvironmentAfterVisibilityUpdateStep(store,logger2){return{name:"IndexEnvironmentAfterVisibilityUpdate",async execute(ctx){let env2=ctx.get(UPDATE_VISIBILITY_ENVIRONMENT_KEY),entry=environmentSearchExtractor.getSearchIndexEntry(env2);if(entry===void 0){logger2.warn("IndexEnvironmentAfterVisibilityUpdate: extractor returned nil, skipping",{id:env2.metadata?.id??""});return}try{await store.upsertSearchIndex(ctx.apiResourceKind,env2.metadata?.id??"",entry)}catch(error2){logger2.warn("IndexEnvironmentAfterVisibilityUpdate: failed (best-effort)",{id:env2.metadata?.id??"",error:error2 instanceof Error?error2.message:String(error2)})}}}}async function updateVariables(deps,req,ctx){let reqCtx=new RequestContext(EnvironmentCommandController.method.updateVariables.input,req,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-update-variables",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.updateVariables,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadEnvironmentByIdStep(deps.store)).addStep(newMergeVariablesAndPersistStep(deps.store,deps.secretService,deps.logger)).build().execute(reqCtx);let updated=reqCtx.get(UPDATED_ENVIRONMENT_KEY);return redactEnvironmentSecrets(updated),updated}async function removeVariables(deps,req,ctx){let reqCtx=new RequestContext(EnvironmentCommandController.method.removeVariables.input,req,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-remove-variables",deps.logger).addStep(newAuthorizeStep(EnvironmentCommandController.method.removeVariables,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadEnvironmentByIdStep(deps.store)).addStep(newRemoveVariableKeysAndPersistStep(deps.store,deps.secretService,deps.logger)).build().execute(reqCtx);let updated=reqCtx.get(UPDATED_ENVIRONMENT_KEY);return redactEnvironmentSecrets(updated),updated}async function get13(deps,id,ctx){let reqCtx=new RequestContext(EnvironmentQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-get",deps.logger).addStep(newAuthorizeStep(EnvironmentQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,EnvironmentSchema)).build().execute(reqCtx);let env2=reqCtx.get(TARGET_RESOURCE_KEY);return redactEnvironmentSecrets(env2),env2}async function getByReference7(deps,ref,ctx){let reqCtx=new RequestContext(EnvironmentQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-get-by-reference",deps.logger).addStep(newAuthorizeStep(EnvironmentQueryController.method.getByReference,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadByReferenceStep(deps.store,EnvironmentSchema)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,loadedTargetAsMethod(EnvironmentQueryController.method.get))).build().execute(reqCtx);let env2=reqCtx.get(TARGET_RESOURCE_KEY);return redactEnvironmentSecrets(env2),env2}async function getSecretValue(deps,input,ctx){let reqCtx=new RequestContext(EnvironmentQueryController.method.getSecretValue.input,input,callerIdentityOf(ctx),kindOf12(ctx));return await newPipeline("environment-get-secret-value",deps.logger).addStep(newAuthorizeStep(EnvironmentQueryController.method.getSecretValue,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadEnvironmentByIdStep(deps.store)).addStep(newExtractAndDecryptSingleKeyStep(deps.secretService,deps.logger)).build().execute(reqCtx),reqCtx.get(SECRET_VALUE_KEY)}var LIST_RESULT_KEY5="listResult";async function list8(deps,req,ctx){let reqCtx=new RequestContext(EnvironmentQueryController.method.list.input,req,callerIdentityOf(ctx),kindOf12(ctx));await newPipeline("environment-list",deps.logger).addStep(newAuthorizeStep(EnvironmentQueryController.method.list,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newListByOrgAndLabelsStep5(deps.store,deps.listReadScope)).build().execute(reqCtx);let result=reqCtx.get(LIST_RESULT_KEY5);if(result===void 0)throw internalError(new Error("environment list not found in context"),"environment list not found in context");return result}function newListByOrgAndLabelsStep5(store,listReadScope){return{name:"ListByOrgAndLabels",async execute(ctx){let{org,labels:filterLabels}=ctx.input,rows;try{rows=await store.listResources(ctx.apiResourceKind)}catch(error2){throw internalError(error2,"failed to list environments")}let decoded=[];for(let bytes of rows)try{decoded.push(fromBinary2(EnvironmentSchema,bytes))}catch{continue}let requested=decoded.filter(env2=>(env2.metadata?.org??"")===org&&matchesAllLabels(env2.metadata?.labels??{},filterLabels)),environments=await restrictListByReadScope(listReadScope,ctx.callerIdentity,ApiResourceKind.environment,requested,"");for(let env2 of environments)redactEnvironmentSecrets(env2);environments.sort((a5,b7)=>compareCreatedAtDesc(a5.status?.audit?.specAudit?.createdAt,b7.status?.audit?.specAudit?.createdAt)),ctx.set(LIST_RESULT_KEY5,create2(EnvironmentListSchema,{totalCount:environments.length,items:environments}))}}}var file_ai_stigmer_agentic_executioncontext_v1_command=fileDesc("CjRhaS9zdGlnbWVyL2FnZW50aWMvZXhlY3V0aW9uY29udGV4dC92MS9jb21tYW5kLnByb3RvEiZhaS5zdGlnbWVyLmFnZW50aWMuZXhlY3V0aW9uY29udGV4dC52MTLpAwohRXhlY3V0aW9uQ29udGV4dENvbW1hbmRDb250cm9sbGVyEnsKBWFwcGx5EjguYWkuc3RpZ21lci5hZ2VudGljLmV4ZWN1dGlvbmNvbnRleHQudjEuRXhlY3V0aW9uQ29udGV4dBo4LmFpLnN0aWdtZXIuYWdlbnRpYy5leGVjdXRpb25jb250ZXh0LnYxLkV4ZWN1dGlvbkNvbnRleHQSggEKBmNyZWF0ZRI4LmFpLnN0aWdtZXIuYWdlbnRpYy5leGVjdXRpb25jb250ZXh0LnYxLkV4ZWN1dGlvbkNvbnRleHQaOC5haS5zdGlnbWVyLmFnZW50aWMuZXhlY3V0aW9uY29udGV4dC52MS5FeGVjdXRpb25Db250ZXh0IgTQuBgBErsBCgZkZWxldGUSNi5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VEZWxldGVJbnB1dBo4LmFpLnN0aWdtZXIuYWdlbnRpYy5leGVjdXRpb25jb250ZXh0LnYxLkV4ZWN1dGlvbkNvbnRleHQiP8K4GDsIAhA2IgtyZXNvdXJjZV9pZCoodW5hdXRob3JpemVkIHRvIGRlbGV0ZSBleGVjdXRpb24gY29udGV4dBoEoP8rNmIGcHJvdG8z",[file_ai_stigmer_agentic_executioncontext_v1_api,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),ExecutionContextCommandController=serviceDesc(file_ai_stigmer_agentic_executioncontext_v1_command,0);var file_ai_stigmer_agentic_executioncontext_v1_io=fileDesc("Ci9haS9zdGlnbWVyL2FnZW50aWMvZXhlY3V0aW9uY29udGV4dC92MS9pby5wcm90bxImYWkuc3RpZ21lci5hZ2VudGljLmV4ZWN1dGlvbmNvbnRleHQudjEiKwoSRXhlY3V0aW9uQ29udGV4dElkEhUKBXZhbHVlGAEgASgJQga6SAPIAQEiQQogRXhlY3V0aW9uQ29udGV4dEV4ZWN1dGlvbklkSW5wdXQSHQoMZXhlY3V0aW9uX2lkGAEgASgJQge6SARyAhABYgZwcm90bzM",[file_buf_validate_validate]);var file_ai_stigmer_agentic_executioncontext_v1_query=fileDesc("CjJhaS9zdGlnbWVyL2FnZW50aWMvZXhlY3V0aW9uY29udGV4dC92MS9xdWVyeS5wcm90bxImYWkuc3RpZ21lci5hZ2VudGljLmV4ZWN1dGlvbmNvbnRleHQudjEyhQQKH0V4ZWN1dGlvbkNvbnRleHRRdWVyeUNvbnRyb2xsZXISswEKA2dldBI6LmFpLnN0aWdtZXIuYWdlbnRpYy5leGVjdXRpb25jb250ZXh0LnYxLkV4ZWN1dGlvbkNvbnRleHRJZBo4LmFpLnN0aWdtZXIuYWdlbnRpYy5leGVjdXRpb25jb250ZXh0LnYxLkV4ZWN1dGlvbkNvbnRleHQiNsK4GDIIARA2IgV2YWx1ZSoldW5hdXRob3JpemVkIHRvIGdldCBleGVjdXRpb24gY29udGV4dBKGAQoOZ2V0QnlSZWZlcmVuY2USNC5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VSZWZlcmVuY2UaOC5haS5zdGlnbWVyLmFnZW50aWMuZXhlY3V0aW9uY29udGV4dC52MS5FeGVjdXRpb25Db250ZXh0IgTQuBgBEpwBChBnZXRCeUV4ZWN1dGlvbklkEkguYWkuc3RpZ21lci5hZ2VudGljLmV4ZWN1dGlvbmNvbnRleHQudjEuRXhlY3V0aW9uQ29udGV4dEV4ZWN1dGlvbklkSW5wdXQaOC5haS5zdGlnbWVyLmFnZW50aWMuZXhlY3V0aW9uY29udGV4dC52MS5FeGVjdXRpb25Db250ZXh0IgTQuBgBGgSg/ys2YgZwcm90bzM",[file_ai_stigmer_agentic_executioncontext_v1_api,file_ai_stigmer_agentic_executioncontext_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),ExecutionContextQueryController=serviceDesc(file_ai_stigmer_agentic_executioncontext_v1_query,0);function redactExecutionContextSecrets(ec2){let data=ec2?.spec?.data;if(data!==void 0)for(let value of Object.values(data))value.isSecret&&value.value!==""&&(value.value=REDACTED_MARKER)}var import_node_crypto19=require("node:crypto"),CONNECT_EXECUTION_ID_PREFIX="connect-";function newConnectExecutionId(mcpServerId){return`${CONNECT_EXECUTION_ID_PREFIX}${mcpServerId}-${(0,import_node_crypto19.randomUUID)().slice(0,8)}`}function isConnectExecutionId(executionId){return executionId.startsWith(CONNECT_EXECUTION_ID_PREFIX)}function isTerminalWorkflowExecutionPhase(phase){switch(phase){case ExecutionPhase2.EXECUTION_COMPLETED:case ExecutionPhase2.EXECUTION_FAILED:case ExecutionPhase2.EXECUTION_CANCELLED:case ExecutionPhase2.EXECUTION_TERMINATED:return!0;default:return!1}}var RUNNER_VERIFIER_NAME="runner",RUNNER_CREDENTIAL_INVALID_MESSAGE="runner credential is not valid on this server",RUNNER_CREDENTIAL_NOT_LIVE_MESSAGE="runner credential names a run that is over or belongs to nobody this server recognizes",RUN_CREDENTIAL_NOT_RUNS_PERSON_MESSAGE="a run credential is minted only for the person whose run it is",WORKFLOW_LINEAGE_BINDING_MISMATCH_MESSAGE="workflow lineage label names a workflow execution this runner credential is not bound to",MEMORY_CAPTURE_ORG_MISMATCH_MESSAGE="memory capture is scoped to the session's organization";function boundExecutionKindOf(executionId){switch(kindByIdPrefix(executionId)){case ApiResourceKind.agent_execution:return"agent-execution";case ApiResourceKind.workflow_execution:return"workflow-execution";default:return isConnectExecutionId(executionId)?"mcp-connect":void 0}}function bindsARun(kind){switch(kind){case"agent-execution":case"workflow-execution":return!0;case"mcp-connect":return!1;default:{let exhaustive=kind;throw new Error(`unknown bound execution kind ${String(exhaustive)}`)}}}async function loadBoundExecution(store,executionId,now=Date.now()){let kind=boundExecutionKindOf(executionId);if(kind!==void 0)switch(kind){case"agent-execution":{let row=await getRow(store,ApiResourceKind.agent_execution,executionId,AgentExecutionSchema);return row===void 0?void 0:{kind,executionId,org:row.metadata?.org??"",createdBy:creatorStampOf(AgentExecutionSchema,row),sessionId:row.spec?.sessionId??"",live:isLive(row.status!==void 0&&isTerminalExecutionPhase(row.status.phase),row.status?.completedAt??"",now)}}case"workflow-execution":{let row=await getRow(store,ApiResourceKind.workflow_execution,executionId,WorkflowExecutionSchema);return row===void 0?void 0:{kind,executionId,org:row.metadata?.org??"",createdBy:creatorStampOf(WorkflowExecutionSchema,row),sessionId:"",live:isLive(row.status!==void 0&&isTerminalWorkflowExecutionPhase(row.status.phase),row.status?.completedAt??"",now)}}case"mcp-connect":{let row=await getExecutionContextRow(store,executionId);return row===void 0?void 0:{kind,executionId,org:row.metadata?.org??"",createdBy:creatorStampOf(ExecutionContextSchema,row),sessionId:"",live:!0}}default:{let exhaustive=kind;throw new Error(`unknown bound execution kind ${String(exhaustive)}`)}}}function isLive(terminal,completedAt,now){if(!terminal)return!0;let finishedAt=Date.parse(completedAt);return Number.isNaN(finishedAt)?!1:now-finishedAt<6e5}function creatorStampOf(schema2,row){return auditOf(schema2,row)?.specAudit?.createdBy?.id??""}async function getRow(store,kind,id,schema2){try{return await store.getResource(kind,id,schema2)}catch(error2){if(error2 instanceof ResourceNotFoundError)return;throw error2}}async function getExecutionContextRow(store,executionId){try{return await store.findByField(ApiResourceKind.execution_context,"spec.executionId",executionId,ExecutionContextSchema)}catch(error2){if(error2 instanceof ResourceNotFoundError)return;throw error2}}function ciphertextShapedMessage(key){return`value for '${key}' looks like stored ciphertext (enc:v<N>: prefix); supply the plaintext value`}var ENCRYPT_BATCH_FAILURE_MESSAGE="failed to encrypt secret values";function encryptionKeyMissingMessage(executionId,key){return`execution context for ${executionId} holds encrypted secret '${key}' but no encryption key is configured`}async function resolveValuesForCaller(deps,ctx,ec2){if(await runnerMayDecrypt(deps,ctx,ec2)){await decryptSecretValues(deps,ec2);return}redactExecutionContextSecrets(ec2)}async function runnerMayDecrypt(deps,ctx,ec2){let authorizeRead=deps.runnerAuthService.authorizeExecutionContextRead?.bind(deps.runnerAuthService);if(authorizeRead!==void 0){let token2=bearerToken(ctx);if(token2==="")return!1;try{return await authorizeRead(token2,ec2.spec?.executionId??"")}catch(error2){return deps.logger.warn("ExecutionContext read authorization failed \u2014 redacting secrets",{error:error2 instanceof Error?error2.message:String(error2)}),!1}}let token=bearerToken(ctx),executionId=verifyRunnerToken(deps,token,ec2);return executionId===void 0?!1:!isClockedToken(token)&&!await runIsLive(deps,executionId)?(deps.logger.debug("Run credential presented for a run that is over - redacting execution context secrets",{executionId}),!1):(deps.logger.debug("Scope-bound runner token presented - decrypting execution context secrets",{executionId}),!0)}function verifyRunnerToken(deps,token,ec2){if(token==="")return;let tokenExecutionId;try{tokenExecutionId=deps.runnerAuthService.verify(TOKEN_TYPE_EXECUTION_SCOPED,token)}catch{deps.logger.debug("Presented runner token failed verification - redacting execution context secrets");return}if(tokenExecutionId!==(ec2.spec?.executionId??"")){deps.logger.warn("Runner token is not scope-bound to this execution context - redacting secrets",{tokenExecutionId,executionId:ec2.spec?.executionId??""});return}return tokenExecutionId}async function runIsLive(deps,executionId){try{let execution=await loadBoundExecution(deps.store,executionId);return execution!==void 0&&bindsARun(execution.kind)&&execution.live}catch(error2){throw internalError(error2,"failed to load the run credential's execution")}}function bearerToken(ctx){return parseBearerToken(ctx.requestHeader.get("authorization")??"")}async function decryptSecretValues(deps,ec2){let executionId=ec2.spec?.executionId??"",data=ec2.spec?.data??{};for(let[key,value]of Object.entries(data))if(!(!value.isSecret||!deps.secretService.isEncrypted(value.value)))try{value.value=await deps.secretService.decrypt(value.value)}catch(error2){if(error2 instanceof EncryptionUnavailableError)throw internalError(error2,encryptionKeyMissingMessage(executionId,key));deps.logger.warn("Undecryptable ciphertext in execution context \u2014 dropping this value from the runner read",{key,executionId,error:error2 instanceof Error?error2.message:String(error2)}),delete data[key]}}var executionContextSearchExtractor={kind:ApiResourceKind.execution_context,schema:ExecutionContextSchema,getSearchSummary(){return""},toSearchResult(resource,score){let ec2=resource;return buildSearchResult({kind:ApiResourceKind.execution_context,metadata:ec2.metadata,summary:"",score,createdAt:ec2.status?.audit?.specAudit?.createdAt,updatedAt:ec2.status?.audit?.specAudit?.updatedAt})},getSearchIndexEntry(resource){let ec2=resource,metadata=ec2.metadata;if(metadata!==void 0)return{name:metadata.name,description:"",tags:metadata.tags.join(" "),org:metadata.org,visibility:ApiResourceVisibility[metadata.visibility]??"",createdAt:Number(ec2.status?.audit?.specAudit?.createdAt?.seconds??0n)}}};function newRejectCiphertextShapedStep(){return{name:"RejectCiphertextShapedValues",execute(ctx){let data=ctx.input.spec?.data??{};for(let[key,value]of Object.entries(data))if(isCiphertextShaped(value.value))throw invalidArgumentError(ciphertextShapedMessage(key))}}}function newEncryptSecretValuesStep2(secretService,logger2){return{name:"EncryptSecretValues",async execute(ctx){let ec2=ctx.newState,data=ec2.spec?.data;if(data===void 0||Object.keys(data).length===0)return;if(!secretService.isEnabled()){hasNonEmptySecret2(data)&&logger2.warn("Encryption disabled: execution context secret values will be stored in plaintext",{executionId:ec2.spec?.executionId??""});return}let toSeal=new Map;for(let[key,value]of Object.entries(data))!value.isSecret||value.value===""||toSeal.set(key,value.value);if(toSeal.size===0)return;let sealed;try{sealed=await secretService.encryptAllAtMostV2(toSeal,EncryptionScope.forOrganization(ec2.metadata?.org??""))}catch(error2){throw internalError(error2,ENCRYPT_BATCH_FAILURE_MESSAGE)}for(let[key,value]of Object.entries(data)){let sealedValue=sealed.get(key);sealedValue!==void 0&&(value.value=sealedValue)}}}}function hasNonEmptySecret2(data){return Object.values(data).some(v=>v.isSecret&&v.value!=="")}function newLoadByExecutionIdStep(store){return{name:"LoadByExecutionId",async execute(ctx){let input=ctx.input;if(input.executionId==="")throw invalidArgumentError("execution_id is required");let executionContext;try{executionContext=await store.findByField(ctx.apiResourceKind,"spec.executionId",input.executionId,ExecutionContextSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("execution_context",`execution_id=${input.executionId}`):internalError(error2,"failed to query execution context")}ctx.set(TARGET_RESOURCE_KEY,executionContext)}}}function newAuthorizeExecutionContextCreateStep(authorizer){return{name:"AuthorizeCreate",async execute(ctx){let caller=ctx.callerIdentity;if(isServerComposedRequest(caller))return;let decision;try{decision=await authorizer.authorize(caller,{permission:IamPermission.can_create_execution_in,resourceKind:ApiResourceKind.organization,resourceId:ctx.newState.metadata?.org??""})}catch(error2){throw internalError(error2 instanceof Error?error2:new Error(String(error2)),"execution-context create authorization could not be completed")}switch(decision.kind){case"allow":return;case"deny":case"not-found":throw new ConnectError("unauthorized to create execution context in this organization",Code.PermissionDenied);case"unavailable":throw internalError(decision.cause,"execution-context create authorization could not be completed");default:{let exhaustive=decision;throw internalError(new Error(`unknown decision ${JSON.stringify(exhaustive)}`),"execution-context create authorization could not be completed")}}}}}function registerExecutionContextServices(router,deps){router.service(ExecutionContextCommandController,{apply:(ec2,ctx)=>apply8(deps,ec2,ctx),create:(ec2,ctx)=>createExecutionContext(deps,ec2,ctx),delete:(input,ctx)=>deleteExecutionContext(deps,input,ctx)}),router.service(ExecutionContextQueryController,{get:(id,ctx)=>get14(deps,id,ctx),getByReference:(ref,ctx)=>getByReference8(deps,ref,ctx),getByExecutionId:(input,ctx)=>getByExecutionId(deps,input,ctx)})}function kindOf13(ctx){return ctx.values.get(apiResourceKindKey)}async function createExecutionContext(deps,ec2,ctx){let reqCtx=new RequestContext(ExecutionContextSchema,ec2,callerIdentityOf(ctx),kindOf13(ctx));return await newPipeline("execution-context-create",deps.logger).addStep(newAuthorizeStep(ExecutionContextCommandController.method.create,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newAuthorizeExecutionContextCreateStep(deps.authorizer)).addStep(newValidateVisibilityStep()).addStep(newRejectCiphertextShapedStep()).addStep(newResolveSlugStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store)).addStep(newEncryptSecretValuesStep2(deps.secretService,deps.logger)).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).addStep(newIndexSearchStep(deps.store,executionContextSearchExtractor,deps.logger)).build().execute(reqCtx),redactExecutionContextSecrets(reqCtx.newState),reqCtx.newState}async function apply8(deps,ec2,ctx){let reqCtx=new RequestContext(ExecutionContextSchema,ec2,callerIdentityOf(ctx),kindOf13(ctx));await newPipeline("execution-context-apply",deps.logger).addStep(newAuthorizeStep(ExecutionContextCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");if(shouldCreate)return createExecutionContext(deps,ec2,ctx);throw deps.logger.warn("ExecutionContext already exists - UPDATE not supported",{slug:ec2.metadata?.name??"",id:ec2.metadata?.id??""}),alreadyExistsError("ExecutionContext",ec2.metadata?.name??"")}async function deleteExecutionContext(deps,input,ctx){let reqCtx=new RequestContext(ExecutionContextCommandController.method.delete.input,input,callerIdentityOf(ctx),kindOf13(ctx));reqCtx.set(RESOURCE_ID_KEY,input.resourceId),await newPipeline("execution-context-delete",deps.logger).addStep(newAuthorizeStep(ExecutionContextCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingForDeleteStep(deps.store,ExecutionContextSchema)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDeleteSearchIndexStep(deps.store,deps.logger)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted execution context not found in context"),"deleted execution context not found in context");let ec2=deleted;return redactExecutionContextSecrets(ec2),ec2}async function get14(deps,id,ctx){let reqCtx=new RequestContext(ExecutionContextQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf13(ctx));await newPipeline("execution-context-get",deps.logger).addStep(newAuthorizeStep(ExecutionContextQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,ExecutionContextSchema)).build().execute(reqCtx);let ec2=reqCtx.get(TARGET_RESOURCE_KEY);return redactExecutionContextSecrets(ec2),ec2}async function getByReference8(deps,ref,ctx){let reqCtx=new RequestContext(ExecutionContextQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf13(ctx));await newPipeline("execution-context-get-by-reference",deps.logger).addStep(newAuthorizeStep(ExecutionContextQueryController.method.getByReference,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadByReferenceStep(deps.store,ExecutionContextSchema)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,loadedTargetAsMethod(ExecutionContextQueryController.method.get))).build().execute(reqCtx);let ec2=reqCtx.get(TARGET_RESOURCE_KEY);return redactExecutionContextSecrets(ec2),ec2}async function getByExecutionId(deps,input,ctx){let reqCtx=new RequestContext(ExecutionContextQueryController.method.getByExecutionId.input,input,callerIdentityOf(ctx),kindOf13(ctx));await newPipeline("execution-context-get-by-execution-id",deps.logger).addStep(newAuthorizeStep(ExecutionContextQueryController.method.getByExecutionId,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadByExecutionIdStep(deps.store)).build().execute(reqCtx);let ec2=reqCtx.get(TARGET_RESOURCE_KEY);return await resolveValuesForCaller(deps,ctx,ec2),ec2}var import_node_crypto20=require("node:crypto");var file_ai_stigmer_platform_github_v1_service=fileDesc("CithaS9zdGlnbWVyL3BsYXRmb3JtL2dpdGh1Yi92MS9zZXJ2aWNlLnByb3RvEh1haS5zdGlnbWVyLnBsYXRmb3JtLmdpdGh1Yi52MSI8ChtHZXRPQXV0aEF1dGhvcml6ZVVybFJlcXVlc3QSHQoMcmVkaXJlY3RfdXJpGAEgASgJQge6SARyAhABIkQKHEdldE9BdXRoQXV0aG9yaXplVXJsUmVzcG9uc2USFQoNYXV0aG9yaXplX3VybBgBIAEoCRINCgVzdGF0ZRgCIAEoCSJoChhFeGNoYW5nZU9BdXRoQ29kZVJlcXVlc3QSFQoEY29kZRgBIAEoCUIHukgEcgIQARIWCgVzdGF0ZRgCIAEoCUIHukgEcgIQARIdCgxyZWRpcmVjdF91cmkYAyABKAlCB7pIBHICEAEiVAoZRXhjaGFuZ2VPQXV0aENvZGVSZXNwb25zZRIUCgxhY2Nlc3NfdG9rZW4YASABKAkSEgoKdG9rZW5fdHlwZRgCIAEoCRINCgVzY29wZRgDIAEoCTK2AgoNR2l0SHViU2VydmljZRKVAQoUZ2V0T0F1dGhBdXRob3JpemVVcmwSOi5haS5zdGlnbWVyLnBsYXRmb3JtLmdpdGh1Yi52MS5HZXRPQXV0aEF1dGhvcml6ZVVybFJlcXVlc3QaOy5haS5zdGlnbWVyLnBsYXRmb3JtLmdpdGh1Yi52MS5HZXRPQXV0aEF1dGhvcml6ZVVybFJlc3BvbnNlIgTQuBgBEowBChFleGNoYW5nZU9BdXRoQ29kZRI3LmFpLnN0aWdtZXIucGxhdGZvcm0uZ2l0aHViLnYxLkV4Y2hhbmdlT0F1dGhDb2RlUmVxdWVzdBo4LmFpLnN0aWdtZXIucGxhdGZvcm0uZ2l0aHViLnYxLkV4Y2hhbmdlT0F1dGhDb2RlUmVzcG9uc2UiBNC4GAFiBnByb3RvMw",[file_ai_stigmer_commons_rpc_method_options,file_buf_validate_validate]);var GetOAuthAuthorizeUrlResponseSchema=messageDesc2(file_ai_stigmer_platform_github_v1_service,1);var ExchangeOAuthCodeResponseSchema=messageDesc2(file_ai_stigmer_platform_github_v1_service,3),GitHubService=serviceDesc(file_ai_stigmer_platform_github_v1_service,0);var GITHUB_AUTHORIZE_URL="https://github.com/login/oauth/authorize",GITHUB_TOKEN_URL="https://github.com/login/oauth/access_token",OAUTH_SCOPES="repo,read:user",HTTP_TIMEOUT_MS=1e4;function registerGitHubServices(router,deps){router.service(GitHubService,{getOAuthAuthorizeUrl:req=>getOAuthAuthorizeUrl(deps,req),exchangeOAuthCode:req=>exchangeOAuthCode(deps,req)})}function getOAuthAuthorizeUrl(deps,req){if(deps.clientId==="")throw failedPreconditionError("GitHub OAuth is not configured (STIGMER_GITHUB_CLIENT_ID not set)");let state2;try{state2=(0,import_node_crypto20.randomBytes)(16).toString("hex")}catch(error2){throw deps.logger.error("failed to generate OAuth state",{error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to generate OAuth state")}let authorizeUrl=GITHUB_AUTHORIZE_URL+"?"+goUrlValuesEncode({client_id:deps.clientId,redirect_uri:req.redirectUri,scope:OAUTH_SCOPES,state:state2});return create2(GetOAuthAuthorizeUrlResponseSchema,{authorizeUrl,state:state2})}async function exchangeOAuthCode(deps,req){if(deps.clientId===""||deps.clientSecret==="")throw failedPreconditionError("GitHub OAuth is not configured");let body=goUrlValuesEncode({client_id:deps.clientId,client_secret:deps.clientSecret,code:req.code,redirect_uri:req.redirectUri}),fetchImpl=deps.fetchImpl??fetch,response;try{response=await fetchImpl(GITHUB_TOKEN_URL,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body,signal:AbortSignal.timeout(HTTP_TIMEOUT_MS)})}catch(error2){throw deps.logger.error("GitHub token exchange failed",{error:error2 instanceof Error?error2.message:String(error2)}),unavailableError("failed to reach GitHub for token exchange")}let raw;try{raw=await response.text()}catch(error2){throw deps.logger.error("failed to read GitHub token response",{error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to read GitHub response")}let tokenResponse;try{tokenResponse=JSON.parse(raw)}catch(error2){throw deps.logger.error("failed to parse GitHub token response",{error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to parse GitHub response")}if(tokenResponse.error!==void 0&&tokenResponse.error!=="")throw deps.logger.warn("GitHub OAuth error",{error:tokenResponse.error,description:tokenResponse.error_description??""}),invalidArgumentError(`GitHub OAuth error: ${tokenResponse.error_description??""}`);return create2(ExchangeOAuthCodeResponseSchema,{accessToken:tokenResponse.access_token??"",tokenType:tokenResponse.token_type??"",scope:tokenResponse.scope??""})}var file_ai_stigmer_agentic_memory_v1_io=fileDesc("CiVhaS9zdGlnbWVyL2FnZW50aWMvbWVtb3J5L3YxL2lvLnByb3RvEhxhaS5zdGlnbWVyLmFnZW50aWMubWVtb3J5LnYxIiEKCE1lbW9yeUlkEhUKBXZhbHVlGAEgASgJQga6SAPIAQEiYAoTTGlzdE1lbW9yaWVzUmVxdWVzdBIUCgNvcmcYASABKAlCB7pIBHICEAESMwoJcGFnZV9pbmZvGAIgASgLMiAuYWkuc3RpZ21lci5jb21tb25zLnJwYy5QYWdlSW5mbyJWCgpNZW1vcnlMaXN0EhMKC3RvdGFsX2NvdW50GAEgASgFEjMKBWl0ZW1zGAIgAygLMiQuYWkuc3RpZ21lci5hZ2VudGljLm1lbW9yeS52MS5NZW1vcnliBnByb3RvMw",[file_ai_stigmer_agentic_memory_v1_api,file_ai_stigmer_commons_rpc_pagination,file_buf_validate_validate]),MemoryIdSchema=messageDesc2(file_ai_stigmer_agentic_memory_v1_io,0);var MemoryListSchema=messageDesc2(file_ai_stigmer_agentic_memory_v1_io,2);var file_ai_stigmer_agentic_memory_v1_command=fileDesc("CiphaS9zdGlnbWVyL2FnZW50aWMvbWVtb3J5L3YxL2NvbW1hbmQucHJvdG8SHGFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEypQUKF01lbW9yeUNvbW1hbmRDb250cm9sbGVyEloKBmNyZWF0ZRIkLmFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEuTWVtb3J5GiQuYWkuc3RpZ21lci5hZ2VudGljLm1lbW9yeS52MS5NZW1vcnkiBNC4GAESigEKBnVwZGF0ZRIkLmFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEuTWVtb3J5GiQuYWkuc3RpZ21lci5hZ2VudGljLm1lbW9yeS52MS5NZW1vcnkiNMK4GDAIAhA5IgttZXRhZGF0YS5pZCoddW5hdXRob3JpemVkIHRvIHVwZGF0ZSBtZW1vcnkShgEKBmRlbGV0ZRImLmFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEuTWVtb3J5SWQaJC5haS5zdGlnbWVyLmFnZW50aWMubWVtb3J5LnYxLk1lbW9yeSIuwrgYKggDEDkiBXZhbHVlKh11bmF1dGhvcml6ZWQgdG8gZGVsZXRlIG1lbW9yeRKIAQoHY29uZmlybRImLmFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEuTWVtb3J5SWQaJC5haS5zdGlnbWVyLmFnZW50aWMubWVtb3J5LnYxLk1lbW9yeSIvwrgYKwgCEDkiBXZhbHVlKh51bmF1dGhvcml6ZWQgdG8gY29uZmlybSBtZW1vcnkShgEKBnJlamVjdBImLmFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEuTWVtb3J5SWQaJC5haS5zdGlnbWVyLmFnZW50aWMubWVtb3J5LnYxLk1lbW9yeSIuwrgYKggCEDkiBXZhbHVlKh11bmF1dGhvcml6ZWQgdG8gcmVqZWN0IG1lbW9yeRoEoP8rOWIGcHJvdG8z",[file_ai_stigmer_agentic_memory_v1_api,file_ai_stigmer_agentic_memory_v1_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),MemoryCommandController=serviceDesc(file_ai_stigmer_agentic_memory_v1_command,0);var file_ai_stigmer_agentic_memory_v1_query=fileDesc("CihhaS9zdGlnbWVyL2FnZW50aWMvbWVtb3J5L3YxL3F1ZXJ5LnByb3RvEhxhaS5zdGlnbWVyLmFnZW50aWMubWVtb3J5LnYxMosCChVNZW1vcnlRdWVyeUNvbnRyb2xsZXISgAEKA2dldBImLmFpLnN0aWdtZXIuYWdlbnRpYy5tZW1vcnkudjEuTWVtb3J5SWQaJC5haS5zdGlnbWVyLmFnZW50aWMubWVtb3J5LnYxLk1lbW9yeSIrwrgYJwgBEDkiBXZhbHVlKhp1bmF1dGhvcml6ZWQgdG8gZ2V0IG1lbW9yeRJpCgRsaXN0EjEuYWkuc3RpZ21lci5hZ2VudGljLm1lbW9yeS52MS5MaXN0TWVtb3JpZXNSZXF1ZXN0GiguYWkuc3RpZ21lci5hZ2VudGljLm1lbW9yeS52MS5NZW1vcnlMaXN0IgTQuBgBGgSg/ys5YgZwcm90bzM",[file_ai_stigmer_agentic_memory_v1_api,file_ai_stigmer_agentic_memory_v1_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),MemoryQueryController=serviceDesc(file_ai_stigmer_agentic_memory_v1_query,0);var MEMORY_CAPTURE_CALLER_MESSAGE="memory can only be captured for a first-party human operator",MEMORY_CAPTURE_CREDENTIAL_KEY="memoryCaptureCredential";function newGuardMemoryCaptureStep(provider){return{name:"GuardMemoryCapture",async execute(ctx){let caller=ctx.callerIdentity;if(isServerComposedRequest(caller))return;let decide=provider?.authorizeMemoryCapture;if(decide!==void 0){let org=metadataOf(ctx.newState)?.org??"",decision=await decide.call(provider,caller,org);switch(decision.verdict){case"admit":ctx.set(MEMORY_CAPTURE_CREDENTIAL_KEY,{subjectIdentityAccountId:decision.subjectIdentityAccountId,provedSessionId:decision.provedSessionId});return;case"refuse":throw new ConnectError(MEMORY_CAPTURE_CALLER_MESSAGE,Code.PermissionDenied);case"no-opinion":break;default:{let exhaustive=decision;throw new Error(`unknown memory capture decision ${JSON.stringify(exhaustive)}`)}}}if(caller.callerClass==="machine"||carriesPlatformClientClaim(caller.rawToken))throw new ConnectError(MEMORY_CAPTURE_CALLER_MESSAGE,Code.PermissionDenied)}}}function memoryCaptureCredentialOf(ctx){let payload=ctx.get(MEMORY_CAPTURE_CREDENTIAL_KEY);if(typeof payload=="object"&&payload!==null&&"subjectIdentityAccountId"in payload&&"provedSessionId"in payload)return payload}var MEMORY_FULL_MESSAGE="memory is full \u2014 review and delete existing memories";function memoryDisabledMessage(org){return`memory is not enabled for organization ${org} \u2014 an organization admin can enable it in organization preferences`}var MEMORY_ACCOUNT_DISABLED_MESSAGE="memory is not enabled for your account \u2014 enable it in account preferences",MEMORY_CONFIRM_REJECTED_MESSAGE="memory was rejected \u2014 delete it and let the agent propose it again",MEMORY_REJECT_CONFIRMED_MESSAGE="memory was confirmed \u2014 delete it to stop it from being recalled",MEMORY_SUBJECT_IMMUTABLE_MESSAGE="spec.subject_identity_account_id is immutable \u2014 it is derived from the capturing credential at create",MEMORY_PROVENANCE_IMMUTABLE_MESSAGE="spec.provenance is immutable \u2014 it records where the fact came from";var LIST_RESULT_KEY6="listResult";function newResolveMemoryDefaultsStep(personAccounts){return{name:"ResolveMemoryDefaults",async execute(ctx){let memory=ctx.newState,metadata=memory.metadata;if((metadata?.org??"")==="")throw invalidArgumentError("metadata.org is required for a memory");if(metadata===void 0)throw internalError(new Error("metadata is nil"),"metadata is nil");metadata.id===""&&(metadata.id=generateId("mem")),metadata.name===""&&metadata.slug===""&&(metadata.name=metadata.id);let spec=memory.spec;if(spec===void 0)throw internalError(new Error("memory spec is nil"),"memory spec is nil");let captureCredential=memoryCaptureCredentialOf(ctx);if(personAccounts===void 0)spec.subjectIdentityAccountId=captureCredential?.subjectIdentityAccountId??"";else{let account2=await resolveSubjectAccount(personAccounts,ctx,captureCredential?.subjectIdentityAccountId);spec.subjectIdentityAccountId=account2?.metadata?.id??"",account2!==void 0&&ctx.set(MEMORY_SUBJECT_ACCOUNT_KEY,account2)}spec.provenance!==void 0&&(spec.provenance.toolCallId=""),captureCredential!==void 0&&(spec.provenance===void 0&&(spec.provenance=create2(MemoryProvenanceSchema,{})),spec.provenance.sessionId=captureCredential.provedSessionId)}}}var MEMORY_SUBJECT_ACCOUNT_KEY="memorySubjectAccount";function memorySubjectAccountOf(ctx){let payload=ctx.get(MEMORY_SUBJECT_ACCOUNT_KEY);return isMessage2(payload,IdentityAccountSchema)?payload:void 0}async function resolveSubjectAccount(personAccounts,ctx,credentialSubject){let account2;try{account2=credentialSubject!==void 0?await accountForStamp(personAccounts,credentialSubject):await accountForCaller(personAccounts,ctx.callerIdentity)}catch(error2){throw internalError(error2,"failed to resolve the identity account a memory is about")}if(account2!==void 0&&(account2.metadata?.id??"")==="")throw internalError(new Error("identity account carries no id"),"failed to resolve the identity account a memory is about");return account2}var MEMORY_CREATE_DENIED_MESSAGE="unauthorized to capture memory in this organization";function resolveMemoryCreateTargets(ctx){return isServerComposedRequest(ctx.callerIdentity)?[]:[{permission:IamPermission.can_create_session,resourceKind:ApiResourceKind.organization,resourceId:ctx.newState.metadata?.org??"",deniedMessage:MEMORY_CREATE_DENIED_MESSAGE}]}function newCheckMemoryEnablementStep(store,personAccounts){return{name:"CheckMemoryEnablement",async execute(ctx){let orgID=ctx.newState.metadata?.org??"",org;try{org=await store.getResource(ApiResourceKind.organization,orgID,OrganizationSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("Organization",orgID):internalError(error2,"failed to load organization for memory enablement check")}if(org.spec?.preferences?.memoryEnabled!==!0)throw failedPreconditionError(memoryDisabledMessage(orgID));if(personAccounts===void 0)return;if(memorySubjectAccountOf(ctx)?.spec?.preferences?.memoryEnabled!==!0)throw failedPreconditionError(MEMORY_ACCOUNT_DISABLED_MESSAGE)}}}function newCheckMemoryCapStep(store){return{name:"CheckMemoryCap",async execute(ctx){let newState=ctx.newState,org=newState.metadata?.org??"",subject=newState.spec?.subjectIdentityAccountId??"",rows;try{rows=await store.listResources(ApiResourceKind.memory)}catch(error2){throw internalError(error2,"failed to count memories for cap check")}let count=0;for(let bytes of rows){let existing=unmarshalMemory(bytes);existing!==void 0&&(existing.metadata?.org??"")===org&&(existing.spec?.subjectIdentityAccountId??"")===subject&&count++}if(count>=100)throw failedPreconditionError(MEMORY_FULL_MESSAGE)}}}function newInitializeMemoryLifecycleStep(){return{name:"InitializeMemoryLifecycle",execute(ctx){let memory=ctx.newState;memory.status===void 0&&(memory.status=create2(MemoryStatusSchema,{})),memory.status.lifecycleState=MemoryLifecycleState.lifecycle_state_proposed,memory.status.stateChangedAt=timestampNow()}}}function newValidateMemoryUpdateStep(){return{name:"ValidateMemoryUpdate",execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)throw internalError(new Error("existing memory not found in context"),"existing memory not found in context");let newState=ctx.newState;if((newState.spec?.subjectIdentityAccountId??"")!==(existing.spec?.subjectIdentityAccountId??""))throw failedPreconditionError(MEMORY_SUBJECT_IMMUTABLE_MESSAGE);let newProvenance=newState.spec?.provenance,existingProvenance=existing.spec?.provenance;if(!(newProvenance===void 0||existingProvenance===void 0?newProvenance===existingProvenance:equals(MemoryProvenanceSchema,newProvenance,existingProvenance)))throw failedPreconditionError(MEMORY_PROVENANCE_IMMUTABLE_MESSAGE)}}}function newPersistMemoryUpdateStep(store){return{name:"PersistMemoryUpdate",async execute(ctx){let newState=ctx.newState,memoryId=newState.metadata?.id??"",live;try{live=await store.updateResource(ApiResourceKind.memory,memoryId,MemorySchema,row=>{row.apiVersion=newState.apiVersion,row.kind=newState.kind,row.metadata=newState.metadata,row.spec=newState.spec,newState.status?.audit!==void 0&&(row.status===void 0&&(row.status=create2(MemoryStatusSchema,{})),row.status.audit=newState.status.audit)})}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("Memory",memoryId):internalError(error2,"failed to persist memory update")}ctx.setNewState(live)}}}function newTransitionMemoryLifecycleStep(store,target,blockedMessage){return{name:"TransitionMemoryLifecycle",async execute(ctx){let memoryId=ctx.get(EXISTING_RESOURCE_KEY).metadata?.id??"",transitionNoOp=new Error("memory already in target state"),blocked,live;try{live=await store.updateResource(ApiResourceKind.memory,memoryId,MemorySchema,row=>{live=row;let current=row.status?.lifecycleState??MemoryLifecycleState.lifecycle_state_unspecified;if(current===target)throw transitionNoOp;if(current!==MemoryLifecycleState.lifecycle_state_proposed&&current!==MemoryLifecycleState.lifecycle_state_unspecified)throw blocked=failedPreconditionError(blockedMessage),blocked;row.status===void 0&&(row.status=create2(MemoryStatusSchema,{})),row.status.lifecycleState=target,row.status.stateChangedAt=timestampNow(),setAuditFieldsForUpdate(MemorySchema,row,"status_audit",ctx.callerIdentity)})}catch(error2){if(error2!==transitionNoOp)throw blocked!==void 0&&error2===blocked?blocked:error2 instanceof ResourceNotFoundError?notFoundError("Memory",memoryId):internalError(error2,"failed to transition memory lifecycle")}if(live===void 0)throw internalError(new Error("transition closure did not observe the row"),"failed to transition memory lifecycle");ctx.set(EXISTING_RESOURCE_KEY,live)}}}function newListMemoriesByOrgStep(store,listReadScope){return{name:"ListMemoriesByOrg",async execute(ctx){let org=ctx.input.org,rows;try{rows=await store.listResources(ApiResourceKind.memory)}catch(error2){throw internalError(error2,"failed to list memories")}let decoded=[];for(let bytes of rows){let memory=unmarshalMemory(bytes);memory!==void 0&&decoded.push(memory)}let memories=await restrictListByReadScope(listReadScope,ctx.callerIdentity,ApiResourceKind.memory,decoded.filter(memory=>(memory.metadata?.org??"")===org),"");memories.sort((a5,b7)=>compareCreatedAtDesc(a5.status?.audit?.specAudit?.createdAt,b7.status?.audit?.specAudit?.createdAt)),ctx.set(LIST_RESULT_KEY6,create2(MemoryListSchema,{totalCount:memories.length,items:memories}))}}}function unmarshalMemory(data){try{return fromBinary2(MemorySchema,data)}catch{return}}function registerMemoryServices(router,deps){router.service(MemoryCommandController,{create:(memory,ctx)=>createMemory(deps,memory,ctx),update:(memory,ctx)=>update11(deps,memory,ctx),delete:(id,ctx)=>deleteMemory(deps,id,ctx),confirm:(id,ctx)=>confirm(deps,id,ctx),reject:(id,ctx)=>reject(deps,id,ctx)}),router.service(MemoryQueryController,{get:(id,ctx)=>get15(deps,id,ctx),list:(req,ctx)=>list9(deps,req,ctx)})}function kindOf14(ctx){return ctx.values.get(apiResourceKindKey)}async function createMemory(deps,memory,ctx){let reqCtx=new RequestContext(MemorySchema,memory,callerIdentityOf(ctx),kindOf14(ctx));return await newPipeline("memory-create",deps.logger).addStep(newAuthorizeStep(MemoryCommandController.method.create,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newGuardMemoryCaptureStep(deps.runnerCredentialProvider)).addStep(newValidateVisibilityStep()).addStep(newResolveMemoryDefaultsStep(deps.personAccounts)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,resolveMemoryCreateTargets)).addStep(newCheckMemoryEnablementStep(deps.store,deps.personAccounts)).addStep(newCheckMemoryCapStep(deps.store)).addStep(newResolveSlugStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newInitializeMemoryLifecycleStep()).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function update11(deps,memory,ctx){let reqCtx=new RequestContext(MemorySchema,memory,callerIdentityOf(ctx),kindOf14(ctx));return await newPipeline("memory-update",deps.logger).addStep(newAuthorizeStep(MemoryCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingStep(deps.store)).addStep(newValidateMemoryUpdateStep()).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newPersistMemoryUpdateStep(deps.store)).build().execute(reqCtx),reqCtx.newState}async function confirm(deps,memoryId,ctx){return runTransition(deps,memoryId,ctx,"memory-confirm",MemoryCommandController.method.confirm,MemoryLifecycleState.lifecycle_state_confirmed,MEMORY_CONFIRM_REJECTED_MESSAGE)}async function reject(deps,memoryId,ctx){return runTransition(deps,memoryId,ctx,"memory-reject",MemoryCommandController.method.reject,MemoryLifecycleState.lifecycle_state_rejected,MEMORY_REJECT_CONFIRMED_MESSAGE)}async function runTransition(deps,memoryId,ctx,name,method,target,blockedMessage){let reqCtx=new RequestContext(MemoryIdSchema,memoryId,callerIdentityOf(ctx),kindOf14(ctx));await newPipeline(name,deps.logger).addStep(newAuthorizeStep(method,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newExtractResourceIdStep()).addStep(newLoadExistingForDeleteStep(deps.store,MemorySchema)).addStep(newTransitionMemoryLifecycleStep(deps.store,target,blockedMessage)).build().execute(reqCtx);let transitioned=reqCtx.get(EXISTING_RESOURCE_KEY);if(transitioned===void 0)throw internalError(new Error("transitioned memory not found in context"),"transitioned memory not found in context");return transitioned}async function deleteMemory(deps,memoryId,ctx){let reqCtx=new RequestContext(MemoryIdSchema,memoryId,callerIdentityOf(ctx),kindOf14(ctx));await newPipeline("memory-delete",deps.logger).addStep(newAuthorizeStep(MemoryCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newExtractResourceIdStep()).addStep(newLoadExistingForDeleteStep(deps.store,MemorySchema)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted memory not found in context"),"deleted memory not found in context");return deleted}async function get15(deps,memoryId,ctx){let reqCtx=new RequestContext(MemoryIdSchema,memoryId,callerIdentityOf(ctx),kindOf14(ctx));await newPipeline("memory-get",deps.logger).addStep(newAuthorizeStep(MemoryQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newExtractResourceIdStep()).addStep(newLoadTargetStep(deps.store,MemorySchema)).build().execute(reqCtx);let target=reqCtx.get(TARGET_RESOURCE_KEY);if(target===void 0)throw internalError(new Error("target memory not found in context"),"target memory not found in context");return target}async function list9(deps,req,ctx){let reqCtx=new RequestContext(MemoryQueryController.method.list.input,req,callerIdentityOf(ctx),kindOf14(ctx));await newPipeline("memory-list",deps.logger).addStep(newAuthorizeStep(MemoryQueryController.method.list,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newListMemoriesByOrgStep(deps.store,deps.listReadScope)).build().execute(reqCtx);let result=reqCtx.get(LIST_RESULT_KEY6);if(result===void 0)throw internalError(new Error("memory list not found in context"),"memory list not found in context");return result}var file_ai_stigmer_iam_oauthapp_v1_command=fileDesc("CihhaS9zdGlnbWVyL2lhbS9vYXV0aGFwcC92MS9jb21tYW5kLnByb3RvEhphaS5zdGlnbWVyLmlhbS5vYXV0aGFwcC52MTLOBAoZT0F1dGhBcHBDb21tYW5kQ29udHJvbGxlchJTCgVhcHBseRIkLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwGiQuYWkuc3RpZ21lci5pYW0ub2F1dGhhcHAudjEuT0F1dGhBcHASowEKBmNyZWF0ZRIkLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwGiQuYWkuc3RpZ21lci5pYW0ub2F1dGhhcHAudjEuT0F1dGhBcHAiTcK4GEkIFxAeIgxtZXRhZGF0YS5vcmcqNXVuYXV0aG9yaXplZCB0byBjcmVhdGUgb2F1dGggYXBwIGluIHRoaXMgb3JnYW5pemF0aW9uEo0BCgZ1cGRhdGUSJC5haS5zdGlnbWVyLmlhbS5vYXV0aGFwcC52MS5PQXV0aEFwcBokLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwIjfCuBgzCAIQFiILbWV0YWRhdGEuaWQqIHVuYXV0aG9yaXplZCB0byB1cGRhdGUgb2F1dGggYXBwEp8BCgZkZWxldGUSNi5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VEZWxldGVJbnB1dBokLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwIjfCuBgzCAMQFiILcmVzb3VyY2VfaWQqIHVuYXV0aG9yaXplZCB0byBkZWxldGUgb2F1dGggYXBwGgSg/ysWYgZwcm90bzM",[file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options,file_ai_stigmer_iam_oauthapp_v1_api]),OAuthAppCommandController=serviceDesc(file_ai_stigmer_iam_oauthapp_v1_command,0);var file_ai_stigmer_iam_oauthapp_v1_io=fileDesc("CiNhaS9zdGlnbWVyL2lhbS9vYXV0aGFwcC92MS9pby5wcm90bxIaYWkuc3RpZ21lci5pYW0ub2F1dGhhcHAudjEiJgoKT0F1dGhBcHBJZBIYCgV2YWx1ZRgBIAEoCUIJukgGcgQQARhAIkIKCU9BdXRoQXBwcxI1CgdlbnRyaWVzGAEgAygLMiQuYWkuc3RpZ21lci5pYW0ub2F1dGhhcHAudjEuT0F1dGhBcHAiLwoXTGlzdE9BdXRoQXBwc0J5T3JnSW5wdXQSFAoDb3JnGAEgASgJQge6SARyAhABYgZwcm90bzM",[file_ai_stigmer_iam_oauthapp_v1_api,file_buf_validate_validate]);var OAuthAppsSchema=messageDesc2(file_ai_stigmer_iam_oauthapp_v1_io,1);var file_ai_stigmer_iam_oauthapp_v1_query=fileDesc("CiZhaS9zdGlnbWVyL2lhbS9vYXV0aGFwcC92MS9xdWVyeS5wcm90bxIaYWkuc3RpZ21lci5pYW0ub2F1dGhhcHAudjEy0AMKF09BdXRoQXBwUXVlcnlDb250cm9sbGVyEosBCgNnZXQSLS5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VJZBokLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwIi/CuBgrCAEQFiIFdmFsdWUqHnVuYXV0aG9yaXplZCB0byB2aWV3IG9hdXRoIGFwcBJyCg5nZXRCeVJlZmVyZW5jZRI0LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVJlZmVyZW5jZRokLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwIgTQuBgBEqwBCglsaXN0QnlPcmcSMy5haS5zdGlnbWVyLmlhbS5vYXV0aGFwcC52MS5MaXN0T0F1dGhBcHBzQnlPcmdJbnB1dBolLmFpLnN0aWdtZXIuaWFtLm9hdXRoYXBwLnYxLk9BdXRoQXBwcyJDwrgYPwgBEB4iA29yZyo0dW5hdXRob3JpemVkIHRvIGxpc3Qgb2F1dGggYXBwcyBpbiB0aGlzIG9yZ2FuaXphdGlvbhoEoP8rFmIGcHJvdG8z",[file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options,file_ai_stigmer_iam_oauthapp_v1_api,file_ai_stigmer_iam_oauthapp_v1_io]),OAuthAppQueryController=serviceDesc(file_ai_stigmer_iam_oauthapp_v1_query,0);var REDACTED_MARKER3="***REDACTED***",MARKER_ON_CREATE_MESSAGE="cannot use the redaction marker as client_secret on create",PRESERVE_NO_EXISTING_SECRET_MESSAGE="cannot preserve client_secret: no existing secret value found",CIPHERTEXT_SHAPED_SECRET_MESSAGE="client_secret must be plaintext \u2014 values carrying the 'enc:' encryption prefix are not accepted from clients";function deleteBlockedByMcpServerMessage(org,slug,mcpServerName){return`cannot delete OAuthApp '${org}/${slug}': referenced by MCP server '${mcpServerName}'`}async function resolveOAuthAppRef(store,ref,logger2){let slug=ref?.slug??"";if(slug==="")return;let rows=await store.listResources(ApiResourceKind.oauth_app),slugMatches=[];for(let data of rows){let app;try{app=fromBinary2(OAuthAppSchema,data)}catch{continue}if((app.metadata?.slug??"")!==slug)continue;let refOrg=ref?.org??"";if(refOrg!==""&&app.metadata?.org===refOrg)return app;slugMatches.push(app)}if(slugMatches.length!==0){if(slugMatches.length===1)return slugMatches[0];logger2.warn("oauth_app_ref is ambiguous (slug exists in several orgs, none matching the ref); refusing to pick \u2014 pin the ref's org to resolve",{oauthAppSlug:slug,refOrg:ref?.org??"",candidateOrgs:slugMatches.map(app=>app.metadata?.org??"")})}}function redactOAuthApp(app){app.spec!==void 0&&app.spec.clientSecret!==""&&(app.spec.clientSecret=REDACTED_MARKER3)}function newEncryptClientSecretForCreateStep(secretService,logger2){return newEncryptClientSecretStep(secretService,logger2,!0)}function newEncryptClientSecretForUpdateStep(secretService,logger2){return newEncryptClientSecretStep(secretService,logger2,!1)}function newEncryptClientSecretStep(secretService,logger2,isCreate){return{name:"EncryptClientSecret",async execute(ctx){let app=ctx.newState;if(app.spec===void 0)return;let clientSecret=app.spec.clientSecret;if(clientSecret!==""){if(clientSecret===REDACTED_MARKER3){preserveExistingSecret(ctx,app,isCreate,logger2);return}if(isCiphertextShaped(clientSecret))throw invalidArgumentError(CIPHERTEXT_SHAPED_SECRET_MESSAGE);if(!secretService.isEnabled()){logger2.warn("encryption disabled: client_secret will be stored in plaintext");return}try{app.spec.clientSecret=await secretService.encrypt(clientSecret,EncryptionScope.forOrganization(app.metadata?.org??""))}catch(error2){throw internalError(error2,"failed to encrypt client_secret")}}}}}function preserveExistingSecret(ctx,app,isCreate,logger2){if(isCreate)throw invalidArgumentError(MARKER_ON_CREATE_MESSAGE);let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)throw internalError(new Error("existing resource not loaded"),"cannot preserve client_secret: existing resource not loaded");let existingSecret=existing.spec?.clientSecret??"";if(existingSecret==="")throw invalidArgumentError(PRESERVE_NO_EXISTING_SECRET_MESSAGE);app.spec!==void 0&&(app.spec.clientSecret=existingSecret),logger2.debug("preserved existing encrypted client_secret",{oauthAppId:app.metadata?.id??""})}function newCheckNoReferencingMcpServersStep(store,logger2){return{name:"CheckNoReferencingMcpServers",async execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)throw internalError(new Error("existing OAuthApp missing from pipeline context"),"existing OAuthApp not loaded in delete pipeline");let resources;try{resources=await store.listResources(ApiResourceKind.mcp_server)}catch(error2){throw internalError(error2,"failed to list MCP servers for referential integrity check")}for(let data of resources){let mcp;try{mcp=fromBinary2(McpServerSchema,data)}catch(error2){logger2.warn("failed to unmarshal MCP server during referential integrity check, skipping",{error:error2 instanceof Error?error2.message:String(error2)});continue}let ref=mcp.spec?.auth?.oauthAppRef;if(ref===void 0)continue;let resolved;try{resolved=await resolveOAuthAppRef(store,ref,logger2)}catch(error2){throw internalError(error2,"failed to resolve oauth_app_ref during referential integrity check")}if(resolved!==void 0&&(resolved.metadata?.id??"")===(existing.metadata?.id??""))throw failedPreconditionError(deleteBlockedByMcpServerMessage(existing.metadata?.org??"",existing.metadata?.slug??"",mcp.metadata?.name??""))}}}}function registerOAuthAppServices(router,deps){router.service(OAuthAppCommandController,{apply:(app,ctx)=>apply9(deps,app,ctx),create:(app,ctx)=>createOAuthApp(deps,app,ctx),update:(app,ctx)=>update12(deps,app,ctx),delete:(input,ctx)=>deleteOAuthApp(deps,input,ctx)}),router.service(OAuthAppQueryController,{get:(id,ctx)=>get16(deps,id,ctx),getByReference:(ref,ctx)=>getByReference9(deps,ref,ctx),listByOrg:(req,ctx)=>listByOrg2(deps,req,ctx)})}function kindOf15(ctx){return ctx.values.get(apiResourceKindKey)}async function createOAuthApp(deps,app,ctx){let reqCtx=new RequestContext(OAuthAppSchema,app,callerIdentityOf(ctx),kindOf15(ctx));await newPipeline("oauthapp-create",deps.logger).addStep(newAuthorizeStep(OAuthAppCommandController.method.create,deps.authorizer)).addStep(newResolveSlugStep()).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newEncryptClientSecretForCreateStep(deps.secretService,deps.logger)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).build().execute(reqCtx);let result=reqCtx.newState;return redactOAuthApp(result),result}async function update12(deps,app,ctx){let reqCtx=new RequestContext(OAuthAppSchema,app,callerIdentityOf(ctx),kindOf15(ctx));await newPipeline("oauthapp-update",deps.logger).addStep(newAuthorizeStep(OAuthAppCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingStep(deps.store)).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newEncryptClientSecretForUpdateStep(deps.secretService,deps.logger)).addStep(newPersistStep(deps.store)).build().execute(reqCtx);let result=reqCtx.newState;return redactOAuthApp(result),result}async function apply9(deps,app,ctx){let reqCtx=new RequestContext(OAuthAppSchema,app,callerIdentityOf(ctx),kindOf15(ctx));await newPipeline("oauthapp-apply",deps.logger).addStep(newAuthorizeStep(OAuthAppCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");return shouldCreate?createOAuthApp(deps,app,ctx):update12(deps,withResolvedApplyId(OAuthAppSchema,app,reqCtx),ctx)}async function deleteOAuthApp(deps,input,ctx){let reqCtx=new RequestContext(OAuthAppCommandController.method.delete.input,input,callerIdentityOf(ctx),kindOf15(ctx));reqCtx.set(RESOURCE_ID_KEY,input.resourceId),await newPipeline("oauthapp-delete",deps.logger).addStep(newAuthorizeStep(OAuthAppCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingForDeleteStep(deps.store,OAuthAppSchema)).addStep(newCheckNoReferencingMcpServersStep(deps.store,deps.logger)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDestroySecretBackingStateStep(deps.secretService,deps.logger,app2=>app2.spec===void 0?[]:[app2.spec.clientSecret])).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted OAuthApp not found in context"),"deleted OAuthApp not found in context");let app=deleted;return redactOAuthApp(app),app}async function get16(deps,id,ctx){let reqCtx=new RequestContext(OAuthAppQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf15(ctx));await newPipeline("oauthapp-get",deps.logger).addStep(newAuthorizeStep(OAuthAppQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,OAuthAppSchema)).build().execute(reqCtx);let app=reqCtx.get(TARGET_RESOURCE_KEY);return redactOAuthApp(app),app}async function getByReference9(deps,ref,ctx){let reqCtx=new RequestContext(OAuthAppQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf15(ctx));await newPipeline("oauthapp-get-by-reference",deps.logger).addStep(newAuthorizeStep(OAuthAppQueryController.method.getByReference,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadByReferenceStep(deps.store,OAuthAppSchema)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,loadedTargetAsMethod(OAuthAppQueryController.method.get))).build().execute(reqCtx);let app=reqCtx.get(TARGET_RESOURCE_KEY);return redactOAuthApp(app),app}var LIST_RESULT_KEY7="listResult";async function listByOrg2(deps,req,ctx){let reqCtx=new RequestContext(OAuthAppQueryController.method.listByOrg.input,req,callerIdentityOf(ctx),kindOf15(ctx));await newPipeline("oauthapp-list-by-org",deps.logger).addStep(newAuthorizeStep(OAuthAppQueryController.method.listByOrg,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newListByOrgStep2(deps.store,deps.listReadScope,deps.logger)).build().execute(reqCtx);let list12=reqCtx.get(LIST_RESULT_KEY7);if(list12===void 0)throw internalError(new Error("list result missing from pipeline context"),"OAuthApp list not found in context");return list12}function newListByOrgStep2(store,listReadScope,logger2){return{name:"ListByOrg",async execute(ctx){let org=ctx.input.org,resources;try{resources=await store.listResources(ApiResourceKind.oauth_app)}catch(error2){throw internalError(error2,"failed to list OAuthApps")}let requested=[];for(let data of resources){let app;try{app=fromBinary2(OAuthAppSchema,data)}catch(error2){logger2.warn("failed to unmarshal OAuthApp, skipping",{error:error2 instanceof Error?error2.message:String(error2)});continue}(app.metadata?.org??"")===org&&requested.push(app)}let apps=await restrictListByReadScope(listReadScope,ctx.callerIdentity,ApiResourceKind.oauth_app,requested,"");for(let app of apps)redactOAuthApp(app);apps.sort((a5,b7)=>compareCreatedAtDesc(a5.status?.audit?.specAudit?.createdAt,b7.status?.audit?.specAudit?.createdAt)),logger2.info("listed OAuthApps by organization",{org,matchCount:apps.length}),ctx.set(LIST_RESULT_KEY7,create2(OAuthAppsSchema,{entries:apps}))}}}var file_ai_stigmer_iam_platformclient_v1_io=fileDesc("CilhaS9zdGlnbWVyL2lhbS9wbGF0Zm9ybWNsaWVudC92MS9pby5wcm90bxIgYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEiLAoQUGxhdGZvcm1DbGllbnRJZBIYCgV2YWx1ZRgBIAEoCUIJukgGcgQQARhAIlQKD1BsYXRmb3JtQ2xpZW50cxJBCgdlbnRyaWVzGAEgAygLMjAuYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuUGxhdGZvcm1DbGllbnQiNQodTGlzdFBsYXRmb3JtQ2xpZW50c0J5T3JnSW5wdXQSFAoDb3JnGAEgASgJQge6SARyAhABIoABChxQbGF0Zm9ybUNsaWVudENyZWF0ZVJlc3BvbnNlEkkKD3BsYXRmb3JtX2NsaWVudBgBIAEoCzIwLmFpLnN0aWdtZXIuaWFtLnBsYXRmb3JtY2xpZW50LnYxLlBsYXRmb3JtQ2xpZW50EhUKDWNsaWVudF9zZWNyZXQYAiABKAliBnByb3RvMw",[file_ai_stigmer_iam_platformclient_v1_api,file_buf_validate_validate]);var PlatformClientsSchema=messageDesc2(file_ai_stigmer_iam_platformclient_v1_io,1);var PlatformClientCreateResponseSchema=messageDesc2(file_ai_stigmer_iam_platformclient_v1_io,3);var file_ai_stigmer_iam_platformclient_v1_command=fileDesc("Ci5haS9zdGlnbWVyL2lhbS9wbGF0Zm9ybWNsaWVudC92MS9jb21tYW5kLnByb3RvEiBhaS5zdGlnbWVyLmlhbS5wbGF0Zm9ybWNsaWVudC52MTKgBgofUGxhdGZvcm1DbGllbnRDb21tYW5kQ29udHJvbGxlchLPAQoGY3JlYXRlEjAuYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuUGxhdGZvcm1DbGllbnQaPi5haS5zdGlnbWVyLmlhbS5wbGF0Zm9ybWNsaWVudC52MS5QbGF0Zm9ybUNsaWVudENyZWF0ZVJlc3BvbnNlIlPCuBhPCBgQHiIMbWV0YWRhdGEub3JnKjt1bmF1dGhvcml6ZWQgdG8gY3JlYXRlIHBsYXRmb3JtIGNsaWVudCBpbiB0aGlzIG9yZ2FuaXphdGlvbhKrAQoGdXBkYXRlEjAuYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuUGxhdGZvcm1DbGllbnQaMC5haS5zdGlnbWVyLmlhbS5wbGF0Zm9ybWNsaWVudC52MS5QbGF0Zm9ybUNsaWVudCI9wrgYOQgCEBciC21ldGFkYXRhLmlkKiZ1bmF1dGhvcml6ZWQgdG8gdXBkYXRlIHBsYXRmb3JtIGNsaWVudBKxAQoGZGVsZXRlEjYuYWkuc3RpZ21lci5jb21tb25zLmFwaXJlc291cmNlLkFwaVJlc291cmNlRGVsZXRlSW5wdXQaMC5haS5zdGlnbWVyLmlhbS5wbGF0Zm9ybWNsaWVudC52MS5QbGF0Zm9ybUNsaWVudCI9wrgYOQgDEBciC3Jlc291cmNlX2lkKiZ1bmF1dGhvcml6ZWQgdG8gZGVsZXRlIHBsYXRmb3JtIGNsaWVudBLCAQoMcm90YXRlU2VjcmV0EjIuYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuUGxhdGZvcm1DbGllbnRJZBo+LmFpLnN0aWdtZXIuaWFtLnBsYXRmb3JtY2xpZW50LnYxLlBsYXRmb3JtQ2xpZW50Q3JlYXRlUmVzcG9uc2UiPsK4GDoIAhAXIgV2YWx1ZSotdW5hdXRob3JpemVkIHRvIHJvdGF0ZSBwbGF0Zm9ybSBjbGllbnQgc2VjcmV0GgSg/ysXYgZwcm90bzM",[file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options,file_ai_stigmer_iam_platformclient_v1_api,file_ai_stigmer_iam_platformclient_v1_io]),PlatformClientCommandController=serviceDesc(file_ai_stigmer_iam_platformclient_v1_command,0);var file_ai_stigmer_iam_platformclient_v1_query=fileDesc("CixhaS9zdGlnbWVyL2lhbS9wbGF0Zm9ybWNsaWVudC92MS9xdWVyeS5wcm90bxIgYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEykgQKHVBsYXRmb3JtQ2xpZW50UXVlcnlDb250cm9sbGVyEp0BCgNnZXQSLS5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuQXBpUmVzb3VyY2VJZBowLmFpLnN0aWdtZXIuaWFtLnBsYXRmb3JtY2xpZW50LnYxLlBsYXRmb3JtQ2xpZW50IjXCuBgxCAEQFyIFdmFsdWUqJHVuYXV0aG9yaXplZCB0byB2aWV3IHBsYXRmb3JtIGNsaWVudBJ+Cg5nZXRCeVJlZmVyZW5jZRI0LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVJlZmVyZW5jZRowLmFpLnN0aWdtZXIuaWFtLnBsYXRmb3JtY2xpZW50LnYxLlBsYXRmb3JtQ2xpZW50IgTQuBgBEsoBCglsaXN0QnlPcmcSPy5haS5zdGlnbWVyLmlhbS5wbGF0Zm9ybWNsaWVudC52MS5MaXN0UGxhdGZvcm1DbGllbnRzQnlPcmdJbnB1dBoxLmFpLnN0aWdtZXIuaWFtLnBsYXRmb3JtY2xpZW50LnYxLlBsYXRmb3JtQ2xpZW50cyJJwrgYRQgBEB4iA29yZyo6dW5hdXRob3JpemVkIHRvIGxpc3QgcGxhdGZvcm0gY2xpZW50cyBpbiB0aGlzIG9yZ2FuaXphdGlvbhoEoP8rF2IGcHJvdG8z",[file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options,file_ai_stigmer_iam_platformclient_v1_api,file_ai_stigmer_iam_platformclient_v1_io]),PlatformClientQueryController=serviceDesc(file_ai_stigmer_iam_platformclient_v1_query,0);var import_node_crypto21=require("node:crypto"),CLIENT_ID_PREFIX="stgm_cid_",CLIENT_SECRET_PREFIX="stgm_cs_",CLIENT_ID_BYTES=32,CLIENT_SECRET_BYTES=48,SECRET_FINGERPRINT_LENGTH=6;function generateClientId(){return CLIENT_ID_PREFIX+(0,import_node_crypto21.randomBytes)(CLIENT_ID_BYTES).toString("base64url")}function generateClientSecret(){return CLIENT_SECRET_PREFIX+(0,import_node_crypto21.randomBytes)(CLIENT_SECRET_BYTES).toString("base64url")}function hashClientSecret(secret){return(0,import_node_crypto21.createHash)("sha256").update(secret,"utf8").digest("base64url")}function secretFingerprint(secret){return secret.length<=SECRET_FINGERPRINT_LENGTH?secret:secret.slice(-SECRET_FINGERPRINT_LENGTH)}function secretMatchesHash(secret,storedHash){if(storedHash==="")return!1;let presented=Buffer.from(hashClientSecret(secret),"utf8"),stored=Buffer.from(storedHash,"utf8");return presented.length===stored.length&&(0,import_node_crypto21.timingSafeEqual)(presented,stored)}var DuplicatePlatformClientError=class extends Error{constructor(message6,options){super(message6,options),this.name="DuplicatePlatformClientError"}};var CLIENT_SECRET_PLAINTEXT_KEY="platformClientSecretPlaintext";function redactPlatformClient(client){return client.spec!==void 0&&(client.spec.clientSecretHash=""),client}function parkedClientSecret(ctx){let secret=ctx.get(CLIENT_SECRET_PLAINTEXT_KEY);if(typeof secret!="string"||secret==="")throw internalError(new Error("no client secret parked \u2014 a credential step must run first"),"platform client credentials");return secret}function newRefuseReservedSlugStep(){return{name:"RefuseReservedSlug",execute(ctx){let slug=metadataOf(ctx.newState)?.slug??"";if(RESERVED_PLATFORM_CLIENT_SLUGS.has(slug))throw invalidArgumentError(reservedSlugMessage(slug))}}}function newCheckDuplicateStep3(clients){return{name:"CheckDuplicate",async execute(ctx){let metadata=requireMetadata2(ctx,"duplicate check"),existing=await clients.findByOrgAndSlug(metadata.org,metadata.slug);if(existing!==void 0)throw alreadyExistsError(PLATFORM_CLIENT_KIND_NAME,`slug '${metadata.slug}' in org '${metadata.org}' (id: ${existing.metadata?.id??""})`)}}}function newGenerateClientCredentialsStep(){return{name:"GenerateClientCredentials",execute(ctx){let spec=specOf3(ctx.newState),secret=generateClientSecret();spec.clientId=generateClientId(),spec.clientSecretHash=hashClientSecret(secret),spec.secretFingerprint=secretFingerprint(secret),ctx.set(CLIENT_SECRET_PLAINTEXT_KEY,secret)}}}function newPersistNewClientStep(clients){return{name:"Persist",async execute(ctx){try{await clients.save(ctx.newState)}catch(error2){if(error2 instanceof DuplicatePlatformClientError){let metadata=requireMetadata2(ctx,"persist");throw alreadyExistsError(PLATFORM_CLIENT_KIND_NAME,`slug '${metadata.slug}' in org '${metadata.org}'`)}throw internalError(error2,"failed to save platform client")}}}}function newLoadExistingClientStep(clients){return{name:"LoadExisting",async execute(ctx){let metadata=requireMetadata2(ctx,"load existing"),existing;if(metadata.id!==""){if(existing=await clients.findById(metadata.id),existing===void 0)throw notFoundError(PLATFORM_CLIENT_KIND_NAME,metadata.id)}else if(metadata.slug!==""){if(existing=await clients.findByOrgAndSlug(metadata.org,metadata.slug),existing===void 0)throw notFoundError(PLATFORM_CLIENT_KIND_NAME,metadata.slug);metadata.id=existing.metadata?.id??""}else throw invalidArgumentError("resource id or slug is required for update");ctx.set(EXISTING_RESOURCE_KEY,existing)}}}function newPreserveClientCredentialsStep(){return{name:"PreserveClientCredentials",execute(ctx){let existing=storedClientOf(ctx,EXISTING_RESOURCE_KEY),spec=specOf3(ctx.newState);spec.clientId=existing.spec?.clientId??"",spec.clientSecretHash=existing.spec?.clientSecretHash??"",spec.secretFingerprint=existing.spec?.secretFingerprint??""}}}function newPersistUpdatedClientStep(clients){return{name:"Persist",async execute(ctx){try{await clients.update(ctx.newState)}catch(error2){throw internalError(error2,"failed to save platform client")}}}}function newRefuseSystemManagedStep(verb,key){return{name:"RefuseSystemManaged",execute(ctx){if(storedClientOf(ctx,key).metadata?.labels[SYSTEM_MANAGED_LABEL]===RESERVED_LABEL_TRUE)throw failedPreconditionError(systemManagedMessage(verb))}}}function newLoadTargetClientStep(clients){return{name:"LoadTarget",async execute(ctx){let id=idValueOf(ctx.input);if(id==="")throw invalidArgumentError("resource id is required");ctx.set(TARGET_RESOURCE_KEY,await readClient(clients,id))}}}function newLoadClientByReferenceStep(clients){return{name:"LoadByReference",async execute(ctx){let ref=ctx.input;if(ref.slug==="")throw invalidArgumentError("slug is required in reference");if(ref.kind!==ApiResourceKind.api_resource_kind_unknown&&ref.kind!==ApiResourceKind.platform_client)throw invalidArgumentError(`kind mismatch: expected platform_client, got ${ApiResourceKind[ref.kind]??String(ref.kind)}`);requireOrgForReference(ApiResourceKind.platform_client,ref.org);let client=await clients.findByOrgAndSlug(ref.org,ref.slug);if(client===void 0)throw new ConnectError(referenceNotFoundMessage(ref.org,ref.slug),Code.NotFound);ctx.set(TARGET_RESOURCE_KEY,client)}}}function newRotateClientCredentialsStep(){return{name:"RotateClientCredentials",execute(ctx){let client=storedClientOf(ctx,TARGET_RESOURCE_KEY),spec=specOf3(client),secret=generateClientSecret();spec.clientSecretHash=hashClientSecret(secret),spec.secretFingerprint=secretFingerprint(secret),updateAuditFields(PlatformClientSchema,client,client,ctx.callerIdentity),ctx.set(CLIENT_SECRET_PLAINTEXT_KEY,secret)}}}function newPersistTargetClientStep(clients){return{name:"Persist",async execute(ctx){try{await clients.update(storedClientOf(ctx,TARGET_RESOURCE_KEY))}catch(error2){throw internalError(error2,"failed to save platform client")}}}}function newLoadExistingClientForDeleteStep(clients){return{name:"LoadExistingForDelete",async execute(ctx){ctx.set(EXISTING_RESOURCE_KEY,await readClient(clients,requireResourceId3(ctx)))}}}function newDeleteClientStep(clients){return{name:"DeleteResource",async execute(ctx){try{await clients.deleteById(requireResourceId3(ctx))}catch(error2){throw internalError(error2,"failed to delete platform client")}}}}async function readClient(clients,id){let client=await clients.findById(id);if(client===void 0)throw notFoundError(PLATFORM_CLIENT_KIND_NAME,id);return client}function storedClientOf(ctx,key){let client=ctx.get(key);if(client===void 0)throw internalError(new Error(`no platform client under '${key}' \u2014 its load step must run first`),"platform client chain ordering");return client}function requireMetadata2(ctx,operation2){let metadata=metadataOf(ctx.newState);if(metadata===void 0)throw internalError(new Error("platform client metadata is nil"),operation2);return metadata}function specOf3(client){return client.spec===void 0&&(client.spec=create2(PlatformClientSpecSchema)),client.spec}function requireResourceId3(ctx){let id=ctx.get(RESOURCE_ID_KEY);if(typeof id!="string"||id==="")throw internalError(new Error("resource id not found in context (the delete handler sets it)"),"platform client delete ordering");return id}function registerPlatformClientServices(router,deps){router.service(PlatformClientCommandController,{create:(client,ctx)=>createClient2(deps,client,ctx),update:(client,ctx)=>updateClient(deps,client,ctx),delete:(input,ctx)=>deleteClient(deps,input,ctx),rotateSecret:(id,ctx)=>rotateSecret(deps,id,ctx)}),router.service(PlatformClientQueryController,{get:(id,ctx)=>get17(deps,id,ctx),getByReference:(ref,ctx)=>getByReference10(deps,ref,ctx),listByOrg:(input,ctx)=>listByOrg3(deps,input,ctx)})}function kindOf16(ctx){return ctx.values.get(apiResourceKindKey)}async function createClient2(deps,client,ctx){let reqCtx=new RequestContext(PlatformClientSchema,client,callerIdentityOf(ctx),kindOf16(ctx));return await newPipeline("platformclient-create",deps.logger).addStep(newAuthorizeStep(PlatformClientCommandController.method.create,deps.authorizer)).addStep(newResolveSlugStep()).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newRefuseReservedSlugStep()).addStep(newCheckDuplicateStep3(deps.clients)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store)).addStep(newGenerateClientCredentialsStep()).addStep(newPersistNewClientStep(deps.clients)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).build().execute(reqCtx),create2(PlatformClientCreateResponseSchema,{platformClient:redactPlatformClient(reqCtx.newState),clientSecret:parkedClientSecret(reqCtx)})}async function updateClient(deps,client,ctx){let reqCtx=new RequestContext(PlatformClientSchema,client,callerIdentityOf(ctx),kindOf16(ctx));return await newPipeline("platformclient-update",deps.logger).addStep(newAuthorizeStep(PlatformClientCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingClientStep(deps.clients)).addStep(newRefuseSystemManagedStep("updated",EXISTING_RESOURCE_KEY)).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store)).addStep(newPreserveClientCredentialsStep()).addStep(newPersistUpdatedClientStep(deps.clients)).build().execute(reqCtx),redactPlatformClient(reqCtx.newState)}async function deleteClient(deps,input,ctx){let reqCtx=new RequestContext(PlatformClientCommandController.method.delete.input,input,callerIdentityOf(ctx),kindOf16(ctx));return reqCtx.set(RESOURCE_ID_KEY,input.resourceId),await newPipeline("platformclient-delete",deps.logger).addStep(newAuthorizeStep(PlatformClientCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingClientForDeleteStep(deps.clients)).addStep(newRefuseSystemManagedStep("deleted",EXISTING_RESOURCE_KEY)).addStep(newDeleteClientStep(deps.clients)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).build().execute(reqCtx),redactPlatformClient(storedClientOf(reqCtx,EXISTING_RESOURCE_KEY))}async function rotateSecret(deps,id,ctx){let reqCtx=new RequestContext(PlatformClientCommandController.method.rotateSecret.input,id,callerIdentityOf(ctx),kindOf16(ctx));return await newPipeline("platformclient-rotate-secret",deps.logger).addStep(newAuthorizeStep(PlatformClientCommandController.method.rotateSecret,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetClientStep(deps.clients)).addStep(newRefuseSystemManagedStep("rotated",TARGET_RESOURCE_KEY)).addStep(newRotateClientCredentialsStep()).addStep(newPersistTargetClientStep(deps.clients)).build().execute(reqCtx),create2(PlatformClientCreateResponseSchema,{platformClient:redactPlatformClient(storedClientOf(reqCtx,TARGET_RESOURCE_KEY)),clientSecret:parkedClientSecret(reqCtx)})}async function get17(deps,id,ctx){let reqCtx=new RequestContext(PlatformClientQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf16(ctx));return await newPipeline("platformclient-get",deps.logger).addStep(newAuthorizeStep(PlatformClientQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetClientStep(deps.clients)).build().execute(reqCtx),redactPlatformClient(storedClientOf(reqCtx,TARGET_RESOURCE_KEY))}async function getByReference10(deps,ref,ctx){let reqCtx=new RequestContext(PlatformClientQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf16(ctx));return await newPipeline("platformclient-get-by-reference",deps.logger).addStep(newAuthorizeStep(PlatformClientQueryController.method.getByReference,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadClientByReferenceStep(deps.clients)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,loadedTargetAsMethod(PlatformClientQueryController.method.get))).build().execute(reqCtx),redactPlatformClient(storedClientOf(reqCtx,TARGET_RESOURCE_KEY))}async function listByOrg3(deps,input,ctx){let caller=callerIdentityOf(ctx),reqCtx=new RequestContext(PlatformClientQueryController.method.listByOrg.input,input,caller,kindOf16(ctx));await newPipeline("platformclient-list-by-org",deps.logger).addStep(newAuthorizeStep(PlatformClientQueryController.method.listByOrg,deps.authorizer)).addStep(newValidateProtoStep()).build().execute(reqCtx);let candidates;try{candidates=await deps.clients.findByOrg(input.org)}catch(error2){throw internalError(error2,"failed to list platform clients")}let entries=[...await restrictListByReadScope(deps.listReadScope,caller,ApiResourceKind.platform_client,candidates,input.org)].sort((a5,b7)=>compareCreatedAtDesc(a5.status?.audit?.specAudit?.createdAt,b7.status?.audit?.specAudit?.createdAt)).map(redactPlatformClient);return create2(PlatformClientsSchema,{entries})}var OPAQUE_ORIGIN="null";function newPlatformClientOriginGuard(deps){return{name:"platform-client-origin",async guard(caller,method,headers2){let origin=headers2.get("origin")??"";if(origin.trim()==="")return;let platformClientId=mintingClientOf(caller);if(platformClientId===void 0)return;let procedure=`/${method.parent.typeName}/${method.name}`,client=await deps.clients.findById(platformClientId);if(client===void 0)throw new ConnectError(DELETED_CLIENT_MESSAGE,Code.Unauthenticated);if(!originAllowed(origin,client.spec?.allowedOrigins??[]))throw deps.logger.warn("origin refusal: origin not in allowed_origins",{procedure,platformClientId,origin}),new ConnectError(originRefusalMessage(origin),Code.PermissionDenied)}}}function mintingClientOf(caller){let payload=decodeVerifiedPlatformTokenPayload(caller.rawToken);if(!(payload===void 0||stringClaim(payload,TOKEN_TYPE_CLAIM)!==void 0))return stringClaim(payload,USER_TOKEN_CLAIMS.platformClientId)}function originAllowed(origin,allowed){if(allowed.length===0)return!0;if(origin===OPAQUE_ORIGIN)return!1;let presented=origin.toLowerCase();return allowed.some(entry=>entry.toLowerCase()===presented)}var KIND5=ApiResourceKind.platform_client;function newResourcePlatformClientStore(store){async function readById(id){try{return await store.getResource(KIND5,id,PlatformClientSchema)}catch(error2){if(error2 instanceof ResourceNotFoundError)return;throw error2}}async function readByClientId(clientId){if(clientId!=="")try{return await store.findByField(KIND5,"spec.clientId",clientId,PlatformClientSchema)}catch(error2){if(error2 instanceof ResourceNotFoundError)return;throw error2}}async function listOrg(org){let clients=[];for(let data of await store.listResources(KIND5)){let client;try{client=fromBinary2(PlatformClientSchema,data)}catch{continue}(client.metadata?.org??"")===org&&clients.push(client)}return clients}async function readByOrgAndSlug(org,slug){if(!(org===""||slug===""))return(await listOrg(org)).find(client=>(client.metadata?.slug??"")===slug)}return{async save(client){let id=client.metadata?.id??"",org=client.metadata?.org??"",slug=client.metadata?.slug??"";if(await readById(id)!==void 0)throw new DuplicatePlatformClientError(`platform client '${id}' already exists`);if(await readByOrgAndSlug(org,slug)!==void 0)throw new DuplicatePlatformClientError(`platform client '${org}/${slug}' already exists`);if(await readByClientId(client.spec?.clientId??"")!==void 0)throw new DuplicatePlatformClientError("a platform client already holds this client_id");await store.saveResource(KIND5,id,PlatformClientSchema,client)},async update(client){let id=client.metadata?.id??"";await readById(id)!==void 0&&await store.saveResource(KIND5,id,PlatformClientSchema,client)},async modifyById(id,modify){try{return await store.updateResource(KIND5,id,PlatformClientSchema,modify)}catch(error2){if(error2 instanceof ResourceNotFoundError)return;throw error2}},async deleteById(id){await store.deleteResource(KIND5,id)},findById:readById,findByClientId:readByClientId,findByOrgAndSlug:readByOrgAndSlug,findByOrg:listOrg}}var file_ai_stigmer_iam_platformclient_v1_token=fileDesc("CixhaS9zdGlnbWVyL2lhbS9wbGF0Zm9ybWNsaWVudC92MS90b2tlbi5wcm90bxIgYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEiugEKFE1pbnRVc2VyVG9rZW5SZXF1ZXN0EhoKCWNsaWVudF9pZBgBIAEoCUIHukgEcgIQARIeCg1jbGllbnRfc2VjcmV0GAIgASgJQge6SARyAhABEhsKB3VzZXJfaWQYAyABKAlCCrpIB3IFEAEYgAISHAoKdXNlcl9lbWFpbBgEIAEoCUIIukgFcgMYwAISGwoJdXNlcl9uYW1lGAUgASgJQgi6SAVyAxiAAhIOCgZvcmdfaWQYBiABKAkiVQoVTWludFVzZXJUb2tlblJlc3BvbnNlEhQKDGFjY2Vzc190b2tlbhgBIAEoCRISCgp0b2tlbl90eXBlGAIgASgJEhIKCmV4cGlyZXNfaW4YAyABKAUiyQMKFU1pbnRHdWVzdFRva2VuUmVxdWVzdBIUCgNvcmcYASABKAlCB7pIBHICEAESFQoEc2x1ZxgCIAEoCUIHukgEcgIQARIXCg9ndWVzdF9jb29raWVfaWQYAyABKAkSywIKDGVtYmVkX29yaWdpbhgEIAEoCUK0ArpIsAK6AawCChNlbWJlZF9vcmlnaW4uZm9ybWF0EndlbWJlZF9vcmlnaW4gbXVzdCBiZSBlbXB0eSwgIm51bGwiLCBvciBhbiBleGFjdCB3ZWIgb3JpZ2luIGxpa2UgaHR0cHM6Ly9leGFtcGxlLmNvbSAobm8gcGF0aCwgcXVlcnksIG9yIHRyYWlsaW5nIHNsYXNoKRqbAXRoaXMgPT0gJycgfHwgdGhpcyA9PSAnbnVsbCcgfHwgdGhpcy5tYXRjaGVzKCdeaHR0cHM/Oi8vW0EtWmEtejAtOV0oW0EtWmEtejAtOS1dKltBLVphLXowLTldKT8oXFwuW0EtWmEtejAtOV0oW0EtWmEtejAtOS1dKltBLVphLXowLTldKT8pKig6WzAtOV17MSw1fSk/JCcpEhwKCmxpbmtfdG9rZW4YBSABKAlCCLpIBXIDGIABIm8KFk1pbnRHdWVzdFRva2VuUmVzcG9uc2USFAoMYWNjZXNzX3Rva2VuGAEgASgJEhIKCnRva2VuX3R5cGUYAiABKAkSEgoKZXhwaXJlc19pbhgDIAEoBRIXCg9ndWVzdF9jb29raWVfaWQYBCABKAkytAIKHVBsYXRmb3JtQ2xpZW50VG9rZW5Db250cm9sbGVyEoYBCg1taW50VXNlclRva2VuEjYuYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuTWludFVzZXJUb2tlblJlcXVlc3QaNy5haS5zdGlnbWVyLmlhbS5wbGF0Zm9ybWNsaWVudC52MS5NaW50VXNlclRva2VuUmVzcG9uc2UiBMi4GAESiQEKDm1pbnRHdWVzdFRva2VuEjcuYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuTWludEd1ZXN0VG9rZW5SZXF1ZXN0GjguYWkuc3RpZ21lci5pYW0ucGxhdGZvcm1jbGllbnQudjEuTWludEd1ZXN0VG9rZW5SZXNwb25zZSIEyLgYAWIGcHJvdG8z",[file_ai_stigmer_commons_rpc_method_options,file_buf_validate_validate]);var MintUserTokenResponseSchema=messageDesc2(file_ai_stigmer_iam_platformclient_v1_token,1);var PlatformClientTokenController=serviceDesc(file_ai_stigmer_iam_platformclient_v1_token,0);var import_node_crypto22=require("node:crypto");var PLATFORM_TOKEN_KEY_ENV_VAR="STIGMER_PLATFORM_TOKEN_KEY",PLATFORM_TOKEN_KEY_FILE_NAME="platform-token.key",DEFAULT_PLATFORM_TOKEN_TTL_SECONDS=900,MIN_RSA_MODULUS_BITS=2048;function canSign(ring){return ring.signer!==void 0}function resolvePlatformTokenKeys(input){if(input.requireAuthentication){if(input.supplied!==void 0)return input.supplied;if(input.edition!==ServerEdition.oss)throw new Error(`the ${ServerEdition[input.edition]} edition requires authentication but registers no platform-token key ring \u2014 register drivers.platformTokenKeys; only open source generates its own key`);return openSourcePlatformTokenKeyRing(input.options)}}function openSourcePlatformTokenKeyRing(options={}){let privateKey=getOrCreateKey(RSA_PRIVATE_KEY,PLATFORM_TOKEN_KEY_ENV_VAR,PLATFORM_TOKEN_KEY_FILE_NAME,options);return{signer:{key:privateKey,kid:kidOf(privateKey)},verificationKeys:[(0,import_node_crypto22.createPublicKey)(privateKey)],audience:"",ttlSeconds:DEFAULT_PLATFORM_TOKEN_TTL_SECONDS}}var RSA_PRIVATE_KEY={fromEnv(envVar,decoded){let key=parseKey2(()=>(0,import_node_crypto22.createPrivateKey)(decoded.toString("utf8")),envVar);return requireRsa(key,envVar)},fromFile(content){try{let key=(0,import_node_crypto22.createPrivateKey)(content.toString("utf8"));return isUsableRsa(key)?key:void 0}catch{return}},generate(){return(0,import_node_crypto22.generateKeyPairSync)("rsa",{modulusLength:MIN_RSA_MODULUS_BITS}).privateKey},toFile(key){return Buffer.from(key.export({format:"pem",type:"pkcs8"}))}};function kidOf(key){let publicKey=key.type==="private"?(0,import_node_crypto22.createPublicKey)(key):key;return(0,import_node_crypto22.createHash)("sha256").update(spkiOf(publicKey)).digest("base64url").slice(0,16)}function spkiOf(publicKey){return publicKey.export({format:"der",type:"spki"})}function parseKey2(parse5,what){try{return parse5()}catch(error2){throw new Error(`${what} is not a readable PEM key: ${error2 instanceof Error?error2.message:String(error2)}`)}}function requireRsa(key,what){if(!isUsableRsa(key))throw new Error(`${what} must be an RSA key of at least ${MIN_RSA_MODULUS_BITS} bits`);return key}function isUsableRsa(key){return key.asymmetricKeyType==="rsa"&&(key.asymmetricKeyDetails?.modulusLength??0)>=MIN_RSA_MODULUS_BITS}var SUBJECT_SEPARATOR="|",DEFAULT_AUTO_GRANT_ROLE=IamRole.viewer;async function mintUserToken(deps,request){let keys=deps.keys;if(keys===void 0)throw new ConnectError(MINTING_REQUIRES_AUTHENTICATION_MESSAGE,Code.FailedPrecondition);if(!canSign(keys))throw new ConnectError(MINTING_DISABLED_MESSAGE,Code.FailedPrecondition);let client=await authenticateClient(deps,request),owningOrg=client.metadata?.org??"";if(request.orgId!==""&&request.orgId!==owningOrg)throw new ConnectError(organizationMismatchMessage(owningOrg),Code.InvalidArgument);let user={externalUserId:request.userId,email:request.userEmail,name:request.userName},accountId=await resolveOrProvisionAccount(deps,client,owningOrg,user),now=deps.now(),signed=signPlatformToken(keys,{[USER_TOKEN_CLAIMS.subject]:accountId,[USER_TOKEN_CLAIMS.externalUserId]:user.externalUserId,[USER_TOKEN_CLAIMS.email]:user.email,[USER_TOKEN_CLAIMS.name]:user.name,[USER_TOKEN_CLAIMS.org]:owningOrg,[USER_TOKEN_CLAIMS.platformClientId]:client.metadata?.id??""},{now});return await recordClientUse(deps,client,now),create2(MintUserTokenResponseSchema,{accessToken:signed.token,tokenType:BEARER_TOKEN_TYPE,expiresIn:keys.ttlSeconds})}async function authenticateClient(deps,request){let client;try{client=await deps.clients.findByClientId(request.clientId)}catch(error2){throw internalError(error2,"failed to authenticate platform client")}if(client===void 0||!secretMatchesHash(request.clientSecret,client.spec?.clientSecretHash??""))throw new ConnectError(INVALID_CLIENT_CREDENTIALS_MESSAGE,Code.Unauthenticated);let spec=client.spec;if(spec?.neverExpires!==!0&&spec?.expiresAt!==void 0&&deps.now().getTime()>timestampDate(spec.expiresAt).getTime())throw new ConnectError(EXPIRED_CLIENT_SECRET_MESSAGE,Code.FailedPrecondition);return client}function recordClientUse(deps,client,now){let id=client.metadata?.id??"";return recordCredentialUse({credential:"platform client",id,lastUsedAt:client.status?.lastUsedAt,now,logger:deps.logger,write:stamp2=>deps.clients.modifyById(id,live=>{live.status??=create2(PlatformClientStatusSchema),stamp2(live.status)})})}async function resolveOrProvisionAccount(deps,client,org,user){let idpId=platformClientSubject(org,user.externalUserId),existing=await findAccount(deps,idpId);if(existing!==void 0)return platformClientAccountId(existing,user,org);let spec=client.spec;if(spec?.autoProvisionAccounts!==!0)throw new ConnectError(noAccountMessage(user.externalUserId,org),Code.FailedPrecondition);let input=accountInput(idpId,org,user),actor=serverActingFor(client.metadata?.id??"");spec.autoGrantOnOrg&&await grantAutoRole(deps,client,org,accountIdFor(idpId),actor);try{return(await deps.createAccount(input,actor)).metadata?.id??""}catch(error2){let winner=await resolveCreateRace(error2,()=>deps.accounts.findByIdpId(idpId));return platformClientAccountId(winner,user,org)}}async function findAccount(deps,idpId){try{return await deps.accounts.findByIdpId(idpId)}catch(error2){throw internalError(error2,"failed to resolve platform client user")}}function platformClientAccountId(account2,user,org){if(account2.spec?.provisioningMode!==IdentityAccountProvisioningMode.platform_client)throw new ConnectError(foreignAccountMessage(user.externalUserId,org),Code.FailedPrecondition);return account2.metadata?.id??""}function accountInput(idpId,org,user){let input={name:user.email!==""?user.email:user.externalUserId,spec:create2(IdentityAccountSpecSchema,{idpId,email:user.email,...splitName(user.name,user.email)}),provisioning:{mode:"platform_client",org}},result=validator().validate(IdentityAccountSchema,create2(IdentityAccountSchema,{apiVersion:"iam.stigmer.ai/v1",kind:"IdentityAccount",metadata:{name:input.name,org},spec:input.spec}));if(result.kind==="invalid")throw new ConnectError(result.error.message,Code.InvalidArgument);if(result.kind==="error")throw new ConnectError(`validation could not run: ${result.error.message}`,Code.Internal);return input}async function grantAutoRole(deps,client,org,accountId,actor){let configured=client.spec?.autoGrantRole??IamRole.iam_role_unspecified;if(configured===IamRole.owner)throw new ConnectError(OWNER_AUTO_GRANT_MESSAGE,Code.InvalidArgument);let role=configured===IamRole.iam_role_unspecified?DEFAULT_AUTO_GRANT_ROLE:configured;try{await deps.grantPath.grant(organizationRole(accountId,role,org),actor)}catch(error2){throw deps.logger.error("platform client auto-grant failed; nothing was provisioned",{accountId,platformClientId:client.metadata?.id??"",error:error2 instanceof Error?error2.message:String(error2)}),new ConnectError(PROVISIONING_FAILED_MESSAGE,Code.Internal)}}function platformClientSubject(org,externalUserId){return requireSubjectPart("org",org),requireSubjectPart("externalUserId",externalUserId),`${PLATFORM_CLIENT_SUBJECT_PREFIX}${org}${SUBJECT_SEPARATOR}${externalUserId}`}function requireSubjectPart(part,value){if(value.trim()==="")throw new ConnectError(blankSubjectPartMessage(part),Code.InvalidArgument);if(value.includes(SUBJECT_SEPARATOR))throw new ConnectError(subjectSeparatorMessage(part,value),Code.InvalidArgument)}function splitName(name,email){if(name!==""){let space=name.indexOf(" ");return space>0?{firstName:name.slice(0,space),lastName:name.slice(space+1)}:{firstName:name,lastName:""}}let at2=email.indexOf("@");return{firstName:at2>=0?email.slice(0,at2):email,lastName:""}}function registerPlatformClientTokenService(router,deps){router.service(PlatformClientTokenController,{mintUserToken:request=>mintUserToken(deps.mint,request),mintGuestToken:(request,ctx)=>{if(deps.guestTokenMinting===void 0)throw new ConnectError(GUEST_MINT_UNIMPLEMENTED_MESSAGE,Code.Unimplemented);return deps.guestTokenMinting.mintGuestToken(request,ctx.requestHeader)}})}function newPlatformClientTokenVerifier(deps){return{name:"platform-client",async verify(token){let result=verifyPlatformToken(deps.keys,token,deps.now?.());switch(result.outcome){case"foreign":return null;case"refused":throw platformTokenRefusalError(result.refusal);case"verified":break;default:{let exhaustive=result;throw new Error(`unknown verification ${JSON.stringify(exhaustive)}`)}}let verified=result.token;if(verified.tokenType!==void 0)return null;let platformClientId=stringClaim(verified.payload,USER_TOKEN_CLAIMS.platformClientId);if(platformClientId===void 0)throw new ConnectError(TOKEN_NAMES_NO_CLIENT_MESSAGE,Code.Unauthenticated);if(await deps.clients.findById(platformClientId)===void 0)throw new ConnectError(DELETED_CLIENT_MESSAGE,Code.Unauthenticated);let email=stringClaim(verified.payload,USER_TOKEN_CLAIMS.email),displayName=stringClaim(verified.payload,USER_TOKEN_CLAIMS.name);return{identityId:verified.subject,callerClass:"user",issuer:PLATFORM_TOKEN_ISSUER,rawToken:token,...email!==void 0?{email}:{},...displayName!==void 0?{displayName}:{},platformClientId}}}}var file_ai_stigmer_tenancy_organization_v1_io=fileDesc("CithaS9zdGlnbWVyL3RlbmFuY3kvb3JnYW5pemF0aW9uL3YxL2lvLnByb3RvEiJhaS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxIlIKDU9yZ2FuaXphdGlvbnMSQQoHZW50cmllcxgBIAMoCzIwLmFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEuT3JnYW5pemF0aW9uImoKEE9yZ2FuaXphdGlvbkxpc3QSEwoLdG90YWxfcGFnZXMYASABKAUSQQoHZW50cmllcxgCIAMoCzIwLmFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEuT3JnYW5pemF0aW9uIioKDk9yZ2FuaXphdGlvbklkEhgKBXZhbHVlGAEgASgJQgm6SAZyBBABGEAimwEKGk9yZ2FuaXphdGlvbkV4dGVybmFsTG9va3VwElsKFWlkZW50aXR5X3Byb3ZpZGVyX3JlZhgBIAEoCzI0LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVJlZmVyZW5jZUIGukgDyAEBEiAKD2V4dGVybmFsX29yZ19pZBgCIAEoCUIHukgEcgIQAWIGcHJvdG8z",[file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_tenancy_organization_v1_api,file_buf_validate_validate]),OrganizationsSchema=messageDesc2(file_ai_stigmer_tenancy_organization_v1_io,0),OrganizationListSchema=messageDesc2(file_ai_stigmer_tenancy_organization_v1_io,1);var file_ai_stigmer_tenancy_organization_v1_command=fileDesc("CjBhaS9zdGlnbWVyL3RlbmFuY3kvb3JnYW5pemF0aW9uL3YxL2NvbW1hbmQucHJvdG8SImFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEy2AQKHU9yZ2FuaXphdGlvbkNvbW1hbmRDb250cm9sbGVyEmsKBWFwcGx5EjAuYWkuc3RpZ21lci50ZW5hbmN5Lm9yZ2FuaXphdGlvbi52MS5Pcmdhbml6YXRpb24aMC5haS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxLk9yZ2FuaXphdGlvbhJyCgZjcmVhdGUSMC5haS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxLk9yZ2FuaXphdGlvbhowLmFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEuT3JnYW5pemF0aW9uIgTQuBgBEqgBCgZ1cGRhdGUSMC5haS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxLk9yZ2FuaXphdGlvbhowLmFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEuT3JnYW5pemF0aW9uIjrCuBg2CAIQHiILbWV0YWRhdGEuaWQqI3VuYXV0aG9yaXplZCB0byB1cGRhdGUgb3JnYW5pemF0aW9uEqQBCgZkZWxldGUSMi5haS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxLk9yZ2FuaXphdGlvbklkGjAuYWkuc3RpZ21lci50ZW5hbmN5Lm9yZ2FuaXphdGlvbi52MS5Pcmdhbml6YXRpb24iNMK4GDAIAxAeIgV2YWx1ZSojdW5hdXRob3JpemVkIHRvIGRlbGV0ZSBvcmdhbml6YXRpb24aBKD/Kx5iBnByb3RvMw",[file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options,file_ai_stigmer_tenancy_organization_v1_api,file_ai_stigmer_tenancy_organization_v1_io]),OrganizationCommandController=serviceDesc(file_ai_stigmer_tenancy_organization_v1_command,0);var file_ai_stigmer_tenancy_organization_v1_query=fileDesc("Ci5haS9zdGlnbWVyL3RlbmFuY3kvb3JnYW5pemF0aW9uL3YxL3F1ZXJ5LnByb3RvEiJhaS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxMrkEChtPcmdhbml6YXRpb25RdWVyeUNvbnRyb2xsZXISnwEKA2dldBIyLmFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEuT3JnYW5pemF0aW9uSWQaMC5haS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxLk9yZ2FuaXphdGlvbiIywrgYLggBEB4iBXZhbHVlKiF1bmF1dGhvcml6ZWQgdG8gdmlldyBvcmdhbml6YXRpb24SewoEZmluZBI3LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5GaW5kQXBpUmVzb3VyY2VzUmVxdWVzdBo0LmFpLnN0aWdtZXIudGVuYW5jeS5vcmdhbml6YXRpb24udjEuT3JnYW5pemF0aW9uTGlzdCIE0LgYARJmChNmaW5kTXlPcmdhbml6YXRpb25zEhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5GjEuYWkuc3RpZ21lci50ZW5hbmN5Lm9yZ2FuaXphdGlvbi52MS5Pcmdhbml6YXRpb25zIgTQuBgBEowBChJnZXRCeUV4dGVybmFsT3JnSWQSPi5haS5zdGlnbWVyLnRlbmFuY3kub3JnYW5pemF0aW9uLnYxLk9yZ2FuaXphdGlvbkV4dGVybmFsTG9va3VwGjAuYWkuc3RpZ21lci50ZW5hbmN5Lm9yZ2FuaXphdGlvbi52MS5Pcmdhbml6YXRpb24iBNC4GAEaBKD/Kx5iBnByb3RvMw",[file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options,file_ai_stigmer_tenancy_organization_v1_api,file_ai_stigmer_tenancy_organization_v1_io,file_google_protobuf_empty]),OrganizationQueryController=serviceDesc(file_ai_stigmer_tenancy_organization_v1_query,0);var organizationSearchExtractor={kind:ApiResourceKind.organization,schema:OrganizationSchema,getSearchSummary(resource){return resource.spec?.description??""},toSearchResult(resource,score){let org=resource;return buildSearchResult({kind:ApiResourceKind.organization,metadata:org.metadata,summary:org.spec?.description??"",score,createdAt:org.status?.audit?.specAudit?.createdAt,updatedAt:org.status?.audit?.specAudit?.updatedAt})},getSearchIndexEntry(resource){let org=resource,metadata=org.metadata;if(metadata!==void 0)return{name:metadata.name,description:org.spec?.description??"",tags:metadata.tags.join(" "),org:metadata.org,visibility:ApiResourceVisibility[metadata.visibility]??"",createdAt:Number(org.status?.audit?.specAudit?.createdAt?.seconds??0n)}}};var ORGANIZATION_SLUG_RESERVED="ORGANIZATION_SLUG_RESERVED",CLAIMED_SLUG_KEY="organizationSlugClaim";function organizationSlugReservedMessage(slug){return`Organization slug '${slug}' belonged to an organization that was deleted, and a slug is never reused`}function refusalForHeldSlug(entry){return entry.retiredAt!==""?alreadyExistsWithReasonError(organizationSlugReservedMessage(entry.slug),{reason:ORGANIZATION_SLUG_RESERVED,metadata:{slug:entry.slug}}):alreadyExistsError("Organization",`slug '${entry.slug}'`)}function newClaimOrganizationSlugStep(store){return{name:"ClaimOrganizationSlug",async execute(ctx){let slug=metadataOf(ctx.newState)?.slug??"";if(slug==="")throw internalError(new Error("organization slug is empty"),"failed to claim the organization slug");let claim;try{claim=await store.organizationSlugs.claim(slug)}catch(error2){throw internalError(error2,"failed to claim the organization slug")}if(!claim.claimed)throw refusalForHeldSlug(claim.entry);ctx.set(CLAIMED_SLUG_KEY,claim.entry)}}}async function releaseSlugClaimAfterFailure(store,logger2,ctx){let entry=ctx.get(CLAIMED_SLUG_KEY);if(entry!==void 0){try{await store.getResource(ApiResourceKind.organization,entry.slug,OrganizationSchema);return}catch(error2){if(!(error2 instanceof ResourceNotFoundError)){logger2.error("organization create failed and its slug claim could not be checked; the slug stays claimed",{slug:entry.slug,error:error2 instanceof Error?error2.message:String(error2)});return}}try{await store.organizationSlugs.release(entry)}catch(error2){logger2.error("organization create failed and its slug claim could not be released; the slug stays claimed",{slug:entry.slug,error:error2 instanceof Error?error2.message:String(error2)})}}}function newRetireOrganizationSlugStep(store){return{name:"RetireOrganizationSlug",async execute(ctx){let id=ctx.get(EXISTING_RESOURCE_KEY)?.metadata?.id??"";if(id==="")throw internalError(new Error("organization delete reached RetireOrganizationSlug without its loaded row"),"failed to retire the organization slug");try{await store.organizationSlugs.retire(id)}catch(error2){throw internalError(error2,"failed to retire the organization slug")}}}}function newCheckOrgDuplicateStep(store){return{name:"CheckDuplicate",async execute(ctx){let metadata=metadataOf(ctx.newState);if(metadata===void 0)throw internalError(new Error("organization metadata is nil"),"duplicate check");if(metadata.slug==="")throw internalError(new Error("organization slug is empty"),"duplicate check");let entry;try{entry=await store.organizationSlugs.find(metadata.slug)}catch(error2){throw internalError(error2,"failed to check for duplicate organization")}if(entry!==void 0)throw refusalForHeldSlug(entry);try{await store.getResource(ctx.apiResourceKind,metadata.slug,OrganizationSchema)}catch(error2){if(error2 instanceof ResourceNotFoundError)return;throw internalError(error2,"failed to check for duplicate organization")}throw alreadyExistsError("Organization",`slug '${metadata.slug}'`)}}}function newCopySlugToIdStep(){return{name:"CopySlugToId",execute(ctx){let metadata=metadataOf(ctx.newState);if(metadata===void 0)throw internalError(new Error("organization metadata is nil"),"copy slug to id");if(metadata.slug==="")throw internalError(new Error("organization slug is empty"),"copy slug to id");metadata.id=metadata.slug}}}function newRevokeOrganizationPoliciesStep(grantPath){return{name:"RevokeOrganizationPolicies",async execute(ctx){let id=ctx.get(EXISTING_RESOURCE_KEY)?.metadata?.id??"";if(id==="")throw internalError(new Error("organization delete reached RevokeOrganizationPolicies without its loaded row"),"failed to remove the organization's access policies");try{await grantPath.cleanupResource(create2(ApiResourceRefSchema,{kind:ApiResourceKind[ApiResourceKind.organization],id}))}catch(error2){throw internalError(error2,"failed to remove the organization's access policies")}}}}function registerOrganizationServices(router,deps){router.service(OrganizationCommandController,{apply:(org,ctx)=>apply10(deps,org,ctx),create:(org,ctx)=>createOrganization(deps,org,ctx),update:(org,ctx)=>update13(deps,org,ctx),delete:(orgId,ctx)=>deleteOrganization(deps,orgId,ctx)});let externalLookup=deps.organizationDirectory?.lookupExternalOrganization?.bind(deps.organizationDirectory);router.service(OrganizationQueryController,{get:(orgId,ctx)=>get18(deps,orgId,ctx),find:(req,ctx)=>find(deps,req,ctx),findMyOrganizations:(_,ctx)=>findMyOrganizations(deps,ctx),...externalLookup===void 0?{}:{getByExternalOrgId:(lookup3,ctx)=>getByExternalOrgId(deps,externalLookup,lookup3,ctx)}})}function kindOf17(ctx){return ctx.values.get(apiResourceKindKey)}async function createOrganization(deps,org,ctx){let reqCtx=new RequestContext(OrganizationSchema,org,callerIdentityOf(ctx),kindOf17(ctx)),builder2=newPipeline("organization-create",deps.logger).addStep(newAuthorizeStep(OrganizationCommandController.method.create,deps.authorizer)).addStep(newResolveSlugStep()).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newCheckOrgDuplicateStep(deps.store)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newCopySlugToIdStep());for(let step of stepsForSlot(deps.gateSteps,"org-create:pre-side-effect-gate"))builder2.addStep(step);builder2.addStep(newClaimOrganizationSlugStep(deps.store)).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger));for(let step of stepsForSlot(deps.gateSteps,"org-create:post-persist"))builder2.addStep(step);let pipeline2=builder2.addStep(newIndexSearchStep(deps.store,organizationSearchExtractor,deps.logger)).build();try{await pipeline2.execute(reqCtx)}catch(error2){throw await releaseSlugClaimAfterFailure(deps.store,deps.logger,reqCtx),error2}return reqCtx.newState}async function update13(deps,org,ctx){let reqCtx=new RequestContext(OrganizationSchema,org,callerIdentityOf(ctx),kindOf17(ctx));return await newPipeline("organization-update",deps.logger).addStep(newAuthorizeStep(OrganizationCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingStep(deps.store)).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newPersistStep(deps.store)).addStep(newIndexSearchStep(deps.store,organizationSearchExtractor,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function apply10(deps,org,ctx){let reqCtx=new RequestContext(OrganizationSchema,org,callerIdentityOf(ctx),kindOf17(ctx));await newPipeline("organization-apply",deps.logger).addStep(newAuthorizeStep(OrganizationCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");return shouldCreate?createOrganization(deps,org,ctx):update13(deps,withResolvedApplyId(OrganizationSchema,org,reqCtx),ctx)}async function deleteOrganization(deps,orgId,ctx){let reqCtx=new RequestContext(OrganizationCommandController.method.delete.input,orgId,callerIdentityOf(ctx),kindOf17(ctx)),builder2=newPipeline("organization-delete",deps.logger).addStep(newAuthorizeStep(OrganizationCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newExtractResourceIdStep()).addStep(newLoadExistingForDeleteStep(deps.store,OrganizationSchema)).addStep(newRetireOrganizationSlugStep(deps.store));for(let step of stepsForSlot(deps.gateSteps,"org-delete:pre-delete"))builder2.addStep(step);await builder2.addStep(newRevokeOrganizationPoliciesStep(deps.grantPath)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDeleteSearchIndexStep(deps.store,deps.logger)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted organization not found in context"),"delete operation lost its loaded resource");return deleted}async function get18(deps,orgId,ctx){let reqCtx=new RequestContext(OrganizationQueryController.method.get.input,orgId,callerIdentityOf(ctx),kindOf17(ctx));return await newPipeline("organization-get",deps.logger).addStep(newAuthorizeStep(OrganizationQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,OrganizationSchema)).build().execute(reqCtx),reqCtx.get(TARGET_RESOURCE_KEY)}var FIND_RESULT_KEY="findResult";async function find(deps,req,ctx){if(deps.organizationDirectory?.refusesEnumeration===!0)throw new ConnectError("ai.stigmer.tenancy.organization.v1.OrganizationQueryController.find is not implemented",Code.Unimplemented);let reqCtx=new RequestContext(OrganizationQueryController.method.find.input,req,callerIdentityOf(ctx),kindOf17(ctx));return await newPipeline("organization-find",deps.logger).addStep(newAuthorizeStep(OrganizationQueryController.method.find,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newListAllOrganizationsStep(deps.store)).build().execute(reqCtx),reqCtx.get(FIND_RESULT_KEY)}function newListAllOrganizationsStep(store){return{name:"ListAllOrganizations",async execute(ctx){let data;try{data=await store.listResources(ctx.apiResourceKind)}catch(error2){throw internalError(error2,"failed to list organizations")}let orgs=[];for(let bytes of data)try{orgs.push(fromBinary2(OrganizationSchema,bytes))}catch{continue}let req=ctx.input,pageSize=req.pageSize,pageNumber=req.pageNumber;req.page!==void 0&&(req.page.size>0&&(pageSize=req.page.size),req.page.num>0&&(pageNumber=req.page.num)),pageSize<=0&&(pageSize=20),pageSize>100&&(pageSize=100),pageNumber<=0&&(pageNumber=1);let totalPages=Math.ceil(orgs.length/pageSize),start=(pageNumber-1)*pageSize,entries=start>=orgs.length?[]:orgs.slice(start,start+pageSize);ctx.set(FIND_RESULT_KEY,create2(OrganizationListSchema,{totalPages,entries}))}}}async function findMyOrganizations(deps,ctx){let directory=deps.organizationDirectory;if(directory!==void 0){let authorized=await directory.listMyOrganizationIds(callerIdentityOf(ctx));if(authorized!=="all"){let entries2=[];for(let id of authorized)try{entries2.push(await deps.store.getResource(ApiResourceKind.organization,id,OrganizationSchema))}catch(error2){if(error2 instanceof ResourceNotFoundError)continue;throw internalError(error2,"failed to list organizations")}return create2(OrganizationsSchema,{entries:entries2})}}let data;try{data=await deps.store.listResources(ApiResourceKind.organization)}catch(error2){throw internalError(error2,"failed to list organizations")}let entries=[];for(let bytes of data)try{entries.push(fromBinary2(OrganizationSchema,bytes))}catch{continue}return create2(OrganizationsSchema,{entries})}async function getByExternalOrgId(deps,lookup3,input,ctx){let reqCtx=new RequestContext(OrganizationQueryController.method.getByExternalOrgId.input,input,callerIdentityOf(ctx),kindOf17(ctx));if(await newPipeline("organization-get-by-external-org-id",deps.logger).addStep(newAuthorizeStep(OrganizationQueryController.method.getByExternalOrgId,deps.authorizer)).addStep(newValidateProtoStep()).build().execute(reqCtx),input.externalOrgId==="")throw invalidArgumentError("external_org_id is required");let found=await lookup3({org:input.identityProviderRef?.org??"",slug:input.identityProviderRef?.slug??""},input.externalOrgId);if(found.kind==="no-identity-provider")throw notFoundError("Organization",input.externalOrgId);await authorizeResolvedResource(deps.authorizer,reqCtx.callerIdentity,{permission:IamPermission.can_view,resourceKind:ApiResourceKind.identity_provider,resourceId:found.identityProviderId},EXTERNAL_LOOKUP_DENIED_MESSAGE);let orgId=found.organizationId;if(orgId===void 0)throw notFoundError("Organization",input.externalOrgId);try{return await deps.store.getResource(ApiResourceKind.organization,orgId,OrganizationSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("Organization",input.externalOrgId):internalError(error2,"failed to load organization")}}var EXTERNAL_LOOKUP_DENIED_MESSAGE="unauthorized to view identity provider";var file_ai_stigmer_agentic_mcpserver_v1_io=fileDesc("CihhaS9zdGlnbWVyL2FnZW50aWMvbWNwc2VydmVyL3YxL2lvLnByb3RvEh9haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxIiQKC01jcFNlcnZlcklkEhUKBXZhbHVlGAEgASgJQga6SAPIAQEiggIKDENvbm5lY3RJbnB1dBIdCg1tY3Bfc2VydmVyX2lkGAEgASgJQga6SAPIAQESUgoLcnVudGltZV9lbnYYAiADKAsyPS5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLkNvbm5lY3RJbnB1dC5SdW50aW1lRW52RW50cnkSFAoDb3JnGAMgASgJQge6SARyAhABGmkKD1J1bnRpbWVFbnZFbnRyeRILCgNrZXkYASABKAkSRQoFdmFsdWUYAiABKAsyNi5haS5zdGlnbWVyLmFnZW50aWMuZXhlY3V0aW9uY29udGV4dC52MS5FeGVjdXRpb25WYWx1ZToCOAEiUAoZSW5pdGlhdGVPQXV0aENvbm5lY3RJbnB1dBIdCg1tY3Bfc2VydmVyX2lkGAEgASgJQga6SAPIAQESFAoDb3JnGAIgASgJQge6SARyAhABIm0KGkluaXRpYXRlT0F1dGhDb25uZWN0T3V0cHV0EhkKEWF1dGhvcml6YXRpb25fdXJsGAEgASgJEg0KBXN0YXRlGAIgASgJEg4KBnNjb3BlcxgDIAMoCRIVCg1wcm92aWRlcl9uYW1lGAQgASgJIncKGUNvbXBsZXRlT0F1dGhDb25uZWN0SW5wdXQSHQoNbWNwX3NlcnZlcl9pZBgBIAEoCUIGukgDyAEBEiMKEmF1dGhvcml6YXRpb25fY29kZRgCIAEoCUIHukgEcgIQARIWCgVzdGF0ZRgDIAEoCUIHukgEcgIQASJkChpDb21wbGV0ZU9BdXRoQ29ubmVjdE91dHB1dBIRCgljb25uZWN0ZWQYASABKAgSFgoOdGFyZ2V0X2Vudl92YXIYAiABKAkSGwoTdG9rZW5fbGlmZXRpbWVfaGludBgDIAEoCSJNChhHZXRPQXV0aEdyYW50U3RhdHVzSW5wdXQSGwoLcmVzb3VyY2VfaWQYASABKAlCBrpIA8gBARIUCgNvcmcYAiABKAlCB7pIBHICEAEizwEKGUdldE9BdXRoR3JhbnRTdGF0dXNPdXRwdXQSEQoJY29ubmVjdGVkGAEgASgIEh8KF2FjY2Vzc190b2tlbl9leHBpcmVzX2F0GAIgASgDEhYKDnRhcmdldF9lbnZfdmFyGAMgASgJEhMKC2F1dGhfbWV0aG9kGAQgASgJElEKEWNvbm5lY3Rpb25faGVhbHRoGAUgASgOMjYuYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5PQXV0aENvbm5lY3Rpb25IZWFsdGgiSQoURGlzY29ubmVjdE9BdXRoSW5wdXQSGwoLcmVzb3VyY2VfaWQYASABKAlCBrpIA8gBARIUCgNvcmcYAiABKAlCB7pIBHICEAEiLQoVRGlzY29ubmVjdE9BdXRoT3V0cHV0EhQKDGRpc2Nvbm5lY3RlZBgBIAEoCCKEAQoTU2V0T3JnT0F1dGhBcHBJbnB1dBIbCgtyZXNvdXJjZV9pZBgBIAEoCUIGukgDyAEBEhQKA29yZxgCIAEoCUIHukgEcgIQARIaCgljbGllbnRfaWQYAyABKAlCB7pIBHICEAESHgoNY2xpZW50X3NlY3JldBgEIAEoCUIHukgEcgIQASIsChRTZXRPcmdPQXV0aEFwcE91dHB1dBIUCgxvYXV0aF9hcHBfaWQYASABKAkiSAoTR2V0T3JnT0F1dGhBcHBJbnB1dBIbCgtyZXNvdXJjZV9pZBgBIAEoCUIGukgDyAEBEhQKA29yZxgCIAEoCUIHukgEcgIQASJVChRHZXRPcmdPQXV0aEFwcE91dHB1dBIUCgxoYXNfb3ZlcnJpZGUYASABKAgSFAoMb2F1dGhfYXBwX2lkGAIgASgJEhEKCWNsaWVudF9pZBgDIAEoCSJLChZEZWxldGVPcmdPQXV0aEFwcElucHV0EhsKC3Jlc291cmNlX2lkGAEgASgJQga6SAPIAQESFAoDb3JnGAIgASgJQge6SARyAhABIioKF0RlbGV0ZU9yZ09BdXRoQXBwT3V0cHV0Eg8KB2RlbGV0ZWQYASABKAgq7QEKFU9BdXRoQ29ubmVjdGlvbkhlYWx0aBInCiNPQVVUSF9DT05ORUNUSU9OX0hFQUxUSF9VTlNQRUNJRklFRBAAEiMKH09BVVRIX0NPTk5FQ1RJT05fSEVBTFRIX0hFQUxUSFkQARIpCiVPQVVUSF9DT05ORUNUSU9OX0hFQUxUSF9UT0tFTl9FWFBJUkVEEAISNQoxT0FVVEhfQ09OTkVDVElPTl9IRUFMVEhfVE9LRU5fRVhQSVJFRF9SRUZSRVNIQUJMRRADEiQKIE9BVVRIX0NPTk5FQ1RJT05fSEVBTFRIX05PX0dSQU5UEARiBnByb3RvMw",[file_ai_stigmer_agentic_executioncontext_v1_spec,file_buf_validate_validate]);var InitiateOAuthConnectOutputSchema=messageDesc2(file_ai_stigmer_agentic_mcpserver_v1_io,3);var CompleteOAuthConnectOutputSchema=messageDesc2(file_ai_stigmer_agentic_mcpserver_v1_io,5);var GetOAuthGrantStatusOutputSchema=messageDesc2(file_ai_stigmer_agentic_mcpserver_v1_io,7);var DisconnectOAuthOutputSchema=messageDesc2(file_ai_stigmer_agentic_mcpserver_v1_io,9);var OAuthConnectionHealth;(function(OAuthConnectionHealth2){OAuthConnectionHealth2[OAuthConnectionHealth2.OAUTH_CONNECTION_HEALTH_UNSPECIFIED=0]="OAUTH_CONNECTION_HEALTH_UNSPECIFIED",OAuthConnectionHealth2[OAuthConnectionHealth2.OAUTH_CONNECTION_HEALTH_HEALTHY=1]="OAUTH_CONNECTION_HEALTH_HEALTHY",OAuthConnectionHealth2[OAuthConnectionHealth2.OAUTH_CONNECTION_HEALTH_TOKEN_EXPIRED=2]="OAUTH_CONNECTION_HEALTH_TOKEN_EXPIRED",OAuthConnectionHealth2[OAuthConnectionHealth2.OAUTH_CONNECTION_HEALTH_TOKEN_EXPIRED_REFRESHABLE=3]="OAUTH_CONNECTION_HEALTH_TOKEN_EXPIRED_REFRESHABLE",OAuthConnectionHealth2[OAuthConnectionHealth2.OAUTH_CONNECTION_HEALTH_NO_GRANT=4]="OAUTH_CONNECTION_HEALTH_NO_GRANT"})(OAuthConnectionHealth||(OAuthConnectionHealth={}));var file_ai_stigmer_agentic_mcpserver_v1_command=fileDesc("Ci1haS9zdGlnbWVyL2FnZW50aWMvbWNwc2VydmVyL3YxL2NvbW1hbmQucHJvdG8SH2FpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEynREKGk1jcFNlcnZlckNvbW1hbmRDb250cm9sbGVyEl8KBWFwcGx5EiouYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5NY3BTZXJ2ZXIaKi5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLk1jcFNlcnZlchKwAQoGY3JlYXRlEiouYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5NY3BTZXJ2ZXIaKi5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLk1jcFNlcnZlciJOwrgYSggrEB4iDG1ldGFkYXRhLm9yZyo2dW5hdXRob3JpemVkIHRvIGNyZWF0ZSBtY3Agc2VydmVyIGluIHRoaXMgb3JnYW5pemF0aW9uEpoBCgZ1cGRhdGUSKi5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLk1jcFNlcnZlchoqLmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuTWNwU2VydmVyIjjCuBg0CAIQLCILbWV0YWRhdGEuaWQqIXVuYXV0aG9yaXplZCB0byB1cGRhdGUgbWNwIHNlcnZlchKmAQoGZGVsZXRlEjYuYWkuc3RpZ21lci5jb21tb25zLmFwaXJlc291cmNlLkFwaVJlc291cmNlRGVsZXRlSW5wdXQaKi5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLk1jcFNlcnZlciI4wrgYNAgDECwiC3Jlc291cmNlX2lkKiF1bmF1dGhvcml6ZWQgdG8gZGVsZXRlIG1jcCBzZXJ2ZXISugEKEHVwZGF0ZVZpc2liaWxpdHkSNS5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuVXBkYXRlVmlzaWJpbGl0eUlucHV0GiouYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5NY3BTZXJ2ZXIiQ8K4GD8IAhAsIgtyZXNvdXJjZV9pZCosdW5hdXRob3JpemVkIHRvIHVwZGF0ZSBtY3Agc2VydmVyIHZpc2liaWxpdHkSpAEKB2Nvbm5lY3QSLS5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLkNvbm5lY3RJbnB1dBoqLmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuTWNwU2VydmVyIj7CuBg6CBYQLCINbWNwX3NlcnZlcl9pZColdW5hdXRob3JpemVkIHRvIGNvbm5lY3QgdG8gbWNwIHNlcnZlchKpAQoMc3RhcnRDb25uZWN0Ei0uYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5Db25uZWN0SW5wdXQaKi5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLk1jcFNlcnZlciI+wrgYOggWECwiDW1jcF9zZXJ2ZXJfaWQqJXVuYXV0aG9yaXplZCB0byBjb25uZWN0IHRvIG1jcCBzZXJ2ZXIS3wEKFGluaXRpYXRlT0F1dGhDb25uZWN0EjouYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5Jbml0aWF0ZU9BdXRoQ29ubmVjdElucHV0GjsuYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5Jbml0aWF0ZU9BdXRoQ29ubmVjdE91dHB1dCJOwrgYSggWECwiDW1jcF9zZXJ2ZXJfaWQqNXVuYXV0aG9yaXplZCB0byBpbml0aWF0ZSBvYXV0aCBjb25uZWN0IGZvciBtY3Agc2VydmVyEt8BChRjb21wbGV0ZU9BdXRoQ29ubmVjdBI6LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuQ29tcGxldGVPQXV0aENvbm5lY3RJbnB1dBo7LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuQ29tcGxldGVPQXV0aENvbm5lY3RPdXRwdXQiTsK4GEoIFhAsIg1tY3Bfc2VydmVyX2lkKjV1bmF1dGhvcml6ZWQgdG8gY29tcGxldGUgb2F1dGggY29ubmVjdCBmb3IgbWNwIHNlcnZlchLIAQoPZGlzY29ubmVjdE9BdXRoEjUuYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5EaXNjb25uZWN0T0F1dGhJbnB1dBo2LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuRGlzY29ubmVjdE9BdXRoT3V0cHV0IkbCuBhCCBYQLCILcmVzb3VyY2VfaWQqL3VuYXV0aG9yaXplZCB0byBkaXNjb25uZWN0IG9hdXRoIGZvciBtY3Agc2VydmVyErgBCg5zZXRPcmdPQXV0aEFwcBI0LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuU2V0T3JnT0F1dGhBcHBJbnB1dBo1LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuU2V0T3JnT0F1dGhBcHBPdXRwdXQiOcK4GDUIFxAeIgNvcmcqKnVuYXV0aG9yaXplZCB0byBzZXQgb3JnIG9hdXRoIGFwcCBvdmVycmlkZRLEAQoRZGVsZXRlT3JnT0F1dGhBcHASNy5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLkRlbGV0ZU9yZ09BdXRoQXBwSW5wdXQaOC5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLkRlbGV0ZU9yZ09BdXRoQXBwT3V0cHV0IjzCuBg4CBcQHiIDb3JnKi11bmF1dGhvcml6ZWQgdG8gZGVsZXRlIG9yZyBvYXV0aCBhcHAgb3ZlcnJpZGUaBKD/KyxiBnByb3RvMw",[file_ai_stigmer_agentic_mcpserver_v1_api,file_ai_stigmer_agentic_mcpserver_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),McpServerCommandController=serviceDesc(file_ai_stigmer_agentic_mcpserver_v1_command,0);var file_ai_stigmer_agentic_mcpserver_v1_query=fileDesc("CithaS9zdGlnbWVyL2FnZW50aWMvbWNwc2VydmVyL3YxL3F1ZXJ5LnByb3RvEh9haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxMssFChhNY3BTZXJ2ZXJRdWVyeUNvbnRyb2xsZXISkgEKA2dldBItLmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZUlkGiouYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5NY3BTZXJ2ZXIiMMK4GCwIARAsIgV2YWx1ZSofdW5hdXRob3JpemVkIHRvIHZpZXcgbWNwIHNlcnZlchJ4Cg5nZXRCeVJlZmVyZW5jZRI0LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVJlZmVyZW5jZRoqLmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuTWNwU2VydmVyIgTQuBgBEtUBChNnZXRPQXV0aEdyYW50U3RhdHVzEjkuYWkuc3RpZ21lci5hZ2VudGljLm1jcHNlcnZlci52MS5HZXRPQXV0aEdyYW50U3RhdHVzSW5wdXQaOi5haS5zdGlnbWVyLmFnZW50aWMubWNwc2VydmVyLnYxLkdldE9BdXRoR3JhbnRTdGF0dXNPdXRwdXQiR8K4GEMIARAsIgtyZXNvdXJjZV9pZCowdW5hdXRob3JpemVkIHRvIHZpZXcgb2F1dGggc3RhdHVzIGZvciBtY3Agc2VydmVyEsEBCg5nZXRPcmdPQXV0aEFwcBI0LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuR2V0T3JnT0F1dGhBcHBJbnB1dBo1LmFpLnN0aWdtZXIuYWdlbnRpYy5tY3BzZXJ2ZXIudjEuR2V0T3JnT0F1dGhBcHBPdXRwdXQiQsK4GD4IARAsIgtyZXNvdXJjZV9pZCordW5hdXRob3JpemVkIHRvIHZpZXcgb3JnIG9hdXRoIGFwcCBvdmVycmlkZRoEoP8rLGIGcHJvdG8z",[file_ai_stigmer_agentic_mcpserver_v1_api,file_ai_stigmer_agentic_mcpserver_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),McpServerQueryController=serviceDesc(file_ai_stigmer_agentic_mcpserver_v1_query,0);async function completeOAuthConnect(deps,input,identity2){let mcpServerId=input.mcpServerId;if(mcpServerId==="")throw invalidArgumentError("mcp_server_id is required");let stateParam=input.state;if(stateParam==="")throw invalidArgumentError("state is required");let code=input.authorizationCode;if(code==="")throw invalidArgumentError("authorization_code is required");let pendingState;try{pendingState=await deps.pendingOAuthStates.getAndDelete(stateParam)}catch(error2){throw internalError(error2,"failed to load pending OAuth state")}if(pendingState===void 0)throw failedPreconditionError("no pending OAuth state found for the given state parameter (expired or already used)");if(pendingState.mcpServerId!==mcpServerId)throw failedPreconditionError("state parameter does not match the requested mcp_server_id");await authorizeDirect(McpServerCommandController.method.completeOAuthConnect,deps.authorizer,identity2,input,{resourceId:pendingState.mcpServerId});try{pendingState=await unsealPendingOAuthState(deps.secretService,pendingState)}catch(error2){throw deps.logger.error("Failed to decrypt pending OAuth state secrets",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to decrypt OAuth handshake secrets \u2014 please retry the connect flow")}let tokenResponse;try{tokenResponse=await exchangeCode(pendingState.tokenEndpoint,code,pendingState.redirectUri,pendingState.codeVerifier,pendingState.clientId,pendingState.clientSecret,pendingState.tokenAuthMethod,deps.outboundFetch)}catch(error2){throw unavailableError(`token exchange failed: ${error2 instanceof Error?error2.message:String(error2)}`)}let mcpServer;try{mcpServer=await deps.store.getResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("mcp_server",mcpServerId):internalError(error2,"failed to load mcp server \u2014 please retry the connect flow")}let org=pendingState.org;org===""&&(org=mcpServer.metadata?.org??"");let managedEnvId=await resolveOrCreateManagedEnvironment(deps,pendingState.identityAccountId,mcpServerId,org,mcpServer.metadata?.name??"",identity2),tokenVars={[pendingState.targetEnvVar]:create2(EnvironmentValueSchema,{value:tokenResponse.accessToken,isSecret:!0})},refreshTokenEnvVar=`${pendingState.targetEnvVar}_REFRESH_TOKEN`;tokenResponse.refreshToken!==""&&(tokenVars[refreshTokenEnvVar]=create2(EnvironmentValueSchema,{value:tokenResponse.refreshToken,isSecret:!0}));try{await deps.managedEnv.updateSecrets(managedEnvId,tokenVars)}catch(error2){throw internalError(error2,"failed to store OAuth tokens in managed environment")}let expiresAt=0;tokenResponse.expiresIn>0&&(expiresAt=Math.floor(Date.now()/1e3)+tokenResponse.expiresIn);try{await deps.oauthGrants.upsert({identityAccountId:pendingState.identityAccountId,resourceId:mcpServerId,resourceKind:"mcp_server",orgId:org,accessTokenExpiresAt:expiresAt,clientId:pendingState.clientId,authMethod:pendingState.authMethod,tokenEndpoint:pendingState.tokenEndpoint,accessTokenEnvVar:pendingState.targetEnvVar,refreshTokenEnvVar,environmentId:managedEnvId,createdAt:0,updatedAt:0})}catch(error2){throw internalError(error2,"failed to create OAuth grant record")}let auth=mcpServer.spec?.auth;return deps.logger.info("OAuth Connect completed: tokens stored in managed environment",{mcp_server_id:mcpServerId,auth_method:pendingState.authMethod,target_env_var:pendingState.targetEnvVar,managed_env_id:managedEnvId,expires_at:expiresAt,has_refresh_token:tokenResponse.refreshToken!==""}),create2(CompleteOAuthConnectOutputSchema,{connected:!0,targetEnvVar:pendingState.targetEnvVar,tokenLifetimeHint:auth?.tokenLifetimeHint??""})}async function unsealPendingOAuthState(secretService,state2){let verifier;try{verifier=await secretService.decrypt(state2.codeVerifier)}catch(error2){throw new Error(`failed to decrypt code_verifier: ${error2 instanceof Error?error2.message:String(error2)}`)}let secret;try{secret=await secretService.decrypt(state2.clientSecret)}catch(error2){throw new Error(`failed to decrypt client_secret: ${error2 instanceof Error?error2.message:String(error2)}`)}return{...state2,codeVerifier:verifier,clientSecret:secret}}async function resolveOrCreateManagedEnvironment(deps,identityAccountId,mcpServerId,org,mcpServerName,caller){let existingGrant;try{existingGrant=await deps.oauthGrants.find(identityAccountId,mcpServerId,org)}catch(error2){deps.logger.warn("Failed to look up existing OAuth grant (non-fatal, will create new managed env)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)})}if(existingGrant!==void 0&&existingGrant.environmentId!=="")return deps.logger.info("Reusing existing managed environment for OAuth re-connect",{mcp_server_id:mcpServerId,environment_id:existingGrant.environmentId}),existingGrant.environmentId;let envName=`OAuth: ${mcpServerName}`;try{return await deps.managedEnv.createManagedEnvironment(envName,org,caller)}catch(error2){throw internalError(error2,"failed to create managed environment for OAuth tokens")}}function convertToDiscoveredCapabilities(output){let capabilities=create2(DiscoveredCapabilitiesSchema,{lastDiscoveredAt:timestampNow()});for(let t of output.tools??[]){let tool=create2(DiscoveredToolSchema,{name:t.name??"",description:t.description??""});t.input_schema!==void 0&&(tool.inputSchema=t.input_schema),capabilities.tools.push(tool)}for(let rt of output.resource_templates??[])capabilities.resourceTemplates.push(create2(DiscoveredResourceTemplateSchema,{uriTemplate:rt.uri_template??"",name:rt.name??"",description:rt.description??"",mimeType:rt.mime_type??""}));return capabilities}function convertToToolApprovals(output){let approvals=[];for(let a5 of output.tool_approvals??[])a5.requires_approval!==!0||(a5.tool_name??"")===""||approvals.push(create2(ToolApprovalPolicySchema,{toolName:a5.tool_name,message:a5.message??"",fromDestructiveHint:a5.from_destructive_hint??!1}));return approvals}function setToolApprovalsFromConnect(status,output){let approvals=convertToToolApprovals(output);return approvals.length>0&&(status.toolApprovals=approvals),approvals.length}function settleConnectStatus(mcpStatus,workflowId,failure){let cs=mcpStatus.connectStatus;if(cs===void 0&&(cs=create2(ConnectStatusSchema),mcpStatus.connectStatus=cs),cs.workflowId=workflowId,cs.finishedAt=timestampNow(),cs.warning="",failure===void 0){cs.phase=ConnectPhase.succeeded,cs.failureCode="",cs.failureMessage="";return}cs.phase=ConnectPhase.failed,cs.failureCode=grpcCodeName(failure.code),cs.failureMessage=failure.rawMessage}async function persistConnectResult(store,mcpServerId,workflowId,output){let toolApprovalCount=0;return{persisted:await store.updateResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema,mcpServer=>{mcpServer.status===void 0&&(mcpServer.status=create2(McpServerStatusSchema)),mcpServer.status.discoveredCapabilities=convertToDiscoveredCapabilities(output),toolApprovalCount=setToolApprovalsFromConnect(mcpServer.status,output),settleConnectStatus(mcpServer.status,workflowId,void 0)}),toolApprovalCount}}async function persistConnectStarting(store,mcpServerId,workflowId,warning2){return store.updateResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema,mcpServer=>{mcpServer.status===void 0&&(mcpServer.status=create2(McpServerStatusSchema)),mcpServer.status.connectStatus=create2(ConnectStatusSchema,{phase:ConnectPhase.connecting,workflowId,startedAt:timestampNow(),warning:warning2})})}async function persistConnectFailure(store,logger2,mcpServerId,failure){try{await store.updateResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema,mcpServer=>{mcpServer.status===void 0&&(mcpServer.status=create2(McpServerStatusSchema)),settleConnectStatus(mcpServer.status,mcpServer.status.connectStatus?.workflowId??"",failure)})}catch(error2){if(error2 instanceof ResourceNotFoundError){logger2.info("Skipping connect failure persistence: MCP server deleted before connect settled",{mcp_server_id:mcpServerId});return}logger2.warn("Failed to record connect failure on connect_status (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)})}}var CONNECT_TIMEOUT={ms:42e4,goLabel:"7m0s"},ASYNC_CONNECT_TIMEOUT={ms:3600*1e3,goLabel:"1h0m0s"},BEST_EFFORT_CONNECT_GET_BUFFER_MS=15e3;async function connect(deps,input,identity2){let mcpServerId=input.mcpServerId;if(mcpServerId==="")throw invalidArgumentError("mcp_server_id is required");if(input.org==="")throw invalidArgumentError("org is required for connect");let mcpServer;try{mcpServer=await deps.store.getResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("mcp_server",mcpServerId):internalError(error2,"failed to load mcp server")}await authorizeDirect(McpServerCommandController.method.connect,deps.authorizer,identity2,input);let engineState=deps.engineState();if(!engineState.connected)throw failedPreconditionError("connect is not available: Temporal not configured");let prepared=await prepareConnect(deps,mcpServer,input,identity2);try{let run;try{run=await engineState.engine.startOrAttachConnect(mcpServerId,prepared.workflowInput,CONNECT_TIMEOUT.ms)}catch(error2){throw deps.logger.error("Failed to start MCP connect workflow",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to start connect workflow")}if(!run.attached)try{await persistConnectStarting(deps.store,mcpServerId,run.workflowId,"")}catch(error2){deps.logger.warn("Failed to record CONNECTING on connect_status (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)})}let outcome=await run.result(CONNECT_TIMEOUT.ms+BEST_EFFORT_CONNECT_GET_BUFFER_MS);if(!outcome.ok){let failure=mapConnectFailure(deps.logger,mcpServer,run.workflowId,outcome.failure,CONNECT_TIMEOUT);throw await persistConnectFailure(deps.store,deps.logger,mcpServerId,failure),failure}let persisted,toolApprovalCount;try{({persisted,toolApprovalCount}=await persistConnectResult(deps.store,mcpServerId,run.workflowId,outcome.output))}catch(error2){throw internalError(error2,"failed to save mcp server after connect")}return deps.logger.info("MCP server connect completed and stored",{mcp_server_id:mcpServerId,tools:persisted.status?.discoveredCapabilities?.tools.length??0,resource_templates:persisted.status?.discoveredCapabilities?.resourceTemplates.length??0,tool_approvals:toolApprovalCount}),persisted}finally{prepared.ecResourceId!==""&&await deleteConnectExecutionContext(deps,prepared.ecResourceId,prepared.executionId)}}async function prepareConnect(deps,mcpServer,input,identity2){let mcpServerId=mcpServer.metadata?.id??"",callerOrg=input.org;Object.keys(input.runtimeEnv).length===0&&await refreshOAuthTokenIfNeeded(deps,mcpServer,callerOrg);let executionId=newConnectExecutionId(mcpServerId),ecResourceId=await createConnectExecutionContext(deps,mcpServer,executionId,callerOrg,input.runtimeEnv,identity2),workflowInput={mcp_server_id:mcpServerId,...ecResourceId!==""?{execution_context_id:executionId}:{}};if(ecResourceId!==""&&deps.runnerAuth.isEnabled(TOKEN_TYPE_EXECUTION_SCOPED))try{let minted=deps.runnerAuth.mint(TOKEN_TYPE_EXECUTION_SCOPED,executionId,0);return{workflowInput:{...workflowInput,execution_context_token:minted.token},ecResourceId,executionId}}catch(error2){deps.logger.warn("Failed to mint connect EC token \u2014 discovery will read redacted credentials",{execution_id:executionId,error:error2 instanceof Error?error2.message:String(error2)})}return{workflowInput,ecResourceId,executionId}}async function createConnectExecutionContext(deps,mcpServer,executionId,callerOrg,runtimeEnv,caller){let ecData;if(Object.keys(runtimeEnv).length>0)ecData=runtimeEnv,deps.logger.info("Using runtime_env for connect ExecutionContext (one-time use)",{execution_id:executionId,runtime_env_count:Object.keys(runtimeEnv).length});else{let envDecls=mcpServer.spec?.env??{};if(Object.keys(envDecls).length===0)return deps.logger.debug("MCP server has no env declarations \u2014 skipping ExecutionContext creation",{execution_id:executionId}),"";let mcpServerId=mcpServer.metadata?.id??"",{oauthVars,remainingDecls}=await resolveOAuthVarsFromManagedEnv(deps,mcpServerId,callerOrg,envDecls),personalVars={};Object.keys(remainingDecls).length>0&&(personalVars=await resolveFromPersonalEnvironment(deps,callerOrg,remainingDecls)),ecData={...personalVars,...oauthVars},deps.logger.info("Resolved env vars for connect ExecutionContext",{execution_id:executionId,oauth_count:Object.keys(oauthVars).length,personal_count:Object.keys(personalVars).length})}if(Object.keys(ecData).length===0)return"";let created;try{created=await deps.executionContext.create(create2(ExecutionContextSchema,{apiVersion:"agentic.stigmer.ai/v1",kind:"ExecutionContext",metadata:{name:`exec-ctx-${executionId}`,org:callerOrg},spec:{executionId,data:ecData}}),caller)}catch(error2){throw internalError(error2,"failed to create connect ExecutionContext")}let resourceId=created.metadata?.id??"";return deps.logger.info("Created ephemeral ExecutionContext for MCP connect",{execution_context_id:resourceId,execution_id:executionId,data_entries:Object.keys(ecData).length}),resourceId}async function resolveOAuthVarsFromManagedEnv(deps,mcpServerId,org,envDecls){let grant;try{grant=await deps.oauthGrants.find("",mcpServerId,org)}catch{return{oauthVars:{},remainingDecls:envDecls}}if(grant===void 0||grant.environmentId==="")return{oauthVars:{},remainingDecls:envDecls};let oauthKey=grant.accessTokenEnvVar;if(!(oauthKey in envDecls))return{oauthVars:{},remainingDecls:envDecls};let tokenValue="";try{tokenValue=await deps.managedEnv.readSecretValue(grant.environmentId,oauthKey)}catch(error2){return deps.logger.warn("Failed to read OAuth token from managed environment \u2014 falling back to personal env",{mcp_server_id:mcpServerId,oauth_key:oauthKey,managed_env_id:grant.environmentId,error:error2 instanceof Error?error2.message:String(error2)}),{oauthVars:{},remainingDecls:envDecls}}if(tokenValue==="")return deps.logger.warn("Failed to read OAuth token from managed environment \u2014 falling back to personal env",{mcp_server_id:mcpServerId,oauth_key:oauthKey,managed_env_id:grant.environmentId}),{oauthVars:{},remainingDecls:envDecls};let remainingDecls={};for(let[k5,v]of Object.entries(envDecls))k5!==oauthKey&&(remainingDecls[k5]=v);return deps.logger.debug("Resolved OAuth token from managed environment",{mcp_server_id:mcpServerId,oauth_key:oauthKey,managed_env_id:grant.environmentId}),{oauthVars:{[oauthKey]:create2(ExecutionValueSchema,{value:tokenValue,isSecret:!0})},remainingDecls}}async function resolveFromPersonalEnvironment(deps,org,envDecls){let resolution=await resolveDeclaredFromPersonalEnvironment(deps.environmentReader,deps.logger,org,envDecls);if(resolution.kind==="no-personal-environment"){let requiredKeys=Object.entries(envDecls).filter(([,decl])=>!decl.optional).map(([key])=>key);if(requiredKeys.length===0)return{};throw failedPreconditionError(`personal environment not found for org '${org}'; save required credentials first: [${requiredKeys.join(" ")}]`)}if(resolution.missing.length>0)throw failedPreconditionError(`missing required credentials in personal environment: [${resolution.missing.join(" ")}]`);return{...resolution.values}}async function deleteConnectExecutionContext(deps,resourceId,executionId){try{await deps.executionContext.delete({resourceId})}catch(error2){deps.logger.warn("Failed to delete connect ExecutionContext (non-fatal)",{resource_id:resourceId,execution_id:executionId,error:error2 instanceof Error?error2.message:String(error2)});return}deps.logger.debug("Deleted ephemeral connect ExecutionContext",{resource_id:resourceId,execution_id:executionId})}function mapConnectFailure(logger2,mcpServer,workflowId,failure,budget){let mcpServerId=mcpServer.metadata?.id??"";switch(logger2.error("MCP connect workflow failed",{workflow_id:workflowId,mcp_server_id:mcpServerId,failure_kind:failure.kind}),failure.kind){case"application":return failedPreconditionError(buildConnectFailureMessage(mcpServer,failure.message));case"timeout":return new ConnectError(`connect did not complete within the ${budget.goLabel} budget for MCP server '${mcpServerId}' \u2014 if this repeats, check that your runner is running and healthy`,Code.DeadlineExceeded);case"service-not-found":return unavailableError(`connect service temporarily unavailable for MCP server '${mcpServerId}'`);case"other":return new ConnectError(buildConnectFailureMessage(mcpServer,failure.message),Code.Internal);default:{let exhaustive=failure;throw new Error(`unhandled connect failure ${String(exhaustive)}`)}}}function buildConnectFailureMessage(mcpServer,cause){let name=mcpServer.metadata?.name??"";if(cause.includes("requires OAuth"))return cause;if(mcpServer.spec?.serverType.case==="stdio"){let slug=mcpServer.metadata?.slug??"";return`connect failed for MCP server '${name}': ${cause}. This is a stdio server launched by your local runner \u2014 verify the command is installed and its arguments and environment variables are correct. Preview discovery locally with: stigmer connect mcp-server ${slug} --dry-run`}return`connect failed for MCP server '${name}': ${cause}. Check that the server URL is reachable and your credentials are valid.`}async function refreshOAuthTokenIfNeeded(deps,mcpServer,callerOrg){if(mcpServer.spec?.auth===void 0)return;let mcpServerId=mcpServer.metadata?.id??"",grant;try{grant=await deps.oauthGrants.find("",mcpServerId,callerOrg)}catch(error2){deps.logger.warn("Failed to load OAuth grant for pre-flight check (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)});return}if(grant===void 0)return;if(grant.environmentId===""){deps.logger.warn("OAuth grant has no managed environment ID \u2014 user must re-authenticate via OAuth Connect",{mcp_server_id:mcpServerId});return}let refreshTokenValue;try{refreshTokenValue=await deps.managedEnv.readSecretValue(grant.environmentId,grant.refreshTokenEnvVar)}catch(error2){deps.logger.debug("No refresh token found in managed environment (may not be OAuth-connected)",{mcp_server_id:mcpServerId,refresh_token_var:grant.refreshTokenEnvVar,managed_env_id:grant.environmentId,error:error2 instanceof Error?error2.message:String(error2)});return}let clientSecret="",tokenAuthMethod="";if(grant.authMethod==="vendor_oauth")try{({clientSecret,tokenAuthMethod}=await loadOAuthAppClientCredentials(deps,mcpServer))}catch(error2){deps.logger.warn("Failed to load OAuthApp client secret for refresh",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)})}let result;try{result=await refreshTokenIfExpired(grant,refreshTokenValue,clientSecret,tokenAuthMethod,deps.logger,deps.outboundFetch)}catch(error2){throw failedPreconditionError(error2 instanceof Error?error2.message:String(error2))}if(!result.refreshed)return;let tokenVars={[grant.accessTokenEnvVar]:create2(EnvironmentValueSchema,{value:result.newAccessToken,isSecret:!0})};result.newRefreshToken!==refreshTokenValue&&(tokenVars[grant.refreshTokenEnvVar]=create2(EnvironmentValueSchema,{value:result.newRefreshToken,isSecret:!0}));try{await deps.managedEnv.updateSecrets(grant.environmentId,tokenVars)}catch(error2){throw internalError(error2,"failed to update refreshed tokens in managed environment")}try{await deps.oauthGrants.upsert({...grant,accessTokenExpiresAt:result.newExpiresAt})}catch(error2){deps.logger.warn("Failed to update OAuth grant after refresh (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)})}}async function loadOAuthAppClientCredentials(deps,mcpServer){let ref=mcpServer.spec?.auth?.oauthAppRef;if(ref===void 0||ref.slug==="")return{clientSecret:"",tokenAuthMethod:""};let app;try{app=await resolveOAuthAppRef(deps.store,ref,deps.logger)}catch(error2){throw new Error(`failed to list oauth apps: ${error2 instanceof Error?error2.message:String(error2)}`)}if(app===void 0)throw new Error(`OAuthApp '${ref.slug}' not found`);let tokenAuthMethod=tokenAuthMethodFromSpec(app.spec?.tokenEndpointAuthMethod??TokenEndpointAuthMethod.UNSPECIFIED),secret=app.spec?.clientSecret??"";return deps.secretService.isEncrypted(secret)&&(secret=await deps.secretService.decrypt(secret)),{clientSecret:secret,tokenAuthMethod}}function tokenAuthMethodFromSpec(method){return method===TokenEndpointAuthMethod.CLIENT_SECRET_POST?TOKEN_AUTH_METHOD_POST:TOKEN_AUTH_METHOD_BASIC}async function startBestEffortConnect(deps,mcpServer){let engineState=deps.engineState();if(!engineState.connected)return;let envKeys=Object.keys(mcpServer.spec?.env??{}).length;if(envKeys>0){deps.logger.debug("Skipping best-effort auto-connect: MCP server has env declarations (requires manual connect)",{mcp_server_id:mcpServer.metadata?.id??"",env_keys:envKeys});return}let mcpServerId=mcpServer.metadata?.id??"",run;try{run=await engineState.engine.startOrAttachConnect(mcpServerId,{mcp_server_id:mcpServerId},CONNECT_TIMEOUT.ms)}catch(error2){deps.logger.warn("Failed to start best-effort connect workflow (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)});return}if(!run.attached)try{await persistConnectStarting(deps.store,mcpServerId,run.workflowId,"")}catch(error2){deps.logger.warn("Failed to record CONNECTING for best-effort connect (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)})}let outcome=await run.result(CONNECT_TIMEOUT.ms+BEST_EFFORT_CONNECT_GET_BUFFER_MS);if(!outcome.ok){let failure=mapConnectFailure(deps.logger,mcpServer,run.workflowId,outcome.failure,CONNECT_TIMEOUT);await persistConnectFailure(deps.store,deps.logger,mcpServerId,failure);return}let persisted,toolApprovalCount;try{({persisted,toolApprovalCount}=await persistConnectResult(deps.store,mcpServerId,run.workflowId,outcome.output))}catch(error2){if(error2 instanceof ResourceNotFoundError){deps.logger.info("Skipping best-effort connect persistence: MCP server deleted before connect completed",{mcp_server_id:mcpServerId});return}deps.logger.warn("Failed to persist best-effort connect result (non-fatal)",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)});return}deps.logger.info("Best-effort auto-connect completed and stored",{workflow_id:run.workflowId,mcp_server_id:mcpServerId,tools:persisted.status?.discoveredCapabilities?.tools.length??0,resource_templates:persisted.status?.discoveredCapabilities?.resourceTemplates.length??0,tool_approvals:toolApprovalCount})}async function disconnectOAuth(deps,input,identity2){let resourceId=input.resourceId;if(resourceId==="")throw invalidArgumentError("resource_id is required");let org=input.org;if(org==="")throw invalidArgumentError("org is required");await authorizeDirect(McpServerCommandController.method.disconnectOAuth,deps.authorizer,identity2,input);let grant;try{grant=await deps.oauthGrants.find("",resourceId,org)}catch(error2){throw internalError(error2,"failed to look up OAuth grant")}if(grant===void 0)return deps.logger.debug("No OAuth grant to disconnect",{resource_id:resourceId,org}),create2(DisconnectOAuthOutputSchema,{disconnected:!1});let envId=grant.environmentId;if(envId!=="")try{await deps.managedEnv.deleteManagedEnvironment(envId)}catch(error2){deps.logger.warn("Failed to delete managed environment \u2014 may already be deleted",{resource_id:resourceId,environment_id:envId,error:error2 instanceof Error?error2.message:String(error2)})}try{await deps.oauthGrants.delete("",resourceId,org)}catch(error2){throw internalError(error2,"failed to delete OAuth grant")}return deps.logger.info("OAuth connection disconnected",{resource_id:resourceId,org,env_deleted:envId!==""}),create2(DisconnectOAuthOutputSchema,{disconnected:!0})}function isOAuthChallenge(wwwAuthenticate){let value=wwwAuthenticate.toLowerCase();return value.includes("bearer")?value.includes("oauth")||value.includes("resource_metadata"):!1}function parseResourceMetadataUrl(wwwAuthenticate){return/resource_metadata="([^"]+)"/i.exec(wwwAuthenticate)?.[1]}function protectedResourceMetadataUrls(resource){let bare=`${resource.origin}/.well-known/oauth-protected-resource`,path14=resource.pathname.replace(/\/+$/,"");return path14===""?[bare]:[`${bare}${path14}`,bare]}function authorizationServerMetadataUrls(issuer){let path14=issuer.pathname.replace(/\/+$/,""),urls=[...path14===""?[]:[`${issuer.origin}/.well-known/oauth-authorization-server${path14}`],`${issuer.origin}/.well-known/oauth-authorization-server`,...path14===""?[]:[`${issuer.origin}${path14}/.well-known/openid-configuration`],`${issuer.origin}/.well-known/openid-configuration`];return[...new Set(urls)]}async function resolveAuthorizationServers(resourceUrl,pointer,deps){let attempts=[],candidates=pointer!==void 0?[pointer]:protectedResourceMetadataUrls(new URL(resourceUrl));for(let candidate of candidates){let read3=await readJson(candidate,deps,attempts);if(read3===void 0)continue;let issuers=readStringArray(read3,"authorization_servers");if(issuers.length>0)return{issuers,attempts}}return{issuers:[],attempts}}async function readAuthorizationServerMetadata(issuer,deps){let attempts=[],parsed;try{parsed=new URL(issuer)}catch{return{kind:"not-found",attempts}}for(let metadataUrl of authorizationServerMetadataUrls(parsed)){let document2=await readJson(metadataUrl,deps,attempts);if(document2===void 0)continue;let authorizationEndpoint=readString(document2,"authorization_endpoint"),tokenEndpoint=readString(document2,"token_endpoint");if(authorizationEndpoint===""||tokenEndpoint===""){let last=attempts.pop();last!==void 0&&attempts.push({...last,missing:authorizationEndpoint===""?"authorization_endpoint":"token_endpoint"});continue}return{kind:"found",attempts,metadata:{metadataUrl,issuer:readString(document2,"issuer"),authorizationEndpoint,tokenEndpoint,registrationEndpoint:readString(document2,"registration_endpoint"),scopesSupported:readStringArray(document2,"scopes_supported"),codeChallengeMethodsSupported:readStringArray(document2,"code_challenge_methods_supported")}}}return{kind:"not-found",attempts}}async function readJson(url,deps,attempts){let response;try{response=await deps.fetchImpl(url,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(deps.timeoutMs)})}catch(error2){attempts.push({url,error:error2 instanceof Error?error2.message:String(error2)});return}if(attempts.push({url,status:response.status}),response.status!==200){await response.body?.cancel().catch(()=>{});return}try{let parsed=await response.json();return isRecord(parsed)?parsed:void 0}catch{return}}function readString(record2,key){let value=record2[key];return typeof value=="string"?value:""}function readStringArray(record2,key){let list12=record2[key];return Array.isArray(list12)?list12.filter(item=>typeof item=="string"):[]}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MCP_PROTOCOL_VERSION="2025-06-18";function baseHeaders(headers2){return{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":MCP_PROTOCOL_VERSION,...headers2??{}}}function initializeRequest(clientName,headers2){return{method:"POST",headers:baseHeaders(headers2),body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:MCP_PROTOCOL_VERSION,capabilities:{},clientInfo:{name:clientName,version:"0"}}})}}async function probeEndpointAuth(url,headers2,deps){let request=initializeRequest(deps.clientName,headers2),response;try{response=await deps.fetchImpl(url,{method:request.method,headers:{...request.headers},body:request.body,signal:AbortSignal.timeout(deps.timeoutMs)})}catch(error2){return{kind:"unreachable",error:describeError(error2)}}if(await response.body?.cancel().catch(()=>{}),response.status===401){let challenge=response.headers.get("www-authenticate")??"";return isOAuthChallenge(challenge)?{kind:"oauth",challenge,resourceMetadataUrl:parseResourceMetadataUrl(challenge)}:{kind:"challenge-not-oauth",challenge}}return response.status>=200&&response.status<300?{kind:"accepted",status:response.status}:{kind:"http-other",status:response.status}}function describeError(error2){return error2 instanceof Error?`${error2.name}: ${error2.message}`:String(error2)}var ENDPOINT_PROBE_TIMEOUT_MS=3e3,PROBE_CLIENT_NAME="stigmer-server",ACCESS_TOKEN_VAR_SUFFIX="_ACCESS_TOKEN",AUTHORIZATION_HEADER="authorization";function newCompleteEndpointAuthStep(deps){return{name:"CompleteEndpointAuth",async execute(ctx){let server=ctx.newState,spec=server.spec;if(spec===void 0)return;applyTokenPathDefault(spec,server.metadata?.slug??"");let existing=ctx.get(EXISTING_RESOURCE_KEY),derived=existing!==void 0?derivedCompletionOf(existing):void 0,url=authorShapeUrl(spec);if(url===void 0){derived!==void 0&&echoesDerived(spec,derived)?stamp(ctx,server):dropLabel(server);return}if(derived!==void 0&&derived.url===url){applyCompletion(spec,derived.variable,derived.description),stamp(ctx,server);return}if(await probe(url,spec,deps)!=="oauth"){dropLabel(server);return}let variable=accessTokenVariable(server.metadata?.slug??"");applyCompletion(spec,variable,tokenDescription(server.metadata?.slug??"")),stamp(ctx,server)}}}function authorShapeUrl(spec){if(spec.serverType.case==="http"&&spec.auth===void 0&&!(Object.keys(spec.env).length>0)){for(let[name,value]of Object.entries(spec.serverType.value.headers))if(name.toLowerCase()===AUTHORIZATION_HEADER||value.includes("${"))return;return spec.serverType.value.url}}function derivedCompletionOf(existing){if(existing.metadata?.labels[MCP_AUTH_LABEL]!==MCP_AUTH_ENDPOINT)return;let spec=existing.spec;if(spec===void 0||spec.serverType.case!=="http")return;let variable=spec.auth?.targetEnvVar??"";if(variable!=="")return{url:spec.serverType.value.url,variable,description:spec.env[variable]?.description??""}}function echoesDerived(spec,derived){if(spec.serverType.case!=="http"||spec.serverType.value.url!==derived.url)return!1;let auth=spec.auth;if(auth===void 0||auth.targetEnvVar!==derived.variable||!auth.oauthOnly||(auth.oauthAppRef?.slug??"")!==""||auth.discoveryUrl!==""||auth.scopeHints.length>0||auth.tokenLifetimeHint!=="")return!1;let envKeys=Object.keys(spec.env);if(envKeys.length!==1||envKeys[0]!==derived.variable)return!1;let declaration=spec.env[derived.variable];if(declaration===void 0||!declaration.isSecret||declaration.optional)return!1;let headers2=Object.entries(spec.serverType.value.headers),authorization=headers2.filter(([name])=>name.toLowerCase()===AUTHORIZATION_HEADER);return authorization.length!==1||authorization[0]?.[1]!==bearerHeader(derived.variable)?!1:headers2.every(([name,value])=>name.toLowerCase()===AUTHORIZATION_HEADER||!value.includes("${"))}function applyCompletion(spec,variable,description){spec.auth=create2(McpServerAuthSchema,{targetEnvVar:variable,oauthOnly:!0}),spec.env[variable]=create2(EnvVarDeclarationSchema,{isSecret:!0,optional:!1,description}),applyTokenPathDefault(spec,"")}function applyTokenPathDefault(spec,slug){let variable=spec.auth?.targetEnvVar??"";if(variable===""||(spec.env[variable]===void 0&&(spec.env[variable]=create2(EnvVarDeclarationSchema,{isSecret:!0,optional:!1,description:tokenDescription(slug)})),spec.serverType.case!=="http"))return;let headers2=spec.serverType.value.headers,reference=`\${${variable}}`;Object.values(headers2).some(value=>value.includes(reference))||(headers2.Authorization=bearerHeader(variable))}function bearerHeader(variable){return`Bearer \${${variable}}`}function accessTokenVariable(slug){let stem=slug.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"");return`${stem===""?"MCP":stem}${ACCESS_TOKEN_VAR_SUFFIX}`}function tokenDescription(slug){return`OAuth access token for the '${slug}' MCP server; Sign in fills it`}function stamp(ctx,server){server.metadata!==void 0&&(server.metadata.labels[MCP_AUTH_LABEL]=MCP_AUTH_ENDPOINT,recordServerStampedReservedLabels(ctx,MCP_AUTH_LABEL))}function dropLabel(server){server.metadata!==void 0&&delete server.metadata.labels[MCP_AUTH_LABEL]}async function probe(url,spec,deps){let headers2=spec.serverType.case==="http"?spec.serverType.value.headers:{};try{let outcome=await probeEndpointAuth(url,headers2,{fetchImpl:deps.outboundFetch,timeoutMs:ENDPOINT_PROBE_TIMEOUT_MS,clientName:PROBE_CLIENT_NAME});return outcome.kind==="unreachable"&&deps.logger.debug("MCP endpoint probe got no answer; saving the spec as sent",{url,error:outcome.error}),outcome.kind==="oauth"?"oauth":"other"}catch(error2){return deps.logger.warn("MCP endpoint probe threw; saving the spec as sent",{url,error:error2 instanceof Error?error2.message:String(error2)}),"other"}}async function getOAuthGrantStatus(deps,input,identity2){if(input.resourceId==="")throw invalidArgumentError("resource_id is required");if(input.org==="")throw invalidArgumentError("org is required");await authorizeDirect(McpServerQueryController.method.getOAuthGrantStatus,deps.authorizer,identity2,input);let grant;try{grant=await deps.oauthGrants.find("",input.resourceId,input.org)}catch(error2){throw internalError(error2,"failed to look up OAuth grant")}return grant===void 0?create2(GetOAuthGrantStatusOutputSchema,{connected:!1,connectionHealth:OAuthConnectionHealth.OAUTH_CONNECTION_HEALTH_NO_GRANT}):create2(GetOAuthGrantStatusOutputSchema,{connected:!0,accessTokenExpiresAt:BigInt(grant.accessTokenExpiresAt),targetEnvVar:grant.accessTokenEnvVar,authMethod:grant.authMethod,connectionHealth:evaluateHealth(grant)})}function evaluateHealth(grant){return grant.accessTokenExpiresAt===0?OAuthConnectionHealth.OAUTH_CONNECTION_HEALTH_HEALTHY:Math.floor(Date.now()/1e3)<grant.accessTokenExpiresAt-REFRESH_EXPIRY_BUFFER_SECONDS?OAuthConnectionHealth.OAUTH_CONNECTION_HEALTH_HEALTHY:grant.refreshTokenEnvVar!==""?OAuthConnectionHealth.OAUTH_CONNECTION_HEALTH_TOKEN_EXPIRED_REFRESHABLE:OAuthConnectionHealth.OAUTH_CONNECTION_HEALTH_TOKEN_EXPIRED}var import_node_crypto24=require("node:crypto");var import_node_crypto23=require("node:crypto");function generatePkce(){let verifier=(0,import_node_crypto23.randomBytes)(32).toString("base64url"),challenge=(0,import_node_crypto23.createHash)("sha256").update(verifier).digest().toString("base64url");return{codeVerifier:verifier,codeChallenge:challenge}}var DISCOVERY_REQUEST_TIMEOUT_MS=1e4;async function discoverForResource(mcpUrl,fetchImpl){let resource=parseDiscoveryUrl(mcpUrl),deps={fetchImpl,timeoutMs:DISCOVERY_REQUEST_TIMEOUT_MS},resolved=await resolveAuthorizationServers(resource.href,void 0,deps),issuers=resolved.issuers.length>0?resolved.issuers:[resource.origin];return readIssuers(issuers,deps)}async function discoverAtIssuer(issuerUrl,fetchImpl){let issuer=parseDiscoveryUrl(issuerUrl);return readIssuers([issuer.href],{fetchImpl,timeoutMs:DISCOVERY_REQUEST_TIMEOUT_MS})}async function readIssuers(issuers,deps){let attempts=[];for(let issuer of issuers){let read3=await readAuthorizationServerMetadata(issuer,deps);if(attempts.push(...read3.attempts),read3.kind==="found"){let metadata=toAuthServerMetadata(read3.metadata);return validateMetadata(metadata,read3.metadata.metadataUrl),metadata}}throw discoveryFailure(issuers,attempts)}function toAuthServerMetadata(m3){return{issuer:m3.issuer,authorizationEndpoint:m3.authorizationEndpoint,tokenEndpoint:m3.tokenEndpoint,registrationEndpoint:m3.registrationEndpoint,scopesSupported:[...m3.scopesSupported],codeChallengeMethodsSupported:[...m3.codeChallengeMethodsSupported]}}function discoveryFailure(issuers,attempts){let firstIssuer=issuers[0]??"",named=firstDocumentFor(firstIssuer),attempt=attempts.find(a5=>a5.url===named)??attempts[0];if(attempt?.error!==void 0)return new Error(`discovery request to ${attempt.url} failed: ${attempt.error}`);if(attempt?.missing!==void 0)return new Error(`authorization server at ${attempt.url} is missing ${attempt.missing}`);let status=attempt?.status??0;return new Error(`authorization server discovery failed: ${named} returned HTTP ${status} (expected 200). This MCP server may not support the MCP Authorization specification`)}function firstDocumentFor(issuer){try{return authorizationServerMetadataUrls(new URL(issuer))[0]??issuer}catch{return issuer}}function parseDiscoveryUrl(serverUrl){let parsed;try{parsed=new URL(serverUrl)}catch(error2){throw new Error(`invalid server URL for discovery: ${error2 instanceof Error?error2.message:String(error2)}`)}let scheme=parsed.protocol.replace(/:$/,"");if(scheme!=="http"&&scheme!=="https")throw new Error(`invalid server URL for discovery: unsupported scheme "${scheme}": only http and https are supported`);if(parsed.host==="")throw new Error("invalid server URL for discovery: server URL has no host");return parsed}function validateMetadata(m3,sourceUrl){if(m3.authorizationEndpoint==="")throw new Error(`authorization server at ${sourceUrl} is missing authorization_endpoint`);if(m3.tokenEndpoint==="")throw new Error(`authorization server at ${sourceUrl} is missing token_endpoint`);if(m3.codeChallengeMethodsSupported.length>0&&!m3.codeChallengeMethodsSupported.includes("S256"))throw new Error(`authorization server at ${sourceUrl} does not support S256 PKCE (supports: [${m3.codeChallengeMethodsSupported.join(" ")}]). S256 is required by the MCP Authorization specification`)}var DCR_REQUEST_TIMEOUT_MS=15e3;async function registerClient(registrationEndpoint,redirectUri,clientName,fetchImpl){let requestBody=JSON.stringify({redirect_uris:[redirectUri],client_name:clientName,grant_types:["authorization_code"],response_types:["code"],token_endpoint_auth_method:"none"}),response;try{response=await fetchImpl(registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:requestBody,signal:AbortSignal.timeout(DCR_REQUEST_TIMEOUT_MS)})}catch(error2){throw new Error(`DCR request to ${registrationEndpoint} failed: ${error2 instanceof Error?error2.message:String(error2)}`)}let body=await response.text();if(response.status!==201&&response.status!==200)throw new Error(`DCR at ${registrationEndpoint} returned HTTP ${response.status}: ${truncateBody(body)}`);let raw;try{raw=JSON.parse(body)}catch(error2){throw new Error(`failed to parse DCR response: ${error2 instanceof Error?error2.message:String(error2)}`)}if((raw.client_id??"")==="")throw new Error(`DCR response from ${registrationEndpoint} is missing client_id`);return{clientId:raw.client_id,clientSecret:raw.client_secret??"",clientName:raw.client_name??"",tokenEndpointAuthMethod:raw.token_endpoint_auth_method??""}}var PREFLIGHT_REQUEST_TIMEOUT_MS=4e3,PREFLIGHT_BODY_READ_CAP=4096;async function preflightAuthorize(authorizationUrl,fetchImpl){let response=await fetchImpl(authorizationUrl,{method:"GET",redirect:"manual",signal:AbortSignal.timeout(PREFLIGHT_REQUEST_TIMEOUT_MS)});if(response.status!==400){await response.text().catch(()=>"");return}let body=(await response.text()).slice(0,PREFLIGHT_BODY_READ_CAP);return{statusCode:response.status,vendorDetail:extractVendorDetail(body),bodySnippet:truncateBody(body)}}function extractVendorDetail(body){let parsed;try{parsed=JSON.parse(body)}catch{return""}return(parsed.error_description??"")!==""?parsed.error_description:parsed.error??""}async function initiateOAuthConnect(deps,input,identity2){if(deps.oauthRedirectUri==="")throw failedPreconditionError("OAuth Connect is not configured: STIGMER_OAUTH_REDIRECT_URI is not set");let mcpServerId=input.mcpServerId;if(mcpServerId==="")throw invalidArgumentError("mcp_server_id is required");let mcpServer;try{mcpServer=await deps.store.getResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("mcp_server",mcpServerId):internalError(error2,"failed to load mcp server")}await authorizeDirect(McpServerCommandController.method.initiateOAuthConnect,deps.authorizer,identity2,input);let auth=mcpServer.spec?.auth;if(auth===void 0)throw failedPreconditionError(`MCP server '${mcpServerId}' does not have an auth block configured`);let pkcePair=generatePkce(),stateParam=generateState(),oauthAppRef=auth.oauthAppRef,isDcr=oauthAppRef===void 0||oauthAppRef.slug==="",result=isDcr?await initiateDcr(deps,mcpServer,pkcePair,stateParam):await initiateVendorOAuth(deps,mcpServer,pkcePair,stateParam),authMethod=isDcr?"mcp_oauth":"vendor_oauth",pendingState={state:stateParam,codeVerifier:pkcePair.codeVerifier,clientId:result.clientId,clientSecret:result.clientSecret,tokenEndpoint:result.tokenEndpoint,mcpServerId,identityAccountId:"",targetEnvVar:auth.targetEnvVar,authMethod,tokenAuthMethod:result.tokenAuthMethod,redirectUri:deps.oauthRedirectUri,org:input.org,createdAt:0},sealed;try{sealed=await sealPendingOAuthState(deps.secretService,deps.logger,pendingState)}catch(error2){throw internalError(error2,"failed to encrypt OAuth handshake secrets")}try{await deps.pendingOAuthStates.save(sealed)}catch(error2){throw internalError(error2,"failed to save pending OAuth state")}return deps.logger.info("Initiated OAuth Connect flow",{mcp_server_id:mcpServerId,auth_method:authMethod,provider:result.providerName}),create2(InitiateOAuthConnectOutputSchema,{authorizationUrl:result.authorizationUrl,state:stateParam,scopes:result.scopes,providerName:result.providerName})}async function initiateDcr(deps,mcpServer,pkcePair,stateParam){let discoveryUrl2=mcpServer.spec?.auth?.discoveryUrl??"",serverType=mcpServer.spec?.serverType,resourceUrl=serverType?.case==="http"?serverType.value.url:"",serverUrl=discoveryUrl2!==""?discoveryUrl2:resourceUrl;if(serverUrl==="")throw failedPreconditionError(`DCR requires a discoverable URL. MCP server '${mcpServer.metadata?.id??""}' has no http.url and no auth.discovery_url. Set auth.discovery_url for stdio servers, oauth_app_ref for vendor OAuth, or switch to HTTP transport`);let metadata;try{metadata=discoveryUrl2!==""?await discoverAtIssuer(discoveryUrl2,deps.outboundFetch):await discoverForResource(resourceUrl,deps.outboundFetch)}catch(error2){throw failedPreconditionError(`OAuth authorization server discovery failed for ${serverUrl}: ${error2 instanceof Error?error2.message:String(error2)}`)}if(metadata.registrationEndpoint==="")throw failedPreconditionError(`MCP server at ${serverUrl} does not advertise a registration_endpoint for DCR: ${loginServerHost(metadata,serverUrl)} does not allow automatic client registration, so this server needs an OAuth app registered with the vendor and referenced from its definition (auth.oauth_app_ref)`);let clientName=`Stigmer (${mcpServer.metadata?.name??""})`,dcrResponse;try{dcrResponse=await registerClient(metadata.registrationEndpoint,deps.oauthRedirectUri,clientName,deps.outboundFetch)}catch(error2){throw failedPreconditionError(`DCR registration failed: ${error2 instanceof Error?error2.message:String(error2)}`)}let scopes=mcpServer.spec?.auth?.scopeHints??[];scopes.length===0&&metadata.scopesSupported.length>0&&(scopes=metadata.scopesSupported);let authUrl=buildAuthorizationUrl(metadata.authorizationEndpoint,dcrResponse.clientId,deps.oauthRedirectUri,pkcePair.codeChallenge,stateParam,scopes,"scope"),rejection;try{rejection=await preflightAuthorize(authUrl,deps.outboundFetch)}catch(probeError){deps.logger.debug("authorize pre-flight probe inconclusive; proceeding",{mcp_server_id:mcpServer.metadata?.id??"",error:probeError instanceof Error?probeError.message:String(probeError)})}if(rejection!==void 0)throw deps.logger.warn("authorization endpoint rejected the sign-in request pre-flight",{status_code:rejection.statusCode,mcp_server_id:mcpServer.metadata?.id??"",body_snippet:rejection.bodySnippet}),failedPreconditionError(dcrRejectionMessage(mcpServer.metadata?.name??"",deps.oauthRedirectUri,rejection));return{authorizationUrl:authUrl,providerName:mcpServer.metadata?.name??"",scopes,clientId:dcrResponse.clientId,clientSecret:"",tokenEndpoint:metadata.tokenEndpoint,tokenAuthMethod:""}}function loginServerHost(metadata,serverUrl){for(let candidate of[metadata.issuer,metadata.authorizationEndpoint,serverUrl])try{let host=new URL(candidate).host;if(host!=="")return host}catch{}return serverUrl}async function initiateVendorOAuth(deps,mcpServer,pkcePair,stateParam){let ref=mcpServer.spec?.auth?.oauthAppRef,oauthApp;try{oauthApp=await resolveOAuthAppRef(deps.store,ref,deps.logger)}catch(error2){throw internalError(error2,"failed to list oauth apps")}if(oauthApp===void 0)throw notFoundError("oauth_app",ref?.slug??"");let approvalStatus=oauthApp.spec?.vendorApprovalStatus;if(approvalStatus===VendorApprovalStatus.PENDING||approvalStatus===VendorApprovalStatus.REJECTED){let statusLabel=approvalStatus===VendorApprovalStatus.REJECTED?"rejected":"pending approval",alternative=mcpServer.spec?.auth?.oauthOnly?"This server only accepts OAuth sign-in; an org admin can configure your own OAuth app instead.":"Please enter a token manually instead.";throw failedPreconditionError(`OAuth sign-in is unavailable: the platform's OAuth app for '${oauthApp.spec?.provider??""}' is ${statusLabel} by the vendor. ${alternative}`)}let clientSecret=oauthApp.spec?.clientSecret??"";if(deps.secretService.isEncrypted(clientSecret))try{clientSecret=await deps.secretService.decrypt(clientSecret)}catch(error2){throw internalError(error2,"failed to decrypt OAuthApp client secret")}let scopes=oauthApp.spec?.scopes??[];return{authorizationUrl:buildAuthorizationUrl(oauthApp.spec?.authorizationUrl??"",oauthApp.spec?.clientId??"",deps.oauthRedirectUri,pkcePair.codeChallenge,stateParam,scopes,oauthApp.spec?.scopeParameterName??""),providerName:oauthApp.spec?.provider??"",scopes,clientId:oauthApp.spec?.clientId??"",clientSecret,tokenEndpoint:oauthApp.spec?.tokenUrl??"",tokenAuthMethod:tokenAuthMethodFromSpec(oauthApp.spec?.tokenEndpointAuthMethod??TokenEndpointAuthMethod.UNSPECIFIED)}}function buildAuthorizationUrl(authEndpoint,clientId,redirectUri,codeChallenge,state2,scopes,scopeParamName){let scopeParam=scopeParamName===""?"scope":scopeParamName,params=new URLSearchParams({response_type:"code",client_id:clientId,redirect_uri:redirectUri,code_challenge:codeChallenge,code_challenge_method:"S256",state:state2});scopes.length>0&&params.set(scopeParam,scopes.join(" ")),params.sort();let separator=authEndpoint.includes("?")?"&":"?";return authEndpoint+separator+params.toString()}function dcrRejectionMessage(providerName,redirectUri,rejection){let callbackHost=redirectUri;try{let parsed=new URL(redirectUri);parsed.host!==""&&(callbackHost=parsed.host)}catch{}let message6=`${providerName} rejected the sign-in request before showing a login page (HTTP ${rejection.statusCode}). The most common cause is a redirect-host allowlist: this deployment's OAuth callback host (${callbackHost}) is not on the provider's approved list. Self-hosted deployments with a localhost callback are typically unaffected.`;return rejection.vendorDetail!==""&&(message6+=" Provider detail: "+rejection.vendorDetail),message6}function generateState(){return(0,import_node_crypto24.randomBytes)(32).toString("base64url")}async function sealPendingOAuthState(secretService,logger2,state2){if(!secretService.isEnabled())return logger2.warn("Encryption disabled: pending OAuth state secrets will be stored in plaintext"),state2;let scope=EncryptionScope.forOrganization(state2.org),sealedVerifier;try{sealedVerifier=await secretService.encrypt(state2.codeVerifier,scope)}catch(error2){throw new Error(`failed to encrypt code_verifier: ${error2 instanceof Error?error2.message:String(error2)}`)}let sealedSecret=state2.clientSecret;if(state2.clientSecret!=="")try{sealedSecret=await secretService.encrypt(state2.clientSecret,scope)}catch(error2){throw new Error(`failed to encrypt client_secret: ${error2 instanceof Error?error2.message:String(error2)}`)}return{...state2,codeVerifier:sealedVerifier,clientSecret:sealedSecret}}var mcpServerSearchExtractor={kind:ApiResourceKind.mcp_server,schema:McpServerSchema,getSearchSummary(resource){return resource.spec?.description??""},toSearchResult(resource,score){let mcpServer=resource;return buildSearchResult({kind:ApiResourceKind.mcp_server,metadata:mcpServer.metadata,summary:mcpServer.spec?.description??"",score,createdAt:mcpServer.status?.audit?.specAudit?.createdAt,updatedAt:mcpServer.status?.audit?.specAudit?.updatedAt,iconUrl:mcpServer.spec?.iconUrl??""})},getSearchIndexEntry(resource){let mcpServer=resource,metadata=mcpServer.metadata;if(metadata!==void 0)return{name:metadata.name,description:mcpServer.spec?.description??"",tags:metadata.tags.join(" "),org:metadata.org,visibility:ApiResourceVisibility[metadata.visibility]??"",createdAt:Number(mcpServer.status?.audit?.specAudit?.createdAt?.seconds??0n)}}};var RUNNER_QUEUE_WARNING="no runner appears to be polling the task queue \u2014 the connect will wait for one to come up (start your local runner if it is not running)";async function startConnect(deps,input,identity2){let mcpServerId=input.mcpServerId;if(mcpServerId==="")throw invalidArgumentError("mcp_server_id is required");if(input.org==="")throw invalidArgumentError("org is required for connect");let mcpServer;try{mcpServer=await deps.store.getResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("mcp_server",mcpServerId):internalError(error2,"failed to load mcp server")}await authorizeDirect(McpServerCommandController.method.startConnect,deps.authorizer,identity2,input);let engineState=deps.engineState();if(!engineState.connected)throw failedPreconditionError("connect is not available: Temporal not configured");let connectStatus=mcpServer.status?.connectStatus;if(connectStatus?.phase===ConnectPhase.connecting&&await engineState.engine.isConnectRunRunning(connectStatus.workflowId))return deps.logger.info("StartConnect attached to in-flight connect operation",{mcp_server_id:mcpServerId,workflow_id:connectStatus.workflowId}),mcpServer;let prepared=await prepareConnect(deps,mcpServer,input,identity2),warning2=await runnerQueueWarning(engineState.engine),run;try{run=await engineState.engine.startOrAttachConnect(mcpServerId,prepared.workflowInput,ASYNC_CONNECT_TIMEOUT.ms)}catch(error2){throw prepared.ecResourceId!==""&&await deleteConnectExecutionContext(deps,prepared.ecResourceId,prepared.executionId),deps.logger.error("Failed to start MCP connect workflow",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)}),internalError(error2,"failed to start connect workflow")}if(run.attached){prepared.ecResourceId!==""&&await deleteConnectExecutionContext(deps,prepared.ecResourceId,prepared.executionId);try{return await deps.store.getResource(ApiResourceKind.mcp_server,mcpServerId,McpServerSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("mcp_server",mcpServerId):internalError(error2,"failed to load mcp server")}}let persisted;try{persisted=await persistConnectStarting(deps.store,mcpServerId,run.workflowId,warning2)}catch(error2){throw detachSettle(deps,mcpServer,run,prepared),internalError(error2,"failed to record connect operation")}return detachSettle(deps,mcpServer,run,prepared),persisted}function detachSettle(deps,mcpServer,run,prepared){settleConnectAsync(deps,mcpServer,run,prepared.ecResourceId,prepared.executionId).catch(error2=>{deps.logger.warn("Async connect settle task failed unexpectedly",{mcp_server_id:mcpServer.metadata?.id??"",error:error2 instanceof Error?error2.message:String(error2)})})}async function settleConnectAsync(deps,mcpServer,run,ecResourceId,executionId){let mcpServerId=mcpServer.metadata?.id??"";try{let outcome=await run.result(ASYNC_CONNECT_TIMEOUT.ms+BEST_EFFORT_CONNECT_GET_BUFFER_MS);if(!outcome.ok){let failure=mapConnectFailure(deps.logger,mcpServer,run.workflowId,outcome.failure,ASYNC_CONNECT_TIMEOUT);await persistConnectFailure(deps.store,deps.logger,mcpServerId,failure);return}let persisted,toolApprovalCount;try{({persisted,toolApprovalCount}=await persistConnectResult(deps.store,mcpServerId,run.workflowId,outcome.output))}catch(error2){if(error2 instanceof ResourceNotFoundError){deps.logger.info("Skipping async connect persistence: MCP server deleted before connect completed",{mcp_server_id:mcpServerId});return}deps.logger.warn("Failed to persist async connect result",{mcp_server_id:mcpServerId,error:error2 instanceof Error?error2.message:String(error2)});return}deps.logger.info("Async MCP server connect completed and stored",{workflow_id:run.workflowId,mcp_server_id:mcpServerId,tools:persisted.status?.discoveredCapabilities?.tools.length??0,resource_templates:persisted.status?.discoveredCapabilities?.resourceTemplates.length??0,tool_approvals:toolApprovalCount})}finally{ecResourceId!==""&&await deleteConnectExecutionContext(deps,ecResourceId,executionId)}}async function runnerQueueWarning(engine){let hasPollers=await engine.hasRunnerQueuePollers();return hasPollers===void 0||hasPollers?"":RUNNER_QUEUE_WARNING}function newValidateDefaultEnabledToolsStep(){return{name:"ValidateDefaultEnabledTools",execute(ctx){let mcpServer=ctx.newState,requested=mcpServer.spec?.defaultEnabledTools??[];if(requested.length===0)return;let caps=mcpServer.status?.discoveredCapabilities;if(caps===void 0)return;let classification=classify(caps,requested);if(isValidClassification(classification))return;let problems=[];throw classification.unknown.length>0&&problems.push(`default_enabled_tools names tool(s) this server does not expose: ${quoteJoin(classification.unknown)}`),classification.resourceTemplates.length>0&&problems.push(`default_enabled_tools names resource template(s): ${quoteJoin(classification.resourceTemplates)} \u2014 resource templates are read-only data endpoints, not callable tools, and must not appear in default_enabled_tools`),invalidArgumentError(`MCP server '${mcpServer.metadata?.slug??""}': ${problems.join("; ")}. Discovered tools: ${quoteJoin(toolNames(caps))}. If the server's toolset changed, run 'stigmer connect' on it to refresh discovered capabilities.`)}}}function newEnrichOAuthStatusStep(store,logger2){return{name:"EnrichOAuthStatus",async execute(ctx){let mcpServer=ctx.get(TARGET_RESOURCE_KEY);if(mcpServer===void 0)return;let ref=mcpServer.spec?.auth?.oauthAppRef;if((ref?.slug??"")==="")return;let oauthApp;try{oauthApp=await resolveOAuthAppRef(store,ref,logger2)}catch(error2){logger2.warn("OAuthApp lookup failed; returning MCP server without oauth_status enrichment",{mcpServerId:mcpServer.metadata?.id??"",oauthAppSlug:ref?.slug??"",error:error2 instanceof Error?error2.message:String(error2)});return}if(oauthApp===void 0){logger2.debug("OAuthApp not found for ref; skipping oauth_status enrichment",{mcpServerId:mcpServer.metadata?.id??"",oauthAppSlug:ref?.slug??""});return}let approvalStatus=oauthApp.spec?.vendorApprovalStatus??VendorApprovalStatus.UNSPECIFIED,docsUrl=oauthApp.spec?.vendorApprovalDocsUrl??"";approvalStatus===VendorApprovalStatus.UNSPECIFIED&&docsUrl===""||(mcpServer.status??=create2(McpServerStatusSchema,{}),mcpServer.status.oauthStatus=create2(OAuthStatusSchema,{vendorApprovalStatus:approvalStatus,vendorApprovalDocsUrl:docsUrl}))}}}function registerMcpServerServices(router,deps){router.service(McpServerCommandController,{apply:(server,ctx)=>apply11(deps,server,ctx),create:(server,ctx)=>createMcpServer(deps,server,ctx),update:(server,ctx)=>update14(deps,server,ctx),updateVisibility:(input,ctx)=>updateVisibility4(deps,input,ctx),delete:(input,ctx)=>deleteMcpServer(deps,input,ctx),connect:(input,ctx)=>connect(deps.connect,input,callerIdentityOf(ctx)),startConnect:(input,ctx)=>startConnect(deps.connect,input,callerIdentityOf(ctx)),initiateOAuthConnect:(input,ctx)=>initiateOAuthConnect(deps.connect,input,callerIdentityOf(ctx)),completeOAuthConnect:(input,ctx)=>completeOAuthConnect(deps.connect,input,callerIdentityOf(ctx)),disconnectOAuth:(input,ctx)=>disconnectOAuth(deps.connect,input,callerIdentityOf(ctx)),setOrgOAuthApp:()=>{throw orgOAuthAppUnimplemented("SetOrgOAuthApp")},deleteOrgOAuthApp:()=>{throw orgOAuthAppUnimplemented("DeleteOrgOAuthApp")}}),router.service(McpServerQueryController,{get:(id,ctx)=>get19(deps,id,ctx),getByReference:(ref,ctx)=>getByReference11(deps,ref,ctx),getOAuthGrantStatus:(input,ctx)=>getOAuthGrantStatus(deps.connect,input,callerIdentityOf(ctx)),getOrgOAuthApp:()=>{throw orgOAuthAppUnimplemented("GetOrgOAuthApp")}})}function orgOAuthAppUnimplemented(method){return new ConnectError(`method ${method} not implemented`,Code.Unimplemented)}function kindOf18(ctx){return ctx.values.get(apiResourceKindKey)}function endpointAuthDeps(deps){return{outboundFetch:deps.connect.outboundFetch,logger:deps.logger}}async function createMcpServer(deps,server,ctx){let reqCtx=new RequestContext(McpServerSchema,server,callerIdentityOf(ctx),kindOf18(ctx));return await newPipeline("mcpserver-create",deps.logger).addStep(newAuthorizeStep(McpServerCommandController.method.create,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newResolveSlugStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newBuildNewStateStep()).addStep(newCompleteEndpointAuthStep(endpointAuthDeps(deps))).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store)).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).addStep(newIndexSearchStep(deps.store,mcpServerSearchExtractor,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function update14(deps,server,ctx){let reqCtx=new RequestContext(McpServerSchema,server,callerIdentityOf(ctx),kindOf18(ctx));return await newPipeline("mcpserver-update",deps.logger).addStep(newAuthorizeStep(McpServerCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingStep(deps.store)).addStep(newGuardPluginManagedStep(deps.store)).addStep(newBuildUpdateStateStep()).addStep(newCompleteEndpointAuthStep(endpointAuthDeps(deps))).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newValidateDefaultEnabledToolsStep()).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store)).addStep(newPersistStep(deps.store)).addStep(newIndexSearchStep(deps.store,mcpServerSearchExtractor,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function apply11(deps,server,ctx){let reqCtx=new RequestContext(McpServerSchema,server,callerIdentityOf(ctx),kindOf18(ctx));await newPipeline("mcpserver-apply",deps.logger).addStep(newAuthorizeStep(McpServerCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");let result=shouldCreate?await createMcpServer(deps,server,ctx):await update14(deps,withResolvedApplyId(McpServerSchema,server,reqCtx),ctx);return startBestEffortConnect(deps.connect,result).catch(error2=>{deps.logger.warn("Best-effort connect task failed unexpectedly",{mcp_server_id:result.metadata?.id??"",error:error2 instanceof Error?error2.message:String(error2)})}),result}async function deleteMcpServer(deps,input,ctx){let reqCtx=new RequestContext(McpServerCommandController.method.delete.input,input,callerIdentityOf(ctx),kindOf18(ctx));reqCtx.set(RESOURCE_ID_KEY,input.resourceId),await newPipeline("mcpserver-delete",deps.logger).addStep(newAuthorizeStep(McpServerCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadExistingForDeleteStep(deps.store,McpServerSchema)).addStep(newGuardPluginManagedStep(deps.store)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDeleteSearchIndexStep(deps.store,deps.logger)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted mcp server not found in context"),"deleted mcp server not found in context");return deleted}var UPDATE_VISIBILITY_MCP_SERVER_KEY="updateVisibilityMcpServer";async function updateVisibility4(deps,input,ctx){let reqCtx=new RequestContext(McpServerCommandController.method.updateVisibility.input,input,callerIdentityOf(ctx),kindOf18(ctx));return await newPipeline("mcpserver-update-visibility",deps.logger).addStep(newAuthorizeStep(McpServerCommandController.method.updateVisibility,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadMcpServerForVisibilityUpdateStep(deps.store)).addStep(newGuardPluginManagedStep(deps.store,{existingKey:UPDATE_VISIBILITY_MCP_SERVER_KEY})).addStep(newRecordVisibilityBeforeUpdateStep(UPDATE_VISIBILITY_MCP_SERVER_KEY)).addStep(newValidateVisibilityUpdateStep()).addStep(newSetMcpServerVisibilityStep()).addStep(newPersistMcpServerForVisibilityUpdateStep(deps.store)).addStep(newUpdateVisibilityTuplesStep(deps.authorizationLifecycle,UPDATE_VISIBILITY_MCP_SERVER_KEY)).addStep(newIndexMcpServerAfterVisibilityUpdateStep(deps.store,deps.logger)).build().execute(reqCtx),reqCtx.get(UPDATE_VISIBILITY_MCP_SERVER_KEY)}function newLoadMcpServerForVisibilityUpdateStep(store){return{name:"LoadMcpServerForVisibilityUpdate",async execute(ctx){let input=ctx.input,mcpServer;try{mcpServer=await store.getResource(ctx.apiResourceKind,input.resourceId,McpServerSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("mcp_server",input.resourceId):internalError(error2,"failed to load mcp server")}ctx.set(UPDATE_VISIBILITY_MCP_SERVER_KEY,mcpServer)}}}function newSetMcpServerVisibilityStep(){return{name:"SetMcpServerVisibility",execute(ctx){let mcpServer=ctx.get(UPDATE_VISIBILITY_MCP_SERVER_KEY);mcpServer.metadata!==void 0&&(mcpServer.metadata.visibility=ctx.input.visibility),setAuditFieldsForUpdate(McpServerSchema,mcpServer,"status_audit",ctx.callerIdentity)}}}function newPersistMcpServerForVisibilityUpdateStep(store){return{name:"PersistMcpServerForVisibilityUpdate",async execute(ctx){let mcpServer=ctx.get(UPDATE_VISIBILITY_MCP_SERVER_KEY);try{await store.saveResource(ctx.apiResourceKind,mcpServer.metadata?.id??"",McpServerSchema,mcpServer)}catch(error2){throw internalError(error2,"failed to save mcp server")}}}}function newIndexMcpServerAfterVisibilityUpdateStep(store,logger2){return{name:"IndexMcpServerAfterVisibilityUpdate",async execute(ctx){let mcpServer=ctx.get(UPDATE_VISIBILITY_MCP_SERVER_KEY),entry=mcpServerSearchExtractor.getSearchIndexEntry(mcpServer);if(entry===void 0){logger2.warn("IndexMcpServerAfterVisibilityUpdate: extractor returned nil, skipping",{id:mcpServer.metadata?.id??""});return}try{await store.upsertSearchIndex(ctx.apiResourceKind,mcpServer.metadata?.id??"",entry)}catch(error2){logger2.warn("IndexMcpServerAfterVisibilityUpdate: failed (best-effort)",{id:mcpServer.metadata?.id??"",error:error2 instanceof Error?error2.message:String(error2)})}}}}async function get19(deps,id,ctx){let reqCtx=new RequestContext(McpServerQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf18(ctx));return await newPipeline("mcpserver-get",deps.logger).addStep(newAuthorizeStep(McpServerQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,McpServerSchema)).addStep(newEnrichOAuthStatusStep(deps.store,deps.logger)).build().execute(reqCtx),reqCtx.get(TARGET_RESOURCE_KEY)}async function getByReference11(deps,ref,ctx){let reqCtx=new RequestContext(McpServerQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf18(ctx));return await newPipeline("mcpserver-get-by-reference",deps.logger).addStep(newAuthorizeStep(McpServerQueryController.method.getByReference,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadByReferenceStep(deps.store,McpServerSchema)).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,loadedTargetAsMethod(McpServerQueryController.method.get))).addStep(newEnrichOAuthStatusStep(deps.store,deps.logger)).build().execute(reqCtx),reqCtx.get(TARGET_RESOURCE_KEY)}function registerPlatformServices(router,deps){router.service(PlatformQueryController,{getServerInfo:()=>getServerInfo(deps),getLicenseStatus:()=>getLicenseStatus(deps),getRunnerBootstrapConfig:(_input,ctx)=>getRunnerBootstrapConfig(deps,ctx),getRunnerScopedToken:(input,ctx)=>getRunnerScopedToken(deps,input,ctx)})}function getServerInfo(deps){return create2(GetServerInfoOutputSchema,{edition:deps.edition,version:deps.version,authenticationRequired:deps.authenticationRequired})}async function getLicenseStatus(deps){let now=deps.now(),report=await deps.licenseStatus.status(now),output=create2(GetLicenseStatusOutputSchema,{state:report.state,checkedAt:timestampFromDate(now)});switch(report.state){case LicenseState.absent:return output;case LicenseState.invalid:return output.keyId=report.keyId,output;case LicenseState.valid:case LicenseState.expiring:case LicenseState.grace:case LicenseState.expired:return output.keyId=report.keyId,output.claims=report.claims,output;default:{let exhaustive=report;throw new Error(`unhandled license report: ${JSON.stringify(exhaustive)}`)}}}async function getRunnerBootstrapConfig(deps,ctx){let output=create2(GetRunnerBootstrapConfigOutputSchema,{temporalAddress:deps.runnerBootstrapTemporalAddress,temporalNamespace:deps.temporalNamespace}),bootstrapCredentials=deps.runnerAuthService.bootstrapCredentials?.bind(deps.runnerAuthService);if(bootstrapCredentials===void 0)return output;try{let credentials=await bootstrapCredentials(callerIdentityOf(ctx));credentials.accessToken!==void 0&&(output.runnerAccessToken=credentials.accessToken.token,output.tokenType="Bearer",output.runnerAccessTokenExpiresInSeconds=credentials.accessToken.expiresInSeconds),credentials.payloadKeys!==void 0&&(output.payloadEncryptionKey=credentials.payloadKeys.keyBase64,output.payloadEncryptionKeyId=credentials.payloadKeys.keyId,output.payloadEncryptionSecondaryKey=credentials.payloadKeys.secondaryKeyBase64??"",output.payloadEncryptionSecondaryKeyId=credentials.payloadKeys.secondaryKeyId??"")}catch(error2){deps.logger.warn("Bootstrap credentials unavailable \u2014 answering coordinates without them",{error:error2 instanceof Error?error2.message:String(error2)})}return output}async function getRunnerScopedToken(deps,input,ctx){let exchange=deps.runnerAuthService.exchangeScopedToken?.bind(deps.runnerAuthService);if(exchange!==void 0){let minted=await exchange(exchangeRequestOf(input),callerIdentityOf(ctx));return minted.minted?create2(GetRunnerScopedTokenOutputSchema,{runnerScopedToken:minted.token,tokenType:"Bearer",expiresInSeconds:minted.expiresInSeconds}):create2(GetRunnerScopedTokenOutputSchema)}let executionId;switch(input.scope.case){case"agentExecutionId":executionId=input.scope.value;break;case"workflowExecutionId":executionId=input.scope.value;break;case"poolClaim":case"renewal":case void 0:return create2(GetRunnerScopedTokenOutputSchema);default:{let exhaustive=input.scope;throw new Error(`unhandled scope arm: ${JSON.stringify(exhaustive)}`)}}if(executionId===""||!deps.runnerAuthService.isEnabled(TOKEN_TYPE_EXECUTION_SCOPED))return create2(GetRunnerScopedTokenOutputSchema);try{let minted=deps.runnerAuthService.mint(TOKEN_TYPE_EXECUTION_SCOPED,executionId,0);return create2(GetRunnerScopedTokenOutputSchema,{runnerScopedToken:minted.token,tokenType:"Bearer",expiresInSeconds:minted.ttlSeconds})}catch(error2){return deps.logger.warn("failed to mint runner scoped token \u2014 answering not-minted",{executionId,error:error2 instanceof Error?error2.message:String(error2)}),create2(GetRunnerScopedTokenOutputSchema)}}function exchangeRequestOf(input){switch(input.scope.case){case"agentExecutionId":return{arm:"agent-execution",executionId:input.scope.value};case"workflowExecutionId":return{arm:"workflow-execution",executionId:input.scope.value};case"poolClaim":return{arm:"pool-claim",sessionId:input.scope.value.sessionId};case"renewal":return{arm:"renewal"};case void 0:return{arm:"unset"};default:{let exhaustive=input.scope;throw new Error(`unhandled scope arm: ${JSON.stringify(exhaustive)}`)}}}var SERVER_VERSION="3.40.1";var file_ai_stigmer_agentic_session_v1_io=fileDesc("CiZhaS9zdGlnbWVyL2FnZW50aWMvc2Vzc2lvbi92MS9pby5wcm90bxIdYWkuc3RpZ21lci5hZ2VudGljLnNlc3Npb24udjEiIgoJU2Vzc2lvbklkEhUKBXZhbHVlGAEgASgJQga6SAPIAQEiIAoHQWdlbnRJZBIVCgV2YWx1ZRgBIAEoCUIGukgDyAEBInQKC1Nlc3Npb25MaXN0EhMKC3RvdGFsX3BhZ2VzGAEgASgFEjcKB2VudHJpZXMYAiADKAsyJi5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5TZXNzaW9uEhcKD25leHRfcGFnZV90b2tlbhgDIAEoCSJgChNMaXN0U2Vzc2lvbnNSZXF1ZXN0EhoKCXBhZ2Vfc2l6ZRgBIAEoBUIHukgEGgIoABISCgpwYWdlX3Rva2VuGAIgASgJEgwKBHRhZ3MYAyADKAkSCwoDb3JnGAQgASgJIncKIkxpc3RTZXNzaW9uc0J5QWdlbnRJbnN0YW5jZVJlcXVlc3QSIQoRYWdlbnRfaW5zdGFuY2VfaWQYASABKAlCBrpIA8gBARIaCglwYWdlX3NpemUYAiABKAVCB7pIBBoCKAASEgoKcGFnZV90b2tlbhgDIAEoCSJqChxMaXN0U2Vzc2lvbnNCeUNoYW5uZWxSZXF1ZXN0EhoKCmNoYW5uZWxfaWQYASABKAlCBrpIA8gBARIaCglwYWdlX3NpemUYAiABKAVCB7pIBBoCKAASEgoKcGFnZV90b2tlbhgDIAEoCSJCChtVcGRhdGVTZXNzaW9uU3ViamVjdFJlcXVlc3QSEgoCaWQYASABKAlCBrpIA8gBARIPCgdzdWJqZWN0GAIgASgJYgZwcm90bzM",[file_ai_stigmer_agentic_session_v1_api,file_buf_validate_validate]),SessionIdSchema=messageDesc2(file_ai_stigmer_agentic_session_v1_io,0);var SessionListSchema=messageDesc2(file_ai_stigmer_agentic_session_v1_io,2);var file_ai_stigmer_agentic_session_v1_command=fileDesc("CithaS9zdGlnbWVyL2FnZW50aWMvc2Vzc2lvbi92MS9jb21tYW5kLnByb3RvEh1haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MTLtBQoYU2Vzc2lvbkNvbW1hbmRDb250cm9sbGVyElcKBWFwcGx5EiYuYWkuc3RpZ21lci5hZ2VudGljLnNlc3Npb24udjEuU2Vzc2lvbhomLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb24SpQEKBmNyZWF0ZRImLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb24aJi5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5TZXNzaW9uIkvCuBhHCAgQHiIMbWV0YWRhdGEub3JnKjN1bmF1dGhvcml6ZWQgdG8gY3JlYXRlIHNlc3Npb24gaW4gdGhpcyBvcmdhbml6YXRpb24SjwEKBnVwZGF0ZRImLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb24aJi5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5TZXNzaW9uIjXCuBgxCAIQKiILbWV0YWRhdGEuaWQqHnVuYXV0aG9yaXplZCB0byB1cGRhdGUgc2Vzc2lvbhKpAQoNdXBkYXRlU3ViamVjdBI6LmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlVwZGF0ZVNlc3Npb25TdWJqZWN0UmVxdWVzdBomLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb24iNMK4GDAIAhAqIgJpZComdW5hdXRob3JpemVkIHRvIHVwZGF0ZSBzZXNzaW9uIHN1YmplY3QSiwEKBmRlbGV0ZRIoLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb25JZBomLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb24iL8K4GCsIAxAqIgV2YWx1ZSoedW5hdXRob3JpemVkIHRvIGRlbGV0ZSBzZXNzaW9uGgSg/ysqYgZwcm90bzM",[file_ai_stigmer_agentic_session_v1_api,file_ai_stigmer_agentic_session_v1_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),SessionCommandController=serviceDesc(file_ai_stigmer_agentic_session_v1_command,0);var file_ai_stigmer_agentic_session_v1_query=fileDesc("CilhaS9zdGlnbWVyL2FnZW50aWMvc2Vzc2lvbi92MS9xdWVyeS5wcm90bxIdYWkuc3RpZ21lci5hZ2VudGljLnNlc3Npb24udjEyoQQKFlNlc3Npb25RdWVyeUNvbnRyb2xsZXIShQEKA2dldBIoLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb25JZBomLmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLlNlc3Npb24iLMK4GCgIARAqIgV2YWx1ZSobdW5hdXRob3JpemVkIHRvIGdldCBzZXNzaW9uEmwKBGxpc3QSMi5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5MaXN0U2Vzc2lvbnNSZXF1ZXN0GiouYWkuc3RpZ21lci5hZ2VudGljLnNlc3Npb24udjEuU2Vzc2lvbkxpc3QiBNC4GAESigEKE2xpc3RCeUFnZW50SW5zdGFuY2USQS5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5MaXN0U2Vzc2lvbnNCeUFnZW50SW5zdGFuY2VSZXF1ZXN0GiouYWkuc3RpZ21lci5hZ2VudGljLnNlc3Npb24udjEuU2Vzc2lvbkxpc3QiBNC4GAESfgoNbGlzdEJ5Q2hhbm5lbBI7LmFpLnN0aWdtZXIuYWdlbnRpYy5zZXNzaW9uLnYxLkxpc3RTZXNzaW9uc0J5Q2hhbm5lbFJlcXVlc3QaKi5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5TZXNzaW9uTGlzdCIE0LgYARoEoP8rKmIGcHJvdG8z",[file_ai_stigmer_agentic_session_v1_api,file_ai_stigmer_agentic_session_v1_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),SessionQueryController=serviceDesc(file_ai_stigmer_agentic_session_v1_query,0);function runAgentInstanceDeniedMessage2(agentInstanceId){return`unauthorized to run agent instance '${agentInstanceId}'`}function sessionRunTarget(session){let agentInstanceId=session.spec?.agentInstanceId??"";if(agentInstanceId!=="")return{...RUN_GATE_CHECKS.agentInstance,resourceId:agentInstanceId,deniedMessage:runAgentInstanceDeniedMessage2(agentInstanceId)}}var sessionSearchExtractor={kind:ApiResourceKind.session,schema:SessionSchema,getSearchSummary(resource){return resource.spec?.subject??""},toSearchResult(resource,score){let session=resource;return buildSearchResult({kind:ApiResourceKind.session,metadata:session.metadata,summary:session.spec?.subject??"",score,createdAt:session.status?.audit?.specAudit?.createdAt,updatedAt:session.status?.audit?.specAudit?.updatedAt})},getSearchIndexEntry(resource){let session=resource,metadata=session.metadata;if(metadata!==void 0)return{name:metadata.name,description:session.spec?.subject??"",tags:metadata.tags.join(" "),org:metadata.org,visibility:ApiResourceVisibility[metadata.visibility]??"",createdAt:Number(session.status?.audit?.specAudit?.createdAt?.seconds??0n)}}};var SESSION_CHANNEL_ID_LABEL="stigmer.ai/channel-id",sessionListIndex=declareListIndex({kind:ApiResourceKind.session,schema:SessionSchema,revision:1,keys:{agent_instance:field2("spec.agent_instance_id"),channel:label(SESSION_CHANNEL_ID_LABEL)}});var LIST_RESULT_KEY8="listResult";function newValidateHarnessImmutabilityStep(){return{name:"ValidateHarnessImmutability",execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)return;let existingSpec=existing.spec;if(existingSpec===void 0||existingSpec.harnessStateId==="")return;let inputSpec=ctx.input.spec;if(inputSpec===void 0)return;let existingHarness=existingSpec.harness,inputHarness=inputSpec.harness;if(existingHarness===Harness.UNSPECIFIED&&(existingHarness=Harness.NATIVE),inputHarness===Harness.UNSPECIFIED&&(inputHarness=Harness.NATIVE),inputHarness!==existingHarness)throw failedPreconditionError("session harness cannot be changed after the first execution \u2014 each harness owns its conversation state independently")}}}var EXECUTION_TARGET_GO_NAMES={[ExecutionTarget.UNSPECIFIED]:"EXECUTION_TARGET_UNSPECIFIED",[ExecutionTarget.LOCAL]:"EXECUTION_TARGET_LOCAL",[ExecutionTarget.CLOUD]:"EXECUTION_TARGET_CLOUD"};function newValidateExecutionTargetImmutabilityStep(temporalConfig){return{name:"ValidateExecutionTargetImmutability",execute(ctx){let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0)return;let existingSpec=existing.spec;if(existingSpec===void 0||existingSpec.harnessStateId==="")return;let inputSpec=ctx.input.spec;if(inputSpec===void 0)return;let existingTarget=temporalConfig.resolveExecutionTarget(existingSpec.executionTarget),inputTarget=temporalConfig.resolveExecutionTarget(inputSpec.executionTarget);if(inputTarget!==existingTarget)throw failedPreconditionError(`session execution_target cannot be changed after the first execution (${EXECUTION_TARGET_GO_NAMES[existingTarget]} \u2192 ${EXECUTION_TARGET_GO_NAMES[inputTarget]}; unset resolves to the deployment default, ${temporalConfig.defaultExecutionTarget}) \u2014 workspace state may not be portable between local and cloud environments`)}}}function newRecordHarnessStateHistoryStep(){return{name:"RecordHarnessStateHistory",execute(ctx){let mergedSpec=ctx.newState.spec;if(mergedSpec===void 0)return;let existing=ctx.get(EXISTING_RESOURCE_KEY);if(existing===void 0||existing.spec===void 0)return;let existingSpec=existing.spec,history=[...existingSpec.harnessStateIdHistory],previousId=existingSpec.harnessStateId;previousId!==""&&previousId!==mergedSpec.harnessStateId&&!history.includes(previousId)&&history.push(previousId),mergedSpec.harnessStateIdHistory=history}}}function isActiveExecutionPhase(phase){switch(phase){case ExecutionPhase.EXECUTION_PENDING:case ExecutionPhase.EXECUTION_IN_PROGRESS:case ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL:case ExecutionPhase.EXECUTION_PAUSED:return!0;default:return!1}}async function listExecutionsBySession(store,logger2,sessionId){let rows;try{rows=await store.queryResources(agentExecutionListIndex,{anyKey:[{name:"session",value:sessionId}]})}catch(error2){throw internalError(error2,"failed to list agent executions")}let executions=[];for(let row of rows)try{executions.push(fromBinary2(AgentExecutionSchema,row.data))}catch(error2){logger2.warn("Failed to unmarshal execution, skipping",{error:error2 instanceof Error?error2.message:String(error2)})}return executions}function newRejectDeleteWithActiveExecutionsStep(store,logger2){return{name:"RejectDeleteWithActiveExecutions",async execute(ctx){let sessionId=requireSessionId(ctx),executions=await listExecutionsBySession(store,logger2,sessionId),activeCount=0;for(let execution of executions)isActiveExecutionPhase(execution.status?.phase??ExecutionPhase.EXECUTION_PHASE_UNSPECIFIED)&&activeCount++;if(activeCount>0)throw failedPreconditionError(`session has ${activeCount} active execution(s); cancel them or wait for completion before deleting`)}}}function newCascadeDeleteAgentExecutionsStep(store,logger2){return{name:"CascadeDeleteAgentExecutions",async execute(ctx){let sessionId=requireSessionId(ctx),executions=await listExecutionsBySession(store,logger2,sessionId);if(executions.length!==0){for(let execution of executions){let executionId=execution.metadata?.id??"";try{await store.deleteResource(ApiResourceKind.agent_execution,executionId)}catch(error2){throw internalError(error2,`failed to cascade-delete execution ${executionId} of session ${sessionId}`)}try{await store.deleteSearchIndex(ApiResourceKind.agent_execution,executionId)}catch(error2){logger2.warn("CascadeDeleteAgentExecutions: failed to remove search index entry (best-effort)",{executionId,error:error2 instanceof Error?error2.message:String(error2)})}}logger2.info("Cascade-deleted executions of session",{sessionId,count:executions.length})}}}}function requireSessionId(ctx){let sessionId=ctx.get(RESOURCE_ID_KEY);if(typeof sessionId!="string"||sessionId==="")throw internalError(new Error("session id not found in context (ExtractResourceId must run first)"),"session id not found in context (ExtractResourceId must run first)");return sessionId}function newListAllSessionsStep(store,logger2,listReadScope){return{name:"ListAllSessions",async execute(ctx){let input=ctx.input,page=await readSessionPage(store,logger2,listReadScope,ctx.callerIdentity,ctx.input,{query:{org:input.org},fingerprint:{lane:"session.list",org:input.org,tags:input.tags}});ctx.set(LIST_RESULT_KEY8,page)}}}function newFilterByAgentInstanceStep(store,logger2,listReadScope){return{name:"FilterByAgentInstance",async execute(ctx){let agentInstanceId=ctx.input.agentInstanceId;if(agentInstanceId==="")throw invalidArgumentError("agent_instance_id is required");let page=await readSessionPage(store,logger2,listReadScope,ctx.callerIdentity,ctx.input,{query:{anyKey:[{name:"agent_instance",value:agentInstanceId}]},fingerprint:{lane:"session.listByAgentInstance",agentInstanceId}});ctx.set(LIST_RESULT_KEY8,page)}}}function newAuthorizeChannelAccessStep(authorizer){return newAuthorizeResolvedTargetStep(authorizer,({input})=>input.channelId===""?[]:[{permission:IamPermission.can_view,resourceKind:ApiResourceKind.agent_channel,resourceId:input.channelId,deniedMessage:"unauthorized to list channel conversations"}],"AuthorizeChannelAccess")}function newFilterByChannelStep(store,logger2,listReadScope){return{name:"FilterByChannel",async execute(ctx){let channelId=ctx.input.channelId;if(channelId==="")throw invalidArgumentError("channel_id is required");let page=await readSessionPage(store,logger2,listReadScope,ctx.callerIdentity,ctx.input,{query:{anyKey:[{name:"channel",value:channelId}]},fingerprint:{lane:"session.listByChannel",channelId}});ctx.set(LIST_RESULT_KEY8,page)}}}async function readSessionPage(store,logger2,listReadScope,caller,request,lane){let page=await readListPage({store,declaration:sessionListIndex,query:lane.query,request,fingerprint:listPageFingerprint(lane.fingerprint),decode:data=>{try{return fromBinary2(SessionSchema,data)}catch(error2){logger2.warn("Failed to unmarshal session, skipping",{error:error2 instanceof Error?error2.message:String(error2)});return}},scope:sessions=>restrictListByReadScope(listReadScope,caller,ApiResourceKind.session,sessions,""),failure:"failed to list sessions"});return create2(SessionListSchema,{entries:page.entries,nextPageToken:page.nextPageToken,totalPages:page.nextPageToken===""?1:0})}function registerSessionServices(router,deps){router.service(SessionCommandController,{apply:(session,ctx)=>apply12(deps,session,ctx),create:(session,ctx)=>createSession(deps,session,ctx),update:(session,ctx)=>update15(deps,session,ctx),updateSubject:(req,ctx)=>updateSubject(deps,req,callerIdentityOf(ctx)),delete:(id,ctx)=>deleteSession(deps,id,ctx)}),router.service(SessionQueryController,{get:(id,ctx)=>get20(deps,id,ctx),list:(req,ctx)=>list10(deps,req,ctx),listByAgentInstance:(req,ctx)=>listByAgentInstance(deps,req,ctx),listByChannel:(req,ctx)=>listByChannel(deps,req,ctx)})}function kindOf19(ctx){return ctx.values.get(apiResourceKindKey)}async function createSession(deps,session,ctx){let reqCtx=new RequestContext(SessionSchema,session,callerIdentityOf(ctx),kindOf19(ctx)),builder2=newPipeline("session-create",deps.logger).addStep(newAuthorizeStep(SessionCommandController.method.create,deps.authorizer)).addStep(newAuthorizeRunTargetStep(deps.authorizer,sessionRunTarget)).addStep(newValidateProtoStep()).addStep(newValidateVisibilityStep()).addStep(newResolveSlugStep()).addStep(newCheckDuplicateStep(deps.store)).addStep(newBuildNewStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newNormalizeReferencesStep()).addStep(newValidateReferencesStep(deps.store));for(let step of stepsForSlot(deps.gateSteps,"session-create:pre-side-effect-gate"))builder2.addStep(step);return await builder2.addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger)).addStep(newIndexSearchStep(deps.store,sessionSearchExtractor,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function update15(deps,session,ctx){let reqCtx=new RequestContext(SessionSchema,session,callerIdentityOf(ctx),kindOf19(ctx));return await newPipeline("session-update",deps.logger).addStep(newAuthorizeStep(SessionCommandController.method.update,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadExistingStep(deps.store)).addStep(newValidateHarnessImmutabilityStep()).addStep(newValidateExecutionTargetImmutabilityStep(deps.temporalConfig)).addStep(newBuildUpdateStateStep()).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newRecordHarnessStateHistoryStep()).addStep(newPersistStep(deps.store)).addStep(newIndexSearchStep(deps.store,sessionSearchExtractor,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function apply12(deps,session,ctx){let reqCtx=new RequestContext(SessionSchema,session,callerIdentityOf(ctx),kindOf19(ctx));await newPipeline("session-apply",deps.logger).addStep(newAuthorizeStep(SessionCommandController.method.apply,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newResolveSlugStep()).addStep(newLoadForApplyStep(deps.store)).build().execute(reqCtx);let shouldCreate=reqCtx.get(SHOULD_CREATE_KEY);if(typeof shouldCreate!="boolean")throw internalError(new Error("apply pipeline did not set shouldCreate flag"),"apply operation failed to determine create vs update");return shouldCreate?createSession(deps,session,ctx):update15(deps,withResolvedApplyId(SessionSchema,session,reqCtx),ctx)}async function deleteSession(deps,sessionId,ctx){let reqCtx=new RequestContext(SessionCommandController.method.delete.input,sessionId,callerIdentityOf(ctx),kindOf19(ctx));await newPipeline("session-delete",deps.logger).addStep(newAuthorizeStep(SessionCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newExtractResourceIdStep()).addStep(newLoadExistingForDeleteStep(deps.store,SessionSchema)).addStep(newRejectDeleteWithActiveExecutionsStep(deps.store,deps.logger)).addStep(newCascadeDeleteAgentExecutionsStep(deps.store,deps.logger)).addStep(newDeleteResourceStep(deps.store)).addStep(newCleanupIamPoliciesStep(deps.authorizationLifecycle,deps.logger)).addStep(newDeleteSearchIndexStep(deps.store,deps.logger)).build().execute(reqCtx);let deleted=reqCtx.get(EXISTING_RESOURCE_KEY);if(deleted===void 0)throw internalError(new Error("deleted session not found in context"),"deleted session not found in context");return await deprovisionSessionSandboxBestEffort(deps.sandboxLane,deps.logger,deleted.metadata?.id??""),deleted}async function updateSubject(deps,req,identity2){if(req.id==="")throw invalidArgumentError("id is required");let kind=ApiResourceKind.session,session;try{session=await deps.store.getResource(kind,req.id,SessionSchema)}catch(error2){throw error2 instanceof ResourceNotFoundError?notFoundError("session",req.id):internalError(error2,"failed to load session")}await authorizeDirect(SessionCommandController.method.updateSubject,deps.authorizer,identity2,req),session.spec===void 0&&(session.spec=create2(SessionSpecSchema,{})),session.spec.subject=req.subject,setAuditFieldsForUpdate(SessionSchema,session,"spec_audit",identity2);try{await deps.store.saveResource(kind,req.id,SessionSchema,session)}catch(error2){throw internalError(error2,"failed to persist session")}return await indexSessionSearch(deps,kind,session),session}async function indexSessionSearch(deps,kind,session){let entry=sessionSearchExtractor.getSearchIndexEntry(session);if(entry!==void 0)try{await deps.store.upsertSearchIndex(kind,session.metadata?.id??"",entry)}catch(error2){deps.logger.warn("UpdateSubject: failed to update search index (best-effort)",{id:session.metadata?.id??"",error:error2 instanceof Error?error2.message:String(error2)})}}async function get20(deps,id,ctx){let reqCtx=new RequestContext(SessionQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf19(ctx));return await newPipeline("session-get",deps.logger).addStep(newAuthorizeStep(SessionQueryController.method.get,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newLoadTargetStep(deps.store,SessionSchema)).build().execute(reqCtx),reqCtx.get(TARGET_RESOURCE_KEY)}async function list10(deps,req,ctx){let reqCtx=new RequestContext(SessionQueryController.method.list.input,req,callerIdentityOf(ctx),kindOf19(ctx));return await newPipeline("session-list",deps.logger).addStep(newAuthorizeStep(SessionQueryController.method.list,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newListAllSessionsStep(deps.store,deps.logger,deps.listReadScope)).build().execute(reqCtx),requireListResult2(reqCtx.get(LIST_RESULT_KEY8))}async function listByAgentInstance(deps,req,ctx){let reqCtx=new RequestContext(SessionQueryController.method.listByAgentInstance.input,req,callerIdentityOf(ctx),kindOf19(ctx));return await newPipeline("session-list-by-agent-instance",deps.logger).addStep(newAuthorizeStep(SessionQueryController.method.listByAgentInstance,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newFilterByAgentInstanceStep(deps.store,deps.logger,deps.listReadScope)).build().execute(reqCtx),requireListResult2(reqCtx.get(LIST_RESULT_KEY8))}async function listByChannel(deps,req,ctx){let reqCtx=new RequestContext(SessionQueryController.method.listByChannel.input,req,callerIdentityOf(ctx),kindOf19(ctx));return await newPipeline("session-list-by-channel",deps.logger).addStep(newAuthorizeStep(SessionQueryController.method.listByChannel,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newAuthorizeChannelAccessStep(deps.authorizer)).addStep(newFilterByChannelStep(deps.store,deps.logger,deps.listReadScope)).build().execute(reqCtx),requireListResult2(reqCtx.get(LIST_RESULT_KEY8))}function requireListResult2(result){if(result===void 0)throw internalError(new Error("session list not found in context"),"session list not found in context");return result}var file_ai_stigmer_agentic_plugin_v1_io=fileDesc("CiVhaS9zdGlnbWVyL2FnZW50aWMvcGx1Z2luL3YxL2lvLnByb3RvEhxhaS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxIiEKCFBsdWdpbklkEhUKBXZhbHVlGAEgASgJQga6SAPIAQEi9wIKEVB1c2hQbHVnaW5SZXF1ZXN0EhMKA29yZxgBIAEoCUIGukgDyAEBEhAKCGFydGlmYWN0GAIgASgMEhsKE2FydGlmYWN0X3VwbG9hZF9yZWYYAyABKAkSUwoKdmlzaWJpbGl0eRgEIAEoDjI1LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVZpc2liaWxpdHlCCLpIBYIBAhABEg8KB21lc3NhZ2UYBSABKAk6twG6SLMBGrABCiNwdXNoX3BsdWdpbl9yZXF1ZXN0LmFydGlmYWN0X3NvdXJjZRJJZXhhY3RseSBvbmUgb2YgYXJ0aWZhY3QgKGlubGluZSBieXRlcykgb3IgYXJ0aWZhY3RfdXBsb2FkX3JlZiBtdXN0IGJlIHNldBo+KHRoaXMuYXJ0aWZhY3Quc2l6ZSgpID4gMCkgIT0gKHRoaXMuYXJ0aWZhY3RfdXBsb2FkX3JlZiAhPSAnJykiWAokQ3JlYXRlUGx1Z2luQXJ0aWZhY3RVcGxvYWRVcmxSZXF1ZXN0EhMKA29yZxgBIAEoCUIGukgDyAEBEhsKCnNpemVfYnl0ZXMYAiABKANCB7pIBCICIAAiWAoXUGx1Z2luQXJ0aWZhY3RVcGxvYWRVcmwSCwoDdXJsGAEgASgJEhsKE2FydGlmYWN0X3VwbG9hZF9yZWYYAiABKAkSEwoLdHRsX3NlY29uZHMYAyABKAUihQEKDFBsdWdpbk1lbWJlchJNCgRraW5kGAEgASgOMj8uYWkuc3RpZ21lci5jb21tb25zLmFwaXJlc291cmNlLmFwaXJlc291cmNla2luZC5BcGlSZXNvdXJjZUtpbmQSCgoCaWQYAiABKAkSDAoEc2x1ZxgDIAEoCRIMCgRuYW1lGAQgASgJIlgKGUxpc3RQbHVnaW5NZW1iZXJzUmVzcG9uc2USOwoHbWVtYmVycxgBIAMoCzIqLmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuUGx1Z2luTWVtYmVyImsKF0xpc3RQbHVnaW5WZXJzaW9uc0lucHV0EhMKA29yZxgBIAEoCUIGukgDyAEBEhQKBHNsdWcYAiABKAlCBrpIA8gBARISCgpwYWdlX3Rva2VuGAMgASgJEhEKCXBhZ2Vfc2l6ZRgEIAEoBSLtAQoSUGx1Z2luVmVyc2lvbkVudHJ5Eg4KBmRpZ2VzdBgBIAEoCRItCglwdXNoZWRfYXQYAiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEkgKCXB1c2hlZF9ieRgDIAEoCzI1LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZUF1ZGl0QWN0b3ISCwoDdGFnGAQgASgJEhIKCmlzX2N1cnJlbnQYBSABKAgSDwoHbWVzc2FnZRgGIAEoCRIcChRhcnRpZmFjdF9zdG9yYWdlX2tleRgHIAEoCSKOAQoaTGlzdFBsdWdpblZlcnNpb25zUmVzcG9uc2USQgoIdmVyc2lvbnMYASADKAsyMC5haS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxLlBsdWdpblZlcnNpb25FbnRyeRIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkSEwoLdG90YWxfY291bnQYAyABKAViBnByb3RvMw",[file_ai_stigmer_commons_apiresource_apiresourcekind_api_resource_kind,file_ai_stigmer_commons_apiresource_enum,file_ai_stigmer_commons_apiresource_status,file_buf_validate_validate,file_google_protobuf_timestamp]);var PushPluginRequestSchema=messageDesc2(file_ai_stigmer_agentic_plugin_v1_io,1);var PluginArtifactUploadUrlSchema=messageDesc2(file_ai_stigmer_agentic_plugin_v1_io,3),PluginMemberSchema=messageDesc2(file_ai_stigmer_agentic_plugin_v1_io,4),ListPluginMembersResponseSchema=messageDesc2(file_ai_stigmer_agentic_plugin_v1_io,5);var PluginVersionEntrySchema=messageDesc2(file_ai_stigmer_agentic_plugin_v1_io,7),ListPluginVersionsResponseSchema=messageDesc2(file_ai_stigmer_agentic_plugin_v1_io,8);var file_ai_stigmer_agentic_plugin_v1_command=fileDesc("CiphaS9zdGlnbWVyL2FnZW50aWMvcGx1Z2luL3YxL2NvbW1hbmQucHJvdG8SHGFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEy2gUKF1BsdWdpbkNvbW1hbmRDb250cm9sbGVyEqEBCgRwdXNoEi8uYWkuc3RpZ21lci5hZ2VudGljLnBsdWdpbi52MS5QdXNoUGx1Z2luUmVxdWVzdBokLmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuUGx1Z2luIkLCuBg+CCgQHiIDb3JnKjN1bmF1dGhvcml6ZWQgdG8gaW5zdGFsbCBwbHVnaW4gaW4gdGhpcyBvcmdhbml6YXRpb24S2AEKF2NyZWF0ZUFydGlmYWN0VXBsb2FkVXJsEkIuYWkuc3RpZ21lci5hZ2VudGljLnBsdWdpbi52MS5DcmVhdGVQbHVnaW5BcnRpZmFjdFVwbG9hZFVybFJlcXVlc3QaNS5haS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxLlBsdWdpbkFydGlmYWN0VXBsb2FkVXJsIkLCuBg+CCgQHiIDb3JnKjN1bmF1dGhvcml6ZWQgdG8gaW5zdGFsbCBwbHVnaW4gaW4gdGhpcyBvcmdhbml6YXRpb24SsAEKEHVwZGF0ZVZpc2liaWxpdHkSNS5haS5zdGlnbWVyLmNvbW1vbnMuYXBpcmVzb3VyY2UuVXBkYXRlVmlzaWJpbGl0eUlucHV0GiQuYWkuc3RpZ21lci5hZ2VudGljLnBsdWdpbi52MS5QbHVnaW4iP8K4GDsIAhA6IgtyZXNvdXJjZV9pZCoodW5hdXRob3JpemVkIHRvIHVwZGF0ZSBwbHVnaW4gdmlzaWJpbGl0eRKGAQoGZGVsZXRlEiYuYWkuc3RpZ21lci5hZ2VudGljLnBsdWdpbi52MS5QbHVnaW5JZBokLmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuUGx1Z2luIi7CuBgqCAMQOiIFdmFsdWUqHXVuYXV0aG9yaXplZCB0byBkZWxldGUgcGx1Z2luGgSg/ys6YgZwcm90bzM",[file_ai_stigmer_agentic_plugin_v1_api,file_ai_stigmer_agentic_plugin_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),PluginCommandController=serviceDesc(file_ai_stigmer_agentic_plugin_v1_command,0);var file_ai_stigmer_agentic_plugin_v1_query=fileDesc("CihhaS9zdGlnbWVyL2FnZW50aWMvcGx1Z2luL3YxL3F1ZXJ5LnByb3RvEhxhaS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxMsMEChVQbHVnaW5RdWVyeUNvbnRyb2xsZXISgAEKA2dldBImLmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuUGx1Z2luSWQaJC5haS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxLlBsdWdpbiIrwrgYJwgBEDoiBXZhbHVlKhp1bmF1dGhvcml6ZWQgdG8gZ2V0IHBsdWdpbhJyCg5nZXRCeVJlZmVyZW5jZRI0LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZVJlZmVyZW5jZRokLmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuUGx1Z2luIgTQuBgBEqQBCgtsaXN0TWVtYmVycxImLmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuUGx1Z2luSWQaNy5haS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxLkxpc3RQbHVnaW5NZW1iZXJzUmVzcG9uc2UiNMK4GDAIARA6IgV2YWx1ZSojdW5hdXRob3JpemVkIHRvIGxpc3QgcGx1Z2luIG1lbWJlcnMShQEKDGxpc3RWZXJzaW9ucxI1LmFpLnN0aWdtZXIuYWdlbnRpYy5wbHVnaW4udjEuTGlzdFBsdWdpblZlcnNpb25zSW5wdXQaOC5haS5zdGlnbWVyLmFnZW50aWMucGx1Z2luLnYxLkxpc3RQbHVnaW5WZXJzaW9uc1Jlc3BvbnNlIgTQuBgBGgSg/ys6YgZwcm90bzM",[file_ai_stigmer_agentic_plugin_v1_api,file_ai_stigmer_agentic_plugin_v1_io,file_ai_stigmer_commons_apiresource_io,file_ai_stigmer_commons_apiresource_rpc_service_options,file_ai_stigmer_commons_rpc_method_options]),PluginQueryController=serviceDesc(file_ai_stigmer_agentic_plugin_v1_query,0);var PLATFORM_ARCHIVE_LIMITS={maxFiles:1e4,maxUncompressedSize:524288e3,maxCompressionRatio:100};var import_node_fs8=__toESM(require("node:fs"),1),import_node_path11=__toESM(require("node:path"),1),import_promises6=require("node:stream/promises"),SlotUnknownError=class extends Error{constructor(){super("upload reference unknown or expired"),this.name="SlotUnknownError"}},SlotConsumedError=class extends Error{constructor(){super("upload reference already carries an upload"),this.name="SlotConsumedError"}},SizeMismatchError=class extends Error{constructor(received,declared){super(`upload size mismatch: received ${received} bytes, declared ${declared}`),this.name="SizeMismatchError"}},STAGED_FILE_NAME=/^[0-9a-f]+\.zip$/,UploadSlots=class{root;stagingPrefix;ttlMs;maxSize;slots=new Map;stagingDir;now;constructor(root5,stagingPrefix,ttlMs,maxSize,now=Date.now){this.root=root5,this.stagingPrefix=stagingPrefix,this.ttlMs=ttlMs,this.maxSize=maxSize,this.stagingDir=import_node_path11.default.join(root5,stagingPrefix),import_node_fs8.default.rmSync(this.stagingDir,{recursive:!0,force:!0}),import_node_fs8.default.mkdirSync(this.stagingDir,{recursive:!0,mode:448}),this.now=now}reserve(key,declaredSize){if(declaredSize<=0||declaredSize>this.maxSize)throw new Error(`declared size ${declaredSize} outside (0, ${this.maxSize}]`);if(this.stagePath(key),this.slots.has(key))throw new Error(`staging key ${key} is already reserved`);return this.sweep(),this.slots.set(key,{declaredSize,expiresAtMs:this.now()+this.ttlMs,uploaded:!1}),{ttlMs:this.ttlMs}}async receive(key,body){let slot=this.slots.get(key);if(slot===void 0||this.now()>slot.expiresAtMs)throw new SlotUnknownError;if(slot.uploaded)throw new SlotConsumedError;let declared=slot.declaredSize,filePath=this.stagePath(key),written=0;try{await import_node_fs8.default.promises.mkdir(import_node_path11.default.dirname(filePath),{recursive:!0,mode:448}),await(0,import_promises6.pipeline)(body,limitBytes(declared+1,n3=>{written+=n3}),import_node_fs8.default.createWriteStream(filePath,{flags:"w",mode:384}))}catch(error2){throw await import_node_fs8.default.promises.rm(filePath,{force:!0}),new Error(`failed to receive upload: ${error2 instanceof Error?error2.message:String(error2)}`)}if(written!==declared)throw await import_node_fs8.default.promises.rm(filePath,{force:!0}),new SizeMismatchError(written,declared);let current=this.slots.get(key);if(current===void 0||this.now()>current.expiresAtMs)throw await import_node_fs8.default.promises.rm(filePath,{force:!0}),new SlotUnknownError;current.uploaded=!0}sweep(){let nowMs=this.now();for(let[key,slot]of this.slots)nowMs>slot.expiresAtMs&&(this.slots.delete(key),import_node_fs8.default.rmSync(this.stagePath(key),{force:!0}))}stagePath(key){if(!key.startsWith(this.stagingPrefix))throw new Error(`staging key ${key} is outside ${this.stagingPrefix}`);let fileName=key.slice(this.stagingPrefix.length);if(!STAGED_FILE_NAME.test(fileName))throw new Error(`staging key ${key} does not name a staged archive`);return import_node_path11.default.join(this.root,key)}};function limitBytes(limit,onBytes){return async function*(source){let remaining=limit;for await(let chunk of source){if(remaining<=0)return;let slice=chunk.length<=remaining?chunk:chunk.subarray(0,remaining);remaining-=slice.length,onBytes(slice.length),yield slice}}}var ARTIFACT_BYTES_KEY="pushArtifactBytes";function newResolveArtifactSourceStep(staging,binding){return{name:"ResolveArtifactSource",async execute(ctx){let{artifact,artifactUploadRef}=binding.source(ctx.input);if(artifactUploadRef===""){ctx.set(ARTIFACT_BYTES_KEY,artifact);return}if(staging===void 0)throw failedPreconditionError(binding.laneNotConfigured);let data;try{data=await staging.consume(artifactUploadRef)}catch(error2){throw error2 instanceof SlotUnknownError?invalidArgumentError(`artifact_upload_ref not usable: ${error2.message} \u2014 request a new upload URL via createArtifactUploadUrl`):error2}ctx.set(ARTIFACT_BYTES_KEY,data)}}}function newArchiveCurrentVersionStep(store,logger2,binding){return{name:binding.stepName,async execute(ctx){let resource=ctx.get(binding.resourceKey),versionHash=binding.headHashOf(resource);if(versionHash==="")return;let tag2=binding.liveTagOf(resource),resourceId=metadataOf(resource)?.id??"",idField=`${binding.noun}Id`,alreadyArchived=!1;try{await store.getAuditByHash(ctx.apiResourceKind,resourceId,versionHash,binding.schema),alreadyArchived=!0}catch(error2){error2 instanceof AuditNotFoundError||logger2.warn(`Could not check for an existing archived ${binding.noun} version \u2014 archiving anyway`,{[idField]:resourceId,versionHash,error:error2 instanceof Error?error2.message:String(error2)})}if(!alreadyArchived)try{await store.saveAudit(ctx.apiResourceKind,resourceId,binding.schema,resource,versionHash,"")}catch(error2){logger2.error(`Failed to archive ${binding.noun} version \u2014 reverting the version hash to maintain the audit-resolvability invariant`,{[idField]:resourceId,versionHash,error:error2 instanceof Error?error2.message:String(error2)}),binding.clearHeadHash(resource);return}if(tag2!=="")try{await store.setAuditTag(ctx.apiResourceKind,resourceId,versionHash,tag2)}catch(error2){logger2.error(`Archived ${binding.noun} version but failed to assign its tag \u2014 clearing the live tag to stay consistent with the audit column`,{[idField]:resourceId,versionHash,tag:tag2,error:error2 instanceof Error?error2.message:String(error2)}),binding.clearLiveTag(resource)}alreadyArchived?logger2.info(`${capitalize(binding.noun)} version content already archived \u2014 repointed head without a new history row`,{[idField]:resourceId,versionHash,tag:tag2}):logger2.info(`Archived ${binding.noun} version to audit history`,{[idField]:resourceId,versionHash,tag:tag2})}}}function newDeleteVersionArchivesStep(store,logger2,binding){return{name:binding.stepName,async execute(ctx){let resourceId=ctx.get(RESOURCE_ID_KEY);if(typeof resourceId!="string")throw new Error("resource id not found in context (ExtractResourceIdStep must run first)");let idField=`${binding.noun}Id`;try{let deletedCount=await store.deleteAuditByResourceId(ctx.apiResourceKind,resourceId);deletedCount>0&&logger2.info(`Deleted archive records for ${binding.noun}`,{[idField]:resourceId,count:deletedCount})}catch(error2){logger2.warn(`failed to delete ${binding.noun} archives (best-effort)`,{[idField]:resourceId,error:error2 instanceof Error?error2.message:String(error2)})}}}}function capitalize(word){return word.charAt(0).toUpperCase()+word.slice(1)}var HASH_PATTERN=/^[a-f0-9]{64}$/;function isVersionHash(version){return HASH_PATTERN.test(version)}function newLoadByReferenceWithVersionStep(store,binding,stepName){return{name:stepName,async execute(ctx){let ref=ctx.input;if(ref.slug==="")throw invalidArgumentError("slug is required in reference");if(requireOrgForReference(ctx.apiResourceKind,ref.org),ref.kind!==ApiResourceKind.api_resource_kind_unknown&&ref.kind!==binding.kind)throw invalidArgumentError(`kind mismatch: expected ${ApiResourceKind[binding.kind]}, got ${ApiResourceKind[ref.kind]}`);let head;try{head=await findResourceBySlug(store,ctx.apiResourceKind,binding.schema,ref.slug,ref.org)}catch(error2){throw internalError(error2,`failed to list ${binding.noun}s`)}if(head===void 0)throw notFoundError(binding.noun,ref.slug);let version=ref.version.trim();if(version===""||version==="latest"){ctx.set(TARGET_RESOURCE_KEY,head);return}if(headMatchesVersion(binding,head,version)){ctx.set(TARGET_RESOURCE_KEY,head);return}let archived=await findAuditByVersion(store,ctx.apiResourceKind,binding.schema,idOf(head),version);if(archived===void 0)throw notFoundError(`${binding.noun} version`,`${ref.slug}:${version}`);ctx.set(TARGET_RESOURCE_KEY,archived)}}}function headMatchesVersion(binding,head,version){if(isVersionHash(version))return binding.headHashOf(head)===version;let liveTag=binding.liveTagOf(head);return liveTag!==""&&liveTag===version}async function findAuditByVersion(store,kind,schema2,resourceId,version){if(isVersionHash(version))try{return await store.getAuditByHash(kind,resourceId,version,schema2)}catch(error2){if(error2 instanceof AuditNotFoundError)return;throw internalError(error2,"failed to query audit by hash")}try{return await store.getAuditByTag(kind,resourceId,version,schema2)}catch(error2){if(error2 instanceof AuditNotFoundError)return;throw internalError(error2,"failed to query audit by tag")}}var DEFAULT_PAGE_SIZE=50,MAX_PAGE_SIZE=100,LIST_VERSIONS_RESOURCE_ID_KEY="listVersionsResourceId",LIST_VERSIONS_HEAD_HASH_KEY="listVersionsHeadHash",LIST_VERSIONS_RESPONSE_KEY="listVersionsResponse";function versionHistoryTarget(kind,deniedMessage,idKey=LIST_VERSIONS_RESOURCE_ID_KEY){return ctx=>{let resourceId=ctx.get(idKey);if(typeof resourceId!="string"||resourceId==="")throw new Error(`ListVersions: no resolved resource id under ${idKey}; the slug resolver must run first`);return[{permission:IamPermission.can_view,resourceKind:kind,resourceId,deniedMessage}]}}function newResolveBySlugForVersionsStep(store,binding,stepName){return{name:stepName,async execute(ctx){let req=binding.input(ctx.input),head;try{head=await findResourceBySlug(store,ctx.apiResourceKind,binding.schema,req.slug,req.org)}catch(error2){throw internalError(error2,`failed to search for ${binding.noun}`)}if(head===void 0)throw notFoundError(binding.noun,`${req.slug} (org: ${req.org})`);ctx.set(LIST_VERSIONS_RESOURCE_ID_KEY,idOf(head)),ctx.set(LIST_VERSIONS_HEAD_HASH_KEY,binding.headHashOf(head))}}}function newLoadAndMapVersionsStep(store,binding,stepName){return{name:stepName,async execute(ctx){let req=binding.input(ctx.input),resourceId=ctx.get(LIST_VERSIONS_RESOURCE_ID_KEY),records;try{records=await store.listAuditRecords(ctx.apiResourceKind,resourceId)}catch(error2){throw internalError(error2,"failed to load version history")}let headHash=ctx.get(LIST_VERSIONS_HEAD_HASH_KEY),currentMarked=!1,entries=[];for(let record2 of records){let snapshot;try{snapshot=fromBinary2(binding.schema,record2.data)}catch{continue}let isCurrent=!currentMarked&&headHash!==""&&binding.headHashOf(snapshot)===headHash;currentMarked=currentMarked||isCurrent,entries.push(binding.mapEntry(snapshot,isCurrent,record2.tag))}let pageSize=req.pageSize;pageSize<=0&&(pageSize=DEFAULT_PAGE_SIZE),pageSize>MAX_PAGE_SIZE&&(pageSize=MAX_PAGE_SIZE);let startIndex=0;req.pageToken!==""&&(startIndex=decodePageToken(req.pageToken));let pageEntries=[],nextPageToken="";if(startIndex<entries.length){let end=Math.min(startIndex+pageSize,entries.length);pageEntries=entries.slice(startIndex,end),end<entries.length&&(nextPageToken=Buffer.from(String(end)).toString("base64"))}ctx.set(LIST_VERSIONS_RESPONSE_KEY,binding.response(pageEntries,nextPageToken,entries.length))}}}function decodePageToken(token){let decoded=Buffer.from(token,"base64");if(decoded.toString("base64")!==token)throw invalidArgumentError("invalid page_token");let text2=decoded.toString("utf8"),index2=Number.parseInt(text2,10);if(!Number.isSafeInteger(index2)||String(index2)!==text2||index2<0)throw invalidArgumentError("invalid page_token");return index2}function idOf(resource){return metadataOf(resource)?.id??""}var PLUGIN_ARTIFACT_KEY_PREFIX="plugins/",VERSION_TAG_PATTERN=/^[a-zA-Z0-9._-]+$/,BUILT_IN_SUB_AGENT_NAMES=new Set(["explore","shell","general-purpose"]);var TRANSFER_LANE_NOT_CONFIGURED="plugin artifact transfer lane is not configured on this server",SERVER_WARNING_KINDS={componentIgnored:"component-ignored",memberAdopted:"member-adopted",modelHintUnresolved:"model-hint-unresolved",subAgentNameBuiltin:"sub-agent-name-builtin",versionNotTaggable:"version-not-taggable"};var MEMBER_KINDS=[{kind:ApiResourceKind.skill,schema:SkillSchema},{kind:ApiResourceKind.mcp_server,schema:McpServerSchema},{kind:ApiResourceKind.agent,schema:AgentSchema},{kind:ApiResourceKind.workflow,schema:WorkflowSchema}];function memberOf(kind,metadata){return{kind,id:metadata.id,slug:metadata.slug,name:metadata.name,version:metadata.labels[PLUGIN_VERSION_LABEL]??"",system:isSystemContent(metadata)}}async function findMembers(store,pluginId,org){let members=[];for(let{kind,schema:schema2}of MEMBER_KINDS){let raws=await store.findAllByLabel(kind,PLUGIN_LABEL,pluginId,schema2);for(let raw of raws){let metadata=metadataOf(fromBinary2(schema2,raw));metadata!==void 0&&metadata.org===org&&members.push(memberOf(kind,metadata))}}return members}async function slugHolder(store,planned,org){let entry=MEMBER_KINDS.find(candidate=>candidate.kind===planned.kind);if(entry===void 0)throw new Error(`kind ${ApiResourceKind[planned.kind]} is not a plugin member kind`);let existing=await findResourceBySlug(store,planned.kind,entry.schema,planned.slug,org),metadata=existing===void 0?void 0:metadataOf(existing);return metadata===void 0?{held:!1}:{held:!0,byPlugin:pluginIdOf(metadata),holder:memberOf(planned.kind,metadata)}}function judgeSlug(holder,planned,pluginId){return holder.held?holder.byPlugin===pluginId?{kind:"ours",holder:holder.holder}:holder.byPlugin!==void 0?{kind:"held-by-plugin",holder:holder.holder,pluginId:holder.byPlugin}:holder.holder.system&&planned.system?{kind:"adopt",holder:holder.holder}:{kind:"held-unmanaged",holder:holder.holder}:{kind:"free"}}function membersConverge(existing,planned,digest3){if(existing.length!==planned.length)return!1;let byKey=new Map(existing.map(member2=>[`${member2.kind}:${member2.slug}`,member2]));return planned.every(member2=>{let found=byKey.get(`${member2.kind}:${member2.slug}`);return found!==void 0&&found.version===digest3})}function droppedMembers(existing,planned){let keep=new Set(planned.map(member2=>`${member2.kind}:${member2.slug}`));return existing.filter(member2=>!keep.has(`${member2.kind}:${member2.slug}`))}var PLUGIN_DOCUMENT_LIMITS={manifest:262144,mcpConfig:262144,skillMd:1048576,subAgent:1048576,overlay:1048576,logo:1048576,marketplace:1048576},encoder5=new TextEncoder,decoder3=new TextDecoder("utf-8",{fatal:!1});function comparePaths(a5,b7){return a5<b7?-1:a5>b7?1:0}function decodeUtf8(bytes){let text2=decoder3.decode(bytes);return text2.charCodeAt(0)===65279?text2.slice(1):text2}function isContainedPath(path14){return path14===""||path14.startsWith("/")||path14.includes("\\")?!1:path14.split("/").every(segment=>segment!==""&&segment!=="."&&segment!=="..")}var GLOB_CHARACTERS=/[*?[\]{}]/;function resolveDeclaredPath(value){if(GLOB_CHARACTERS.test(value))return{ok:!1,kind:"path-glob-unsupported"};if(value==="."||value==="./")return{ok:!0,path:""};if(!value.startsWith("./"))return{ok:!1,kind:"path-not-relative"};let trimmed=value.slice(2).replace(/\/+$/,"");return trimmed===""?{ok:!0,path:""}:isContainedPath(trimmed)?{ok:!0,path:trimmed}:{ok:!1,kind:"path-escapes-root"}}function joinPath(dir,name){return dir===""?name:`${dir}/${name}`}function basename(path14){let slash=path14.lastIndexOf("/");return slash===-1?path14:path14.slice(slash+1)}function dirname(path14){let slash=path14.lastIndexOf("/");return slash===-1?"":path14.slice(0,slash)}var PluginFileIndex=class{files;byPath;constructor(files){this.files=files,this.byPath=new Map(files.entries.map(entry=>[entry.path,entry]))}has(path14){return this.byPath.has(path14)}entry(path14){return this.byPath.get(path14)}filesUnder(dir){if(dir==="")return this.files.entries.map(entry=>entry.path);let prefix=`${dir}/`;return this.files.entries.filter(entry=>entry.path.startsWith(prefix)).map(entry=>entry.path)}isDirectory(dir){if(dir==="")return this.files.entries.length>0;let prefix=`${dir}/`;return this.files.entries.some(entry=>entry.path.startsWith(prefix))}childDirectories(dir){let prefix=dir===""?"":`${dir}/`,names=new Set;for(let entry of this.files.entries){if(!entry.path.startsWith(prefix))continue;let rest=entry.path.slice(prefix.length),slash=rest.indexOf("/");slash!==-1&&names.add(rest.slice(0,slash))}return[...names].sort(comparePaths)}childFiles(dir){let prefix=dir===""?"":`${dir}/`,names=[];for(let entry of this.files.entries){if(!entry.path.startsWith(prefix))continue;let rest=entry.path.slice(prefix.length);rest.includes("/")||names.push(rest)}return names.sort(comparePaths)}};function readText(index2,path14,cls,findings){let bytes=readBytes(index2,path14,cls,findings);return bytes===void 0?void 0:decodeUtf8(bytes)}function readBytes(index2,path14,cls,findings){let limit=PLUGIN_DOCUMENT_LIMITS[cls],entry=index2.entry(path14);if(entry===void 0)throw new Error(`plugin file '${path14}' is not listed`);if(entry.size>limit){findings.error("document-too-large",{path:path14,subject:String(entry.size),detail:String(limit)});return}let bytes=index2.files.read(path14);if(bytes.length>limit){findings.error("document-too-large",{path:path14,subject:String(bytes.length),detail:String(limit)});return}return bytes}function parseJsonObject2(text2,path14,kind,findings){let value;try{value=JSON.parse(text2)}catch(error2){findings.error(kind,{path:path14,detail:error2 instanceof Error?error2.message:String(error2)});return}if(!isJsonObject2(value)){findings.error(kind,{path:path14,detail:"the document is not a JSON object"});return}return value}function isJsonObject2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStringArray(value){return Array.isArray(value)&&value.every(item=>typeof item=="string")}function isStringRecord(value){return isJsonObject2(value)&&Object.values(value).every(item=>typeof item=="string")}function describeValue(value){return typeof value=="string"?value:JSON.stringify(value)}function fields(object){return Object.entries(object)}function optionalString(object,field3,path14,findings){let value=object[field3];if(value!==void 0){if(typeof value!="string"){findings.error("manifest-field-type",{path:path14,subject:field3,detail:"a string"});return}return value}}function optionalStringArray(object,field3,path14,findings){let value=object[field3];if(value!==void 0){if(!isStringArray(value)){findings.error("manifest-field-type",{path:path14,subject:field3,detail:"an array of strings"});return}return value}}function stringOrStringArray(object,field3,path14,findings){let value=object[field3];if(value!==void 0){if(typeof value=="string")return[value];if(isStringArray(value))return value;findings.error("manifest-field-type",{path:path14,subject:field3,detail:"a string or an array of strings"})}}function warnUnknownFields(object,known,path14,findings){for(let[name]of fields(object))known.has(name)||findings.warn("manifest-field-unknown",{path:path14,subject:name})}function readIdentity(object,path14,findings){let identity2={},name=optionalString(object,"name",path14,findings);name!==void 0&&(identity2.name=name);let version=optionalString(object,"version",path14,findings);version!==void 0&&(identity2.version=version);let description=optionalString(object,"description",path14,findings);description!==void 0&&(identity2.description=description);let homepage=optionalString(object,"homepage",path14,findings);homepage!==void 0&&(identity2.homepage=homepage);let repository=optionalString(object,"repository",path14,findings);repository!==void 0&&(identity2.repository=repository);let license=optionalString(object,"license",path14,findings);license!==void 0&&(identity2.license=license);let keywords=optionalStringArray(object,"keywords",path14,findings);keywords!==void 0&&(identity2.keywords=keywords);let author=readAuthor(object,path14,findings);return author!==void 0&&(identity2.author=author),identity2}function readAuthor(object,path14,findings){let value=object.author;if(value===void 0)return;if(!isJsonObject2(value)){findings.error("manifest-field-type",{path:path14,subject:"author",detail:"an object"});return}let author={},name=optionalString(value,"name",path14,findings);name!==void 0&&(author.name=name);let email=optionalString(value,"email",path14,findings);email!==void 0&&(author.email=email);let url=optionalString(value,"url",path14,findings);return url!==void 0&&(author.url=url),author}function readDeclaredPaths(object,field3,path14,findings){let values=stringOrStringArray(object,field3,path14,findings);if(values===void 0)return;let declared=[];for(let value of values){let resolved=resolveDeclaredPath(value);if(!resolved.ok){findings.error(resolved.kind,{path:path14,subject:value});continue}declared.push({path:resolved.path,manifest:path14})}return declared}function readMcpSources(object,field3,path14,dialect,findings){let value=object[field3];if(value===void 0)return[];let items=Array.isArray(value)?value:[value],sources=[];for(let item of items)if(typeof item=="string"){let resolved=resolveDeclaredPath(item);if(!resolved.ok){findings.error(resolved.kind,{path:path14,subject:item});continue}sources.push({kind:"file",path:resolved.path,dialect,manifest:path14})}else isJsonObject2(item)?sources.push({kind:"inline",manifest:path14,servers:item,dialect}):findings.error("manifest-field-type",{path:path14,subject:field3,detail:"a path, an object, or an array of either"});return sources}var IGNORED_FIELD_KINDS={hooks:"hooks",rules:"rules",commands:"commands",workflows:"workflows",outputStyles:"output-styles",lspServers:"lsp-servers",channels:"channels",dependencies:"dependencies",defaultEnabled:"default-enabled",minClientVersions:"min-client-versions",logo:"logo",apps:"apps"};function ignoredFieldComponents(object,path14){let ignored=[];for(let[name,value]of fields(object)){let kind=IGNORED_FIELD_KINDS[name];if(kind!==void 0&&ignored.push({kind,path:`${path14}#${name}`}),name==="experimental"&&isJsonObject2(value))for(let[sub]of fields(value)){let subKind=EXPERIMENTAL_KINDS[sub];subKind!==void 0&&ignored.push({kind:subKind,path:`${path14}#experimental.${sub}`})}}return ignored}var EXPERIMENTAL_KINDS={themes:"themes",monitors:"monitors",evals:"evals"},STIGMER_EXTENSION_NAMESPACE="ai.stigmer",STIGMER_EXTENSION_FIELDS=new Set(["displayName","logo","category"]);function extensionComponents(object,path14,findings){let value=object.extensions;if(value===void 0)return[];if(!isJsonObject2(value))return findings.warn("manifest-extensions-invalid",{path:path14}),[];let ignored=[];for(let[namespace,content]of fields(value)){if(isJsonObject2(content)&&fields(content).length===0)continue;let at2=`${path14}#extensions.${namespace}`;if(namespace===STIGMER_EXTENSION_NAMESPACE&&isJsonObject2(content)){content.logo!==void 0&&ignored.push({kind:"logo",path:`${at2}.logo`}),fields(content).some(([name])=>!STIGMER_EXTENSION_FIELDS.has(name))&&ignored.push({kind:"extension",path:at2});continue}ignored.push({kind:"extension",path:at2})}return ignored}var CLAUDE_KNOWN_FIELDS=new Set(["name","version","description","author","homepage","repository","license","keywords","skills","commands","agents","workflows","hooks","mcpServers","outputStyles","lspServers","experimental","userConfig","channels","dependencies","defaultEnabled"]),CLAUDE_DEFAULT_MCP_CONFIG=".mcp.json";function readClaudeManifest(object,path14,findings){return readClaudeShapedManifest(object,path14,"claude",CLAUDE_KNOWN_FIELDS,findings)}function readClaudeShapedManifest(object,path14,dialect,known,findings){warnUnknownFields(object,known,path14,findings);let identity2=readIdentity(object,path14,findings),skillPaths=readDeclaredPaths(object,"skills",path14,findings)??[],agentPaths=readDeclaredPaths(object,"agents",path14,findings),declaredMcp=readMcpSources(object,"mcpServers",path14,dialect,findings),manifest={dialect,path:path14,identity:identity2,skillPaths,mcpConfigs:declaredMcp,ignored:ignoredFieldComponents(object,path14)};return agentPaths!==void 0&&(manifest.agentPaths=agentPaths),object.userConfig!==void 0&&(manifest.variables={dialect:"claude",value:object.userConfig,manifest:path14}),manifest}var KNOWN_FIELDS=new Set([...CLAUDE_KNOWN_FIELDS,"apps","interface"]);function readCodexManifest(object,path14,findings){return readClaudeShapedManifest(object,path14,"codex",KNOWN_FIELDS,findings)}var KNOWN_FIELDS2=new Set(["name","displayName","description","version","minClientVersions","author","publisher","homepage","repository","license","logo","keywords","category","tags","commands","agents","skills","rules","hooks","variables","mcpServers"]);function readCursorManifest(object,path14,findings){warnUnknownFields(object,KNOWN_FIELDS2,path14,findings);let identity2=readIdentity(object,path14,findings),skillPaths=readDeclaredPaths(object,"skills",path14,findings)??[],agentPaths=readDeclaredPaths(object,"agents",path14,findings),manifest={dialect:"cursor",path:path14,identity:identity2,skillPaths,mcpConfigs:readMcpSources(object,"mcpServers",path14,"cursor",findings),ignored:ignoredFieldComponents(object,path14)};return agentPaths!==void 0&&(manifest.agentPaths=agentPaths),object.variables!==void 0&&(manifest.variables={dialect:"cursor",value:object.variables,manifest:path14}),manifest}var AGENT_PLUGINS_MANIFEST_SCHEMA="https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",AGENT_PLUGINS_MCP_SCHEMA="https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",MANIFEST_LOCATIONS={"agent-plugins":"plugin.json",claude:".claude-plugin/plugin.json",cursor:".cursor-plugin/plugin.json",codex:".codex-plugin/plugin.json"},q3=value=>`'${value??""}'`,at=path14=>path14===void 0?"":` in ${q3(path14)}`,ERROR_MESSAGES={"no-manifest":()=>`no plugin manifest found: expected one of ${Object.values(MANIFEST_LOCATIONS).map(p3=>q3(p3)).join(", ")}`,"manifest-unreadable":c5=>`manifest ${q3(c5.path)} is not valid JSON: ${c5.detail??"parse error"}`,"manifest-schema-missing":c5=>`manifest ${q3(c5.path)} is missing the required '$schema' field; an Agent Plugins manifest declares ${q3(AGENT_PLUGINS_MANIFEST_SCHEMA)}`,"manifest-schema-unsupported":c5=>`manifest ${q3(c5.path)} declares an unsupported '$schema' ${q3(c5.detail)}; this reader supports ${q3(AGENT_PLUGINS_MANIFEST_SCHEMA)}`,"manifest-name-missing":c5=>`manifest ${q3(c5.path)} is missing the required 'name' field`,"manifest-name-invalid":c5=>`plugin name ${q3(c5.subject)}${at(c5.path)} is invalid: 1 to 64 characters of lowercase letters, digits, hyphens and periods, starting and ending alphanumeric, with no '--' or '..'`,"manifest-name-conflict":c5=>`manifests disagree on the plugin name: ${q3(c5.subject)} in ${q3(c5.path)} versus ${c5.detail??"another manifest"}`,"manifest-field-type":c5=>`field ${q3(c5.subject)}${at(c5.path)} has the wrong type: expected ${c5.detail??"a different type"}`,"path-not-relative":c5=>`path ${q3(c5.subject)}${at(c5.path)} must be plugin-relative and begin with './'`,"path-escapes-root":c5=>`path ${q3(c5.subject)}${at(c5.path)} escapes the plugin root`,"path-glob-unsupported":c5=>`path ${q3(c5.subject)}${at(c5.path)} is a glob pattern; declare directories and files by path`,"path-uncontained":c5=>`the reader listed a path outside the plugin root: ${q3(c5.path)}`,"document-too-large":c5=>`${q3(c5.path)} is ${c5.subject??"too many"} bytes, over the ${c5.detail??""}-byte limit for this kind of document`,"skill-frontmatter-missing":c5=>`${q3(c5.path)} must start with YAML frontmatter ('---')`,"skill-frontmatter-unclosed":c5=>`${q3(c5.path)} frontmatter is not closed (missing the closing '---')`,"skill-frontmatter-unreadable":c5=>`${q3(c5.path)} frontmatter is not valid YAML: ${c5.detail??"parse error"}`,"skill-name-invalid":c5=>`skill name ${q3(c5.subject)}${at(c5.path)} is invalid: lowercase letters, digits and hyphens, optionally dot-scoped, with every segment alphanumeric`,"skill-name-duplicate":c5=>`skill name ${q3(c5.subject)} appears more than once (again${at(c5.path)})`,"mcp-config-unreadable":c5=>`MCP configuration ${q3(c5.path)} is not valid JSON: ${c5.detail??"parse error"}`,"mcp-config-shape":c5=>`MCP configuration ${q3(c5.path)} must be an object with an 'mcpServers' object`,"mcp-config-schema-missing":c5=>`MCP configuration ${q3(c5.path)} is missing the required '$schema' field; an Agent Plugins configuration declares ${q3(AGENT_PLUGINS_MCP_SCHEMA)}`,"mcp-config-schema-unsupported":c5=>`MCP configuration ${q3(c5.path)} declares an unsupported '$schema' ${q3(c5.detail)}; this reader supports ${q3(AGENT_PLUGINS_MCP_SCHEMA)}`,"mcp-config-field-unknown":c5=>`MCP configuration ${q3(c5.path)} has an unexpected top-level field ${q3(c5.subject)}; only '$schema' and 'mcpServers' are allowed`,"mcp-server-shape":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} must be an object`,"mcp-server-type-missing":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} is missing the 'type' field the Agent Plugins format requires ('stdio', 'streamable-http' or 'sse')`,"mcp-server-transport-unknown":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has no 'type' and neither a 'command' nor a 'url' to infer it from`,"mcp-server-type-ambiguous":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} declares both 'command' and 'url'; a server is either stdio or HTTP`,"mcp-server-type-unknown":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has an unknown 'type' ${q3(c5.detail)}; expected 'stdio', 'http', 'streamable-http' or 'sse'`,"mcp-server-field-unknown":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has a field ${q3(c5.detail)} that its transport does not define`,"mcp-server-field-type":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} field ${q3(c5.detail)} has the wrong type`,"mcp-server-url-missing":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} is missing the 'url' its HTTP transport requires`,"mcp-server-url-invalid":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has an invalid 'url' ${q3(c5.detail)}: expected an absolute HTTPS URL (HTTP only for localhost) with no user information or fragment`,"mcp-server-url-variable":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has a variable in its 'url'; Stigmer sends the URL as written, so write the URL out and put variables in 'headers'`,"mcp-server-command-missing":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} is missing the 'command' its stdio transport requires`,"mcp-server-command-invalid":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has a 'command' that is not a single executable name; put arguments in 'args'`,"mcp-server-command-relative":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} runs a command bundled in the plugin ${q3(c5.detail)}; Stigmer runs only commands on the runner's PATH (for example 'npx' or 'uvx')`,"mcp-server-plugin-root-reference":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} references the plugin's own files through ${q3(c5.detail)}; Stigmer does not mount plugin files into the runner`,"mcp-server-cwd-unsupported":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} sets a working directory; Stigmer does not mount plugin files, so a bundled directory cannot be reached`,"mcp-server-env-literal":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} sets environment variable ${q3(c5.detail)} to a literal value; Stigmer passes declared variables by name, so write ${q3(`${c5.detail??"KEY"}: "\${${c5.detail??"KEY"}}"`)} and declare the variable`,"mcp-server-env-rename":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} maps environment variable ${q3(c5.detail)} to a differently named variable; Stigmer passes declared variables by name, so use the same name on both sides`,"mcp-server-name-duplicate":c5=>`MCP server name ${q3(c5.subject)} appears more than once (again${at(c5.path)})`,"mcp-server-header-duplicate":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} declares header ${q3(c5.detail)} more than once (header names are case-insensitive)`,"mcp-server-header-invalid":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has an invalid header name ${q3(c5.detail)}`,"sub-agent-frontmatter-unreadable":c5=>`${q3(c5.path)} frontmatter is not valid YAML: ${c5.detail??"parse error"}`,"sub-agent-instructions-short":c5=>`sub-agent ${q3(c5.subject)}${at(c5.path)} has instructions under ${c5.detail??""} characters; the body of the file is the sub-agent's prompt`,"sub-agent-name-duplicate":c5=>`sub-agent name ${q3(c5.subject)} appears more than once (again${at(c5.path)})`,"variable-name-invalid":c5=>`variable name ${q3(c5.subject)}${at(c5.path)} is invalid: an environment variable name is letters, digits and underscores, not starting with a digit`,"overlay-server-unknown":c5=>`${q3(c5.path)} overlays MCP server ${q3(c5.subject)}, which the plugin does not declare`,"overlay-document-unknown":c5=>`${q3(c5.path)} is not a document Stigmer reads; the 'ai.stigmer/' folder holds 'agent.yaml', 'workflows/<name>.yaml' and 'mcp-servers/<server>.yaml'`},WARNING_MESSAGES={"manifest-field-unknown":c5=>`manifest ${q3(c5.path)} has an unknown field ${q3(c5.subject)}, ignored`,"manifest-extensions-invalid":c5=>`manifest ${q3(c5.path)} has an 'extensions' field that is not an object, ignored`,"path-missing":c5=>`path ${q3(c5.subject)} declared${at(c5.path)} does not exist in the plugin`,"skill-name-defaulted":c5=>`${q3(c5.path)} has no 'name' in its frontmatter; the skill is named after its directory, ${q3(c5.subject)}`,"skill-name-differs-from-directory":c5=>`skill ${q3(c5.subject)}${at(c5.path)} is named differently from its directory ${q3(c5.detail)}`,"skill-description-missing":c5=>`skill ${q3(c5.subject)}${at(c5.path)} has no 'description'`,"mcp-config-field-ignored":c5=>`MCP configuration ${q3(c5.path)} has a top-level field ${q3(c5.subject)} Stigmer does not read, ignored`,"mcp-server-sse-mapped":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} declares the legacy 'sse' transport; Stigmer connects over Streamable HTTP and falls back to SSE only when the server rejects it`,"mcp-server-field-ignored":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has a field ${q3(c5.detail)} Stigmer does not read, ignored`,"mcp-server-auth-ignored":c5=>`MCP server ${q3(c5.subject)}${at(c5.path)} has an 'auth' block Stigmer does not read; OAuth for a server is declared in 'ai.stigmer/mcp-servers/${c5.subject??"<server>"}.yaml'`,"variable-inferred":c5=>`variable ${q3(c5.subject)} is referenced by MCP server ${q3(c5.detail)} but not declared; it is declared as a required secret`,"variable-unreferenced":c5=>`variable ${q3(c5.subject)}${at(c5.path)} is declared but no MCP server references it`,"variable-default-dropped":c5=>`variable ${q3(c5.subject)}${at(c5.path)} has a default value, which Stigmer does not carry; the user supplies the value`,"variable-type-narrowed":c5=>`variable ${q3(c5.subject)}${at(c5.path)} is typed ${q3(c5.detail)}; Stigmer variables are strings`,"variable-option-dropped":c5=>`variable ${q3(c5.subject)}${at(c5.path)} has a ${q3(c5.detail)} constraint, which Stigmer does not carry`,"sub-agent-name-defaulted":c5=>`${q3(c5.path)} has no 'name' in its frontmatter; the sub-agent is named after the file, ${q3(c5.subject)}`,"sub-agent-skill-unknown":c5=>`sub-agent ${q3(c5.subject)}${at(c5.path)} asks for skill ${q3(c5.detail)}, which the plugin does not ship`,"sub-agent-model-unknown":c5=>`sub-agent ${q3(c5.subject)}${at(c5.path)} names model ${q3(c5.detail)}, which Stigmer cannot map; the sub-agent runs on the session's model`,"sub-agent-field-ignored":c5=>`sub-agent ${q3(c5.subject)}${at(c5.path)} has a field ${q3(c5.detail)} Stigmer does not read, ignored`};var FindingCollector=class{errorSentences;warningSentences;errors=[];warnings=[];constructor(errorSentences,warningSentences){this.errorSentences=errorSentences,this.warningSentences=warningSentences}error(kind,ctx={}){this.errors.push(compose(kind,ctx,this.errorSentences[kind](ctx)))}warn(kind,ctx={}){this.warnings.push(compose(kind,ctx,this.warningSentences[kind](ctx)))}},Findings=class extends FindingCollector{constructor(){super(ERROR_MESSAGES,WARNING_MESSAGES)}};function compose(kind,ctx,message6){return{kind,...ctx.path!==void 0&&{path:ctx.path},...ctx.subject!==void 0&&{subject:ctx.subject},...ctx.detail!==void 0&&{detail:ctx.detail},message:message6}}var KNOWN_FIELDS3=new Set(["$schema","name","version","description","author","homepage","repository","license","keywords","extensions"]);function readOpenManifest(object,path14,findings){let schema2=object.$schema;return schema2===void 0?findings.error("manifest-schema-missing",{path:path14}):schema2!==AGENT_PLUGINS_MANIFEST_SCHEMA&&findings.error("manifest-schema-unsupported",{path:path14,detail:describeValue(schema2)}),warnUnknownFields(object,KNOWN_FIELDS3,path14,findings),{dialect:"agent-plugins",path:path14,identity:readIdentity(object,path14,findings),skillPaths:[],mcpConfigs:[],ignored:extensionComponents(object,path14,findings)}}var OPEN_MCP_CONFIG="mcp.json",VENDOR_PRECEDENCE=["claude","cursor","codex"],MANIFEST_PRECEDENCE=["agent-plugins",...VENDOR_PRECEDENCE],NAME_MAX_LENGTH=64,NAME_PATTERN=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/;function detectManifests(index2,findings){let manifests=[],present=dialect=>{let path14=MANIFEST_LOCATIONS[dialect];if(!index2.has(path14))return;let object=readManifestObject(index2,path14,findings),manifest=object===void 0?emptyManifest(dialect,path14):readDialect(dialect,object,path14,findings);return manifests.push(manifest),manifest},root5=present("agent-plugins"),vendors=VENDOR_PRECEDENCE.map(present).filter(m3=>m3!==void 0);if(manifests.length===0){findings.error("no-manifest");return}let identity2=root5??vendors[0];if(identity2===void 0)throw new Error("manifest set without an identity manifest");let ordered=[identity2,...manifests.filter(m3=>m3!==identity2)],name=resolveName(identity2,ordered,findings);return{dialect:identity2.dialect,manifests:ordered,name,readsAgents:vendors.length>0,mcpSources:resolveMcpSources(index2,root5,vendors)}}function readManifestObject(index2,path14,findings){let text2=readText(index2,path14,"manifest",findings);return text2===void 0?void 0:parseJsonObject2(text2,path14,"manifest-unreadable",findings)}function readDialect(dialect,object,path14,findings){switch(dialect){case"agent-plugins":return readOpenManifest(object,path14,findings);case"claude":return readClaudeManifest(object,path14,findings);case"cursor":return readCursorManifest(object,path14,findings);case"codex":return readCodexManifest(object,path14,findings);default:{let exhaustive=dialect;throw new Error(`unknown dialect ${String(exhaustive)}`)}}}function emptyManifest(dialect,path14){return{dialect,path:path14,identity:{},skillPaths:[],mcpConfigs:[],ignored:[]}}function resolveName(identity2,all,findings){let name=identity2.identity.name;if(name===void 0){if(findings.errors.some(f5=>f5.kind==="manifest-unreadable"&&f5.path===identity2.path))return;findings.error("manifest-name-missing",{path:identity2.path});return}let valid=!0;isValidPluginName(name)||(findings.error("manifest-name-invalid",{path:identity2.path,subject:name}),valid=!1);for(let other of all){if(other===identity2)continue;let otherName=other.identity.name;otherName!==void 0&&otherName!==name&&(findings.error("manifest-name-conflict",{path:identity2.path,subject:name,detail:`'${otherName}' in '${other.path}'`}),valid=!1)}return valid?name:void 0}function isValidPluginName(name){return name.length<=NAME_MAX_LENGTH&&NAME_PATTERN.test(name)&&!name.includes("--")&&!name.includes("..")}function resolveMcpSources(index2,root5,vendors){let sources=[];root5!==void 0&&index2.has(OPEN_MCP_CONFIG)&&sources.push({kind:"file",path:OPEN_MCP_CONFIG,dialect:"agent-plugins",manifest:root5.path});for(let vendor of vendors)vendor.mcpConfigs.length>0?sources.push(...vendor.mcpConfigs):vendor.dialect!=="cursor"&&index2.has(CLAUDE_DEFAULT_MCP_CONFIG)&&sources.push({kind:"file",path:CLAUDE_DEFAULT_MCP_CONFIG,dialect:vendor.dialect,manifest:vendor.path});let seen=new Set;return sources.filter(source=>source.kind==="inline"?!0:seen.has(source.path)?!1:(seen.add(source.path),!0))}var import_yaml=__toESM(require_dist2(),1);var SKILL_NAME_PATTERN=/^[a-z0-9]+([.-][a-z0-9]+)*$/;function extractFrontmatter(content){let lines=content.split(/\r?\n/);if(lines.length===0||lines[0]?.trim()!=="---")return{ok:!1,reason:"missing"};for(let i6=1;i6<lines.length;i6++)if(lines[i6]?.trim()==="---")return{ok:!0,yaml:lines.slice(1,i6).join(`
489
489
  `),body:lines.slice(i6+1).join(`
490
490
  `)};return{ok:!1,reason:"unclosed"}}function parseFrontmatter(yaml2){let value;try{value=(0,import_yaml.parse)(yaml2)}catch(error2){return{ok:!1,detail:error2 instanceof Error?error2.message:String(error2)}}return value==null?{ok:!0,fields:{}}:isJsonObject2(value)?{ok:!0,fields:value}:{ok:!1,detail:"the frontmatter is not a mapping"}}var DEFAULT_AGENTS_DIR="agents",SUB_AGENT_INSTRUCTIONS_MIN=10,READ_FIELDS=new Set(["name","description","model","skills"]);function normaliseSubAgents(index2,set2,skills,findings){if(!set2.readsAgents)return[];let skillNames=new Set(skills.map(skill=>skill.name)),agents=[],seen=new Set;for(let path14 of discoverAgentFiles(index2,set2,findings)){let agent=readSubAgent(index2,path14,skillNames,findings);if(agent!==void 0){if(seen.has(agent.name)){findings.error("sub-agent-name-duplicate",{subject:agent.name,path:path14});continue}seen.add(agent.name),agents.push(agent)}}return agents}function discoverAgentFiles(index2,set2,findings){let files=new Set,addMarkdownUnder=dir=>{for(let name of index2.childFiles(dir))name.endsWith(".md")&&files.add(joinPath(dir,name))},declared=set2.manifests.flatMap(m3=>m3.agentPaths??[]);set2.manifests.every(m3=>m3.agentPaths===void 0)&&addMarkdownUnder(DEFAULT_AGENTS_DIR);for(let{path:path14,manifest}of declared)path14!==""&&index2.has(path14)&&path14.endsWith(".md")?files.add(path14):index2.isDirectory(path14)?addMarkdownUnder(path14):findings.warn("path-missing",{path:manifest,subject:path14===""?".":`./${path14}`});return[...files].sort(comparePaths)}function readSubAgent(index2,path14,skillNames,findings){let text2=readText(index2,path14,"subAgent",findings);if(text2===void 0)return;let extracted=extractFrontmatter(text2),fieldsMap={},body=text2;if(extracted.ok){let parsed=parseFrontmatter(extracted.yaml);if(!parsed.ok){findings.error("sub-agent-frontmatter-unreadable",{path:path14,detail:parsed.detail});return}fieldsMap=parsed.fields,body=extracted.body}else if(extracted.reason==="unclosed"){findings.error("sub-agent-frontmatter-unreadable",{path:path14,detail:"the frontmatter is not closed (missing the closing '---')"});return}let stem=basename(path14).replace(/\.md$/,""),name;typeof fieldsMap.name=="string"&&fieldsMap.name!==""?name=fieldsMap.name:(name=stem,findings.warn("sub-agent-name-defaulted",{path:path14,subject:name}));let instructions=body.trim();if(instructions.length<SUB_AGENT_INSTRUCTIONS_MIN){findings.error("sub-agent-instructions-short",{path:path14,subject:name,detail:String(SUB_AGENT_INSTRUCTIONS_MIN)});return}let description=fieldsMap.description,requested=fieldsMap.skills,matchedSkills=[];if(Array.isArray(requested))for(let skill of requested)typeof skill=="string"&&(skillNames.has(skill)?matchedSkills.push(skill):findings.warn("sub-agent-skill-unknown",{path:path14,subject:name,detail:skill}));let modelHint,model=fieldsMap.model;typeof model=="string"&&model.trim()!==""&&(modelHint=classifyModel(model),modelHint.alias==="unknown"&&findings.warn("sub-agent-model-unknown",{path:path14,subject:name,detail:model}));for(let field3 of Object.keys(fieldsMap))READ_FIELDS.has(field3)||findings.warn("sub-agent-field-ignored",{path:path14,subject:name,detail:field3});return{name,...typeof description=="string"&&description!==""&&{description},instructions,skillNames:matchedSkills,...modelHint!==void 0&&{modelHint},path:path14}}function classifyModel(raw){let value=raw.trim().toLowerCase(),alias=value==="inherit"?"inherit":value==="fast"?"fast":value.includes("haiku")?"haiku":value.includes("sonnet")?"sonnet":value.includes("opus")?"opus":"unknown";return{raw,alias}}var PLACEHOLDER_PATTERN=/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,VARIABLE_NAME_PATTERN=/^[A-Za-z_][A-Za-z0-9_]*$/,USER_CONFIG_PATTERN=/\$\{user_config\.([A-Za-z_][A-Za-z0-9_]*)\}/g,PLUGIN_ROOT_PLACEHOLDERS=new Set(["${PLUGIN_ROOT}","${PLUGIN_DATA}","${CLAUDE_PLUGIN_ROOT}","${CLAUDE_PLUGIN_DATA}","${CLAUDE_PROJECT_DIR}","${CURSOR_PLUGIN_ROOT}"]),PLUGIN_ROOT_ENV_NAMES=new Set(["PLUGIN_ROOT","PLUGIN_DATA"]);function rewriteUserConfig(value){return value.replace(USER_CONFIG_PATTERN,(_match,key)=>`\${${key}}`)}function findPluginRootPlaceholder(value){for(let placeholder of PLUGIN_ROOT_PLACEHOLDERS)if(value.includes(placeholder))return placeholder}function referencedVariables(value){let names=[];for(let match of value.matchAll(PLACEHOLDER_PATTERN)){let name=match[1];name!==void 0&&!names.includes(name)&&names.push(name)}return names}function singlePlaceholderName(value){return/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(value)?.[1]}var IGNORED_DIRECTORIES={rules:"rules",hooks:"hooks",commands:"commands",canvases:"canvases",workflows:"workflows","output-styles":"output-styles",themes:"themes",monitors:"monitors",bin:"bin",assets:"assets",evals:"evals"},IGNORED_FILES={".lsp.json":"lsp-servers","settings.json":"settings",".app.json":"apps"};function ignoredOnDisk(index2,readsAgents){let ignored=[];for(let dir of index2.childDirectories("")){let kind=IGNORED_DIRECTORIES[dir];kind!==void 0&&ignored.push({kind,path:`${dir}/`}),dir==="agents"&&!readsAgents&&ignored.push({kind:"agents",path:`${dir}/`})}for(let file of index2.childFiles("")){let kind=IGNORED_FILES[file];kind!==void 0&&ignored.push({kind,path:file})}return ignored}function dedupeIgnored(lists){let seen=new Set,out=[];for(let list12 of lists)for(let component of list12){let key=`${component.kind}\0${component.path}`;seen.has(key)||(seen.add(key),out.push(component))}return out}var OPEN_CONFIG_FIELDS=new Set(["$schema","mcpServers"]),OPEN_STDIO_FIELDS=new Set(["type","command","args","env","cwd"]),OPEN_HTTP_FIELDS=new Set(["type","url","headers"]),VENDOR_STDIO_FIELDS=new Set(["type","command","args","env","cwd"]),VENDOR_HTTP_FIELDS=new Set(["type","url","headers"]),HEADER_NAME_PATTERN=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function normaliseMcpServers(index2,sources,findings){let servers=[],seen=new Set,refused=0;for(let source of sources){let entries=readSource(index2,source,findings);if(entries===void 0){refused++;continue}for(let[name,raw]of fields(entries.servers)){if(seen.has(name)){findings.error("mcp-server-name-duplicate",{subject:name,path:entries.path}),refused++;continue}seen.add(name);let server=readServer(name,raw,entries.path,source.dialect==="agent-plugins",findings);server!==void 0?servers.push(server):refused++}}return{servers,refused,declaredNames:seen}}function readSource(index2,source,findings){let open=source.dialect==="agent-plugins";if(source.kind==="inline"){let wrapped=isJsonObject2(source.servers)?source.servers.mcpServers:void 0,servers2=isJsonObject2(wrapped)?wrapped:source.servers;if(!isJsonObject2(servers2)){findings.error("mcp-config-shape",{path:source.manifest});return}return{path:source.manifest,servers:servers2}}if(!index2.has(source.path)){findings.warn("path-missing",{path:source.manifest,subject:`./${source.path}`});return}let text2=readText(index2,source.path,"mcpConfig",findings);if(text2===void 0)return;let object=parseJsonObject2(text2,source.path,"mcp-config-unreadable",findings);if(object===void 0)return;if(open){let schema2=object.$schema;schema2===void 0?findings.error("mcp-config-schema-missing",{path:source.path}):schema2!==AGENT_PLUGINS_MCP_SCHEMA&&findings.error("mcp-config-schema-unsupported",{path:source.path,detail:describeValue(schema2)})}for(let[name]of fields(object))OPEN_CONFIG_FIELDS.has(name)||(open?findings.error("mcp-config-field-unknown",{path:source.path,subject:name}):findings.warn("mcp-config-field-ignored",{path:source.path,subject:name}));let servers=object.mcpServers;if(!isJsonObject2(servers)){findings.error("mcp-config-shape",{path:source.path});return}return{path:source.path,servers}}function readServer(name,raw,path14,open,findings){let ctx={subject:name,path:path14};if(!isJsonObject2(raw)){findings.error("mcp-server-shape",ctx);return}let transport=resolveTransport(raw,ctx,open,findings);if(transport===void 0)return;let known=transport==="stdio"?open?OPEN_STDIO_FIELDS:VENDOR_STDIO_FIELDS:open?OPEN_HTTP_FIELDS:VENDOR_HTTP_FIELDS,references=new Set,valid=!0;for(let[field3,value]of fields(raw))if(!known.has(field3))if(open)findings.error("mcp-server-field-unknown",{...ctx,detail:field3}),valid=!1;else if(field3==="auth"){findings.warn("mcp-server-auth-ignored",ctx);for(let text2 of stringsWithin(value))collectReferences(text2,references)}else findings.warn("mcp-server-field-ignored",{...ctx,detail:field3});if(valid)return transport==="stdio"?readStdio(name,raw,ctx,references,findings):readHttp(name,raw,ctx,references,findings)}function resolveTransport(raw,ctx,open,findings){let type2=raw.type;if(type2!==void 0&&typeof type2!="string"){findings.error("mcp-server-field-type",{...ctx,detail:"type"});return}if(type2===void 0){if(open){findings.error("mcp-server-type-missing",ctx);return}let hasCommand=raw.command!==void 0,hasUrl=raw.url!==void 0;if(hasCommand&&hasUrl){findings.error("mcp-server-type-ambiguous",ctx);return}if(hasCommand)return"stdio";if(hasUrl)return"http";findings.error("mcp-server-transport-unknown",ctx);return}switch(type2){case"stdio":return"stdio";case"streamable-http":return"http";case"http":if(open){findings.error("mcp-server-type-unknown",{...ctx,detail:type2});return}return"http";case"sse":return findings.warn("mcp-server-sse-mapped",ctx),"http";default:findings.error("mcp-server-type-unknown",{...ctx,detail:type2});return}}function readStdio(name,raw,ctx,references,findings){let valid=!0,fail=()=>{valid=!1},command5=raw.command;if(command5===void 0)findings.error("mcp-server-command-missing",ctx),fail();else if(typeof command5!="string")findings.error("mcp-server-field-type",{...ctx,detail:"command"}),fail();else{let root5=findPluginRootPlaceholder(command5);root5!==void 0?(findings.error("mcp-server-plugin-root-reference",{...ctx,detail:root5}),fail()):command5.startsWith("./")?(findings.error("mcp-server-command-relative",{...ctx,detail:command5}),fail()):(command5===""||/\s/.test(command5)||command5.includes("/"))&&(findings.error("mcp-server-command-invalid",ctx),fail())}let args=[],rawArgs=raw.args;if(rawArgs!==void 0)if(!isStringArray(rawArgs))findings.error("mcp-server-field-type",{...ctx,detail:"args"}),fail();else for(let arg of rawArgs){let rewritten=rewriteUserConfig(arg),root5=findPluginRootPlaceholder(rewritten);if(root5!==void 0){findings.error("mcp-server-plugin-root-reference",{...ctx,detail:root5}),fail();continue}collectReferences(rewritten,references),args.push(rewritten)}let rawEnv=raw.env;if(rawEnv!==void 0)if(!isStringRecord(rawEnv))findings.error("mcp-server-field-type",{...ctx,detail:"env"}),fail();else for(let[key,value]of Object.entries(rawEnv)){if(PLUGIN_ROOT_ENV_NAMES.has(key)){findings.error("mcp-server-plugin-root-reference",{...ctx,detail:key}),fail();continue}if(!VARIABLE_NAME_PATTERN.test(key)){findings.error("variable-name-invalid",{subject:key,path:ctx.path}),fail();continue}let rewritten=rewriteUserConfig(value),root5=findPluginRootPlaceholder(rewritten);if(root5!==void 0){findings.error("mcp-server-plugin-root-reference",{...ctx,detail:root5}),fail();continue}let referenced=singlePlaceholderName(rewritten);referenced===void 0?(findings.error("mcp-server-env-literal",{...ctx,detail:key}),fail()):referenced!==key?(findings.error("mcp-server-env-rename",{...ctx,detail:key}),fail()):references.add(key)}if(raw.cwd!==void 0&&(findings.error("mcp-server-cwd-unsupported",ctx),fail()),!(!valid||typeof command5!="string"))return{name,transport:"stdio",command:command5,args,env:[...references].sort()}}function readHttp(name,raw,ctx,references,findings){let valid=!0,fail=()=>{valid=!1},url,rawUrl=raw.url;if(rawUrl===void 0)findings.error("mcp-server-url-missing",ctx),fail();else if(typeof rawUrl!="string")findings.error("mcp-server-field-type",{...ctx,detail:"url"}),fail();else{url=rewriteUserConfig(rawUrl);let root5=findPluginRootPlaceholder(url);root5!==void 0?(findings.error("mcp-server-plugin-root-reference",{...ctx,detail:root5}),fail()):referencedVariables(url).length>0?(findings.error("mcp-server-url-variable",ctx),fail()):isAcceptableServerUrl(url)||(findings.error("mcp-server-url-invalid",{...ctx,detail:url}),fail())}let headers2=[],rawHeaders=raw.headers;if(rawHeaders!==void 0)if(!isStringRecord(rawHeaders))findings.error("mcp-server-field-type",{...ctx,detail:"headers"}),fail();else{let lowered=new Set;for(let[header,value]of Object.entries(rawHeaders)){if(!HEADER_NAME_PATTERN.test(header)){findings.error("mcp-server-header-invalid",{...ctx,detail:header}),fail();continue}let key=header.toLowerCase();if(lowered.has(key)){findings.error("mcp-server-header-duplicate",{...ctx,detail:header}),fail();continue}lowered.add(key);let rewritten=rewriteUserConfig(value),root5=findPluginRootPlaceholder(rewritten);if(root5!==void 0){findings.error("mcp-server-plugin-root-reference",{...ctx,detail:root5}),fail();continue}collectReferences(rewritten,references),headers2.push([header,rewritten])}}if(!(!valid||url===void 0))return{name,transport:"http",url,headers:Object.fromEntries(headers2),env:[...references].sort()}}function isAcceptableServerUrl(value){let url;try{url=new URL(value)}catch{return!1}return url.username!==""||url.password!==""||url.hash!==""?!1:url.protocol==="https:"?!0:url.protocol!=="http:"?!1:isLoopbackHost(url.hostname)}function isLoopbackHost(hostname){return hostname==="localhost"||hostname==="[::1]"||hostname==="::1"?!0:/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname)}function collectReferences(text2,into){for(let name of referencedVariables(text2))into.add(name)}function stringsWithin(value){return typeof value=="string"?[rewriteUserConfig(value)]:Array.isArray(value)?value.flatMap(stringsWithin):isJsonObject2(value)?Object.values(value).flatMap(stringsWithin):[]}var OVERLAY_DIR="ai.stigmer",AGENT_DOCUMENT=`${OVERLAY_DIR}/agent.yaml`,WORKFLOWS_DIR=`${OVERLAY_DIR}/workflows`,MCP_SERVERS_DIR=`${OVERLAY_DIR}/mcp-servers`;function normaliseOverlay(index2,serverNames,findings){let overlay={workflows:[],mcpServers:[]},workflows=[],mcpServers=[];for(let path14 of index2.filesUnder(OVERLAY_DIR)){if(path14===AGENT_DOCUMENT){let bytes=readBytes(index2,path14,"overlay",findings);bytes!==void 0&&(overlay.agent={path:path14,bytes});continue}let name=yamlStem(path14);if(name!==void 0&&dirname(path14)===WORKFLOWS_DIR){let bytes=readBytes(index2,path14,"overlay",findings);bytes!==void 0&&workflows.push({path:path14,bytes,name});continue}if(name!==void 0&&dirname(path14)===MCP_SERVERS_DIR){if(!serverNames.has(name)){findings.error("overlay-server-unknown",{path:path14,subject:name});continue}let bytes=readBytes(index2,path14,"overlay",findings);bytes!==void 0&&mcpServers.push({path:path14,bytes,server:name});continue}findings.error("overlay-document-unknown",{path:path14})}return overlay.workflows=workflows,overlay.mcpServers=mcpServers,overlay}function yamlStem(path14){let name=basename(path14);return name.endsWith(".yaml")&&name.length>5?name.slice(0,-5):void 0}var SKILL_FILE="SKILL.md",DEFAULT_SKILLS_DIR="skills";function normaliseSkills(index2,set2,findings){let skills=[],seenNames=new Map;for(let dir of discoverSkillDirs(index2,set2,findings)){let skill=readSkill(index2,dir,set2,findings);if(skill===void 0)continue;if(seenNames.get(skill.name)!==void 0){findings.error("skill-name-duplicate",{subject:skill.name,path:joinPath(dir,SKILL_FILE)});continue}seenNames.set(skill.name,dir),skills.push(skill)}return skills}function discoverSkillDirs(index2,set2,findings){let dirs=new Set,addSkillsUnder=parent=>{for(let child of index2.childDirectories(parent)){let dir=joinPath(parent,child);index2.has(joinPath(dir,SKILL_FILE))&&dirs.add(dir)}};addSkillsUnder(DEFAULT_SKILLS_DIR);let declared=set2.manifests.flatMap(m3=>m3.skillPaths);for(let{path:path14,manifest}of declared)index2.has(joinPath(path14,SKILL_FILE))?dirs.add(path14):index2.isDirectory(path14)?addSkillsUnder(path14):findings.warn("path-missing",{path:manifest,subject:path14===""?".":`./${path14}`});return declared.length===0&&!index2.isDirectory(DEFAULT_SKILLS_DIR)&&index2.has(SKILL_FILE)&&dirs.add(""),[...dirs].sort(comparePaths)}function readSkill(index2,dir,set2,findings){let path14=joinPath(dir,SKILL_FILE),text2=readText(index2,path14,"skillMd",findings);if(text2===void 0)return;let extracted=extractFrontmatter(text2);if(!extracted.ok){findings.error(extracted.reason==="missing"?"skill-frontmatter-missing":"skill-frontmatter-unclosed",{path:path14});return}let parsed=parseFrontmatter(extracted.yaml);if(!parsed.ok){findings.error("skill-frontmatter-unreadable",{path:path14,detail:parsed.detail});return}let directoryName=dir===""?set2.name??"skill":basename(dir),name;if(typeof parsed.fields.name=="string"&&parsed.fields.name!==""?name=parsed.fields.name:(name=directoryName,findings.warn("skill-name-defaulted",{path:path14,subject:name})),!SKILL_NAME_PATTERN.test(name)){findings.error("skill-name-invalid",{path:path14,subject:name});return}dir!==""&&name!==directoryName&&findings.warn("skill-name-differs-from-directory",{path:path14,subject:name,detail:directoryName});let description=parsed.fields.description;return(typeof description!="string"||description==="")&&findings.warn("skill-description-missing",{path:path14,subject:name}),{name,...typeof description=="string"&&description!==""&&{description},dir,files:index2.filesUnder(dir)}}function normaliseVariables(set2,servers,findings){let declared=new Map,declaredIn=new Map;for(let manifest of set2.manifests){let declaration=manifest.variables;if(declaration===void 0)continue;let variables=declaration.dialect==="cursor"?readCursorVariables(declaration.value,declaration.manifest,findings):readClaudeVariables(declaration.value,declaration.manifest,findings);for(let variable of variables)declared.has(variable.name)||(declared.set(variable.name,variable),declaredIn.set(variable.name,declaration.manifest))}let referencedBy=new Map;for(let server of servers.servers)for(let name of server.env)referencedBy.has(name)||referencedBy.set(name,server.name);if(servers.refused===0)for(let[name,variable]of declared)referencedBy.has(name)||findings.warn("variable-unreferenced",{subject:variable.name,path:declaredIn.get(name)});let inferred=[];for(let[name,server]of[...referencedBy].sort(([a5],[b7])=>a5<b7?-1:a5>b7?1:0))declared.has(name)||(findings.warn("variable-inferred",{subject:name,detail:server}),inferred.push({name,isSecret:!0,optional:!1,declaredBy:"inferred"}));return[...declared.values(),...inferred]}function readCursorVariables(value,manifest,findings){if(!isJsonObject2(value)||value.type!=="object")return findings.error("manifest-field-type",{path:manifest,subject:"variables",detail:"a JSON Schema object with type 'object'"}),[];let properties=value.properties??{};if(!isJsonObject2(properties))return findings.error("manifest-field-type",{path:manifest,subject:"variables.properties",detail:"an object"}),[];let required=value.required??[];if(!isStringArray(required))return findings.error("manifest-field-type",{path:manifest,subject:"variables.required",detail:"an array of strings"}),[];let variables=[];for(let[name,schema2]of fields(properties)){if(!VARIABLE_NAME_PATTERN.test(name)){findings.error("variable-name-invalid",{subject:name,path:manifest});continue}let property=isJsonObject2(schema2)?schema2:{},type2=property.type;type2!==void 0&&type2!=="string"&&findings.warn("variable-type-narrowed",{subject:name,path:manifest,detail:describeValue(type2)}),property.default!==void 0&&findings.warn("variable-default-dropped",{subject:name,path:manifest}),property.enum!==void 0&&findings.warn("variable-option-dropped",{subject:name,path:manifest,detail:"enum"});let description=describe(property);variables.push({name,...description!==void 0&&{description},isSecret:!0,optional:!required.includes(name),declaredBy:"cursor"})}return variables}function readClaudeVariables(value,manifest,findings){if(!isJsonObject2(value))return findings.error("manifest-field-type",{path:manifest,subject:"userConfig",detail:"an object"}),[];let variables=[];for(let[name,entry]of fields(value)){if(!VARIABLE_NAME_PATTERN.test(name)){findings.error("variable-name-invalid",{subject:name,path:manifest});continue}if(!isJsonObject2(entry)){findings.error("manifest-field-type",{path:manifest,subject:`userConfig.${name}`,detail:"an object"});continue}let type2=entry.type;type2!==void 0&&type2!=="string"&&findings.warn("variable-type-narrowed",{subject:name,path:manifest,detail:describeValue(type2)}),entry.default!==void 0&&findings.warn("variable-default-dropped",{subject:name,path:manifest});for(let option of["options","multiple","min","max"])entry[option]!==void 0&&findings.warn("variable-option-dropped",{subject:name,path:manifest,detail:option});let description=describe(entry);variables.push({name,...description!==void 0&&{description},isSecret:entry.sensitive===!0,optional:entry.required!==!0,declaredBy:"claude"})}return variables}function describe(entry){let parts=[entry.title,entry.description].filter(part=>typeof part=="string"&&part!=="");return parts.length===0?void 0:parts.join(": ")}function readPluginPackage(files){let findings=new Findings;for(let entry of files.entries)isContainedPath(entry.path)||findings.error("path-uncontained",{path:entry.path});let index2=new PluginFileIndex(files),set2=detectManifests(index2,findings);if(set2===void 0)return{ok:!1,errors:findings.errors,warnings:findings.warnings};let skills=normaliseSkills(index2,set2,findings),servers=normaliseMcpServers(index2,set2.mcpSources,findings),mcpServers=servers.servers,variables=normaliseVariables(set2,servers,findings),subAgents=normaliseSubAgents(index2,set2,skills,findings),overlay=normaliseOverlay(index2,servers.declaredNames,findings),ignored=dedupeIgnored([ignoredOnDisk(index2,set2.readsAgents),...set2.manifests.map(m3=>m3.ignored)]);if(findings.errors.length>0||set2.name===void 0)return{ok:!1,errors:findings.errors,warnings:findings.warnings};let identity2=set2.manifests[0]?.identity??{};return{ok:!0,plugin:{name:set2.name,...identity2.version!==void 0&&{version:identity2.version},...identity2.description!==void 0&&{description:identity2.description},...identity2.author!==void 0&&{author:identity2.author},...identity2.homepage!==void 0&&{homepage:identity2.homepage},...identity2.repository!==void 0&&{repository:identity2.repository},...identity2.license!==void 0&&{license:identity2.license},keywords:identity2.keywords??[],dialect:set2.dialect,manifestsFound:set2.manifests.map(m3=>m3.path),skills,mcpServers,subAgents,variables,overlay,ignored},warnings:findings.warnings}}var import_node_zlib=require("node:zlib");function parseZipStructure(data){let view=new DataView(data.buffer,data.byteOffset,data.byteLength),eocd=findEndOfCentralDirectory(data,view),entries=[],offset=eocd.centralDirectoryOffset;for(let i6=0;i6<eocd.entryCount;i6++){if(offset+46>data.length||view.getUint32(offset,!0)!==33639248)throw new Error(`invalid central directory record at offset ${offset}`);let versionMadeBy=view.getUint16(offset+4,!0),compressionMethod=view.getUint16(offset+10,!0),crc323=view.getUint32(offset+16,!0),compressedSize=view.getUint32(offset+20,!0),uncompressedSize=view.getUint32(offset+24,!0),fileNameLength=view.getUint16(offset+28,!0),extraFieldLength=view.getUint16(offset+30,!0),commentLength=view.getUint16(offset+32,!0),externalAttributes=view.getUint32(offset+38,!0),localHeaderOffset=view.getUint32(offset+42,!0),fileName=new TextDecoder().decode(data.subarray(offset+46,offset+46+fileNameLength)),dataStart=payloadStart(data,view,localHeaderOffset,fileName);if(dataStart+compressedSize>data.length)throw new Error(`entry "${fileName}" payload runs past end of archive`);entries.push({name:fileName,isDirectory:fileName.endsWith("/"),compressionMethod,uncompressedSize,compressedSize,crc32:crc323,versionMadeBy,externalAttributes,compressedData:data.subarray(dataStart,dataStart+compressedSize)}),offset+=46+fileNameLength+extraFieldLength+commentLength}return entries}function findEndOfCentralDirectory(data,view){let scanFloor=Math.max(0,data.length-22-65535);for(let pos=data.length-22;pos>=scanFloor;pos--){if(view.getUint32(pos,!0)!==101010256)continue;let entryCount=view.getUint16(pos+10,!0),centralDirectorySize=view.getUint32(pos+12,!0),centralDirectoryOffset=view.getUint32(pos+16,!0),directoryEndsAtRecord=centralDirectoryOffset+centralDirectorySize<=pos,directoryLooksReal=entryCount===0||centralDirectoryOffset+4<=data.length&&view.getUint32(centralDirectoryOffset,!0)===33639248;if(directoryEndsAtRecord&&directoryLooksReal)return{centralDirectoryOffset,entryCount}}throw new Error("no end-of-central-directory record found")}var CRC_TABLE=(()=>{let table2=new Uint32Array(256);for(let n3=0;n3<256;n3++){let c5=n3;for(let bit=0;bit<8;bit++)c5=c5>>>1^3988292384&-(c5&1);table2[n3]=c5}return table2})();function crc322(data){let crc2=4294967295;for(let i6=0;i6<data.length;i6++)crc2=crc2>>>8^CRC_TABLE[(crc2^data[i6])&255];return(crc2^4294967295)>>>0}function payloadStart(data,view,localHeaderOffset,fileName){if(localHeaderOffset+30>data.length||view.getUint32(localHeaderOffset,!0)!==67324752)throw new Error(`entry "${fileName}" has no local file header at offset ${localHeaderOffset}`);let localNameLength=view.getUint16(localHeaderOffset+26,!0),localExtraLength=view.getUint16(localHeaderOffset+28,!0);return localHeaderOffset+30+localNameLength+localExtraLength}var METHOD_STORED=0,METHOD_DEFLATED=8,InflateError=class extends Error{kind;detail;constructor(kind,detail){super(`${kind}: ${detail}`),this.kind=kind,this.detail=detail,this.name="InflateError"}};function inflateEntry(entry,maxSize){let content;switch(entry.compressionMethod){case METHOD_STORED:content=entry.compressedData;break;case METHOD_DEFLATED:try{content=new Uint8Array((0,import_node_zlib.inflateRawSync)(entry.compressedData,{maxOutputLength:maxSize+1}))}catch(error2){throw isOutputLengthError(error2)?new InflateError("too-large",`output exceeds ${maxSize} bytes`):new InflateError("read-failed",error2 instanceof Error?error2.message:String(error2))}break;default:throw new InflateError("unsupported-method","zip: unsupported compression algorithm")}if(content.length>maxSize)throw new InflateError("too-large",`output exceeds ${maxSize} bytes`);if(crc322(content)!==entry.crc32)throw new InflateError("checksum","zip: checksum error");return content}function isOutputLengthError(error2){return error2 instanceof Error&&("code"in error2&&error2.code==="ERR_BUFFER_TOO_LARGE"||error2.message.includes("maxOutputLength"))}var import_node_crypto25=require("node:crypto");function sanitizePath(input){let sanitized=sanitizeCore(input);return input.length>0&&(input.endsWith("/")||input.endsWith("\\"))&&sanitized.length>0?`${sanitized}/`:sanitized}function sanitizeCore(input){let segments=`/${input.replaceAll("\\","/")}`.split("/"),resolved=[];for(let segment of segments)if(!(segment===""||segment===".")){if(segment===".."){resolved.pop();continue}resolved.push(segment)}return resolved.join("/")}var WINDOWS_SHORT_FILENAME_PATTERN=/~\d+\.?/;function hasWindowsShortFilenames(input){return input.replaceAll("\\","/").split("/").some(part=>WINDOWS_SHORT_FILENAME_PATTERN.test(part))}var CREATOR_UNIX=3,CREATOR_MACOSX=19,S_IFMT=61440,S_IFBLK=24576,S_IFCHR=8192,S_IFIFO=4096,S_IFLNK=40960,S_IFSOCK=49152;function entryTypeBits(entry){let creator=entry.versionMadeBy>>8;if(creator!==CREATOR_UNIX&&creator!==CREATOR_MACOSX)return{isSymlink:!1,isSpecial:!1};let fileType=entry.externalAttributes>>>16&65535&S_IFMT;return{isSymlink:fileType===S_IFLNK,isSpecial:fileType===S_IFBLK||fileType===S_IFCHR||fileType===S_IFIFO||fileType===S_IFSOCK}}function applyEntryPrefilter(entries){let symlinks=new Set,result=[];for(let entry of entries){let name=sanitizePath(entry.name);if(hasWindowsShortFilenames(name))continue;let shadowKey=trimTrailingSlash(sanitizePath(name)).toLowerCase(),parts=shadowKey.split("/"),traversal=!1;for(let i6=1;i6<=parts.length;i6++)if(symlinks.has(parts.slice(0,i6).join("/"))){traversal=!0;break}if(traversal)continue;let typeBits=entryTypeBits(entry);typeBits.isSymlink&&symlinks.add(shadowKey),!typeBits.isSpecial&&result.push({name,entry})}return result}function trimTrailingSlash(path14){return path14.endsWith("/")?path14.slice(0,-1):path14}function openArchive(bytes,maxZipSize=104857600){if(bytes.length>maxZipSize)throw new Error(`ZIP file too large: ${bytes.length} bytes (max: ${maxZipSize})`);let hash=calculateHash(bytes),entries;try{entries=parseZipStructure(bytes)}catch{throw new Error("invalid ZIP file: zip: not a valid zip file")}return{hash,entries:applyEntryPrefilter(entries)}}function validateArchiveStructure(entries,limits,onEntry){if(entries.length===0)throw new Error("ZIP file is empty");if(entries.length>limits.maxFiles)throw new Error(`too many files in ZIP: ${entries.length} (max: ${limits.maxFiles})`);let totalUncompressedSize=0;for(let{name,entry}of entries){onEntry?.(name);for(let ch of name){let codePoint=ch.codePointAt(0);if(codePoint<32||codePoint===127)throw new Error(`invalid character in filename: ${name}`)}if(totalUncompressedSize+=entry.uncompressedSize,totalUncompressedSize>limits.maxUncompressedSize)throw new Error(`total uncompressed size too large: ${totalUncompressedSize} bytes (max: ${limits.maxUncompressedSize})`);if(entry.compressedSize>0){let ratio=Math.floor(entry.uncompressedSize/entry.compressedSize);if(ratio>limits.maxCompressionRatio)throw new Error(`suspicious compression ratio in ${name}: ${ratio}:1 (max: ${limits.maxCompressionRatio}:1)`)}}}function calculateHash(data){return(0,import_node_crypto25.createHash)("sha256").update(data).digest("hex")}function openPluginArchive(bytes){let{hash,entries}=openArchive(bytes,104857600);validateArchiveStructure(entries,PLATFORM_ARCHIVE_LIMITS);let byPath=new Map;for(let prefiltered of entries){let{name}=prefiltered;name.endsWith("/")||!isContainedPath(name)||byPath.has(name)||byPath.set(name,prefiltered)}let files={entries:[...byPath.values()].map(({name,entry})=>({path:name,size:entry.uncompressedSize})).sort((a5,b7)=>comparePaths(a5.path,b7.path)),read(path14){let prefiltered=byPath.get(path14);if(prefiltered===void 0)throw new Error(`plugin file '${path14}' is not listed`);try{return inflateEntry(prefiltered.entry,prefiltered.entry.uncompressedSize)}catch(error2){throw error2 instanceof InflateError?new Error(`failed to read '${path14}' from the plugin archive: ${error2.detail}`):error2}}};return{digest:hash,files}}function memberLabels(identity2){return{[PLUGIN_LABEL]:identity2.id,[PLUGIN_VERSION_LABEL]:identity2.digest}}function memberMetadata(identity2,member2,authored){let metadata=authored===void 0?create2(ApiResourceMetadataSchema,{}):authored;return metadata.org=identity2.org,metadata.name=member2.name,metadata.slug=member2.slug,metadata.id="",identity2.visibility!==ApiResourceVisibility.api_resource_visibility_unspecified&&(metadata.visibility=identity2.visibility),metadata.labels={...metadata.labels,...memberLabels(identity2)},metadata}var McpServerOverlayError=class extends Error{constructor(server,reason){super(`overlay for MCP server '${server}': ${reason}`),this.name="McpServerOverlayError"}};function mcpServerSlugOf(server){return generateSlug(server.name)}function planMcpServers(plugin2,overlays,identity2){let env2=declaredVariables(plugin2);return plugin2.mcpServers.map(server=>{let overlay=overlays.get(server.name),spec=create2(McpServerSpecSchema,{description:plugin2.description??"",env:Object.fromEntries(server.env.map(name=>[name,env2.get(name)??inferredSecret()]))});switch(server.transport){case"http":spec.serverType={case:"http",value:create2(HttpServerConfigSchema,{url:server.url,headers:{...server.headers}})};break;case"stdio":spec.serverType={case:"stdio",value:create2(StdioServerConfigSchema,{command:server.command,args:[...server.args]})};break;default:{let exhaustive=server;throw new Error(`unknown transport ${JSON.stringify(exhaustive)}`)}}overlay!==void 0&&layerOverlay(server.name,spec,overlay);let slug=mcpServerSlugOf(server);return{name:server.name,slug,resource:create2(McpServerSchema,{apiVersion:"agentic.stigmer.ai/v1",kind:"McpServer",metadata:memberMetadata(identity2,{name:server.name,slug},overlay?.metadata),spec})}})}function declaredVariables(plugin2){return new Map(plugin2.variables.map(variable=>[variable.name,create2(EnvVarDeclarationSchema,{isSecret:variable.isSecret,description:variable.description??"",optional:variable.optional})]))}function inferredSecret(){return create2(EnvVarDeclarationSchema,{isSecret:!0,optional:!1})}function layerOverlay(serverName,spec,overlay){let authored=overlay.spec;if(authored!==void 0){if(authored.serverType.case!==void 0)throw new McpServerOverlayError(serverName,"the transport (http or stdio) lives in mcp.json, where every client reads it; the overlay may not redefine it");if(Object.keys(authored.env).length>0)throw new McpServerOverlayError(serverName,"variables are declared where mcp.json references them (the plugin's variables or userConfig); the overlay may not declare env");authored.description!==""&&(spec.description=authored.description),authored.iconUrl!==""&&(spec.iconUrl=authored.iconUrl),authored.tags.length>0&&(spec.tags=[...authored.tags]),authored.defaultEnabledTools.length>0&&(spec.defaultEnabledTools=[...authored.defaultEnabledTools]),authored.pinnedToolApprovals.length>0&&(spec.pinnedToolApprovals=[...authored.pinnedToolApprovals]),authored.repositoryUrl!==""&&(spec.repositoryUrl=authored.repositoryUrl),authored.auth!==void 0&&(spec.auth=authored.auth)}}function renderDefaultAgentInstructions(plugin2){let lines=[],description=plugin2.description?.trim()??"";if(lines.push(description===""?`You are ${plugin2.name}, an agent installed from the ${plugin2.name} plugin.`:`You are ${plugin2.name}: ${description}`),plugin2.skills.length>0){lines.push(""),lines.push("Your skills:");for(let skill of plugin2.skills){let summary=skill.description?.trim()??"";lines.push(summary===""?`- ${skill.name}`:`- ${skill.name}: ${summary}`)}}if(plugin2.mcpServers.length>0){lines.push(""),lines.push("Your tools come from these MCP servers:");for(let server of plugin2.mcpServers)lines.push(`- ${server.name}`)}return lines.push(""),lines.push("Before acting on a task a skill covers, read that skill and follow it. Use the tools your servers provide rather than guessing at their results. When you finish, state what you did and what you could not do."),lines.join(`
491
491
  `)}var file_ai_stigmer_agentic_skill_v1_io=fileDesc("CiRhaS9zdGlnbWVyL2FnZW50aWMvc2tpbGwvdjEvaW8ucHJvdG8SG2FpLnN0aWdtZXIuYWdlbnRpYy5za2lsbC52MSIgCgdTa2lsbElkEhUKBXZhbHVlGAEgASgJQga6SAPIAQEijgQKEFB1c2hTa2lsbFJlcXVlc3QSEwoDb3JnGAEgASgJQga6SAPIAQESEAoIYXJ0aWZhY3QYAiABKAwSKAoDdGFnGAMgASgJQhu6SBhyFjIUXiR8XlthLXpBLVowLTkuXy1dKyQSQgoOZ2l0X3Byb3ZlbmFuY2UYBCABKAsyKi5haS5zdGlnbWVyLmFnZW50aWMuc2tpbGwudjEuR2l0UHJvdmVuYW5jZRIPCgdtZXNzYWdlGAYgASgJEhsKE2FydGlmYWN0X3VwbG9hZF9yZWYYByABKAkSSQoGbGFiZWxzGAggAygLMjkuYWkuc3RpZ21lci5hZ2VudGljLnNraWxsLnYxLlB1c2hTa2lsbFJlcXVlc3QuTGFiZWxzRW50cnkaLQoLTGFiZWxzRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ATq2AbpIsgEarwEKInB1c2hfc2tpbGxfcmVxdWVzdC5hcnRpZmFjdF9zb3VyY2USSWV4YWN0bHkgb25lIG9mIGFydGlmYWN0IChpbmxpbmUgYnl0ZXMpIG9yIGFydGlmYWN0X3VwbG9hZF9yZWYgbXVzdCBiZSBzZXQaPih0aGlzLmFydGlmYWN0LnNpemUoKSA+IDApICE9ICh0aGlzLmFydGlmYWN0X3VwbG9hZF9yZWYgIT0gJycpSgQIBRAGIlcKI0NyZWF0ZVNraWxsQXJ0aWZhY3RVcGxvYWRVcmxSZXF1ZXN0EhMKA29yZxgBIAEoCUIGukgDyAEBEhsKCnNpemVfYnl0ZXMYAiABKANCB7pIBCICIAAiVwoWU2tpbGxBcnRpZmFjdFVwbG9hZFVybBILCgN1cmwYASABKAkSGwoTYXJ0aWZhY3RfdXBsb2FkX3JlZhgCIAEoCRITCgt0dGxfc2Vjb25kcxgDIAEoBSJQChhTa2lsbEFydGlmYWN0RG93bmxvYWRVcmwSCwoDdXJsGAEgASgJEhMKC3R0bF9zZWNvbmRzGAIgASgFEhIKCnNpemVfYnl0ZXMYAyABKAMiowEKJVB1c2hTa2lsbEZyb21FeGVjdXRpb25BcnRpZmFjdFJlcXVlc3QSEwoDb3JnGAEgASgJQga6SAPIAQESHQoMZXhlY3V0aW9uX2lkGAIgASgJQge6SARyAhABEhwKC3N0b3JhZ2Vfa2V5GAMgASgJQge6SARyAhABEigKA3RhZxgEIAEoCUIbukgYchYyFF4kfF5bYS16QS1aMC05Ll8tXSskIjoKEkdldEFydGlmYWN0UmVxdWVzdBIkChRhcnRpZmFjdF9zdG9yYWdlX2tleRgBIAEoCUIGukgDyAEBIicKE0dldEFydGlmYWN0UmVzcG9uc2USEAoIYXJ0aWZhY3QYASABKAwiagoWTGlzdFNraWxsVmVyc2lvbnNJbnB1dBITCgNvcmcYASABKAlCBrpIA8gBARIUCgRzbHVnGAIgASgJQga6SAPIAQESEgoKcGFnZV90b2tlbhgDIAEoCRIRCglwYWdlX3NpemUYBCABKAUitgIKEVNraWxsVmVyc2lvbkVudHJ5EhQKDHZlcnNpb25faGFzaBgBIAEoCRItCglwdXNoZWRfYXQYAiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEkgKCXB1c2hlZF9ieRgDIAEoCzI1LmFpLnN0aWdtZXIuY29tbW9ucy5hcGlyZXNvdXJjZS5BcGlSZXNvdXJjZUF1ZGl0QWN0b3ISCwoDdGFnGAQgASgJEhIKCmlzX2N1cnJlbnQYBSABKAgSQgoOZ2l0X3Byb3ZlbmFuY2UYBiABKAsyKi5haS5zdGlnbWVyLmFnZW50aWMuc2tpbGwudjEuR2l0UHJvdmVuYW5jZRIPCgdtZXNzYWdlGAcgASgJEhwKFGFydGlmYWN0X3N0b3JhZ2Vfa2V5GAggASgJIosBChlMaXN0U2tpbGxWZXJzaW9uc1Jlc3BvbnNlEkAKCHZlcnNpb25zGAEgAygLMi4uYWkuc3RpZ21lci5hZ2VudGljLnNraWxsLnYxLlNraWxsVmVyc2lvbkVudHJ5EhcKD25leHRfcGFnZV90b2tlbhgCIAEoCRITCgt0b3RhbF9jb3VudBgDIAEoBWIGcHJvdG8z",[file_ai_stigmer_agentic_skill_v1_status,file_ai_stigmer_commons_apiresource_status,file_buf_validate_validate,file_google_protobuf_timestamp]),SkillIdSchema=messageDesc2(file_ai_stigmer_agentic_skill_v1_io,0),PushSkillRequestSchema=messageDesc2(file_ai_stigmer_agentic_skill_v1_io,1);var SkillArtifactUploadUrlSchema=messageDesc2(file_ai_stigmer_agentic_skill_v1_io,3),SkillArtifactDownloadUrlSchema=messageDesc2(file_ai_stigmer_agentic_skill_v1_io,4);var GetArtifactResponseSchema=messageDesc2(file_ai_stigmer_agentic_skill_v1_io,7);var SkillVersionEntrySchema=messageDesc2(file_ai_stigmer_agentic_skill_v1_io,9),ListSkillVersionsResponseSchema=messageDesc2(file_ai_stigmer_agentic_skill_v1_io,10);var DETERMINISTIC_ZIP_MTIME=new Date(1980,0,1),DEFLATE_LEVEL=6;function writeArchive(files){let sorted=[...files].sort((a5,b7)=>a5.path<b7.path?-1:a5.path>b7.path?1:0),tree={};for(let file of sorted){if(file.path in tree)throw new Error(`archive path '${file.path}' listed twice`);tree[file.path]=file.bytes}return zipSync(tree,{level:DEFLATE_LEVEL,mtime:DETERMINISTIC_ZIP_MTIME})}function skillSlugOf(skill){return generateSlug(skill.name)}function planSkills(plugin2,files,identity2,tag2,message6){return plugin2.skills.map(skill=>{let prefix=skill.dir===""?"":`${skill.dir}/`,archive=writeArchive(skill.files.map(path14=>({path:path14.startsWith(prefix)?path14.slice(prefix.length):path14,bytes:files.read(path14)})));return{name:skill.name,slug:skillSlugOf(skill),request:create2(PushSkillRequestSchema,{org:identity2.org,artifact:archive,tag:tag2,message:message6,labels:memberLabels(identity2)})}})}function carriesAgent(plugin2){return plugin2.skills.length>0||plugin2.subAgents.length>0||plugin2.overlay.agent!==void 0}function planAgent(plugin2,overlayAgent,mcpServers,identity2,warnings){if(!carriesAgent(plugin2))return;let member2={name:identity2.name,slug:identity2.slug};if(overlayAgent!==void 0)return{...member2,resource:create2(AgentSchema,{apiVersion:"agentic.stigmer.ai/v1",kind:"Agent",metadata:memberMetadata(identity2,member2,overlayAgent.metadata),spec:overlayAgent.spec})};let serverSlugs=plugin2.mcpServers.map(mcpServerSlugOf),skillSlugByName=new Map(plugin2.skills.map(skill=>[skill.name,skillSlugOf(skill)])),spec=create2(AgentSpecSchema,{description:plugin2.description??"",instructions:renderDefaultAgentInstructions(plugin2),env:toolVariables(mcpServers),skillRefs:[...skillSlugByName.values()].map(slug=>create2(ApiResourceReferenceSchema,{org:identity2.org,kind:ApiResourceKind.skill,slug})),mcpServerUsages:serverSlugs.map(slug=>create2(McpServerUsageSchema,{mcpServerRef:create2(ApiResourceReferenceSchema,{org:identity2.org,kind:ApiResourceKind.mcp_server,slug})})),subAgents:plugin2.subAgents.map(subAgent=>planSubAgent(subAgent,identity2,serverSlugs,skillSlugByName,warnings))});return{...member2,resource:create2(AgentSchema,{apiVersion:"agentic.stigmer.ai/v1",kind:"Agent",metadata:memberMetadata(identity2,member2),spec})}}function toolVariables(mcpServers){let declarations={};for(let server of mcpServers){let spec=server.resource.spec;if(spec===void 0)continue;let oauthTarget=spec.auth?.targetEnvVar??"";for(let[name,declaration]of Object.entries(spec.env))name===oauthTarget||name in declarations||(declarations[name]=declaration)}return declarations}function planSubAgent(subAgent,identity2,serverSlugs,skillSlugByName,warnings){BUILT_IN_SUB_AGENT_NAMES.has(subAgent.name)&&warnings.push(create2(PluginWarningSchema,{kind:SERVER_WARNING_KINDS.subAgentNameBuiltin,path:subAgent.path,message:`sub-agent '${subAgent.name}' shares its name with a built-in sub-agent; the runner warns and runs the plugin's`}));let hint=subAgent.modelHint;return hint!==void 0&&hint.alias!=="inherit"&&hint.alias!=="unknown"&&warnings.push(create2(PluginWarningSchema,{kind:SERVER_WARNING_KINDS.modelHintUnresolved,path:subAgent.path,message:`sub-agent '${subAgent.name}' names model '${hint.raw}'; Stigmer does not pin a model from a plugin, so it runs on the session's model`})),create2(SubAgentSchema,{name:subAgent.name,description:subAgent.description??"",instructions:subAgent.instructions,mcpAccess:serverSlugs.map(slug=>create2(McpAccessSchema,{mcpServer:slug})),skillRefs:subAgent.skillNames.flatMap(name=>{let slug=skillSlugByName.get(name);return slug===void 0?[]:[create2(ApiResourceReferenceSchema,{org:identity2.org,kind:ApiResourceKind.skill,slug})]})})}function workflowSlugOf(name){return generateSlug(name)}function planWorkflows(overlays,identity2){return overlays.map(({name,resource})=>{let slug=workflowSlugOf(name);return{name,slug,resource:create2(WorkflowSchema,{apiVersion:"agentic.stigmer.ai/v1",kind:"Workflow",metadata:memberMetadata(identity2,{name,slug},resource.metadata),spec:resource.spec})}})}function versionTag(version,warnings){return version===void 0||version===""?"":VERSION_TAG_PATTERN.test(version)?version:(warnings.push(create2(PluginWarningSchema,{kind:SERVER_WARNING_KINDS.versionNotTaggable,message:`version '${version}' cannot be a tag (letters, digits, '.', '_' and '-' only); this version is reachable by its digest but not by name`})),"")}function planMaterialization(plugin2,files,overlays,identity2,message6){let warnings=[];for(let ignored of plugin2.ignored)warnings.push(create2(PluginWarningSchema,{kind:SERVER_WARNING_KINDS.componentIgnored,path:ignored.path,message:`${ignored.kind} at '${ignored.path}' is not installed; Stigmer reads skills, MCP servers, sub-agents and the ai.stigmer/ overlay`}));let tag2=versionTag(plugin2.version,warnings),skills=planSkills(plugin2,files,identity2,tag2,message6),mcpServers=planMcpServers(plugin2,new Map(overlays.mcpServers.map(document2=>[document2.server,document2.resource])),identity2),agent=planAgent(plugin2,overlays.agent?.resource,mcpServers,identity2,warnings),workflows=planWorkflows(overlays.workflows,identity2),members=[...skills.map(skill=>({kind:ApiResourceKind.skill,slug:skill.slug,name:skill.name,system:skill.request.labels[SYSTEM_LABEL]===RESERVED_LABEL_TRUE})),...mcpServers.map(server=>({kind:ApiResourceKind.mcp_server,slug:server.slug,name:server.name,system:isSystemContent(server.resource.metadata)})),...agent===void 0?[]:[{kind:ApiResourceKind.agent,slug:agent.slug,name:agent.name,system:isSystemContent(agent.resource.metadata)}],...workflows.map(workflow=>({kind:ApiResourceKind.workflow,slug:workflow.slug,name:workflow.name,system:isSystemContent(workflow.resource.metadata)}))];return{skills,mcpServers,agent,workflows,members,tag:tag2,warnings}}function getDefaultExportFromCjs(x2){return x2&&x2.__esModule&&Object.prototype.hasOwnProperty.call(x2,"default")?x2.default:x2}var jsYaml={},loader={},common={},hasRequiredCommon;function requireCommon(){if(hasRequiredCommon)return common;hasRequiredCommon=1;function isNothing(subject){return typeof subject>"u"||subject===null}function isObject4(subject){return typeof subject=="object"&&subject!==null}function toArray(sequence){return Array.isArray(sequence)?sequence:isNothing(sequence)?[]:[sequence]}function extend(target,source){if(source){let sourceKeys=Object.keys(source);for(let index2=0,length=sourceKeys.length;index2<length;index2+=1){let key=sourceKeys[index2];target[key]=source[key]}}return target}function repeat(string,count){let result="";for(let cycle=0;cycle<count;cycle+=1)result+=string;return result}function isNegativeZero(number){return number===0&&Number.NEGATIVE_INFINITY===1/number}return common.isNothing=isNothing,common.isObject=isObject4,common.toArray=toArray,common.repeat=repeat,common.isNegativeZero=isNegativeZero,common.extend=extend,common}var exception,hasRequiredException;function requireException(){if(hasRequiredException)return exception;hasRequiredException=1;function formatError2(exception2,compact){let where="",message6=exception2.reason||"(unknown reason)";return exception2.mark?(exception2.mark.name&&(where+='in "'+exception2.mark.name+'" '),where+="("+(exception2.mark.line+1)+":"+(exception2.mark.column+1)+")",!compact&&exception2.mark.snippet&&(where+=`
@@ -1548,7 +1548,7 @@ Headers: `+JSON.stringify(headers2)),this.code=code,this.body=body,this.headers=
1548
1548
  \r
1549
1549
  SM\r
1550
1550
  \r
1551
- `,"latin1");function createProtocolDemuxServer(targets){return(0,import_node_net4.createServer)({noDelay:!0},socket=>{routeByPreface(socket,targets)})}function routeByPreface(socket,targets){let peeked=[],peekedLength=0,cleanup=()=>{socket.removeListener("data",onData),socket.removeListener("error",onPeekError),socket.removeListener("close",cleanup)},onPeekError=()=>{cleanup(),socket.destroy()},onData=chunk=>{peeked.push(chunk),peekedLength+=chunk.length;let seen=Buffer.concat(peeked,Math.min(peekedLength,HTTP2_CONNECTION_PREFACE.length)),comparable=seen.subarray(0,Math.min(seen.length,HTTP2_CONNECTION_PREFACE.length));if(!HTTP2_CONNECTION_PREFACE.subarray(0,comparable.length).equals(comparable)){handoffHttp1();return}if(peekedLength>=HTTP2_CONNECTION_PREFACE.length){handoffHttp2();return}};function handoffHttp1(){cleanup(),socket.pause(),socket.unshift(Buffer.concat(peeked,peekedLength)),targets.http1.emit("connection",socket),socket.resume()}function handoffHttp2(){cleanup(),socket.pause();let replay=createReplayDuplex(socket,Buffer.concat(peeked,peekedLength));targets.http2.emit("connection",replay)}socket.on("data",onData),socket.on("error",onPeekError),socket.on("close",cleanup)}function createReplayDuplex(socket,head){let replay=new import_node_stream13.Duplex({read(){socket.resume()},write(chunk,encoding,callback){socket.write(chunk,encoding,callback)},final(callback){socket.end(callback)},destroy(error2,callback){socket.destroy(),callback(error2)}});return socket.on("data",chunk=>{replay.push(chunk)||socket.pause()}),socket.on("end",()=>{replay.push(null)}),socket.on("error",error2=>{replay.destroy(error2)}),replay.push(head),replay}function createUnifiedPortServer(options){let rpcHandler=connectNodeAdapter({routes:options.routes,interceptors:options.interceptors,readMaxBytes:10485760,writeMaxBytes:10485760}),laneRouter=(request,response)=>{let path14=(request.url??"").split("?",1)[0]??"";if(path14===TASK_KIND_REGISTRY_PATH){options.taskKindRegistryLane(request,response);return}if(path14===MODEL_REGISTRY_PATH){options.modelRegistryLane(request,response);return}if(options.skillTransferLane!==void 0&&path14.startsWith(SKILL_ARTIFACTS_PATH_PREFIX)){options.skillTransferLane(request,response);return}if(options.consoleLane!==void 0&&consoleLaneEligible(request)){options.consoleLane(request,response);return}if(isRpcPreflight(request)){handleRpcPreflight(request,response);return}applyRpcCorsHeaders(request,response),rpcHandler(request,response)},http1=(0,import_node_http4.createServer)(laneRouter),http22=(0,import_node_http22.createServer)(laneRouter),liveSessions=new Set;http22.on("session",session=>{liveSessions.add(session),session.on("close",()=>liveSessions.delete(session)),armKeepalivePings(session,options.logger)}),http22.on("sessionError",error2=>{options.logger.debug("http2 session error",{error:String(error2)})});let demux=createProtocolDemuxServer({http1,http2:http22}),liveSockets=new Set;return demux.on("connection",socket=>{liveSockets.add(socket),socket.on("close",()=>liveSockets.delete(socket))}),{listen(port,host="0.0.0.0"){return new Promise((resolve,reject2)=>{demux.once("error",reject2),demux.listen(port,host,()=>{let address=demux.address();if(address===null||typeof address=="string"){reject2(new Error("unified port bound without a TCP address"));return}resolve(address.port)})})},async shutdown(){let closed=new Promise(resolve=>demux.close(()=>resolve()));http1.close(),http1.closeIdleConnections(),http22.close();for(let session of liveSessions)session.close();await Promise.race([closed.then(()=>!0),new Promise(resolve=>setTimeout(()=>resolve(!1),1e4).unref())])||options.logger.warn("shutdown drain budget exhausted; destroying remaining connections",{remaining:liveSockets.size});for(let socket of liveSockets)socket.destroy();await closed}}}function armKeepalivePings(session,logger2){let interval=setInterval(()=>{let acked=!1,deadline=setTimeout(()=>{!acked&&!session.destroyed&&(logger2.debug("closing http2 session: keepalive ping unacknowledged"),session.destroy())},5e3);deadline.unref();try{session.ping(()=>{acked=!0,clearTimeout(deadline)})}catch{clearTimeout(deadline),session.destroyed||session.destroy()}},15e3);interval.unref(),session.on("close",()=>clearInterval(interval))}function registerExtensionServicesUnshadowed(router,registrations){let servedBy=new Map(router.handlers.map(handler=>[handler.requestPath,"the core"]));for(let{unit,register}of registrations){let before=router.handlers.length;register(router);for(let handler of router.handlers.slice(before)){let server=servedBy.get(handler.requestPath);if(server!==void 0)throw new Error(`extension '${unit}' registers ${handler.requestPath}, which ${server} already serves \u2014 a route is never registered twice; an edition changes a core domain's behaviour through its driver points`);servedBy.set(handler.requestPath,`extension '${unit}'`)}}}function createInProcessClients(routes,logger2){let transport=createRouterTransport(routes,{router:{interceptors:buildInterceptorChain(logger2,createInProcessCallerInterceptor())}}),agentInstanceCommand=createClient(AgentInstanceCommandController,transport),agentInstanceQuery=createClient(AgentInstanceQueryController,transport),agentQuery=createClient(AgentQueryController,transport),sessionCommand=createClient(SessionCommandController,transport),sessionQuery=createClient(SessionQueryController,transport),environmentCommand=createClient(EnvironmentCommandController,transport),environmentQuery=createClient(EnvironmentQueryController,transport),executionContextCommand=createClient(ExecutionContextCommandController,transport),workflowInstanceCommand=createClient(WorkflowInstanceCommandController,transport),workflowInstanceQuery=createClient(WorkflowInstanceQueryController,transport),workflowQuery=createClient(WorkflowQueryController,transport),agentExecutionCommand=createClient(AgentExecutionCommandController,transport),agentCommand=createClient(AgentCommandController,transport),workflowCommand=createClient(WorkflowCommandController,transport),mcpServerCommand=createClient(McpServerCommandController,transport),skillCommand=createClient(SkillCommandController,transport),asCaller=caller=>({headers:{[IN_PROCESS_CALLER_HEADER]:encodeInProcessCaller(caller)}}),clients={agentInstanceApplier:{applyAsCaller:(instance,caller)=>agentInstanceCommand.apply(instance,asCaller(caller))},parentAgentLoader:{get:agentId=>agentQuery.get(create2(AgentIdSchema,{value:agentId}))},workflowInstanceCreator:{createAsCaller:(instance,caller)=>workflowInstanceCommand.create(instance,asCaller(caller))},parentWorkflowLoader:{get:workflowId=>workflowQuery.get(create2(WorkflowIdSchema,{value:workflowId}))},executionAgentLoader:{get:agentId=>agentQuery.get(create2(AgentIdSchema,{value:agentId}))},executionAgentInstanceLoader:{get:instanceId=>agentInstanceQuery.get(create2(AgentInstanceIdSchema,{value:instanceId}))},executionAgentInstanceCreator:{createAsCaller:(instance,caller)=>agentInstanceCommand.create(instance,asCaller(caller))},executionSessionLoader:{get:sessionId=>sessionQuery.get(create2(SessionIdSchema,{value:sessionId}))},executionSessionCreator:{createAsCaller:(session,caller)=>sessionCommand.create(session,asCaller(caller))},executionEnvironmentReader:{list:request=>environmentQuery.list(request),getSecretValue:input=>environmentQuery.getSecretValue(input),updateVariables:request=>environmentCommand.updateVariables(request),create:(environment,caller)=>environmentCommand.create(environment,caller===void 0?void 0:asCaller(caller)),delete:input=>environmentCommand.delete(input)},executionContextCreator:{create:ec2=>executionContextCommand.create(ec2)},connectExecutionContextClient:{create:(ec2,caller)=>executionContextCommand.create(ec2,asCaller(caller)),delete:input=>executionContextCommand.delete(input)},workflowExecutionInstanceCreator:{createAsCaller:(instance,caller)=>workflowInstanceCommand.create(instance,asCaller(caller))},workflowExecutionInstanceLoader:{get:instanceId=>workflowInstanceQuery.get(create2(WorkflowInstanceIdSchema,{value:instanceId}))},workflowExecutionContextCreator:{create:ec2=>executionContextCommand.create(ec2)},workflowExecutionApprovalForwarder:{submitApproval:input=>agentExecutionCommand.submitApproval(input)},workflowExecutionFileDecisionForwarder:{submitFileDecision:input=>agentExecutionCommand.submitFileDecision(input)},scheduleExecutionCreator:{create:(execution,fireCaller)=>agentExecutionCommand.create(execution,fireCaller===void 0?void 0:asCaller(fireCaller))},executionStatusWriter:{updateStatus:input=>agentExecutionCommand.updateStatus(input)},pluginMaterializer:{pushSkill:(request,caller)=>skillCommand.push(request,asCaller(caller)),applyMcpServer:(server,caller)=>mcpServerCommand.apply(server,asCaller(caller)),applyAgent:(agent,caller)=>agentCommand.apply(agent,asCaller(caller)),applyWorkflow:(workflow,caller)=>workflowCommand.apply(workflow,asCaller(caller)),updateVisibility:(kind,resourceId,visibility,caller)=>updateVisibilityByKind(kind,resourceId,visibility,asCaller(caller)),deleteByKind:(kind,resourceId,caller)=>deleteByKind(kind,resourceId,asCaller(caller))}};async function deleteByKind(kind,resourceId,options){switch(kind){case ApiResourceKind.agent:await agentCommand.delete(create2(AgentIdSchema,{value:resourceId}),options);return;case ApiResourceKind.workflow:await workflowCommand.delete(create2(WorkflowIdSchema,{value:resourceId}),options);return;case ApiResourceKind.mcp_server:await mcpServerCommand.delete(create2(ApiResourceDeleteInputSchema,{resourceId}),options);return;case ApiResourceKind.skill:await skillCommand.delete(create2(SkillIdSchema,{value:resourceId}),options);return;default:throw new Error(`unsupported resource kind for delete: ${ApiResourceKind[kind]??String(kind)}`)}}async function updateVisibilityByKind(kind,resourceId,visibility,options){let input=create2(UpdateVisibilityInputSchema,{resourceId,visibility});switch(kind){case ApiResourceKind.agent:await agentCommand.updateVisibility(input,options);return;case ApiResourceKind.workflow:await workflowCommand.updateVisibility(input,options);return;case ApiResourceKind.mcp_server:await mcpServerCommand.updateVisibility(input,options);return;case ApiResourceKind.skill:await skillCommand.updateVisibility(input,options);return;default:throw new Error(`unsupported resource kind for updateVisibility: ${ApiResourceKind[kind]??String(kind)}`)}}return{clients,transport}}var LIST_INDEXES=[agentExecutionListIndex,artifactListIndex,iamPolicyListIndex,sessionListIndex,workflowExecutionListIndex];async function composeServer(options){let{config:config2,logger:logger2}=options,extensions=resolveExtensions(options.extensions);extensions.unitNames.length>0&&logger2.info("extension units composed",{units:extensions.unitNames.join(", ")});let store,storeOptions={listIndexes:LIST_INDEXES};config2.databaseUrl!==""?(store=await PostgresStore.open(config2.databaseUrl,logger2,storeOptions),logger2.info("storage driver selected",{driver:"postgres"})):(store=SqliteStore.open(config2.dbPath,logger2,storeOptions),logger2.info("storage driver selected",{driver:"sqlite",dbPath:config2.dbPath}));let authEnabled=config2.oidcIssuer!=="",requireAuthentication=authEnabled||extensions.requireAuthentication!==void 0,authorizationPosture=authorizationPostureOf({unitAuthorizer:extensions.authorizer!==void 0,requireAuthentication}),builtInAuthorization=authorizationPosture!=="unit-authorizer";if(authorizationPosture==="built-in"&&extensions.edition!==ServerEdition.oss)throw new Error(`the composition serves edition '${ServerEdition[extensions.edition]}' under the require-authentication posture but registers no Authorizer \u2014 the built-in authorizer enforces the open-source kinds only; register an Authorizer or serve the open-source edition`);let identityAccounts=extensions.drivers.identityAccountStore??newResourceIdentityAccountStore(store),iamPolicies=extensions.drivers.iamPolicyStore??newResourceIamPolicyStore(store),platformClients=extensions.drivers.platformClientStore??newResourcePlatformClientStore(store),iamPolicyGrantPath=newIamPolicyGrantPath({policies:iamPolicies,lifecycle:extensions.drivers.resourceAuthorizationLifecycle,logger:logger2}),authorizationLifecycle=extensions.drivers.resourceAuthorizationLifecycle,roleLifecycle=authorizationLifecycle??(builtInAuthorization?newBuiltInRoleLifecycle({grantPath:iamPolicyGrantPath,accounts:identityAccounts}):void 0),operatorIdentity=operatorIdentitySnapshot(),membership=builtInAuthorization?newMembershipRules({grantPath:iamPolicyGrantPath,policies:iamPolicies,store,operatorEmail:operatorIdentity.email}):void 0,runnerAuthService=RunnerAuthService.fromEnv(),runnerCredentials=extensions.drivers.runnerCredentialProvider??(authorizationPosture==="built-in"?newBuiltInRunnerCredentialProvider({service:runnerAuthService,store,accounts:identityAccounts}):newExecutionScopedRunnerCredentialProvider(runnerAuthService)),authorizer=extensions.authorizer??(authorizationPosture==="built-in"?newLaneAdmittedAuthorizer(newBuiltInAuthorizer({store,policies:iamPolicies,accounts:identityAccounts,edition:extensions.edition,logger:logger2}),caller=>isWorkflowBoundRunner(runnerAuthService,caller)):newPermissiveSingleTeamAuthorizer()),organizationDirectory=extensions.drivers.organizationDirectory??(authorizationPosture==="built-in"?newBuiltInOrganizationDirectory({store,policies:iamPolicies,accounts:identityAccounts}):void 0),scheduleFireCaller=extensions.drivers.scheduleFireCaller??(authorizationPosture==="built-in"?newBuiltInScheduleFireCaller({store,accounts:identityAccounts}):void 0),listReadScope=extensions.drivers.listReadScope??(authorizationPosture==="built-in"?newBuiltInListReadScope({store,policies:iamPolicies,accounts:identityAccounts,logger:logger2}):void 0),personAccounts=requireAuthentication?identityAccounts:void 0;logger2.info("authorization posture resolved",{posture:authorizationPosture,authorizer:extensions.authorizer!==void 0?"extension":authorizationPosture==="built-in"?"built-in":"permissive",listReadScope:extensions.drivers.listReadScope!==void 0?"extension":authorizationPosture==="built-in"?"built-in":"none"});let identityAccountPath={accounts:identityAccounts,logger:logger2,authorizer,authorizationLifecycle:roleLifecycle},createIdentityAccount=newCreateAccountPath(identityAccountPath,ApiResourceKind.identity_account),issuerDiscovery=newIssuerDiscovery(),identityAccountProvisioner=newDirectAccountProvisioner({accounts:identityAccounts,createAccount:createIdentityAccount,userInfo:newOidcUserInfoClient(issuerDiscovery)});if(!requireAuthentication){let operator=await ensureOperatorAccount({accounts:identityAccounts,createAccount:createIdentityAccount},operatorIdentity);logger2.info("trusted-local operator account ensured",{accountId:operator.metadata?.id??""}),membership!==void 0&&(await membership.ensureOperatorOwnership(operator),logger2.info("trusted-local operator ownership ensured",{accountId:operator.metadata?.id??""}))}authorizationPosture==="built-in"&&membership!==void 0&&(await membership.ensureRolesForExistingAccounts(),logger2.info("built-in posture role reconciliation ensured"));let v1Key;try{v1Key=getOrCreateNamedKey(ENCRYPTION_KEY_ENV_VAR,ENCRYPTION_KEY_FILE_NAME)}catch(error2){logger2.warn("Failed to initialize encryption - secret values will be stored in plaintext",{error:error2 instanceof Error?error2.message:String(error2)}),v1Key=void 0}let secretCodecs=new Map([[V1_VERSION,new StaticKeySecretCodec(v1Key)],...extensions.drivers.secretCodecs]),writeVersionValue=process.env[ENCRYPTION_WRITE_VERSION_ENV_VAR]??"",secretService=SecretService.withCodecs({codecs:secretCodecs,writeVersion:writeVersionValue===""?DEFAULT_WRITE_VERSION:writeVersionValue});logger2.info("secret encryption configured",{writeVersion:writeVersionValue===""?DEFAULT_WRITE_VERSION:writeVersionValue,registeredCodecs:[...secretCodecs.keys()].sort()});let platformTokenKeys=resolvePlatformTokenKeys({requireAuthentication,supplied:extensions.drivers.platformTokenKeys,edition:extensions.edition});logger2.info("platform-token keys resolved",{source:platformTokenKeys===void 0?"none (no authentication posture)":extensions.drivers.platformTokenKeys!==void 0?"extension":"open-source ladder",signing:platformTokenKeys?.signer!==void 0});let temporalConfig=newConfigFromEnv(),workflowExecutionTemporalConfig=newWorkflowExecutionConfigFromEnv(),sandboxProvisioner=newSandboxProvisioner(config2.sandboxProvisionerType,{config:{backendEndpoint:config2.sandboxBackendEndpoint,temporalAddress:config2.sandboxTemporalAddress,temporalNamespace:config2.temporalNamespace,temporalConnectionEnv:temporalConnectionEnv(config2.temporalConnection),runnerImage:config2.sandboxRunnerImage,runnerCommand:config2.sandboxRunnerCommand,kubernetesNamespace:config2.sandboxKubernetesNamespace},logger:logger2},builtInSandboxProvisionerFactories(),extensions.drivers.sandboxProvisionerDrivers);if(sandboxProvisioner!==void 0&&temporalConfig.activityRouting!==ROUTING_SESSION&&workflowExecutionTemporalConfig.workflowActivityRouting!==WORKFLOW_ROUTING_EXECUTION)throw new Error(`SANDBOX_PROVISIONER_TYPE='${config2.sandboxProvisionerType}' requires a per-queue routing mode \u2014 set STIGMER_ACTIVITY_ROUTING=session and/or STIGMER_WORKFLOW_ACTIVITY_ROUTING=execution (a provisioner no dispatch can reach must fail loudly, not sit dark)`);let sandboxLane=newSandboxLane(sandboxProvisioner,runnerCredentials);sandboxLane.enabled&&logger2.info("sandbox provisioner composed",{type:config2.sandboxProvisionerType});let workflowSandboxTerminalObserver=newWorkflowSandboxTerminalObserver(sandboxLane,logger2),healthState=new HealthState,modelCatalog,ossModelRegistryStore;extensions.drivers.modelCatalogProvider!==void 0?modelCatalog=extensions.drivers.modelCatalogProvider:(ossModelRegistryStore=new ModelRegistryStore({bundledDocument:bundledModelRegistryDocument(),upstreamOrigin:config2.modelRegistryUpstream,refreshEnabled:config2.modelRegistryRefreshEnabled,logger:logger2,fetchImpl:options.fetchImpl}),modelCatalog=ossModelRegistryStore);let registryLanes=createRegistryLanes({taskKindRegistryDocument:bundledTaskKindRegistryDocument(),modelRegistryStore:modelCatalog}),workflowValidator=new InProcessValidator(modelCatalog,logger2),agentExecutionStreamBroker=new StreamBroker(logger2),workflowExecutionStreamBroker=new StreamBroker2(logger2),scheduleTemporalConfig=newScheduleConfigFromEnv(),scheduleClientProvider=()=>temporalManager.getClient(),scheduleArtifact=new ScheduleArtifact(scheduleTemporalConfig),scheduleSyncer=new ScheduleSyncer(scheduleClientProvider,store,scheduleArtifact,logger2),scheduleRunStarter=new RunStarter({store,config:scheduleTemporalConfig,executions:{create:(execution,fireCaller)=>requireInProcess().scheduleExecutionCreator.create(execution,fireCaller)},fireCallerMint:scheduleFireCaller,logger:logger2}),scheduleReconciler=new ScheduleReconciler(scheduleClientProvider,store,scheduleSyncer,scheduleTemporalConfig,logger2),temporalManager=new TemporalManager({hostPort:config2.temporalHostPort,namespace:config2.temporalNamespace,connection:config2.temporalConnection,logger:logger2,payloadCodecs:loadServerPayloadCodecs(runnerCredentials.resolvePayloadKey?.bind(runnerCredentials)),workerFactories:[newAgentExecutionWorkerFactory({store,logger:logger2,statusWriter:()=>requireInProcess().executionStatusWriter,temporalConfig}),newWorkflowExecutionWorkerFactory({store,logger:logger2,broker:workflowExecutionStreamBroker,temporalConfig:workflowExecutionTemporalConfig,sandboxTerminalObserver:workflowSandboxTerminalObserver}),newScheduleWorkerFactory({store,config:scheduleTemporalConfig,syncer:scheduleSyncer,runStarter:scheduleRunStarter,logger:logger2}),...extensions.workers]}),executionEngineState=newExecutionEngineStateProvider({manager:temporalManager,config:temporalConfig,store,runnerCredentials,logger:logger2}),workflowExecutionEngineState=newWorkflowExecutionEngineStateProvider({manager:temporalManager,config:workflowExecutionTemporalConfig,runnerCredentials,logger:logger2}),artifactLanePort=resolveArtifactLanePort({configured:config2.artifactHttpPort,unifiedPort:options.portOverride??config2.grpcPort}),artifactLaneBoundPort,artifactStorage=newArtifactStorage({type:config2.artifactStorageType,localBasePath:config2.artifactLocalBasePath,localServeUrl:resolveArtifactServeUrl(config2.artifactLocalServeUrl,()=>artifactLaneBoundPort),r2Bucket:config2.r2Bucket,r2Endpoint:config2.r2Endpoint,r2AccessKeyId:config2.r2AccessKeyId,r2SecretAccessKey:config2.r2SecretAccessKey,r2Region:config2.r2Region},extensions.drivers.artifactStorageDrivers),artifactFileServer=config2.artifactStorageType==="local"?createArtifactFileServer({basePath:config2.artifactLocalBasePath,logger:logger2}):void 0,skillUploadSlots=new UploadSlots(config2.storagePath,STAGING_KEY_PREFIX,DEFAULT_SLOT_TTL_MS,104857600),skillType=config2.skillArtifactStorageType===""?"local":config2.skillArtifactStorageType,skillStorageDriver=skillType==="local"?((0,import_node_fs16.mkdirSync)(import_node_path18.default.join(config2.storagePath,"skills"),{recursive:!0,mode:493}),new LocalArtifactStorage(config2.storagePath,transferServeUrl(config2.skillTransferBaseUrl),{reserve:(key,declaredSizeBytes)=>{let{ttlMs}=skillUploadSlots.reserve(key,declaredSizeBytes);return{url:uploadUrl(config2.skillTransferBaseUrl,uploadRefOf(key)),ttlMs}}})):newArtifactStorage({type:skillType,localBasePath:config2.storagePath,localServeUrl:"",r2Bucket:config2.r2Bucket,r2Endpoint:config2.r2Endpoint,r2AccessKeyId:config2.r2AccessKeyId,r2SecretAccessKey:config2.r2SecretAccessKey,r2Region:config2.r2Region},extensions.drivers.artifactStorageDrivers),skillArtifactStorage=newSkillArtifactStorage(skillStorageDriver),pluginArtifactStorage=newContentAddressedArchiveStore(skillStorageDriver,PLUGIN_ARTIFACT_KEY_PREFIX),skillArchiveStaging=newArchiveStaging(skillStorageDriver,logger2),skillTransferLane=newSkillTransferLane(skillUploadSlots,skillArtifactStorage,logger2),transferOrigin=assessSkillTransferOrigin({baseUrl:config2.skillTransferBaseUrl,relaysThroughServer:skillType==="local",requireAuthentication});transferOrigin.kind==="loopback-hosted"&&logger2.warn("skill artifact transfer lane mints capability URLs on the server's own loopback while the server requires authentication; pushes above the gRPC message cap and sandbox skill downloads will fail \u2014 set SKILL_TRANSFER_BASE_URL to the origin callers reach this server on",{baseUrl:transferOrigin.baseUrl});let consoleAssets=resolveConsoleAssets(config2.consoleDir,logger2);consoleAssets!==void 0?logger2.info("web console serving from unified port",{dir:consoleAssets.root,files:consoleAssets.fileCount}):logger2.debug("no web console export bundled; console lane disabled");let consoleSignIn=authEnabled?{posture:"oidc",issuer:config2.oidcIssuer,audience:config2.oidcAudience,consoleClientId:config2.oidcConsoleClientId}:{posture:"trusted-local"};consoleAssets!==void 0&&consoleSignIn.posture==="oidc"&&consoleSignIn.consoleClientId===""&&logger2.warn("STIGMER_OIDC_ISSUER is set but STIGMER_OIDC_CONSOLE_CLIENT_ID is not \u2014 the web console this server serves cannot sign in; register a public PKCE client for the console at the issuer and set it");let consoleLane=consoleAssets!==void 0?createConsoleLane({assets:consoleAssets,signIn:consoleSignIn,logger:logger2}):void 0,searchRegistry=newSearchableResourceRegistry();searchRegistry.validateExpectedKinds(logger2);let searchQueryStore=new SqliteSearchQueryStore(store,searchRegistry,logger2),searchHandler=new SearchHandler(searchQueryStore,logger2,listReadScope),activityHandler=new ActivityHandler(store,logger2,listReadScope),environmentResolution=new RuntimeResolutionService(store,secretService,logger2),managedEnvService=new ManagedEnvironmentService({getSecretValue:input=>requireInProcess().executionEnvironmentReader.getSecretValue(input),updateVariables:request=>requireInProcess().executionEnvironmentReader.updateVariables(request),create:(environment,caller)=>requireInProcess().executionEnvironmentReader.create(environment,caller),delete:input=>requireInProcess().executionEnvironmentReader.delete(input)},logger2),mcpServerEngineState=newMcpServerEngineStateProvider({manager:temporalManager,config:temporalConfig,logger:logger2}),oauthRedirect=resolveOAuthRedirectUri({configured:config2.oauthRedirectUri,servesConsole:consoleAssets!==void 0,port:options.portOverride??config2.grpcPort});switch(oauthRedirect.kind){case"configured":break;case"derived":logger2.info("STIGMER_OAUTH_REDIRECT_URI is not set \u2014 deriving the served console's callback for MCP server OAuth Connect",{redirectUri:oauthRedirect.uri});break;case"absent":logger2.warn("STIGMER_OAUTH_REDIRECT_URI is not set \u2014 OAuth Connect flows for MCP servers are unavailable (initiateOAuthConnect will refuse)");break;default:{let exhaustive=oauthRedirect;throw new Error(String(exhaustive))}}let oauthRedirectUri=oauthRedirect.kind==="absent"?"":oauthRedirect.uri,outboundFetch=guardedFetch(extensions.drivers.outboundEgress??relaxedEgressPolicy(),{fetchImpl:options.fetchImpl??fetch,lookup:nodeLookup()}),inProcess;function requireInProcess(){if(inProcess===void 0)throw new Error("in-process clients not wired (boot ordering bug)");return inProcess}let routes=router=>{registerHealthService(router,healthState),registerOrganizationServices(router,{store,logger:logger2,authorizer,gateSteps:extensions.gateSteps,grantPath:iamPolicyGrantPath,authorizationLifecycle:roleLifecycle,organizationDirectory}),registerApiKeyServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,listReadScope}),registerIdentityAccountServices(router,{...identityAccountPath,provisioner:identityAccountProvisioner,federation:extensions.drivers.identityFederation,gateSteps:extensions.gateSteps,membership}),registerIamPolicyServices(router,{grantPath:iamPolicyGrantPath,policies:iamPolicies,accounts:identityAccounts,authorizer,grantScope:extensions.drivers.policyGrantScope??newOrganizationOnlyGrantScope(),queries:extensions.drivers.authorizationQueries,principalDisplay:extensions.drivers.principalDisplay,gateSteps:extensions.gateSteps,edition:extensions.edition,logger:logger2}),registerEnvironmentServices(router,{store,logger:logger2,authorizer,secretService,authorizationLifecycle,listReadScope}),registerOAuthAppServices(router,{store,secretService,logger:logger2,authorizer,authorizationLifecycle,listReadScope}),registerPlatformClientServices(router,{clients:platformClients,store,logger:logger2,authorizer,authorizationLifecycle,listReadScope}),registerPlatformClientTokenService(router,{mint:{clients:platformClients,accounts:identityAccounts,createAccount:createIdentityAccount,grantPath:iamPolicyGrantPath,keys:platformTokenKeys,logger:logger2,now:()=>new Date},guestTokenMinting:extensions.drivers.guestTokenMinting}),registerExecutionContextServices(router,{store,logger:logger2,authorizer,secretService,runnerAuthService:runnerCredentials,authorizationLifecycle}),registerAgentServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,agentInstanceApplier:()=>requireInProcess().agentInstanceApplier}),registerAgentInstanceServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,parentAgentLoader:()=>requireInProcess().parentAgentLoader,listReadScope}),registerSessionServices(router,{store,logger:logger2,authorizer,temporalConfig,gateSteps:extensions.gateSteps,sandboxLane,authorizationLifecycle,listReadScope}),registerAgentShareServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,listReadScope}),registerAgentChannelServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,listReadScope,modelRegistry:modelCatalog,channelRuntime:extensions.drivers.channelRuntime}),registerChannelMessageServices(router,extensions.drivers.channelRuntime),registerChannelConversationServices(router,extensions.drivers.channelRuntime),registerChannelAppServices(router,{store,logger:logger2,authorizer,secretService,authorizationLifecycle}),registerScheduleServices(router,{store,logger:logger2,authorizer,modelRegistry:modelCatalog,clock:()=>scheduleSyncer,runner:()=>scheduleRunStarter,authorizationLifecycle,listReadScope}),registerMemoryServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,listReadScope,personAccounts,runnerCredentialProvider:runnerCredentials}),registerAgentExecutionServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,listReadScope,personAccounts,runnerCredentialProvider:runnerCredentials,broker:agentExecutionStreamBroker,engineState:executionEngineState,modelRegistry:modelCatalog,artifactStorage,gateSteps:extensions.gateSteps,statusObservers:extensions.statusObservers,responseDecorators:extensions.responseDecorators,sandboxLane,temporalConfig,agentLoader:()=>requireInProcess().executionAgentLoader,agentInstanceCreator:()=>requireInProcess().executionAgentInstanceCreator,sessionCreator:()=>requireInProcess().executionSessionCreator,executionContextBuilder:{store,logger:logger2,agentLoader:()=>requireInProcess().executionAgentLoader,agentInstanceLoader:()=>requireInProcess().executionAgentInstanceLoader,sessionLoader:()=>requireInProcess().executionSessionLoader,environmentReader:()=>requireInProcess().executionEnvironmentReader,environmentResolution,executionContextCreator:()=>requireInProcess().executionContextCreator,managedEnvService,platformClients,fetchImpl:asFetch(outboundFetch)}}),registerWorkflowServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,validator:workflowValidator,workflowInstanceCreator:()=>requireInProcess().workflowInstanceCreator}),registerWorkflowInstanceServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,parentWorkflowLoader:()=>requireInProcess().parentWorkflowLoader,listReadScope}),registerWorkflowExecutionServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,listReadScope,gateSteps:extensions.gateSteps,engineState:workflowExecutionEngineState,broker:workflowExecutionStreamBroker,sandboxLane,temporalConfig:workflowExecutionTemporalConfig,sandboxTerminalObserver:workflowSandboxTerminalObserver,workflowInstanceCreator:()=>requireInProcess().workflowExecutionInstanceCreator,approvalForwarder:()=>requireInProcess().workflowExecutionApprovalForwarder,fileDecisionForwarder:()=>requireInProcess().workflowExecutionFileDecisionForwarder,executionContextBuilder:{store,logger:logger2,workflowInstanceLoader:()=>requireInProcess().workflowExecutionInstanceLoader,environmentResolution,executionContextCreator:()=>requireInProcess().workflowExecutionContextCreator}}),registerMcpServerServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,connect:{store,logger:logger2,authorizer,engineState:mcpServerEngineState,environmentReader:{list:request=>requireInProcess().executionEnvironmentReader.list(request),getSecretValue:input=>requireInProcess().executionEnvironmentReader.getSecretValue(input)},executionContext:{create:(ec2,caller)=>requireInProcess().connectExecutionContextClient.create(ec2,caller),delete:input=>requireInProcess().connectExecutionContextClient.delete(input)},runnerAuth:runnerCredentials,managedEnv:managedEnvService,oauthGrants:store.oauthGrants,pendingOAuthStates:store.pendingOAuthStates,secretService,oauthRedirectUri,outboundFetch}}),registerSkillServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,artifactStorage:skillArtifactStorage,executionArtifactStorage:artifactStorage,staging:skillArchiveStaging}),registerPluginServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,artifactStorage:pluginArtifactStorage,materializerProvider:()=>requireInProcess().pluginMaterializer,staging:skillArchiveStaging}),registerArtifactServices(router,{store,artifactStorage,logger:logger2,authorizer}),registerSearchServices(router,{handler:searchHandler,logger:logger2}),registerActivityServices(router,{handler:activityHandler,logger:logger2}),registerGitHubServices(router,{clientId:config2.gitHubOAuthClientId,clientSecret:config2.gitHubOAuthClientSecret,logger:logger2,fetchImpl:options.fetchImpl}),registerPlatformServices(router,{runnerBootstrapTemporalAddress:config2.runnerBootstrapTemporalAddress,temporalNamespace:config2.temporalNamespace,runnerAuthService:runnerCredentials,edition:extensions.edition,version:options.version??SERVER_VERSION,authenticationRequired:requireAuthentication,licenseStatus:extensions.drivers.licenseStatus??ABSENT_LICENSE_STATUS,now:()=>new Date,logger:logger2}),registerExtensionServicesUnshadowed(router,extensions.services)},inProcessWiring=createInProcessClients(routes,logger2);inProcess=inProcessWiring.clients;let identityVerifiers=[...requireAuthentication?[newApiKeyIdentityVerifier({store,accounts:identityAccounts,logger:logger2,now:()=>new Date})]:[],...platformTokenKeys!==void 0?[newPlatformClientTokenVerifier({keys:platformTokenKeys,clients:platformClients})]:[],...authorizationPosture==="built-in"?[newRunnerSubjectIdentityVerifier({store,accounts:identityAccounts,credentials:runnerCredentials})]:[],...authEnabled?[newOidcIdentityVerifier({issuer:config2.oidcIssuer,audience:config2.oidcAudience,accounts:identityAccounts,discovery:issuerDiscovery})]:[],...extensions.identityVerifiers];if(extensions.requireAuthentication!==void 0&&extensions.identityVerifiers.length===0)throw new Error(`extension '${extensions.requireAuthentication.declaredBy}' declares the require-authentication posture, but registers no identity verifier of its own \u2014 the OSS API-key lane alone cannot admit the first caller (nobody could mint a key), so every non-public request would be refused; register a verifier or omit the declaration`);let postureSources=[...authEnabled?["oidc-issuer"]:[],...extensions.requireAuthentication!==void 0?[`extension '${extensions.requireAuthentication.declaredBy}'`]:[]],callerGuards=[...platformTokenKeys!==void 0?[newPlatformClientOriginGuard({clients:platformClients,logger:logger2})]:[],...extensions.callerGuards];logger2.info("authentication posture resolved",{posture:requireAuthentication?"required":"trusted-local",source:postureSources.length>0?postureSources.join(" + "):"none",verifiers:identityVerifiers.map(v=>v.name).join(", ")});let server=createUnifiedPortServer({logger:logger2,routes,interceptors:buildInterceptorChain(logger2,createVerifierChainInterceptor(identityVerifiers,callerGuards,logger2,requireAuthentication),{errorBoundary:createErrorBoundaryInterceptor(logger2,extensions.drivers.visitorErrorPolicy),requestMetrics:createRequestMetricsInterceptor()}),taskKindRegistryLane:registryLanes.taskKindRegistryLane,modelRegistryLane:registryLanes.modelRegistryLane,skillTransferLane,consoleLane});return{healthState,store,secrets:secretService,temporalManager,runnerAuthService,agentExecutionStreamBroker,workflowExecutionStreamBroker,inProcessTransport:inProcessWiring.transport,identityVerifiers,routes,async start(){await temporalManager.initialConnect()&&await temporalManager.startWorkers(),temporalManager.startHealthMonitor();let kickScheduleReconcile=scheduleReconciler.startReconciliation();if(temporalManager.addReconnectHook(kickScheduleReconcile),await artifactStorage.health(),artifactFileServer!==void 0){await warnOnLegacyArtifactLayout(config2.artifactLocalBasePath,logger2);try{artifactLaneBoundPort=await artifactFileServer.listen(artifactLanePort,config2.artifactHttpHost)}catch(error2){throw artifactLaneBindError(error2,config2.artifactHttpHost,artifactLanePort,config2.artifactHttpPort!==void 0)}}try{let indexed=await searchQueryStore.rebuildIndex();logger2.info("Search index rebuilt at startup",{indexed})}catch(error2){logger2.warn("Failed to rebuild search index at startup",{error:error2 instanceof Error?error2.message:String(error2)})}await initRpcMetrics(),logger2.info("request metrics",{posture:await metricsExportPosture(),instruments:"stigmer.grpc.request.count, stigmer.grpc.request.duration"}),healthState.setOverall(HealthCheckResponse_ServingStatus.SERVING),ossModelRegistryStore?.startRefresh();let port=await server.listen(options.portOverride??config2.grpcPort,options.host);return logger2.info("stigmer-server listening",{port}),port},async shutdown(){healthState.setOverall(HealthCheckResponse_ServingStatus.NOT_SERVING),ossModelRegistryStore?.stopRefresh(),await artifactFileServer?.shutdown(),await scheduleReconciler.stop(),await temporalManager.close(),await server.shutdown(),await store.close(),logger2.info("stigmer-server stopped")}}}var LEVEL_RANK={debug:10,info:20,warn:30,error:40};function createLogger(options){let threshold=LEVEL_RANK[options.level]??LEVEL_RANK.info,write2=options.write??(line=>process.stderr.write(line+`
1551
+ `,"latin1");function createProtocolDemuxServer(targets){return(0,import_node_net4.createServer)({noDelay:!0},socket=>{routeByPreface(socket,targets)})}function routeByPreface(socket,targets){let peeked=[],peekedLength=0,cleanup=()=>{socket.removeListener("data",onData),socket.removeListener("error",onPeekError),socket.removeListener("close",cleanup)},onPeekError=()=>{cleanup(),socket.destroy()},onData=chunk=>{peeked.push(chunk),peekedLength+=chunk.length;let seen=Buffer.concat(peeked,Math.min(peekedLength,HTTP2_CONNECTION_PREFACE.length)),comparable=seen.subarray(0,Math.min(seen.length,HTTP2_CONNECTION_PREFACE.length));if(!HTTP2_CONNECTION_PREFACE.subarray(0,comparable.length).equals(comparable)){handoffHttp1();return}if(peekedLength>=HTTP2_CONNECTION_PREFACE.length){handoffHttp2();return}};function handoffHttp1(){cleanup(),socket.pause(),socket.unshift(Buffer.concat(peeked,peekedLength)),targets.http1.emit("connection",socket),socket.resume()}function handoffHttp2(){cleanup(),socket.pause();let replay=createReplayDuplex(socket,Buffer.concat(peeked,peekedLength));targets.http2.emit("connection",replay)}socket.on("data",onData),socket.on("error",onPeekError),socket.on("close",cleanup)}function createReplayDuplex(socket,head){let replay=new import_node_stream13.Duplex({read(){socket.resume()},write(chunk,encoding,callback){socket.write(chunk,encoding,callback)},final(callback){socket.end(callback)},destroy(error2,callback){socket.destroy(),callback(error2)}});return socket.on("data",chunk=>{replay.push(chunk)||socket.pause()}),socket.on("end",()=>{replay.push(null)}),socket.on("error",error2=>{replay.destroy(error2)}),replay.push(head),replay}function createUnifiedPortServer(options){let rpcHandler=connectNodeAdapter({routes:options.routes,interceptors:options.interceptors,readMaxBytes:10485760,writeMaxBytes:10485760}),laneRouter=(request,response)=>{let path14=(request.url??"").split("?",1)[0]??"";if(path14===TASK_KIND_REGISTRY_PATH){options.taskKindRegistryLane(request,response);return}if(path14===MODEL_REGISTRY_PATH){options.modelRegistryLane(request,response);return}if(options.skillTransferLane!==void 0&&path14.startsWith(SKILL_ARTIFACTS_PATH_PREFIX)){options.skillTransferLane(request,response);return}if(options.consoleLane!==void 0&&consoleLaneEligible(request)){options.consoleLane(request,response);return}if(isRpcPreflight(request)){handleRpcPreflight(request,response);return}applyRpcCorsHeaders(request,response),rpcHandler(request,response)},http1=(0,import_node_http4.createServer)(laneRouter),http22=(0,import_node_http22.createServer)(laneRouter),liveSessions=new Set;http22.on("session",session=>{liveSessions.add(session),session.on("close",()=>liveSessions.delete(session)),armKeepalivePings(session,options.logger)}),http22.on("sessionError",error2=>{options.logger.debug("http2 session error",{error:String(error2)})});let demux=createProtocolDemuxServer({http1,http2:http22}),liveSockets=new Set;return demux.on("connection",socket=>{liveSockets.add(socket),socket.on("close",()=>liveSockets.delete(socket))}),{listen(port,host="0.0.0.0"){return new Promise((resolve,reject2)=>{demux.once("error",reject2),demux.listen(port,host,()=>{let address=demux.address();if(address===null||typeof address=="string"){reject2(new Error("unified port bound without a TCP address"));return}resolve(address.port)})})},async shutdown(){let closed=new Promise(resolve=>demux.close(()=>resolve()));http1.close(),http1.closeIdleConnections(),http22.close();for(let session of liveSessions)session.close();await Promise.race([closed.then(()=>!0),new Promise(resolve=>setTimeout(()=>resolve(!1),1e4).unref())])||options.logger.warn("shutdown drain budget exhausted; destroying remaining connections",{remaining:liveSockets.size});for(let socket of liveSockets)socket.destroy();await closed}}}function armKeepalivePings(session,logger2){let interval=setInterval(()=>{let acked=!1,deadline=setTimeout(()=>{!acked&&!session.destroyed&&(logger2.debug("closing http2 session: keepalive ping unacknowledged"),session.destroy())},5e3);deadline.unref();try{session.ping(()=>{acked=!0,clearTimeout(deadline)})}catch{clearTimeout(deadline),session.destroyed||session.destroy()}},15e3);interval.unref(),session.on("close",()=>clearInterval(interval))}function registerExtensionServicesUnshadowed(router,registrations){let servedBy=new Map(router.handlers.map(handler=>[handler.requestPath,"the core"]));for(let{unit,register}of registrations){let before=router.handlers.length;register(router);for(let handler of router.handlers.slice(before)){let server=servedBy.get(handler.requestPath);if(server!==void 0)throw new Error(`extension '${unit}' registers ${handler.requestPath}, which ${server} already serves \u2014 a route is never registered twice; an edition changes a core domain's behaviour through its driver points`);servedBy.set(handler.requestPath,`extension '${unit}'`)}}}function createInProcessClients(routes,logger2){let transport=createRouterTransport(routes,{router:{interceptors:buildInterceptorChain(logger2,createInProcessCallerInterceptor())}}),agentInstanceCommand=createClient(AgentInstanceCommandController,transport),agentInstanceQuery=createClient(AgentInstanceQueryController,transport),agentQuery=createClient(AgentQueryController,transport),sessionCommand=createClient(SessionCommandController,transport),sessionQuery=createClient(SessionQueryController,transport),environmentCommand=createClient(EnvironmentCommandController,transport),environmentQuery=createClient(EnvironmentQueryController,transport),executionContextCommand=createClient(ExecutionContextCommandController,transport),workflowInstanceCommand=createClient(WorkflowInstanceCommandController,transport),workflowInstanceQuery=createClient(WorkflowInstanceQueryController,transport),workflowQuery=createClient(WorkflowQueryController,transport),agentExecutionCommand=createClient(AgentExecutionCommandController,transport),agentCommand=createClient(AgentCommandController,transport),workflowCommand=createClient(WorkflowCommandController,transport),mcpServerCommand=createClient(McpServerCommandController,transport),skillCommand=createClient(SkillCommandController,transport),asCaller=caller=>({headers:{[IN_PROCESS_CALLER_HEADER]:encodeInProcessCaller(caller)}}),clients={agentInstanceApplier:{applyAsCaller:(instance,caller)=>agentInstanceCommand.apply(instance,asCaller(caller))},parentAgentLoader:{get:agentId=>agentQuery.get(create2(AgentIdSchema,{value:agentId}))},workflowInstanceCreator:{createAsCaller:(instance,caller)=>workflowInstanceCommand.create(instance,asCaller(caller))},parentWorkflowLoader:{get:workflowId=>workflowQuery.get(create2(WorkflowIdSchema,{value:workflowId}))},executionAgentLoader:{get:agentId=>agentQuery.get(create2(AgentIdSchema,{value:agentId}))},executionAgentInstanceLoader:{get:instanceId=>agentInstanceQuery.get(create2(AgentInstanceIdSchema,{value:instanceId}))},executionAgentInstanceCreator:{createAsCaller:(instance,caller)=>agentInstanceCommand.create(instance,asCaller(caller))},executionSessionLoader:{get:sessionId=>sessionQuery.get(create2(SessionIdSchema,{value:sessionId}))},executionSessionCreator:{createAsCaller:(session,caller)=>sessionCommand.create(session,asCaller(caller))},executionEnvironmentReader:{list:request=>environmentQuery.list(request),getSecretValue:input=>environmentQuery.getSecretValue(input),updateVariables:request=>environmentCommand.updateVariables(request),create:(environment,caller)=>environmentCommand.create(environment,caller===void 0?void 0:asCaller(caller)),delete:input=>environmentCommand.delete(input)},executionContextCreator:{create:ec2=>executionContextCommand.create(ec2)},connectExecutionContextClient:{create:(ec2,caller)=>executionContextCommand.create(ec2,asCaller(caller)),delete:input=>executionContextCommand.delete(input)},workflowExecutionInstanceCreator:{createAsCaller:(instance,caller)=>workflowInstanceCommand.create(instance,asCaller(caller))},workflowExecutionInstanceLoader:{get:instanceId=>workflowInstanceQuery.get(create2(WorkflowInstanceIdSchema,{value:instanceId}))},workflowExecutionContextCreator:{create:ec2=>executionContextCommand.create(ec2)},workflowExecutionApprovalForwarder:{submitApproval:input=>agentExecutionCommand.submitApproval(input)},workflowExecutionFileDecisionForwarder:{submitFileDecision:input=>agentExecutionCommand.submitFileDecision(input)},scheduleExecutionCreator:{create:(execution,fireCaller)=>agentExecutionCommand.create(execution,fireCaller===void 0?void 0:asCaller(fireCaller))},executionStatusWriter:{updateStatus:input=>agentExecutionCommand.updateStatus(input)},pluginMaterializer:{pushSkill:(request,caller)=>skillCommand.push(request,asCaller(caller)),applyMcpServer:(server,caller)=>mcpServerCommand.apply(server,asCaller(caller)),applyAgent:(agent,caller)=>agentCommand.apply(agent,asCaller(caller)),applyWorkflow:(workflow,caller)=>workflowCommand.apply(workflow,asCaller(caller)),updateVisibility:(kind,resourceId,visibility,caller)=>updateVisibilityByKind(kind,resourceId,visibility,asCaller(caller)),deleteByKind:(kind,resourceId,caller)=>deleteByKind(kind,resourceId,asCaller(caller))}};async function deleteByKind(kind,resourceId,options){switch(kind){case ApiResourceKind.agent:await agentCommand.delete(create2(AgentIdSchema,{value:resourceId}),options);return;case ApiResourceKind.workflow:await workflowCommand.delete(create2(WorkflowIdSchema,{value:resourceId}),options);return;case ApiResourceKind.mcp_server:await mcpServerCommand.delete(create2(ApiResourceDeleteInputSchema,{resourceId}),options);return;case ApiResourceKind.skill:await skillCommand.delete(create2(SkillIdSchema,{value:resourceId}),options);return;default:throw new Error(`unsupported resource kind for delete: ${ApiResourceKind[kind]??String(kind)}`)}}async function updateVisibilityByKind(kind,resourceId,visibility,options){let input=create2(UpdateVisibilityInputSchema,{resourceId,visibility});switch(kind){case ApiResourceKind.agent:await agentCommand.updateVisibility(input,options);return;case ApiResourceKind.workflow:await workflowCommand.updateVisibility(input,options);return;case ApiResourceKind.mcp_server:await mcpServerCommand.updateVisibility(input,options);return;case ApiResourceKind.skill:await skillCommand.updateVisibility(input,options);return;default:throw new Error(`unsupported resource kind for updateVisibility: ${ApiResourceKind[kind]??String(kind)}`)}}return{clients,transport}}var LIST_INDEXES=[agentExecutionListIndex,artifactListIndex,iamPolicyListIndex,sessionListIndex,workflowExecutionListIndex];async function composeServer(options){let{config:config2,logger:logger2}=options,extensions=resolveExtensions(options.extensions);extensions.unitNames.length>0&&logger2.info("extension units composed",{units:extensions.unitNames.join(", ")});let store,storeOptions={listIndexes:LIST_INDEXES};config2.databaseUrl!==""?(store=await PostgresStore.open(config2.databaseUrl,logger2,storeOptions),logger2.info("storage driver selected",{driver:"postgres"})):(store=SqliteStore.open(config2.dbPath,logger2,storeOptions),logger2.info("storage driver selected",{driver:"sqlite",dbPath:config2.dbPath}));let authEnabled=config2.oidcIssuer!=="",requireAuthentication=authEnabled||extensions.requireAuthentication!==void 0,authorizationPosture=authorizationPostureOf({unitAuthorizer:extensions.authorizer!==void 0,requireAuthentication}),builtInAuthorization=authorizationPosture!=="unit-authorizer";if(authorizationPosture==="built-in"&&extensions.edition!==ServerEdition.oss)throw new Error(`the composition serves edition '${ServerEdition[extensions.edition]}' under the require-authentication posture but registers no Authorizer \u2014 the built-in authorizer enforces the open-source kinds only; register an Authorizer or serve the open-source edition`);let identityAccounts=extensions.drivers.identityAccountStore??newResourceIdentityAccountStore(store),iamPolicies=extensions.drivers.iamPolicyStore??newResourceIamPolicyStore(store),platformClients=extensions.drivers.platformClientStore??newResourcePlatformClientStore(store),iamPolicyGrantPath=newIamPolicyGrantPath({policies:iamPolicies,lifecycle:extensions.drivers.resourceAuthorizationLifecycle,logger:logger2}),authorizationLifecycle=extensions.drivers.resourceAuthorizationLifecycle,roleLifecycle=authorizationLifecycle??(builtInAuthorization?newBuiltInRoleLifecycle({grantPath:iamPolicyGrantPath,accounts:identityAccounts}):void 0),operatorIdentity=operatorIdentitySnapshot(),membership=builtInAuthorization?newMembershipRules({grantPath:iamPolicyGrantPath,policies:iamPolicies,store,operatorEmail:operatorIdentity.email}):void 0,runnerAuthService=RunnerAuthService.fromEnv(),runnerCredentials=extensions.drivers.runnerCredentialProvider??(authorizationPosture==="built-in"?newBuiltInRunnerCredentialProvider({service:runnerAuthService,store,accounts:identityAccounts}):newExecutionScopedRunnerCredentialProvider(runnerAuthService)),authorizer=extensions.authorizer??(authorizationPosture==="built-in"?newLaneAdmittedAuthorizer(newBuiltInAuthorizer({store,policies:iamPolicies,accounts:identityAccounts,edition:extensions.edition,logger:logger2}),caller=>isWorkflowBoundRunner(runnerAuthService,caller)):newPermissiveSingleTeamAuthorizer()),organizationDirectory=extensions.drivers.organizationDirectory??(authorizationPosture==="built-in"?newBuiltInOrganizationDirectory({store,policies:iamPolicies,accounts:identityAccounts}):void 0),scheduleFireCaller=extensions.drivers.scheduleFireCaller??(authorizationPosture==="built-in"?newBuiltInScheduleFireCaller({store,accounts:identityAccounts}):void 0),listReadScope=extensions.drivers.listReadScope??(authorizationPosture==="built-in"?newBuiltInListReadScope({store,policies:iamPolicies,accounts:identityAccounts,logger:logger2}):void 0),personAccounts=requireAuthentication?identityAccounts:void 0;logger2.info("authorization posture resolved",{posture:authorizationPosture,authorizer:extensions.authorizer!==void 0?"extension":authorizationPosture==="built-in"?"built-in":"permissive",listReadScope:extensions.drivers.listReadScope!==void 0?"extension":authorizationPosture==="built-in"?"built-in":"none"});let identityAccountPath={accounts:identityAccounts,logger:logger2,authorizer,authorizationLifecycle:roleLifecycle},createIdentityAccount=newCreateAccountPath(identityAccountPath,ApiResourceKind.identity_account),issuerDiscovery=newIssuerDiscovery(),identityAccountProvisioner=newDirectAccountProvisioner({accounts:identityAccounts,createAccount:createIdentityAccount,userInfo:newOidcUserInfoClient(issuerDiscovery)});if(!requireAuthentication){let operator=await ensureOperatorAccount({accounts:identityAccounts,createAccount:createIdentityAccount},operatorIdentity);logger2.info("trusted-local operator account ensured",{accountId:operator.metadata?.id??""}),membership!==void 0&&(await membership.ensureOperatorOwnership(operator),logger2.info("trusted-local operator ownership ensured",{accountId:operator.metadata?.id??""}))}authorizationPosture==="built-in"&&membership!==void 0&&(await membership.ensureRolesForExistingAccounts(),logger2.info("built-in posture role reconciliation ensured"));let v1Key;try{v1Key=getOrCreateNamedKey(ENCRYPTION_KEY_ENV_VAR,ENCRYPTION_KEY_FILE_NAME)}catch(error2){logger2.warn("Failed to initialize encryption - secret values will be stored in plaintext",{error:error2 instanceof Error?error2.message:String(error2)}),v1Key=void 0}let secretCodecs=new Map([[V1_VERSION,new StaticKeySecretCodec(v1Key)],...extensions.drivers.secretCodecs]),writeVersionValue=process.env[ENCRYPTION_WRITE_VERSION_ENV_VAR]??"",secretService=SecretService.withCodecs({codecs:secretCodecs,writeVersion:writeVersionValue===""?DEFAULT_WRITE_VERSION:writeVersionValue});logger2.info("secret encryption configured",{writeVersion:writeVersionValue===""?DEFAULT_WRITE_VERSION:writeVersionValue,registeredCodecs:[...secretCodecs.keys()].sort()});let platformTokenKeys=resolvePlatformTokenKeys({requireAuthentication,supplied:extensions.drivers.platformTokenKeys,edition:extensions.edition});logger2.info("platform-token keys resolved",{source:platformTokenKeys===void 0?"none (no authentication posture)":extensions.drivers.platformTokenKeys!==void 0?"extension":"open-source ladder",signing:platformTokenKeys?.signer!==void 0});let temporalConfig=newConfigFromEnv(),workflowExecutionTemporalConfig=newWorkflowExecutionConfigFromEnv(),sandboxProvisioner=newSandboxProvisioner(config2.sandboxProvisionerType,{config:{backendEndpoint:config2.sandboxBackendEndpoint,temporalAddress:config2.sandboxTemporalAddress,temporalNamespace:config2.temporalNamespace,temporalConnectionEnv:temporalConnectionEnv(config2.temporalConnection),runnerImage:config2.sandboxRunnerImage,runnerCommand:config2.sandboxRunnerCommand,kubernetesNamespace:config2.sandboxKubernetesNamespace},logger:logger2},builtInSandboxProvisionerFactories(),extensions.drivers.sandboxProvisionerDrivers);if(sandboxProvisioner!==void 0&&temporalConfig.activityRouting!==ROUTING_SESSION&&workflowExecutionTemporalConfig.workflowActivityRouting!==WORKFLOW_ROUTING_EXECUTION)throw new Error(`SANDBOX_PROVISIONER_TYPE='${config2.sandboxProvisionerType}' requires a per-queue routing mode \u2014 set STIGMER_ACTIVITY_ROUTING=session and/or STIGMER_WORKFLOW_ACTIVITY_ROUTING=execution (a provisioner no dispatch can reach must fail loudly, not sit dark)`);let sandboxLane=newSandboxLane(sandboxProvisioner,runnerCredentials);sandboxLane.enabled&&logger2.info("sandbox provisioner composed",{type:config2.sandboxProvisionerType});let workflowSandboxTerminalObserver=newWorkflowSandboxTerminalObserver(sandboxLane,logger2),healthState=new HealthState,modelCatalog,ossModelRegistryStore;extensions.drivers.modelCatalogProvider!==void 0?modelCatalog=extensions.drivers.modelCatalogProvider:(ossModelRegistryStore=new ModelRegistryStore({bundledDocument:bundledModelRegistryDocument(),upstreamOrigin:config2.modelRegistryUpstream,refreshEnabled:config2.modelRegistryRefreshEnabled,logger:logger2,fetchImpl:options.fetchImpl}),modelCatalog=ossModelRegistryStore);let registryLanes=createRegistryLanes({taskKindRegistryDocument:bundledTaskKindRegistryDocument(),modelRegistryStore:modelCatalog}),workflowValidator=new InProcessValidator(modelCatalog,logger2),agentExecutionStreamBroker=new StreamBroker(logger2),workflowExecutionStreamBroker=new StreamBroker2(logger2),scheduleTemporalConfig=newScheduleConfigFromEnv(),scheduleClientProvider=()=>temporalManager.getClient(),scheduleArtifact=new ScheduleArtifact(scheduleTemporalConfig),scheduleSyncer=new ScheduleSyncer(scheduleClientProvider,store,scheduleArtifact,logger2),scheduleRunStarter=new RunStarter({store,config:scheduleTemporalConfig,executions:{create:(execution,fireCaller)=>requireInProcess().scheduleExecutionCreator.create(execution,fireCaller)},fireCallerMint:scheduleFireCaller,logger:logger2}),scheduleReconciler=new ScheduleReconciler(scheduleClientProvider,store,scheduleSyncer,scheduleTemporalConfig,logger2),temporalManager=new TemporalManager({hostPort:config2.temporalHostPort,namespace:config2.temporalNamespace,connection:config2.temporalConnection,logger:logger2,payloadCodecs:loadServerPayloadCodecs(runnerCredentials.resolvePayloadKey?.bind(runnerCredentials)),workerFactories:[newAgentExecutionWorkerFactory({store,logger:logger2,statusWriter:()=>requireInProcess().executionStatusWriter,temporalConfig}),newWorkflowExecutionWorkerFactory({store,logger:logger2,broker:workflowExecutionStreamBroker,temporalConfig:workflowExecutionTemporalConfig,sandboxTerminalObserver:workflowSandboxTerminalObserver}),newScheduleWorkerFactory({store,config:scheduleTemporalConfig,syncer:scheduleSyncer,runStarter:scheduleRunStarter,logger:logger2}),...extensions.workers]}),executionEngineState=newExecutionEngineStateProvider({manager:temporalManager,config:temporalConfig,store,runnerCredentials,logger:logger2}),workflowExecutionEngineState=newWorkflowExecutionEngineStateProvider({manager:temporalManager,config:workflowExecutionTemporalConfig,runnerCredentials,logger:logger2}),artifactLanePort=resolveArtifactLanePort({configured:config2.artifactHttpPort,unifiedPort:options.portOverride??config2.grpcPort}),artifactLaneBoundPort,artifactStorage=newArtifactStorage({type:config2.artifactStorageType,localBasePath:config2.artifactLocalBasePath,localServeUrl:resolveArtifactServeUrl(config2.artifactLocalServeUrl,()=>artifactLaneBoundPort),r2Bucket:config2.r2Bucket,r2Endpoint:config2.r2Endpoint,r2AccessKeyId:config2.r2AccessKeyId,r2SecretAccessKey:config2.r2SecretAccessKey,r2Region:config2.r2Region},extensions.drivers.artifactStorageDrivers),artifactFileServer=config2.artifactStorageType==="local"?createArtifactFileServer({basePath:config2.artifactLocalBasePath,logger:logger2}):void 0,skillUploadSlots=new UploadSlots(config2.storagePath,STAGING_KEY_PREFIX,DEFAULT_SLOT_TTL_MS,104857600),skillType=config2.skillArtifactStorageType===""?"local":config2.skillArtifactStorageType,skillStorageDriver=skillType==="local"?((0,import_node_fs16.mkdirSync)(import_node_path18.default.join(config2.storagePath,"skills"),{recursive:!0,mode:493}),new LocalArtifactStorage(config2.storagePath,transferServeUrl(config2.skillTransferBaseUrl),{reserve:(key,declaredSizeBytes)=>{let{ttlMs}=skillUploadSlots.reserve(key,declaredSizeBytes);return{url:uploadUrl(config2.skillTransferBaseUrl,uploadRefOf(key)),ttlMs}}})):newArtifactStorage({type:skillType,localBasePath:config2.storagePath,localServeUrl:"",r2Bucket:config2.r2Bucket,r2Endpoint:config2.r2Endpoint,r2AccessKeyId:config2.r2AccessKeyId,r2SecretAccessKey:config2.r2SecretAccessKey,r2Region:config2.r2Region},extensions.drivers.artifactStorageDrivers),skillArtifactStorage=newSkillArtifactStorage(skillStorageDriver),pluginArtifactStorage=newContentAddressedArchiveStore(skillStorageDriver,PLUGIN_ARTIFACT_KEY_PREFIX),skillArchiveStaging=newArchiveStaging(skillStorageDriver,logger2),skillTransferLane=newSkillTransferLane(skillUploadSlots,skillArtifactStorage,logger2),transferOrigin=assessSkillTransferOrigin({baseUrl:config2.skillTransferBaseUrl,relaysThroughServer:skillType==="local",requireAuthentication});transferOrigin.kind==="loopback-hosted"&&logger2.warn("skill artifact transfer lane mints capability URLs on the server's own loopback while the server requires authentication; pushes above the gRPC message cap and sandbox skill downloads will fail \u2014 set SKILL_TRANSFER_BASE_URL to the origin callers reach this server on",{baseUrl:transferOrigin.baseUrl});let consoleAssets=resolveConsoleAssets(config2.consoleDir,logger2);consoleAssets!==void 0?logger2.info("web console serving from unified port",{dir:consoleAssets.root,files:consoleAssets.fileCount}):logger2.debug("no web console export bundled; console lane disabled");let consoleSignIn=authEnabled?{posture:"oidc",issuer:config2.oidcIssuer,audience:config2.oidcAudience,consoleClientId:config2.oidcConsoleClientId}:{posture:"trusted-local"};consoleAssets!==void 0&&consoleSignIn.posture==="oidc"&&consoleSignIn.consoleClientId===""&&logger2.warn("STIGMER_OIDC_ISSUER is set but STIGMER_OIDC_CONSOLE_CLIENT_ID is not \u2014 the web console this server serves cannot sign in; register a public PKCE client for the console at the issuer and set it");let consoleLane=consoleAssets!==void 0?createConsoleLane({assets:consoleAssets,signIn:consoleSignIn,logger:logger2}):void 0,searchRegistry=newSearchableResourceRegistry();searchRegistry.validateExpectedKinds(logger2);let searchQueryStore=new SqliteSearchQueryStore(store,searchRegistry,logger2),searchHandler=new SearchHandler(searchQueryStore,logger2,listReadScope),activityHandler=new ActivityHandler(store,logger2,listReadScope),environmentResolution=new RuntimeResolutionService(store,secretService,logger2),managedEnvService=new ManagedEnvironmentService({getSecretValue:input=>requireInProcess().executionEnvironmentReader.getSecretValue(input),updateVariables:request=>requireInProcess().executionEnvironmentReader.updateVariables(request),create:(environment,caller)=>requireInProcess().executionEnvironmentReader.create(environment,caller),delete:input=>requireInProcess().executionEnvironmentReader.delete(input)},logger2),mcpServerEngineState=newMcpServerEngineStateProvider({manager:temporalManager,config:temporalConfig,logger:logger2}),oauthRedirect=resolveOAuthRedirectUri({configured:config2.oauthRedirectUri,servesConsole:consoleAssets!==void 0,port:options.portOverride??config2.grpcPort});switch(oauthRedirect.kind){case"configured":break;case"derived":logger2.info("STIGMER_OAUTH_REDIRECT_URI is not set \u2014 deriving the served console's callback for MCP server OAuth Connect",{redirectUri:oauthRedirect.uri});break;case"absent":logger2.warn("STIGMER_OAUTH_REDIRECT_URI is not set \u2014 OAuth Connect flows for MCP servers are unavailable (initiateOAuthConnect will refuse)");break;default:{let exhaustive=oauthRedirect;throw new Error(String(exhaustive))}}let oauthRedirectUri=oauthRedirect.kind==="absent"?"":oauthRedirect.uri,outboundFetch=guardedFetch(extensions.drivers.outboundEgress??relaxedEgressPolicy(),{fetchImpl:options.fetchImpl??fetch,lookup:nodeLookup()}),inProcess;function requireInProcess(){if(inProcess===void 0)throw new Error("in-process clients not wired (boot ordering bug)");return inProcess}let routes=router=>{registerHealthService(router,healthState),registerOrganizationServices(router,{store,logger:logger2,authorizer,gateSteps:extensions.gateSteps,grantPath:iamPolicyGrantPath,authorizationLifecycle:roleLifecycle,organizationDirectory}),registerApiKeyServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,listReadScope}),registerIdentityAccountServices(router,{...identityAccountPath,provisioner:identityAccountProvisioner,federation:extensions.drivers.identityFederation,gateSteps:extensions.gateSteps,membership}),registerIamPolicyServices(router,{grantPath:iamPolicyGrantPath,policies:iamPolicies,accounts:identityAccounts,authorizer,grantScope:extensions.drivers.policyGrantScope??newOrganizationOnlyGrantScope(),queries:extensions.drivers.authorizationQueries,principalDisplay:extensions.drivers.principalDisplay,gateSteps:extensions.gateSteps,edition:extensions.edition,logger:logger2}),registerEnvironmentServices(router,{store,logger:logger2,authorizer,secretService,authorizationLifecycle,listReadScope}),registerOAuthAppServices(router,{store,secretService,logger:logger2,authorizer,authorizationLifecycle,listReadScope}),registerPlatformClientServices(router,{clients:platformClients,store,logger:logger2,authorizer,authorizationLifecycle,listReadScope}),registerPlatformClientTokenService(router,{mint:{clients:platformClients,accounts:identityAccounts,createAccount:createIdentityAccount,grantPath:iamPolicyGrantPath,keys:platformTokenKeys,logger:logger2,now:()=>new Date},guestTokenMinting:extensions.drivers.guestTokenMinting}),registerExecutionContextServices(router,{store,logger:logger2,authorizer,secretService,runnerAuthService:runnerCredentials,authorizationLifecycle}),registerAgentServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,agentInstanceApplier:()=>requireInProcess().agentInstanceApplier}),registerAgentInstanceServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,parentAgentLoader:()=>requireInProcess().parentAgentLoader,listReadScope}),registerSessionServices(router,{store,logger:logger2,authorizer,temporalConfig,gateSteps:extensions.gateSteps,sandboxLane,authorizationLifecycle,listReadScope}),registerAgentShareServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,listReadScope}),registerAgentChannelServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,listReadScope,modelRegistry:modelCatalog,channelRuntime:extensions.drivers.channelRuntime}),registerChannelMessageServices(router,extensions.drivers.channelRuntime),registerChannelConversationServices(router,extensions.drivers.channelRuntime),registerChannelAppServices(router,{store,logger:logger2,authorizer,secretService,authorizationLifecycle,listReadScope}),registerScheduleServices(router,{store,logger:logger2,authorizer,modelRegistry:modelCatalog,clock:()=>scheduleSyncer,runner:()=>scheduleRunStarter,authorizationLifecycle,listReadScope}),registerMemoryServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,listReadScope,personAccounts,runnerCredentialProvider:runnerCredentials}),registerAgentExecutionServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,listReadScope,personAccounts,runnerCredentialProvider:runnerCredentials,broker:agentExecutionStreamBroker,engineState:executionEngineState,modelRegistry:modelCatalog,artifactStorage,gateSteps:extensions.gateSteps,statusObservers:extensions.statusObservers,responseDecorators:extensions.responseDecorators,sandboxLane,temporalConfig,agentLoader:()=>requireInProcess().executionAgentLoader,agentInstanceCreator:()=>requireInProcess().executionAgentInstanceCreator,sessionCreator:()=>requireInProcess().executionSessionCreator,executionContextBuilder:{store,logger:logger2,agentLoader:()=>requireInProcess().executionAgentLoader,agentInstanceLoader:()=>requireInProcess().executionAgentInstanceLoader,sessionLoader:()=>requireInProcess().executionSessionLoader,environmentReader:()=>requireInProcess().executionEnvironmentReader,environmentResolution,executionContextCreator:()=>requireInProcess().executionContextCreator,managedEnvService,platformClients,fetchImpl:asFetch(outboundFetch)}}),registerWorkflowServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,validator:workflowValidator,workflowInstanceCreator:()=>requireInProcess().workflowInstanceCreator}),registerWorkflowInstanceServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,parentWorkflowLoader:()=>requireInProcess().parentWorkflowLoader,listReadScope}),registerWorkflowExecutionServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,listReadScope,gateSteps:extensions.gateSteps,engineState:workflowExecutionEngineState,broker:workflowExecutionStreamBroker,sandboxLane,temporalConfig:workflowExecutionTemporalConfig,sandboxTerminalObserver:workflowSandboxTerminalObserver,workflowInstanceCreator:()=>requireInProcess().workflowExecutionInstanceCreator,approvalForwarder:()=>requireInProcess().workflowExecutionApprovalForwarder,fileDecisionForwarder:()=>requireInProcess().workflowExecutionFileDecisionForwarder,executionContextBuilder:{store,logger:logger2,workflowInstanceLoader:()=>requireInProcess().workflowExecutionInstanceLoader,environmentResolution,executionContextCreator:()=>requireInProcess().workflowExecutionContextCreator}}),registerMcpServerServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,connect:{store,logger:logger2,authorizer,engineState:mcpServerEngineState,environmentReader:{list:request=>requireInProcess().executionEnvironmentReader.list(request),getSecretValue:input=>requireInProcess().executionEnvironmentReader.getSecretValue(input)},executionContext:{create:(ec2,caller)=>requireInProcess().connectExecutionContextClient.create(ec2,caller),delete:input=>requireInProcess().connectExecutionContextClient.delete(input)},runnerAuth:runnerCredentials,managedEnv:managedEnvService,oauthGrants:store.oauthGrants,pendingOAuthStates:store.pendingOAuthStates,secretService,oauthRedirectUri,outboundFetch}}),registerSkillServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,artifactStorage:skillArtifactStorage,executionArtifactStorage:artifactStorage,staging:skillArchiveStaging}),registerPluginServices(router,{store,logger:logger2,authorizer,authorizationLifecycle,artifactStorage:pluginArtifactStorage,materializerProvider:()=>requireInProcess().pluginMaterializer,staging:skillArchiveStaging}),registerArtifactServices(router,{store,artifactStorage,logger:logger2,authorizer}),registerSearchServices(router,{handler:searchHandler,logger:logger2}),registerActivityServices(router,{handler:activityHandler,logger:logger2}),registerGitHubServices(router,{clientId:config2.gitHubOAuthClientId,clientSecret:config2.gitHubOAuthClientSecret,logger:logger2,fetchImpl:options.fetchImpl}),registerPlatformServices(router,{runnerBootstrapTemporalAddress:config2.runnerBootstrapTemporalAddress,temporalNamespace:config2.temporalNamespace,runnerAuthService:runnerCredentials,edition:extensions.edition,version:options.version??SERVER_VERSION,authenticationRequired:requireAuthentication,licenseStatus:extensions.drivers.licenseStatus??ABSENT_LICENSE_STATUS,now:()=>new Date,logger:logger2}),registerExtensionServicesUnshadowed(router,extensions.services)},inProcessWiring=createInProcessClients(routes,logger2);inProcess=inProcessWiring.clients;let identityVerifiers=[...requireAuthentication?[newApiKeyIdentityVerifier({store,accounts:identityAccounts,logger:logger2,now:()=>new Date})]:[],...platformTokenKeys!==void 0?[newPlatformClientTokenVerifier({keys:platformTokenKeys,clients:platformClients})]:[],...authorizationPosture==="built-in"?[newRunnerSubjectIdentityVerifier({store,accounts:identityAccounts,credentials:runnerCredentials})]:[],...authEnabled?[newOidcIdentityVerifier({issuer:config2.oidcIssuer,audience:config2.oidcAudience,accounts:identityAccounts,discovery:issuerDiscovery})]:[],...extensions.identityVerifiers];if(extensions.requireAuthentication!==void 0&&extensions.identityVerifiers.length===0)throw new Error(`extension '${extensions.requireAuthentication.declaredBy}' declares the require-authentication posture, but registers no identity verifier of its own \u2014 the OSS API-key lane alone cannot admit the first caller (nobody could mint a key), so every non-public request would be refused; register a verifier or omit the declaration`);let postureSources=[...authEnabled?["oidc-issuer"]:[],...extensions.requireAuthentication!==void 0?[`extension '${extensions.requireAuthentication.declaredBy}'`]:[]],callerGuards=[...platformTokenKeys!==void 0?[newPlatformClientOriginGuard({clients:platformClients,logger:logger2})]:[],...extensions.callerGuards];logger2.info("authentication posture resolved",{posture:requireAuthentication?"required":"trusted-local",source:postureSources.length>0?postureSources.join(" + "):"none",verifiers:identityVerifiers.map(v=>v.name).join(", ")});let server=createUnifiedPortServer({logger:logger2,routes,interceptors:buildInterceptorChain(logger2,createVerifierChainInterceptor(identityVerifiers,callerGuards,logger2,requireAuthentication),{errorBoundary:createErrorBoundaryInterceptor(logger2,extensions.drivers.visitorErrorPolicy),requestMetrics:createRequestMetricsInterceptor()}),taskKindRegistryLane:registryLanes.taskKindRegistryLane,modelRegistryLane:registryLanes.modelRegistryLane,skillTransferLane,consoleLane});return{healthState,store,secrets:secretService,temporalManager,runnerAuthService,agentExecutionStreamBroker,workflowExecutionStreamBroker,inProcessTransport:inProcessWiring.transport,identityVerifiers,routes,async start(){await temporalManager.initialConnect()&&await temporalManager.startWorkers(),temporalManager.startHealthMonitor();let kickScheduleReconcile=scheduleReconciler.startReconciliation();if(temporalManager.addReconnectHook(kickScheduleReconcile),await artifactStorage.health(),artifactFileServer!==void 0){await warnOnLegacyArtifactLayout(config2.artifactLocalBasePath,logger2);try{artifactLaneBoundPort=await artifactFileServer.listen(artifactLanePort,config2.artifactHttpHost)}catch(error2){throw artifactLaneBindError(error2,config2.artifactHttpHost,artifactLanePort,config2.artifactHttpPort!==void 0)}}try{let indexed=await searchQueryStore.rebuildIndex();logger2.info("Search index rebuilt at startup",{indexed})}catch(error2){logger2.warn("Failed to rebuild search index at startup",{error:error2 instanceof Error?error2.message:String(error2)})}await initRpcMetrics(),logger2.info("request metrics",{posture:await metricsExportPosture(),instruments:"stigmer.grpc.request.count, stigmer.grpc.request.duration"}),healthState.setOverall(HealthCheckResponse_ServingStatus.SERVING),ossModelRegistryStore?.startRefresh();let port=await server.listen(options.portOverride??config2.grpcPort,options.host);return logger2.info("stigmer-server listening",{port}),port},async shutdown(){healthState.setOverall(HealthCheckResponse_ServingStatus.NOT_SERVING),ossModelRegistryStore?.stopRefresh(),await artifactFileServer?.shutdown(),await scheduleReconciler.stop(),await temporalManager.close(),await server.shutdown(),await store.close(),logger2.info("stigmer-server stopped")}}}var LEVEL_RANK={debug:10,info:20,warn:30,error:40};function createLogger(options){let threshold=LEVEL_RANK[options.level]??LEVEL_RANK.info,write2=options.write??(line=>process.stderr.write(line+`
1552
1552
  `)),sink=options.sink,emit=(level,message6,fields2)=>{if(LEVEL_RANK[level]<threshold)return;let time2=new Date;if(options.pretty){let suffix=fields2===void 0||Object.keys(fields2).length===0?"":" "+JSON.stringify(fields2);write2(`${time2.toISOString()} ${level.toUpperCase().padEnd(5)} ${message6}${suffix}`)}else write2(JSON.stringify({level,time:time2.toISOString(),message:message6,...fields2}));sink?.({level,time:time2,message:message6,fields:fields2})};return{debug:(message6,fields2)=>emit("debug",message6,fields2),info:(message6,fields2)=>emit("info",message6,fields2),warn:(message6,fields2)=>emit("warn",message6,fields2),error:(message6,fields2)=>emit("error",message6,fields2)}}async function main(){let config2=loadConfig(),logger2=createLogger({level:config2.logLevel,pretty:config2.env==="local"});setOperatorIdentity(config2.operatorEmail,config2.operatorName);let server=await composeServer({config:config2,logger:logger2}),shuttingDown=!1,shutdown=signal3=>{shuttingDown||(shuttingDown=!0,logger2.info("shutting down",{signal:signal3}),server.shutdown().then(()=>process.exit(0)).catch(error2=>{logger2.error("shutdown failed",{error:String(error2)}),process.exit(1)}))};process.on("SIGTERM",()=>shutdown("SIGTERM")),process.on("SIGINT",()=>shutdown("SIGINT"));try{await server.start()}catch(error2){logger2.error("boot failed",{error:error2 instanceof Error?error2.message:String(error2)}),process.exit(1)}}main().catch(error2=>{console.error("boot failed:",error2 instanceof Error?error2.message:String(error2)),process.exit(1)});
1553
1553
  /*! Bundled license information:
1554
1554