@stigmer/server-slim 3.22.0 → 3.22.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 (535) hide show
  1. package/console/404.html +1 -1
  2. package/console/__next.__PAGE__.txt +1 -1
  3. package/console/__next._full.txt +1 -1
  4. package/console/__next._head.txt +1 -1
  5. package/console/__next._index.txt +1 -1
  6. package/console/__next._tree.txt +1 -1
  7. package/console/_not-found/__next._full.txt +1 -1
  8. package/console/_not-found/__next._head.txt +1 -1
  9. package/console/_not-found/__next._index.txt +1 -1
  10. package/console/_not-found/__next._not-found.__PAGE__.txt +1 -1
  11. package/console/_not-found/__next._not-found.txt +1 -1
  12. package/console/_not-found/__next._tree.txt +1 -1
  13. package/console/_not-found.html +1 -1
  14. package/console/_not-found.txt +1 -1
  15. package/console/auth/callback/__next._full.txt +1 -1
  16. package/console/auth/callback/__next._head.txt +1 -1
  17. package/console/auth/callback/__next._index.txt +1 -1
  18. package/console/auth/callback/__next._tree.txt +1 -1
  19. package/console/auth/callback/__next.auth.callback.__PAGE__.txt +1 -1
  20. package/console/auth/callback/__next.auth.callback.txt +1 -1
  21. package/console/auth/callback/__next.auth.txt +1 -1
  22. package/console/auth/callback.html +1 -1
  23. package/console/auth/callback.txt +1 -1
  24. package/console/auth/github/callback/__next._full.txt +1 -1
  25. package/console/auth/github/callback/__next._head.txt +1 -1
  26. package/console/auth/github/callback/__next._index.txt +1 -1
  27. package/console/auth/github/callback/__next._tree.txt +1 -1
  28. package/console/auth/github/callback/__next.auth.github.callback.__PAGE__.txt +1 -1
  29. package/console/auth/github/callback/__next.auth.github.callback.txt +1 -1
  30. package/console/auth/github/callback/__next.auth.github.txt +1 -1
  31. package/console/auth/github/callback/__next.auth.txt +1 -1
  32. package/console/auth/github/callback.html +1 -1
  33. package/console/auth/github/callback.txt +1 -1
  34. package/console/auth/oauth/callback/__next._full.txt +1 -1
  35. package/console/auth/oauth/callback/__next._head.txt +1 -1
  36. package/console/auth/oauth/callback/__next._index.txt +1 -1
  37. package/console/auth/oauth/callback/__next._tree.txt +1 -1
  38. package/console/auth/oauth/callback/__next.auth.oauth.callback.__PAGE__.txt +1 -1
  39. package/console/auth/oauth/callback/__next.auth.oauth.callback.txt +1 -1
  40. package/console/auth/oauth/callback/__next.auth.oauth.txt +1 -1
  41. package/console/auth/oauth/callback/__next.auth.txt +1 -1
  42. package/console/auth/oauth/callback.html +1 -1
  43. package/console/auth/oauth/callback.txt +1 -1
  44. package/console/chat/__placeholder__/__placeholder__/__next._full.txt +1 -1
  45. package/console/chat/__placeholder__/__placeholder__/__next._head.txt +1 -1
  46. package/console/chat/__placeholder__/__placeholder__/__next._index.txt +1 -1
  47. package/console/chat/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  48. package/console/chat/__placeholder__/__placeholder__/__next.chat.$d$org.$d$slug.__PAGE__.txt +1 -1
  49. package/console/chat/__placeholder__/__placeholder__/__next.chat.$d$org.$d$slug.txt +1 -1
  50. package/console/chat/__placeholder__/__placeholder__/__next.chat.$d$org.txt +1 -1
  51. package/console/chat/__placeholder__/__placeholder__/__next.chat.txt +1 -1
  52. package/console/chat/__placeholder__/__placeholder__.html +1 -1
  53. package/console/chat/__placeholder__/__placeholder__.txt +1 -1
  54. package/console/conversations/__next._full.txt +1 -1
  55. package/console/conversations/__next._head.txt +1 -1
  56. package/console/conversations/__next._index.txt +1 -1
  57. package/console/conversations/__next._tree.txt +1 -1
  58. package/console/conversations/__next.conversations.__PAGE__.txt +1 -1
  59. package/console/conversations/__next.conversations.txt +1 -1
  60. package/console/conversations/__placeholder__/__placeholder__/__next._full.txt +1 -1
  61. package/console/conversations/__placeholder__/__placeholder__/__next._head.txt +1 -1
  62. package/console/conversations/__placeholder__/__placeholder__/__next._index.txt +1 -1
  63. package/console/conversations/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  64. package/console/conversations/__placeholder__/__placeholder__/__next.conversations.$d$channelId.$d$key.__PAGE__.txt +1 -1
  65. package/console/conversations/__placeholder__/__placeholder__/__next.conversations.$d$channelId.$d$key.txt +1 -1
  66. package/console/conversations/__placeholder__/__placeholder__/__next.conversations.$d$channelId.txt +1 -1
  67. package/console/conversations/__placeholder__/__placeholder__/__next.conversations.txt +1 -1
  68. package/console/conversations/__placeholder__/__placeholder__.html +1 -1
  69. package/console/conversations/__placeholder__/__placeholder__.txt +1 -1
  70. package/console/conversations.html +1 -1
  71. package/console/conversations.txt +1 -1
  72. package/console/dashboard/__next._full.txt +1 -1
  73. package/console/dashboard/__next._head.txt +1 -1
  74. package/console/dashboard/__next._index.txt +1 -1
  75. package/console/dashboard/__next._tree.txt +1 -1
  76. package/console/dashboard/__next.dashboard.__PAGE__.txt +1 -1
  77. package/console/dashboard/__next.dashboard.txt +1 -1
  78. package/console/dashboard.html +1 -1
  79. package/console/dashboard.txt +1 -1
  80. package/console/executions/__placeholder__/__next._full.txt +1 -1
  81. package/console/executions/__placeholder__/__next._head.txt +1 -1
  82. package/console/executions/__placeholder__/__next._index.txt +1 -1
  83. package/console/executions/__placeholder__/__next._tree.txt +1 -1
  84. package/console/executions/__placeholder__/__next.executions.$d$id.__PAGE__.txt +1 -1
  85. package/console/executions/__placeholder__/__next.executions.$d$id.txt +1 -1
  86. package/console/executions/__placeholder__/__next.executions.txt +1 -1
  87. package/console/executions/__placeholder__.html +1 -1
  88. package/console/executions/__placeholder__.txt +1 -1
  89. package/console/index.html +1 -1
  90. package/console/index.txt +1 -1
  91. package/console/invite/__placeholder__/__next._full.txt +1 -1
  92. package/console/invite/__placeholder__/__next._head.txt +1 -1
  93. package/console/invite/__placeholder__/__next._index.txt +1 -1
  94. package/console/invite/__placeholder__/__next._tree.txt +1 -1
  95. package/console/invite/__placeholder__/__next.invite.$d$token.__PAGE__.txt +1 -1
  96. package/console/invite/__placeholder__/__next.invite.$d$token.txt +1 -1
  97. package/console/invite/__placeholder__/__next.invite.txt +1 -1
  98. package/console/invite/__placeholder__.html +1 -1
  99. package/console/invite/__placeholder__.txt +1 -1
  100. package/console/library/__next._full.txt +1 -1
  101. package/console/library/__next._head.txt +1 -1
  102. package/console/library/__next._index.txt +1 -1
  103. package/console/library/__next._tree.txt +1 -1
  104. package/console/library/__next.library.__PAGE__.txt +1 -1
  105. package/console/library/__next.library.txt +1 -1
  106. package/console/library/agents/__next._full.txt +1 -1
  107. package/console/library/agents/__next._head.txt +1 -1
  108. package/console/library/agents/__next._index.txt +1 -1
  109. package/console/library/agents/__next._tree.txt +1 -1
  110. package/console/library/agents/__next.library.agents.__PAGE__.txt +1 -1
  111. package/console/library/agents/__next.library.agents.txt +1 -1
  112. package/console/library/agents/__next.library.txt +1 -1
  113. package/console/library/agents/__placeholder__/__placeholder__/__next._full.txt +1 -1
  114. package/console/library/agents/__placeholder__/__placeholder__/__next._head.txt +1 -1
  115. package/console/library/agents/__placeholder__/__placeholder__/__next._index.txt +1 -1
  116. package/console/library/agents/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  117. package/console/library/agents/__placeholder__/__placeholder__/__next.library.agents.$d$org.$d$slug.__PAGE__.txt +1 -1
  118. package/console/library/agents/__placeholder__/__placeholder__/__next.library.agents.$d$org.$d$slug.txt +1 -1
  119. package/console/library/agents/__placeholder__/__placeholder__/__next.library.agents.$d$org.txt +1 -1
  120. package/console/library/agents/__placeholder__/__placeholder__/__next.library.agents.txt +1 -1
  121. package/console/library/agents/__placeholder__/__placeholder__/__next.library.txt +1 -1
  122. package/console/library/agents/__placeholder__/__placeholder__.html +1 -1
  123. package/console/library/agents/__placeholder__/__placeholder__.txt +1 -1
  124. package/console/library/agents/new/__next._full.txt +1 -1
  125. package/console/library/agents/new/__next._head.txt +1 -1
  126. package/console/library/agents/new/__next._index.txt +1 -1
  127. package/console/library/agents/new/__next._tree.txt +1 -1
  128. package/console/library/agents/new/__next.library.agents.new.__PAGE__.txt +1 -1
  129. package/console/library/agents/new/__next.library.agents.new.txt +1 -1
  130. package/console/library/agents/new/__next.library.agents.txt +1 -1
  131. package/console/library/agents/new/__next.library.txt +1 -1
  132. package/console/library/agents/new.html +1 -1
  133. package/console/library/agents/new.txt +1 -1
  134. package/console/library/agents.html +1 -1
  135. package/console/library/agents.txt +1 -1
  136. package/console/library/mcp-servers/__next._full.txt +1 -1
  137. package/console/library/mcp-servers/__next._head.txt +1 -1
  138. package/console/library/mcp-servers/__next._index.txt +1 -1
  139. package/console/library/mcp-servers/__next._tree.txt +1 -1
  140. package/console/library/mcp-servers/__next.library.mcp-servers.__PAGE__.txt +1 -1
  141. package/console/library/mcp-servers/__next.library.mcp-servers.txt +1 -1
  142. package/console/library/mcp-servers/__next.library.txt +1 -1
  143. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next._full.txt +1 -1
  144. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next._head.txt +1 -1
  145. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next._index.txt +1 -1
  146. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  147. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next.library.mcp-servers.$d$org.$d$slug.__PAGE__.txt +1 -1
  148. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next.library.mcp-servers.$d$org.$d$slug.txt +1 -1
  149. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next.library.mcp-servers.$d$org.txt +1 -1
  150. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next.library.mcp-servers.txt +1 -1
  151. package/console/library/mcp-servers/__placeholder__/__placeholder__/__next.library.txt +1 -1
  152. package/console/library/mcp-servers/__placeholder__/__placeholder__.html +1 -1
  153. package/console/library/mcp-servers/__placeholder__/__placeholder__.txt +1 -1
  154. package/console/library/mcp-servers/new/__next._full.txt +1 -1
  155. package/console/library/mcp-servers/new/__next._head.txt +1 -1
  156. package/console/library/mcp-servers/new/__next._index.txt +1 -1
  157. package/console/library/mcp-servers/new/__next._tree.txt +1 -1
  158. package/console/library/mcp-servers/new/__next.library.mcp-servers.new.__PAGE__.txt +1 -1
  159. package/console/library/mcp-servers/new/__next.library.mcp-servers.new.txt +1 -1
  160. package/console/library/mcp-servers/new/__next.library.mcp-servers.txt +1 -1
  161. package/console/library/mcp-servers/new/__next.library.txt +1 -1
  162. package/console/library/mcp-servers/new.html +1 -1
  163. package/console/library/mcp-servers/new.txt +1 -1
  164. package/console/library/mcp-servers.html +1 -1
  165. package/console/library/mcp-servers.txt +1 -1
  166. package/console/library/plugins/__next._full.txt +1 -1
  167. package/console/library/plugins/__next._head.txt +1 -1
  168. package/console/library/plugins/__next._index.txt +1 -1
  169. package/console/library/plugins/__next._tree.txt +1 -1
  170. package/console/library/plugins/__next.library.plugins.__PAGE__.txt +1 -1
  171. package/console/library/plugins/__next.library.plugins.txt +1 -1
  172. package/console/library/plugins/__next.library.txt +1 -1
  173. package/console/library/plugins/__placeholder__/__placeholder__/__next._full.txt +1 -1
  174. package/console/library/plugins/__placeholder__/__placeholder__/__next._head.txt +1 -1
  175. package/console/library/plugins/__placeholder__/__placeholder__/__next._index.txt +1 -1
  176. package/console/library/plugins/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  177. package/console/library/plugins/__placeholder__/__placeholder__/__next.library.plugins.$d$org.$d$slug.__PAGE__.txt +1 -1
  178. package/console/library/plugins/__placeholder__/__placeholder__/__next.library.plugins.$d$org.$d$slug.txt +1 -1
  179. package/console/library/plugins/__placeholder__/__placeholder__/__next.library.plugins.$d$org.txt +1 -1
  180. package/console/library/plugins/__placeholder__/__placeholder__/__next.library.plugins.txt +1 -1
  181. package/console/library/plugins/__placeholder__/__placeholder__/__next.library.txt +1 -1
  182. package/console/library/plugins/__placeholder__/__placeholder__.html +1 -1
  183. package/console/library/plugins/__placeholder__/__placeholder__.txt +1 -1
  184. package/console/library/plugins/upload/__next._full.txt +1 -1
  185. package/console/library/plugins/upload/__next._head.txt +1 -1
  186. package/console/library/plugins/upload/__next._index.txt +1 -1
  187. package/console/library/plugins/upload/__next._tree.txt +1 -1
  188. package/console/library/plugins/upload/__next.library.plugins.txt +1 -1
  189. package/console/library/plugins/upload/__next.library.plugins.upload.__PAGE__.txt +1 -1
  190. package/console/library/plugins/upload/__next.library.plugins.upload.txt +1 -1
  191. package/console/library/plugins/upload/__next.library.txt +1 -1
  192. package/console/library/plugins/upload.html +1 -1
  193. package/console/library/plugins/upload.txt +1 -1
  194. package/console/library/plugins.html +1 -1
  195. package/console/library/plugins.txt +1 -1
  196. package/console/library/schedules/__next._full.txt +1 -1
  197. package/console/library/schedules/__next._head.txt +1 -1
  198. package/console/library/schedules/__next._index.txt +1 -1
  199. package/console/library/schedules/__next._tree.txt +1 -1
  200. package/console/library/schedules/__next.library.schedules.__PAGE__.txt +1 -1
  201. package/console/library/schedules/__next.library.schedules.txt +1 -1
  202. package/console/library/schedules/__next.library.txt +1 -1
  203. package/console/library/schedules/__placeholder__/__placeholder__/__next._full.txt +1 -1
  204. package/console/library/schedules/__placeholder__/__placeholder__/__next._head.txt +1 -1
  205. package/console/library/schedules/__placeholder__/__placeholder__/__next._index.txt +1 -1
  206. package/console/library/schedules/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  207. package/console/library/schedules/__placeholder__/__placeholder__/__next.library.schedules.$d$org.$d$slug.__PAGE__.txt +1 -1
  208. package/console/library/schedules/__placeholder__/__placeholder__/__next.library.schedules.$d$org.$d$slug.txt +1 -1
  209. package/console/library/schedules/__placeholder__/__placeholder__/__next.library.schedules.$d$org.txt +1 -1
  210. package/console/library/schedules/__placeholder__/__placeholder__/__next.library.schedules.txt +1 -1
  211. package/console/library/schedules/__placeholder__/__placeholder__/__next.library.txt +1 -1
  212. package/console/library/schedules/__placeholder__/__placeholder__.html +1 -1
  213. package/console/library/schedules/__placeholder__/__placeholder__.txt +1 -1
  214. package/console/library/schedules/new/__next._full.txt +1 -1
  215. package/console/library/schedules/new/__next._head.txt +1 -1
  216. package/console/library/schedules/new/__next._index.txt +1 -1
  217. package/console/library/schedules/new/__next._tree.txt +1 -1
  218. package/console/library/schedules/new/__next.library.schedules.new.__PAGE__.txt +1 -1
  219. package/console/library/schedules/new/__next.library.schedules.new.txt +1 -1
  220. package/console/library/schedules/new/__next.library.schedules.txt +1 -1
  221. package/console/library/schedules/new/__next.library.txt +1 -1
  222. package/console/library/schedules/new.html +1 -1
  223. package/console/library/schedules/new.txt +1 -1
  224. package/console/library/schedules.html +1 -1
  225. package/console/library/schedules.txt +1 -1
  226. package/console/library/skills/__next._full.txt +1 -1
  227. package/console/library/skills/__next._head.txt +1 -1
  228. package/console/library/skills/__next._index.txt +1 -1
  229. package/console/library/skills/__next._tree.txt +1 -1
  230. package/console/library/skills/__next.library.skills.__PAGE__.txt +1 -1
  231. package/console/library/skills/__next.library.skills.txt +1 -1
  232. package/console/library/skills/__next.library.txt +1 -1
  233. package/console/library/skills/__placeholder__/__placeholder__/__next._full.txt +1 -1
  234. package/console/library/skills/__placeholder__/__placeholder__/__next._head.txt +1 -1
  235. package/console/library/skills/__placeholder__/__placeholder__/__next._index.txt +1 -1
  236. package/console/library/skills/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  237. package/console/library/skills/__placeholder__/__placeholder__/__next.library.skills.$d$org.$d$slug.__PAGE__.txt +1 -1
  238. package/console/library/skills/__placeholder__/__placeholder__/__next.library.skills.$d$org.$d$slug.txt +1 -1
  239. package/console/library/skills/__placeholder__/__placeholder__/__next.library.skills.$d$org.txt +1 -1
  240. package/console/library/skills/__placeholder__/__placeholder__/__next.library.skills.txt +1 -1
  241. package/console/library/skills/__placeholder__/__placeholder__/__next.library.txt +1 -1
  242. package/console/library/skills/__placeholder__/__placeholder__.html +1 -1
  243. package/console/library/skills/__placeholder__/__placeholder__.txt +1 -1
  244. package/console/library/skills/new/__next._full.txt +1 -1
  245. package/console/library/skills/new/__next._head.txt +1 -1
  246. package/console/library/skills/new/__next._index.txt +1 -1
  247. package/console/library/skills/new/__next._tree.txt +1 -1
  248. package/console/library/skills/new/__next.library.skills.new.__PAGE__.txt +1 -1
  249. package/console/library/skills/new/__next.library.skills.new.txt +1 -1
  250. package/console/library/skills/new/__next.library.skills.txt +1 -1
  251. package/console/library/skills/new/__next.library.txt +1 -1
  252. package/console/library/skills/new.html +1 -1
  253. package/console/library/skills/new.txt +1 -1
  254. package/console/library/skills.html +1 -1
  255. package/console/library/skills.txt +1 -1
  256. package/console/library/workflows/__next._full.txt +1 -1
  257. package/console/library/workflows/__next._head.txt +1 -1
  258. package/console/library/workflows/__next._index.txt +1 -1
  259. package/console/library/workflows/__next._tree.txt +1 -1
  260. package/console/library/workflows/__next.library.txt +1 -1
  261. package/console/library/workflows/__next.library.workflows.__PAGE__.txt +1 -1
  262. package/console/library/workflows/__next.library.workflows.txt +1 -1
  263. package/console/library/workflows/__placeholder__/__placeholder__/__next._full.txt +1 -1
  264. package/console/library/workflows/__placeholder__/__placeholder__/__next._head.txt +1 -1
  265. package/console/library/workflows/__placeholder__/__placeholder__/__next._index.txt +1 -1
  266. package/console/library/workflows/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  267. package/console/library/workflows/__placeholder__/__placeholder__/__next.library.txt +1 -1
  268. package/console/library/workflows/__placeholder__/__placeholder__/__next.library.workflows.$d$org.$d$slug.__PAGE__.txt +1 -1
  269. package/console/library/workflows/__placeholder__/__placeholder__/__next.library.workflows.$d$org.$d$slug.txt +1 -1
  270. package/console/library/workflows/__placeholder__/__placeholder__/__next.library.workflows.$d$org.txt +1 -1
  271. package/console/library/workflows/__placeholder__/__placeholder__/__next.library.workflows.txt +1 -1
  272. package/console/library/workflows/__placeholder__/__placeholder__.html +1 -1
  273. package/console/library/workflows/__placeholder__/__placeholder__.txt +1 -1
  274. package/console/library/workflows/executions/__next._full.txt +1 -1
  275. package/console/library/workflows/executions/__next._head.txt +1 -1
  276. package/console/library/workflows/executions/__next._index.txt +1 -1
  277. package/console/library/workflows/executions/__next._tree.txt +1 -1
  278. package/console/library/workflows/executions/__next.library.txt +1 -1
  279. package/console/library/workflows/executions/__next.library.workflows.executions.__PAGE__.txt +1 -1
  280. package/console/library/workflows/executions/__next.library.workflows.executions.txt +1 -1
  281. package/console/library/workflows/executions/__next.library.workflows.txt +1 -1
  282. package/console/library/workflows/executions.html +1 -1
  283. package/console/library/workflows/executions.txt +1 -1
  284. package/console/library/workflows/new/__next._full.txt +1 -1
  285. package/console/library/workflows/new/__next._head.txt +1 -1
  286. package/console/library/workflows/new/__next._index.txt +1 -1
  287. package/console/library/workflows/new/__next._tree.txt +1 -1
  288. package/console/library/workflows/new/__next.library.txt +1 -1
  289. package/console/library/workflows/new/__next.library.workflows.new.__PAGE__.txt +1 -1
  290. package/console/library/workflows/new/__next.library.workflows.new.txt +1 -1
  291. package/console/library/workflows/new/__next.library.workflows.txt +1 -1
  292. package/console/library/workflows/new.html +1 -1
  293. package/console/library/workflows/new.txt +1 -1
  294. package/console/library/workflows.html +1 -1
  295. package/console/library/workflows.txt +1 -1
  296. package/console/library.html +1 -1
  297. package/console/library.txt +1 -1
  298. package/console/login/__next._full.txt +1 -1
  299. package/console/login/__next._head.txt +1 -1
  300. package/console/login/__next._index.txt +1 -1
  301. package/console/login/__next._tree.txt +1 -1
  302. package/console/login/__next.login.__PAGE__.txt +1 -1
  303. package/console/login/__next.login.txt +1 -1
  304. package/console/login.html +1 -1
  305. package/console/login.txt +1 -1
  306. package/console/marketplace/__next._full.txt +1 -1
  307. package/console/marketplace/__next._head.txt +1 -1
  308. package/console/marketplace/__next._index.txt +1 -1
  309. package/console/marketplace/__next._tree.txt +1 -1
  310. package/console/marketplace/__next.marketplace.__PAGE__.txt +1 -1
  311. package/console/marketplace/__next.marketplace.txt +1 -1
  312. package/console/marketplace.html +1 -1
  313. package/console/marketplace.txt +1 -1
  314. package/console/oauth/slack/callback/__next._full.txt +1 -1
  315. package/console/oauth/slack/callback/__next._head.txt +1 -1
  316. package/console/oauth/slack/callback/__next._index.txt +1 -1
  317. package/console/oauth/slack/callback/__next._tree.txt +1 -1
  318. package/console/oauth/slack/callback/__next.oauth.slack.callback.__PAGE__.txt +1 -1
  319. package/console/oauth/slack/callback/__next.oauth.slack.callback.txt +1 -1
  320. package/console/oauth/slack/callback/__next.oauth.slack.txt +1 -1
  321. package/console/oauth/slack/callback/__next.oauth.txt +1 -1
  322. package/console/oauth/slack/callback.html +1 -1
  323. package/console/oauth/slack/callback.txt +1 -1
  324. package/console/sessions/__placeholder__/__next._full.txt +1 -1
  325. package/console/sessions/__placeholder__/__next._head.txt +1 -1
  326. package/console/sessions/__placeholder__/__next._index.txt +1 -1
  327. package/console/sessions/__placeholder__/__next._tree.txt +1 -1
  328. package/console/sessions/__placeholder__/__next.sessions.$d$id.__PAGE__.txt +1 -1
  329. package/console/sessions/__placeholder__/__next.sessions.$d$id.txt +1 -1
  330. package/console/sessions/__placeholder__/__next.sessions.txt +1 -1
  331. package/console/sessions/__placeholder__.html +1 -1
  332. package/console/sessions/__placeholder__.txt +1 -1
  333. package/console/settings/__next._full.txt +1 -1
  334. package/console/settings/__next._head.txt +1 -1
  335. package/console/settings/__next._index.txt +1 -1
  336. package/console/settings/__next._tree.txt +1 -1
  337. package/console/settings/__next.settings.__PAGE__.txt +1 -1
  338. package/console/settings/__next.settings.txt +1 -1
  339. package/console/settings/account-preferences/__next._full.txt +1 -1
  340. package/console/settings/account-preferences/__next._head.txt +1 -1
  341. package/console/settings/account-preferences/__next._index.txt +1 -1
  342. package/console/settings/account-preferences/__next._tree.txt +1 -1
  343. package/console/settings/account-preferences/__next.settings.account-preferences.__PAGE__.txt +1 -1
  344. package/console/settings/account-preferences/__next.settings.account-preferences.txt +1 -1
  345. package/console/settings/account-preferences/__next.settings.txt +1 -1
  346. package/console/settings/account-preferences.html +1 -1
  347. package/console/settings/account-preferences.txt +1 -1
  348. package/console/settings/api-keys/__next._full.txt +1 -1
  349. package/console/settings/api-keys/__next._head.txt +1 -1
  350. package/console/settings/api-keys/__next._index.txt +1 -1
  351. package/console/settings/api-keys/__next._tree.txt +1 -1
  352. package/console/settings/api-keys/__next.settings.api-keys.__PAGE__.txt +1 -1
  353. package/console/settings/api-keys/__next.settings.api-keys.txt +1 -1
  354. package/console/settings/api-keys/__next.settings.txt +1 -1
  355. package/console/settings/api-keys.html +1 -1
  356. package/console/settings/api-keys.txt +1 -1
  357. package/console/settings/billing/__next._full.txt +1 -1
  358. package/console/settings/billing/__next._head.txt +1 -1
  359. package/console/settings/billing/__next._index.txt +1 -1
  360. package/console/settings/billing/__next._tree.txt +1 -1
  361. package/console/settings/billing/__next.settings.billing.__PAGE__.txt +1 -1
  362. package/console/settings/billing/__next.settings.billing.txt +1 -1
  363. package/console/settings/billing/__next.settings.txt +1 -1
  364. package/console/settings/billing.html +1 -1
  365. package/console/settings/billing.txt +1 -1
  366. package/console/settings/channel-apps/__next._full.txt +1 -1
  367. package/console/settings/channel-apps/__next._head.txt +1 -1
  368. package/console/settings/channel-apps/__next._index.txt +1 -1
  369. package/console/settings/channel-apps/__next._tree.txt +1 -1
  370. package/console/settings/channel-apps/__next.settings.channel-apps.__PAGE__.txt +1 -1
  371. package/console/settings/channel-apps/__next.settings.channel-apps.txt +1 -1
  372. package/console/settings/channel-apps/__next.settings.txt +1 -1
  373. package/console/settings/channel-apps.html +1 -1
  374. package/console/settings/channel-apps.txt +1 -1
  375. package/console/settings/cursor-accounts/__next._full.txt +1 -1
  376. package/console/settings/cursor-accounts/__next._head.txt +1 -1
  377. package/console/settings/cursor-accounts/__next._index.txt +1 -1
  378. package/console/settings/cursor-accounts/__next._tree.txt +1 -1
  379. package/console/settings/cursor-accounts/__next.settings.cursor-accounts.__PAGE__.txt +1 -1
  380. package/console/settings/cursor-accounts/__next.settings.cursor-accounts.txt +1 -1
  381. package/console/settings/cursor-accounts/__next.settings.txt +1 -1
  382. package/console/settings/cursor-accounts.html +1 -1
  383. package/console/settings/cursor-accounts.txt +1 -1
  384. package/console/settings/environments/__next._full.txt +1 -1
  385. package/console/settings/environments/__next._head.txt +1 -1
  386. package/console/settings/environments/__next._index.txt +1 -1
  387. package/console/settings/environments/__next._tree.txt +1 -1
  388. package/console/settings/environments/__next.settings.environments.__PAGE__.txt +1 -1
  389. package/console/settings/environments/__next.settings.environments.txt +1 -1
  390. package/console/settings/environments/__next.settings.txt +1 -1
  391. package/console/settings/environments.html +1 -1
  392. package/console/settings/environments.txt +1 -1
  393. package/console/settings/identity-providers/__next._full.txt +1 -1
  394. package/console/settings/identity-providers/__next._head.txt +1 -1
  395. package/console/settings/identity-providers/__next._index.txt +1 -1
  396. package/console/settings/identity-providers/__next._tree.txt +1 -1
  397. package/console/settings/identity-providers/__next.settings.identity-providers.__PAGE__.txt +1 -1
  398. package/console/settings/identity-providers/__next.settings.identity-providers.txt +1 -1
  399. package/console/settings/identity-providers/__next.settings.txt +1 -1
  400. package/console/settings/identity-providers.html +1 -1
  401. package/console/settings/identity-providers.txt +1 -1
  402. package/console/settings/invitations/__next._full.txt +1 -1
  403. package/console/settings/invitations/__next._head.txt +1 -1
  404. package/console/settings/invitations/__next._index.txt +1 -1
  405. package/console/settings/invitations/__next._tree.txt +1 -1
  406. package/console/settings/invitations/__next.settings.invitations.__PAGE__.txt +1 -1
  407. package/console/settings/invitations/__next.settings.invitations.txt +1 -1
  408. package/console/settings/invitations/__next.settings.txt +1 -1
  409. package/console/settings/invitations.html +1 -1
  410. package/console/settings/invitations.txt +1 -1
  411. package/console/settings/members/__next._full.txt +1 -1
  412. package/console/settings/members/__next._head.txt +1 -1
  413. package/console/settings/members/__next._index.txt +1 -1
  414. package/console/settings/members/__next._tree.txt +1 -1
  415. package/console/settings/members/__next.settings.members.__PAGE__.txt +1 -1
  416. package/console/settings/members/__next.settings.members.txt +1 -1
  417. package/console/settings/members/__next.settings.txt +1 -1
  418. package/console/settings/members.html +1 -1
  419. package/console/settings/members.txt +1 -1
  420. package/console/settings/memory/__next._full.txt +1 -1
  421. package/console/settings/memory/__next._head.txt +1 -1
  422. package/console/settings/memory/__next._index.txt +1 -1
  423. package/console/settings/memory/__next._tree.txt +1 -1
  424. package/console/settings/memory/__next.settings.memory.__PAGE__.txt +1 -1
  425. package/console/settings/memory/__next.settings.memory.txt +1 -1
  426. package/console/settings/memory/__next.settings.txt +1 -1
  427. package/console/settings/memory.html +1 -1
  428. package/console/settings/memory.txt +1 -1
  429. package/console/settings/oauth-apps/__next._full.txt +1 -1
  430. package/console/settings/oauth-apps/__next._head.txt +1 -1
  431. package/console/settings/oauth-apps/__next._index.txt +1 -1
  432. package/console/settings/oauth-apps/__next._tree.txt +1 -1
  433. package/console/settings/oauth-apps/__next.settings.oauth-apps.__PAGE__.txt +1 -1
  434. package/console/settings/oauth-apps/__next.settings.oauth-apps.txt +1 -1
  435. package/console/settings/oauth-apps/__next.settings.txt +1 -1
  436. package/console/settings/oauth-apps.html +1 -1
  437. package/console/settings/oauth-apps.txt +1 -1
  438. package/console/settings/org-preferences/__next._full.txt +1 -1
  439. package/console/settings/org-preferences/__next._head.txt +1 -1
  440. package/console/settings/org-preferences/__next._index.txt +1 -1
  441. package/console/settings/org-preferences/__next._tree.txt +1 -1
  442. package/console/settings/org-preferences/__next.settings.org-preferences.__PAGE__.txt +1 -1
  443. package/console/settings/org-preferences/__next.settings.org-preferences.txt +1 -1
  444. package/console/settings/org-preferences/__next.settings.txt +1 -1
  445. package/console/settings/org-preferences.html +1 -1
  446. package/console/settings/org-preferences.txt +1 -1
  447. package/console/settings/org-profile/__next._full.txt +1 -1
  448. package/console/settings/org-profile/__next._head.txt +1 -1
  449. package/console/settings/org-profile/__next._index.txt +1 -1
  450. package/console/settings/org-profile/__next._tree.txt +1 -1
  451. package/console/settings/org-profile/__next.settings.org-profile.__PAGE__.txt +1 -1
  452. package/console/settings/org-profile/__next.settings.org-profile.txt +1 -1
  453. package/console/settings/org-profile/__next.settings.txt +1 -1
  454. package/console/settings/org-profile.html +1 -1
  455. package/console/settings/org-profile.txt +1 -1
  456. package/console/settings/platform-clients/__next._full.txt +1 -1
  457. package/console/settings/platform-clients/__next._head.txt +1 -1
  458. package/console/settings/platform-clients/__next._index.txt +1 -1
  459. package/console/settings/platform-clients/__next._tree.txt +1 -1
  460. package/console/settings/platform-clients/__next.settings.platform-clients.__PAGE__.txt +1 -1
  461. package/console/settings/platform-clients/__next.settings.platform-clients.txt +1 -1
  462. package/console/settings/platform-clients/__next.settings.txt +1 -1
  463. package/console/settings/platform-clients.html +1 -1
  464. package/console/settings/platform-clients.txt +1 -1
  465. package/console/settings/pricing-governance/__next._full.txt +1 -1
  466. package/console/settings/pricing-governance/__next._head.txt +1 -1
  467. package/console/settings/pricing-governance/__next._index.txt +1 -1
  468. package/console/settings/pricing-governance/__next._tree.txt +1 -1
  469. package/console/settings/pricing-governance/__next.settings.pricing-governance.__PAGE__.txt +1 -1
  470. package/console/settings/pricing-governance/__next.settings.pricing-governance.txt +1 -1
  471. package/console/settings/pricing-governance/__next.settings.txt +1 -1
  472. package/console/settings/pricing-governance.html +1 -1
  473. package/console/settings/pricing-governance.txt +1 -1
  474. package/console/settings/provider-standing/__next._full.txt +1 -1
  475. package/console/settings/provider-standing/__next._head.txt +1 -1
  476. package/console/settings/provider-standing/__next._index.txt +1 -1
  477. package/console/settings/provider-standing/__next._tree.txt +1 -1
  478. package/console/settings/provider-standing/__next.settings.provider-standing.__PAGE__.txt +1 -1
  479. package/console/settings/provider-standing/__next.settings.provider-standing.txt +1 -1
  480. package/console/settings/provider-standing/__next.settings.txt +1 -1
  481. package/console/settings/provider-standing.html +1 -1
  482. package/console/settings/provider-standing.txt +1 -1
  483. package/console/settings/usage/__next._full.txt +1 -1
  484. package/console/settings/usage/__next._head.txt +1 -1
  485. package/console/settings/usage/__next._index.txt +1 -1
  486. package/console/settings/usage/__next._tree.txt +1 -1
  487. package/console/settings/usage/__next.settings.txt +1 -1
  488. package/console/settings/usage/__next.settings.usage.__PAGE__.txt +1 -1
  489. package/console/settings/usage/__next.settings.usage.txt +1 -1
  490. package/console/settings/usage.html +1 -1
  491. package/console/settings/usage.txt +1 -1
  492. package/console/settings.html +1 -1
  493. package/console/settings.txt +1 -1
  494. package/console/workflows/__next._full.txt +1 -1
  495. package/console/workflows/__next._head.txt +1 -1
  496. package/console/workflows/__next._index.txt +1 -1
  497. package/console/workflows/__next._tree.txt +1 -1
  498. package/console/workflows/__next.workflows.__PAGE__.txt +1 -1
  499. package/console/workflows/__next.workflows.txt +1 -1
  500. package/console/workflows/__placeholder__/__placeholder__/__next._full.txt +1 -1
  501. package/console/workflows/__placeholder__/__placeholder__/__next._head.txt +1 -1
  502. package/console/workflows/__placeholder__/__placeholder__/__next._index.txt +1 -1
  503. package/console/workflows/__placeholder__/__placeholder__/__next._tree.txt +1 -1
  504. package/console/workflows/__placeholder__/__placeholder__/__next.workflows.$d$org.$d$slug.__PAGE__.txt +1 -1
  505. package/console/workflows/__placeholder__/__placeholder__/__next.workflows.$d$org.$d$slug.txt +1 -1
  506. package/console/workflows/__placeholder__/__placeholder__/__next.workflows.$d$org.txt +1 -1
  507. package/console/workflows/__placeholder__/__placeholder__/__next.workflows.txt +1 -1
  508. package/console/workflows/__placeholder__/__placeholder__.html +1 -1
  509. package/console/workflows/__placeholder__/__placeholder__.txt +1 -1
  510. package/console/workflows/executions/__next._full.txt +1 -1
  511. package/console/workflows/executions/__next._head.txt +1 -1
  512. package/console/workflows/executions/__next._index.txt +1 -1
  513. package/console/workflows/executions/__next._tree.txt +1 -1
  514. package/console/workflows/executions/__next.workflows.executions.__PAGE__.txt +1 -1
  515. package/console/workflows/executions/__next.workflows.executions.txt +1 -1
  516. package/console/workflows/executions/__next.workflows.txt +1 -1
  517. package/console/workflows/executions/__placeholder__/__next._full.txt +1 -1
  518. package/console/workflows/executions/__placeholder__/__next._head.txt +1 -1
  519. package/console/workflows/executions/__placeholder__/__next._index.txt +1 -1
  520. package/console/workflows/executions/__placeholder__/__next._tree.txt +1 -1
  521. package/console/workflows/executions/__placeholder__/__next.workflows.executions.$d$id.__PAGE__.txt +1 -1
  522. package/console/workflows/executions/__placeholder__/__next.workflows.executions.$d$id.txt +1 -1
  523. package/console/workflows/executions/__placeholder__/__next.workflows.executions.txt +1 -1
  524. package/console/workflows/executions/__placeholder__/__next.workflows.txt +1 -1
  525. package/console/workflows/executions/__placeholder__.html +1 -1
  526. package/console/workflows/executions/__placeholder__.txt +1 -1
  527. package/console/workflows/executions.html +1 -1
  528. package/console/workflows/executions.txt +1 -1
  529. package/console/workflows.html +1 -1
  530. package/console/workflows.txt +1 -1
  531. package/main.js +1 -1
  532. package/package.json +6 -6
  533. /package/console/_next/static/{lfaVPQEp6QVtLMoAxlVdY → DIP6TU4_3iTuSMsvqDdVC}/_buildManifest.js +0 -0
  534. /package/console/_next/static/{lfaVPQEp6QVtLMoAxlVdY → DIP6TU4_3iTuSMsvqDdVC}/_clientMiddlewareManifest.js +0 -0
  535. /package/console/_next/static/{lfaVPQEp6QVtLMoAxlVdY → DIP6TU4_3iTuSMsvqDdVC}/_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_fs6.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{throw notFoundError("environment",environmentId)}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)=>list7(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(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(newAuthorizeVisibilityTransitionStep(UPDATE_VISIBILITY_ENVIRONMENT_KEY,deps.authorizer)).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{throw notFoundError("environment",input.resourceId)}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 list7(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_crypto18=require("node:crypto"),CONNECT_EXECUTION_ID_PREFIX="connect-";function newConnectExecutionId(mcpServerId){return`${CONNECT_EXECUTION_ID_PREFIX}${mcpServerId}-${(0,import_node_crypto18.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(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_crypto19=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_crypto19.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}function carriesPlatformClientClaim(rawToken){let segments=rawToken.split(".");if(segments.length!==3)return!1;try{let payload=JSON.parse(Buffer.from(segments[1],"base64url").toString("utf8"));return typeof payload.platform_client_id=="string"&&payload.platform_client_id!==""}catch{return!1}}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_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(){return{name:"ResolveMemoryDefaults",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);spec.subjectIdentityAccountId=captureCredential?.subjectIdentityAccountId??"",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_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){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))}}}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)=>list8(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()).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,resolveMemoryCreateTargets)).addStep(newCheckMemoryEnablementStep(deps.store)).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 list8(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){if(ref.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??"")===ref.slug){if(ref.org!==""&&app.metadata?.org===ref.org)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:ref.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,app=>app.spec===void 0?[]:[app.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");return deleted}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.logger)).build().execute(reqCtx);let list11=reqCtx.get(LIST_RESULT_KEY7);if(list11===void 0)throw internalError(new Error("list result missing from pipeline context"),"OAuthApp list not found in context");return list11}function newListByOrgStep2(store,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 apps=[];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&&(redactOAuthApp(app),apps.push(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_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)}}};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");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 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?.getOrganizationIdByExternalOrgId?.bind(deps.organizationDirectory);router.service(OrganizationQueryController,{get:(orgId,ctx)=>get17(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 kindOf16(ctx){return ctx.values.get(apiResourceKindKey)}async function createOrganization(deps,org,ctx){let reqCtx=new RequestContext(OrganizationSchema,org,callerIdentityOf(ctx),kindOf16(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()).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger));for(let step of stepsForSlot(deps.gateSteps,"org-create:post-persist"))builder2.addStep(step);return await builder2.addStep(newIndexSearchStep(deps.store,organizationSearchExtractor,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function update13(deps,org,ctx){let reqCtx=new RequestContext(OrganizationSchema,org,callerIdentityOf(ctx),kindOf16(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),kindOf16(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),kindOf16(ctx));await newPipeline("organization-delete",deps.logger).addStep(newAuthorizeStep(OrganizationCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newExtractResourceIdStep()).addStep(newLoadExistingForDeleteStep(deps.store,OrganizationSchema)).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 get17(deps,orgId,ctx){let reqCtx=new RequestContext(OrganizationQueryController.method.get.input,orgId,callerIdentityOf(ctx),kindOf16(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),kindOf16(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),kindOf16(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 orgId=await lookup3(input.externalOrgId);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 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{throw notFoundError("mcp_server",mcpServerId)}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")}}async function resolveOAuthAppRef2(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 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{throw notFoundError("mcp_server",mcpServerId)}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 resolveOAuthAppRef2(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(record,key){let value=record[key];return typeof value=="string"?value:""}function readStringArray(record,key){let list11=record[key];return Array.isArray(list11)?list11.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_crypto21=require("node:crypto");var import_node_crypto20=require("node:crypto");function generatePkce(){let verifier=(0,import_node_crypto20.randomBytes)(32).toString("base64url"),challenge=(0,import_node_crypto20.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{throw notFoundError("mcp_server",mcpServerId)}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 resolveOAuthAppRef2(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_crypto21.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{throw notFoundError("mcp_server",mcpServerId)}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{throw notFoundError("mcp_server",mcpServerId)}}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 resolveOAuthAppRef2(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)=>get18(deps,id,ctx),getByReference:(ref,ctx)=>getByReference10(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 kindOf17(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),kindOf17(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(newGuardPublicVisibilityStep(deps.authorizer)).addStep(newCompleteEndpointAuthStep(endpointAuthDeps(deps))).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newNormalizeReferencesStep()).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),kindOf17(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(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),kindOf17(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),kindOf17(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),kindOf17(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(newAuthorizeVisibilityTransitionStep(UPDATE_VISIBILITY_MCP_SERVER_KEY,deps.authorizer)).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{throw notFoundError("mcp_server",input.resourceId)}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 get18(deps,id,ctx){let reqCtx=new RequestContext(McpServerQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf17(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 getByReference10(deps,ref,ctx){let reqCtx=new RequestContext(McpServerQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf17(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})}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.temporalHostPort,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.22.0";var file_ai_stigmer_agentic_session_v1_io=fileDesc("CiZhaS9zdGlnbWVyL2FnZW50aWMvc2Vzc2lvbi92MS9pby5wcm90bxIdYWkuc3RpZ21lci5hZ2VudGljLnNlc3Npb24udjEiIgoJU2Vzc2lvbklkEhUKBXZhbHVlGAEgASgJQga6SAPIAQEiIAoHQWdlbnRJZBIVCgV2YWx1ZRgBIAEoCUIGukgDyAEBIlsKC1Nlc3Npb25MaXN0EhMKC3RvdGFsX3BhZ2VzGAEgASgFEjcKB2VudHJpZXMYAiADKAsyJi5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5TZXNzaW9uIkoKE0xpc3RTZXNzaW9uc1JlcXVlc3QSEQoJcGFnZV9zaXplGAEgASgFEhIKCnBhZ2VfdG9rZW4YAiABKAkSDAoEdGFncxgDIAMoCSJuCiJMaXN0U2Vzc2lvbnNCeUFnZW50SW5zdGFuY2VSZXF1ZXN0EiEKEWFnZW50X2luc3RhbmNlX2lkGAEgASgJQga6SAPIAQESEQoJcGFnZV9zaXplGAIgASgFEhIKCnBhZ2VfdG9rZW4YAyABKAkiYQocTGlzdFNlc3Npb25zQnlDaGFubmVsUmVxdWVzdBIaCgpjaGFubmVsX2lkGAEgASgJQga6SAPIAQESEQoJcGFnZV9zaXplGAIgASgFEhIKCnBhZ2VfdG9rZW4YAyABKAkiQgobVXBkYXRlU2Vzc2lvblN1YmplY3RSZXF1ZXN0EhIKAmlkGAEgASgJQga6SAPIAQESDwoHc3ViamVjdBgCIAEoCWIGcHJvdG8z",[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 LIST_RESULT_KEY8="listResult",CHANNEL_ID_LABEL_KEY="stigmer.ai/channel-id";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.listResources(ApiResourceKind.agent_execution)}catch(error2){throw internalError(error2,"failed to list agent executions")}let executions=[];for(let data of rows){let execution;try{execution=fromBinary2(AgentExecutionSchema,data)}catch(error2){logger2.warn("Failed to unmarshal execution, skipping",{error:error2 instanceof Error?error2.message:String(error2)});continue}(execution.spec?.sessionId??"")===sessionId&&executions.push(execution)}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 sessions=await restrictListByReadScope(listReadScope,ctx.callerIdentity,ApiResourceKind.session,await loadAllSessions(store,logger2,ctx.apiResourceKind),"");sessions.sort((a5,b7)=>compareCreatedAtDesc(a5.status?.audit?.specAudit?.createdAt,b7.status?.audit?.specAudit?.createdAt)),logger2.info("Loaded sessions from database",{count:sessions.length}),ctx.set(LIST_RESULT_KEY8,create2(SessionListSchema,{entries:sessions}))}}}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 sessions=await loadAllSessions(store,logger2,ctx.apiResourceKind),filtered=await restrictListByReadScope(listReadScope,ctx.callerIdentity,ApiResourceKind.session,sessions.filter(session=>(session.spec?.agentInstanceId??"")===agentInstanceId),"");logger2.info("Filtered sessions by agent instance",{agentInstanceId,totalSessions:sessions.length,filteredSessions:filtered.length}),ctx.set(LIST_RESULT_KEY8,create2(SessionListSchema,{entries:filtered}))}}}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 sessions=await loadAllSessions(store,logger2,ctx.apiResourceKind),filtered=await restrictListByReadScope(listReadScope,ctx.callerIdentity,ApiResourceKind.session,sessions.filter(session=>(session.metadata?.labels??{})[CHANNEL_ID_LABEL_KEY]===channelId),"");logger2.info("Filtered sessions by channel",{channelId,totalSessions:sessions.length,filteredSessions:filtered.length}),ctx.set(LIST_RESULT_KEY8,create2(SessionListSchema,{entries:filtered}))}}}async function loadAllSessions(store,logger2,kind){let rows;try{rows=await store.listResources(kind)}catch(error2){throw internalError(error2,"failed to list sessions")}let sessions=[];for(let data of rows){let session;try{session=fromBinary2(SessionSchema,data)}catch(error2){logger2.warn("Failed to unmarshal session, skipping",{error:error2 instanceof Error?error2.message:String(error2)});continue}sessions.push(session)}return sessions}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)=>get19(deps,id,ctx),list:(req,ctx)=>list9(deps,req,ctx),listByAgentInstance:(req,ctx)=>listByAgentInstance(deps,req,ctx),listByChannel:(req,ctx)=>listByChannel(deps,req,ctx)})}function kindOf18(ctx){return ctx.values.get(apiResourceKindKey)}async function createSession(deps,session,ctx){let reqCtx=new RequestContext(SessionSchema,session,callerIdentityOf(ctx),kindOf18(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());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),kindOf18(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),kindOf18(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),kindOf18(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 get19(deps,id,ctx){let reqCtx=new RequestContext(SessionQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf18(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 list9(deps,req,ctx){let reqCtx=new RequestContext(SessionQueryController.method.list.input,req,callerIdentityOf(ctx),kindOf18(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),kindOf18(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),kindOf18(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 ARTIFACT_BYTES_KEY="pushArtifactBytes";function newResolveArtifactSourceStep(slots,binding){return{name:"ResolveArtifactSource",async execute(ctx){let{artifact,artifactUploadRef}=binding.source(ctx.input);if(artifactUploadRef===""){ctx.set(ARTIFACT_BYTES_KEY,artifact);return}if(slots===void 0)throw failedPreconditionError(binding.laneNotConfigured);let data;try{data=await slots.consume(artifactUploadRef)}catch(error2){throw invalidArgumentError(`artifact_upload_ref not usable: ${error2 instanceof Error?error2.message:String(error2)} \u2014 request a new upload URL via createArtifactUploadUrl`)}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 record of records){let snapshot;try{snapshot=fromBinary2(binding.schema,record.data)}catch{continue}let isCurrent=!currentMarked&&headHash!==""&&binding.headHashOf(snapshot)===headHash;currentMarked=currentMarked||isCurrent,entries.push(binding.mapEntry(snapshot,isCurrent,record.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 text=decoded.toString("utf8"),index2=Number.parseInt(text,10);if(!Number.isSafeInteger(index2)||String(index2)!==text||index2<0)throw invalidArgumentError("invalid page_token");return index2}function idOf(resource){return metadataOf(resource)?.id??""}var TASK_KIND_REGISTRY_PATH="/v1/proxy/task-kind-registry",MODEL_REGISTRY_PATH="/v1/proxy/model-registry",SKILL_ARTIFACTS_PATH_PREFIX="/v1/skill-artifacts";var MAX_SKILL_MD_SIZE=1*1024*1024,DEFAULT_SLOT_TTL_MS=900*1e3,REF_BYTE_LEN=16,REF_PREFIX="sau_",UPLOADS_SEGMENT="/uploads/",DOWNLOAD_KEY_PREFIX="skills/",NESTED_SKILL_MD_HINT="SKILL.md must be at the archive root \u2014 zip the skill folder's contents, not the folder itself",TRANSFER_LANE_NOT_CONFIGURED="skill artifact transfer lane is not configured on this server";var import_node_path11=__toESM(require("node:path"),1);var ArtifactNotFoundError=class extends Error{constructor(storageKey){super(`artifact not found: ${storageKey}`),this.name="ArtifactNotFoundError"}},ARCHIVE_CONTENT_TYPE="application/zip";function newContentAddressedArchiveStore(driver,keyPrefix){let virtualRoot=import_node_path11.default.resolve(import_node_path11.default.sep,"archive-store"),keyEscapesStore=storageKey=>{let resolved=import_node_path11.default.resolve(virtualRoot,storageKey);return resolved!==virtualRoot&&!resolved.startsWith(virtualRoot+import_node_path11.default.sep)};return{getStorageKey(hash){return`${keyPrefix}${hash}.zip`},async store(hash,data){let storageKey=this.getStorageKey(hash);return await driver.upload(storageKey,data,ARCHIVE_CONTENT_TYPE),storageKey},async get(storageKey){if(keyEscapesStore(storageKey))throw new ArtifactNotFoundError(storageKey);try{return await driver.download(storageKey)}catch(error2){throw error2 instanceof ArtifactStorageNotFoundError?new ArtifactNotFoundError(storageKey):new Error(`failed to read artifact: ${error2 instanceof Error?error2.message:String(error2)}`)}},async exists(hash){return driver.exists(this.getStorageKey(hash))},async size(storageKey){if(keyEscapesStore(storageKey))throw new ArtifactNotFoundError(storageKey);try{return await driver.size(storageKey)}catch(error2){throw error2 instanceof ArtifactStorageNotFoundError?new ArtifactNotFoundError(storageKey):new Error(`failed to stat artifact: ${error2 instanceof Error?error2.message:String(error2)}`)}}}}var SKILL_ARTIFACT_KEY_PREFIX="skills/";function newSkillArtifactStorage(driver){return newContentAddressedArchiveStore(driver,SKILL_ARTIFACT_KEY_PREFIX)}var import_node_crypto22=require("node:crypto"),import_node_fs7=__toESM(require("node:fs"),1),import_node_path12=__toESM(require("node:path"),1),import_promises6=require("node:stream/promises");var 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"}},SlotEmptyError=class extends Error{constructor(){super("upload reference has no uploaded bytes"),this.name="SlotEmptyError"}},SizeMismatchError=class extends Error{constructor(received,declared){super(`upload size mismatch: received ${received} bytes, declared ${declared}`),this.name="SizeMismatchError"}},UploadSlots=class{slots=new Map;stagingDir;ttlMs;maxSize;now;constructor(stagingDir,ttlMs,maxSize,now=Date.now){import_node_fs7.default.rmSync(stagingDir,{recursive:!0,force:!0}),import_node_fs7.default.mkdirSync(stagingDir,{recursive:!0,mode:448}),this.stagingDir=stagingDir,this.ttlMs=ttlMs,this.maxSize=maxSize,this.now=now}mint(declaredSize){if(declaredSize<=0||declaredSize>this.maxSize)throw new Error(`declared size ${declaredSize} outside (0, ${this.maxSize}]`);let ref=REF_PREFIX+(0,import_node_crypto22.randomBytes)(REF_BYTE_LEN).toString("hex");return this.sweep(),this.slots.set(ref,{declaredSize,expiresAtMs:this.now()+this.ttlMs,uploaded:!1}),{ref,ttlMs:this.ttlMs}}async receive(ref,body){let slot=this.slots.get(ref);if(slot===void 0||this.now()>slot.expiresAtMs)throw new SlotUnknownError;if(slot.uploaded)throw new SlotConsumedError;let declared=slot.declaredSize,filePath=this.stagePath(ref),written=0;try{await(0,import_promises6.pipeline)(body,limitBytes(declared+1,n3=>{written+=n3}),import_node_fs7.default.createWriteStream(filePath,{flags:"w",mode:384}))}catch(error2){throw await import_node_fs7.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_fs7.default.promises.rm(filePath,{force:!0}),new SizeMismatchError(written,declared);let current=this.slots.get(ref);if(current===void 0||this.now()>current.expiresAtMs)throw await import_node_fs7.default.promises.rm(filePath,{force:!0}),new SlotUnknownError;current.uploaded=!0}async consume(ref){let slot=this.slots.get(ref);if(slot===void 0||this.now()>slot.expiresAtMs)throw new SlotUnknownError;if(!slot.uploaded)throw new SlotEmptyError;this.slots.delete(ref);let filePath=this.stagePath(ref);try{return await import_node_fs7.default.promises.readFile(filePath)}catch(error2){throw new Error(`failed to read staged artifact: ${error2 instanceof Error?error2.message:String(error2)}`)}finally{await import_node_fs7.default.promises.rm(filePath,{force:!0})}}sweep(){let nowMs=this.now();for(let[ref,slot]of this.slots)nowMs>slot.expiresAtMs&&(this.slots.delete(ref),import_node_fs7.default.rmSync(this.stagePath(ref),{force:!0}))}stagedFileName(ref){return`${ref}.zip`}stagePath(ref){return import_node_path12.default.join(this.stagingDir,this.stagedFileName(ref))}};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}}}function uploadUrl(baseUrl,ref){return`${trimTrailingSlash(baseUrl)}${SKILL_ARTIFACTS_PATH_PREFIX}${UPLOADS_SEGMENT}${ref}`}function downloadUrl(baseUrl,storageKey){return`${trimTrailingSlash(baseUrl)}${SKILL_ARTIFACTS_PATH_PREFIX}/${storageKey}`}function trimTrailingSlash(url){return url.endsWith("/")?url.slice(0,-1):url}function newSkillTransferLane(slots,artifacts,logger2){return(request,response)=>{let pathOnly=(request.url??"").split("?")[0]??"";if(!pathOnly.startsWith(SKILL_ARTIFACTS_PATH_PREFIX)){writeText(response,404,"404 page not found");return}let rest=pathOnly.slice(SKILL_ARTIFACTS_PATH_PREFIX.length),logDetachedFailure=arm=>error2=>{logger2.error(`skill transfer lane ${arm} handler failed`,{error:error2 instanceof Error?error2.message:String(error2)})};if(rest.startsWith(UPLOADS_SEGMENT)){let ref=rest.slice(UPLOADS_SEGMENT.length);handleUpload(request,response,slots,ref,logger2).catch(logDetachedFailure("upload"));return}handleDownload(request,response,artifacts,rest.replace(/^\//,""),logger2).catch(logDetachedFailure("download"))}}async function handleUpload(request,response,slots,ref,logger2){if(request.method!=="PUT"){response.setHeader("Allow","PUT"),writeText(response,405,"method not allowed");return}try{await slots.receive(ref,request),response.statusCode=204,response.end()}catch(error2){error2 instanceof SlotUnknownError?writeText(response,404,"upload reference unknown or expired \u2014 request a new upload URL"):error2 instanceof SlotConsumedError?writeText(response,409,"upload reference already used \u2014 request a new upload URL"):error2 instanceof SizeMismatchError?writeText(response,400,`${error2.message} \u2014 the upload must match the size declared to createArtifactUploadUrl`):(logger2.error("skill artifact upload failed",{ref,error:error2 instanceof Error?error2.message:String(error2)}),writeText(response,500,"failed to stage upload"))}}async function handleDownload(request,response,artifacts,key,logger2){if(request.method!=="GET"){response.setHeader("Allow","GET"),writeText(response,405,"method not allowed");return}if(!key.startsWith(DOWNLOAD_KEY_PREFIX)){writeText(response,404,"404 page not found");return}let data;try{data=await artifacts.get(key)}catch(error2){if(error2 instanceof ArtifactNotFoundError){writeText(response,404,"404 page not found");return}logger2.error("skill artifact download failed",{storageKey:key,error:error2 instanceof Error?error2.message:String(error2)}),writeText(response,500,"failed to load artifact");return}response.setHeader("Content-Type","application/zip"),response.setHeader("Content-Length",String(data.length)),response.statusCode=200,response.end(Buffer.from(data))}function writeText(response,status,body){response.statusCode=status,response.setHeader("Content-Type","text/plain; charset=utf-8"),response.end(`${body}
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_fs6.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{throw notFoundError("environment",environmentId)}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)=>list7(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(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(newAuthorizeVisibilityTransitionStep(UPDATE_VISIBILITY_ENVIRONMENT_KEY,deps.authorizer)).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{throw notFoundError("environment",input.resourceId)}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 list7(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_crypto18=require("node:crypto"),CONNECT_EXECUTION_ID_PREFIX="connect-";function newConnectExecutionId(mcpServerId){return`${CONNECT_EXECUTION_ID_PREFIX}${mcpServerId}-${(0,import_node_crypto18.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(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_crypto19=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_crypto19.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}function carriesPlatformClientClaim(rawToken){let segments=rawToken.split(".");if(segments.length!==3)return!1;try{let payload=JSON.parse(Buffer.from(segments[1],"base64url").toString("utf8"));return typeof payload.platform_client_id=="string"&&payload.platform_client_id!==""}catch{return!1}}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_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(){return{name:"ResolveMemoryDefaults",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);spec.subjectIdentityAccountId=captureCredential?.subjectIdentityAccountId??"",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_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){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))}}}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)=>list8(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()).addStep(newAuthorizeResolvedTargetStep(deps.authorizer,resolveMemoryCreateTargets)).addStep(newCheckMemoryEnablementStep(deps.store)).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 list8(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){if(ref.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??"")===ref.slug){if(ref.org!==""&&app.metadata?.org===ref.org)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:ref.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,app=>app.spec===void 0?[]:[app.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");return deleted}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.logger)).build().execute(reqCtx);let list11=reqCtx.get(LIST_RESULT_KEY7);if(list11===void 0)throw internalError(new Error("list result missing from pipeline context"),"OAuthApp list not found in context");return list11}function newListByOrgStep2(store,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 apps=[];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&&(redactOAuthApp(app),apps.push(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_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)}}};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");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 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?.getOrganizationIdByExternalOrgId?.bind(deps.organizationDirectory);router.service(OrganizationQueryController,{get:(orgId,ctx)=>get17(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 kindOf16(ctx){return ctx.values.get(apiResourceKindKey)}async function createOrganization(deps,org,ctx){let reqCtx=new RequestContext(OrganizationSchema,org,callerIdentityOf(ctx),kindOf16(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()).addStep(newPersistStep(deps.store)).addStep(newCreateAuthorizationTuplesStep(deps.authorizationLifecycle,deps.logger));for(let step of stepsForSlot(deps.gateSteps,"org-create:post-persist"))builder2.addStep(step);return await builder2.addStep(newIndexSearchStep(deps.store,organizationSearchExtractor,deps.logger)).build().execute(reqCtx),reqCtx.newState}async function update13(deps,org,ctx){let reqCtx=new RequestContext(OrganizationSchema,org,callerIdentityOf(ctx),kindOf16(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),kindOf16(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),kindOf16(ctx));await newPipeline("organization-delete",deps.logger).addStep(newAuthorizeStep(OrganizationCommandController.method.delete,deps.authorizer)).addStep(newValidateProtoStep()).addStep(newExtractResourceIdStep()).addStep(newLoadExistingForDeleteStep(deps.store,OrganizationSchema)).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 get17(deps,orgId,ctx){let reqCtx=new RequestContext(OrganizationQueryController.method.get.input,orgId,callerIdentityOf(ctx),kindOf16(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),kindOf16(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),kindOf16(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 orgId=await lookup3(input.externalOrgId);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 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{throw notFoundError("mcp_server",mcpServerId)}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")}}async function resolveOAuthAppRef2(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 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{throw notFoundError("mcp_server",mcpServerId)}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 resolveOAuthAppRef2(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(record,key){let value=record[key];return typeof value=="string"?value:""}function readStringArray(record,key){let list11=record[key];return Array.isArray(list11)?list11.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_crypto21=require("node:crypto");var import_node_crypto20=require("node:crypto");function generatePkce(){let verifier=(0,import_node_crypto20.randomBytes)(32).toString("base64url"),challenge=(0,import_node_crypto20.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{throw notFoundError("mcp_server",mcpServerId)}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 resolveOAuthAppRef2(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_crypto21.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{throw notFoundError("mcp_server",mcpServerId)}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{throw notFoundError("mcp_server",mcpServerId)}}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 resolveOAuthAppRef2(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)=>get18(deps,id,ctx),getByReference:(ref,ctx)=>getByReference10(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 kindOf17(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),kindOf17(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(newGuardPublicVisibilityStep(deps.authorizer)).addStep(newCompleteEndpointAuthStep(endpointAuthDeps(deps))).addStep(newGuardReservedLabelsStep(deps.authorizer)).addStep(newNormalizeReferencesStep()).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),kindOf17(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(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),kindOf17(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),kindOf17(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),kindOf17(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(newAuthorizeVisibilityTransitionStep(UPDATE_VISIBILITY_MCP_SERVER_KEY,deps.authorizer)).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{throw notFoundError("mcp_server",input.resourceId)}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 get18(deps,id,ctx){let reqCtx=new RequestContext(McpServerQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf17(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 getByReference10(deps,ref,ctx){let reqCtx=new RequestContext(McpServerQueryController.method.getByReference.input,ref,callerIdentityOf(ctx),kindOf17(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})}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.temporalHostPort,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.22.1";var file_ai_stigmer_agentic_session_v1_io=fileDesc("CiZhaS9zdGlnbWVyL2FnZW50aWMvc2Vzc2lvbi92MS9pby5wcm90bxIdYWkuc3RpZ21lci5hZ2VudGljLnNlc3Npb24udjEiIgoJU2Vzc2lvbklkEhUKBXZhbHVlGAEgASgJQga6SAPIAQEiIAoHQWdlbnRJZBIVCgV2YWx1ZRgBIAEoCUIGukgDyAEBIlsKC1Nlc3Npb25MaXN0EhMKC3RvdGFsX3BhZ2VzGAEgASgFEjcKB2VudHJpZXMYAiADKAsyJi5haS5zdGlnbWVyLmFnZW50aWMuc2Vzc2lvbi52MS5TZXNzaW9uIkoKE0xpc3RTZXNzaW9uc1JlcXVlc3QSEQoJcGFnZV9zaXplGAEgASgFEhIKCnBhZ2VfdG9rZW4YAiABKAkSDAoEdGFncxgDIAMoCSJuCiJMaXN0U2Vzc2lvbnNCeUFnZW50SW5zdGFuY2VSZXF1ZXN0EiEKEWFnZW50X2luc3RhbmNlX2lkGAEgASgJQga6SAPIAQESEQoJcGFnZV9zaXplGAIgASgFEhIKCnBhZ2VfdG9rZW4YAyABKAkiYQocTGlzdFNlc3Npb25zQnlDaGFubmVsUmVxdWVzdBIaCgpjaGFubmVsX2lkGAEgASgJQga6SAPIAQESEQoJcGFnZV9zaXplGAIgASgFEhIKCnBhZ2VfdG9rZW4YAyABKAkiQgobVXBkYXRlU2Vzc2lvblN1YmplY3RSZXF1ZXN0EhIKAmlkGAEgASgJQga6SAPIAQESDwoHc3ViamVjdBgCIAEoCWIGcHJvdG8z",[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 LIST_RESULT_KEY8="listResult",CHANNEL_ID_LABEL_KEY="stigmer.ai/channel-id";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.listResources(ApiResourceKind.agent_execution)}catch(error2){throw internalError(error2,"failed to list agent executions")}let executions=[];for(let data of rows){let execution;try{execution=fromBinary2(AgentExecutionSchema,data)}catch(error2){logger2.warn("Failed to unmarshal execution, skipping",{error:error2 instanceof Error?error2.message:String(error2)});continue}(execution.spec?.sessionId??"")===sessionId&&executions.push(execution)}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 sessions=await restrictListByReadScope(listReadScope,ctx.callerIdentity,ApiResourceKind.session,await loadAllSessions(store,logger2,ctx.apiResourceKind),"");sessions.sort((a5,b7)=>compareCreatedAtDesc(a5.status?.audit?.specAudit?.createdAt,b7.status?.audit?.specAudit?.createdAt)),logger2.info("Loaded sessions from database",{count:sessions.length}),ctx.set(LIST_RESULT_KEY8,create2(SessionListSchema,{entries:sessions}))}}}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 sessions=await loadAllSessions(store,logger2,ctx.apiResourceKind),filtered=await restrictListByReadScope(listReadScope,ctx.callerIdentity,ApiResourceKind.session,sessions.filter(session=>(session.spec?.agentInstanceId??"")===agentInstanceId),"");logger2.info("Filtered sessions by agent instance",{agentInstanceId,totalSessions:sessions.length,filteredSessions:filtered.length}),ctx.set(LIST_RESULT_KEY8,create2(SessionListSchema,{entries:filtered}))}}}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 sessions=await loadAllSessions(store,logger2,ctx.apiResourceKind),filtered=await restrictListByReadScope(listReadScope,ctx.callerIdentity,ApiResourceKind.session,sessions.filter(session=>(session.metadata?.labels??{})[CHANNEL_ID_LABEL_KEY]===channelId),"");logger2.info("Filtered sessions by channel",{channelId,totalSessions:sessions.length,filteredSessions:filtered.length}),ctx.set(LIST_RESULT_KEY8,create2(SessionListSchema,{entries:filtered}))}}}async function loadAllSessions(store,logger2,kind){let rows;try{rows=await store.listResources(kind)}catch(error2){throw internalError(error2,"failed to list sessions")}let sessions=[];for(let data of rows){let session;try{session=fromBinary2(SessionSchema,data)}catch(error2){logger2.warn("Failed to unmarshal session, skipping",{error:error2 instanceof Error?error2.message:String(error2)});continue}sessions.push(session)}return sessions}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)=>get19(deps,id,ctx),list:(req,ctx)=>list9(deps,req,ctx),listByAgentInstance:(req,ctx)=>listByAgentInstance(deps,req,ctx),listByChannel:(req,ctx)=>listByChannel(deps,req,ctx)})}function kindOf18(ctx){return ctx.values.get(apiResourceKindKey)}async function createSession(deps,session,ctx){let reqCtx=new RequestContext(SessionSchema,session,callerIdentityOf(ctx),kindOf18(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());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),kindOf18(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),kindOf18(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),kindOf18(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 get19(deps,id,ctx){let reqCtx=new RequestContext(SessionQueryController.method.get.input,id,callerIdentityOf(ctx),kindOf18(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 list9(deps,req,ctx){let reqCtx=new RequestContext(SessionQueryController.method.list.input,req,callerIdentityOf(ctx),kindOf18(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),kindOf18(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),kindOf18(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 ARTIFACT_BYTES_KEY="pushArtifactBytes";function newResolveArtifactSourceStep(slots,binding){return{name:"ResolveArtifactSource",async execute(ctx){let{artifact,artifactUploadRef}=binding.source(ctx.input);if(artifactUploadRef===""){ctx.set(ARTIFACT_BYTES_KEY,artifact);return}if(slots===void 0)throw failedPreconditionError(binding.laneNotConfigured);let data;try{data=await slots.consume(artifactUploadRef)}catch(error2){throw invalidArgumentError(`artifact_upload_ref not usable: ${error2 instanceof Error?error2.message:String(error2)} \u2014 request a new upload URL via createArtifactUploadUrl`)}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 record of records){let snapshot;try{snapshot=fromBinary2(binding.schema,record.data)}catch{continue}let isCurrent=!currentMarked&&headHash!==""&&binding.headHashOf(snapshot)===headHash;currentMarked=currentMarked||isCurrent,entries.push(binding.mapEntry(snapshot,isCurrent,record.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 text=decoded.toString("utf8"),index2=Number.parseInt(text,10);if(!Number.isSafeInteger(index2)||String(index2)!==text||index2<0)throw invalidArgumentError("invalid page_token");return index2}function idOf(resource){return metadataOf(resource)?.id??""}var TASK_KIND_REGISTRY_PATH="/v1/proxy/task-kind-registry",MODEL_REGISTRY_PATH="/v1/proxy/model-registry",SKILL_ARTIFACTS_PATH_PREFIX="/v1/skill-artifacts";var MAX_SKILL_MD_SIZE=1*1024*1024,DEFAULT_SLOT_TTL_MS=900*1e3,REF_BYTE_LEN=16,REF_PREFIX="sau_",UPLOADS_SEGMENT="/uploads/",DOWNLOAD_KEY_PREFIX="skills/",NESTED_SKILL_MD_HINT="SKILL.md must be at the archive root \u2014 zip the skill folder's contents, not the folder itself",TRANSFER_LANE_NOT_CONFIGURED="skill artifact transfer lane is not configured on this server";var import_node_path11=__toESM(require("node:path"),1);var ArtifactNotFoundError=class extends Error{constructor(storageKey){super(`artifact not found: ${storageKey}`),this.name="ArtifactNotFoundError"}},ARCHIVE_CONTENT_TYPE="application/zip";function newContentAddressedArchiveStore(driver,keyPrefix){let virtualRoot=import_node_path11.default.resolve(import_node_path11.default.sep,"archive-store"),keyEscapesStore=storageKey=>{let resolved=import_node_path11.default.resolve(virtualRoot,storageKey);return resolved!==virtualRoot&&!resolved.startsWith(virtualRoot+import_node_path11.default.sep)};return{getStorageKey(hash){return`${keyPrefix}${hash}.zip`},async store(hash,data){let storageKey=this.getStorageKey(hash);return await driver.upload(storageKey,data,ARCHIVE_CONTENT_TYPE),storageKey},async get(storageKey){if(keyEscapesStore(storageKey))throw new ArtifactNotFoundError(storageKey);try{return await driver.download(storageKey)}catch(error2){throw error2 instanceof ArtifactStorageNotFoundError?new ArtifactNotFoundError(storageKey):new Error(`failed to read artifact: ${error2 instanceof Error?error2.message:String(error2)}`)}},async exists(hash){return driver.exists(this.getStorageKey(hash))},async size(storageKey){if(keyEscapesStore(storageKey))throw new ArtifactNotFoundError(storageKey);try{return await driver.size(storageKey)}catch(error2){throw error2 instanceof ArtifactStorageNotFoundError?new ArtifactNotFoundError(storageKey):new Error(`failed to stat artifact: ${error2 instanceof Error?error2.message:String(error2)}`)}}}}var SKILL_ARTIFACT_KEY_PREFIX="skills/";function newSkillArtifactStorage(driver){return newContentAddressedArchiveStore(driver,SKILL_ARTIFACT_KEY_PREFIX)}var import_node_crypto22=require("node:crypto"),import_node_fs7=__toESM(require("node:fs"),1),import_node_path12=__toESM(require("node:path"),1),import_promises6=require("node:stream/promises");var 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"}},SlotEmptyError=class extends Error{constructor(){super("upload reference has no uploaded bytes"),this.name="SlotEmptyError"}},SizeMismatchError=class extends Error{constructor(received,declared){super(`upload size mismatch: received ${received} bytes, declared ${declared}`),this.name="SizeMismatchError"}},UploadSlots=class{slots=new Map;stagingDir;ttlMs;maxSize;now;constructor(stagingDir,ttlMs,maxSize,now=Date.now){import_node_fs7.default.rmSync(stagingDir,{recursive:!0,force:!0}),import_node_fs7.default.mkdirSync(stagingDir,{recursive:!0,mode:448}),this.stagingDir=stagingDir,this.ttlMs=ttlMs,this.maxSize=maxSize,this.now=now}mint(declaredSize){if(declaredSize<=0||declaredSize>this.maxSize)throw new Error(`declared size ${declaredSize} outside (0, ${this.maxSize}]`);let ref=REF_PREFIX+(0,import_node_crypto22.randomBytes)(REF_BYTE_LEN).toString("hex");return this.sweep(),this.slots.set(ref,{declaredSize,expiresAtMs:this.now()+this.ttlMs,uploaded:!1}),{ref,ttlMs:this.ttlMs}}async receive(ref,body){let slot=this.slots.get(ref);if(slot===void 0||this.now()>slot.expiresAtMs)throw new SlotUnknownError;if(slot.uploaded)throw new SlotConsumedError;let declared=slot.declaredSize,filePath=this.stagePath(ref),written=0;try{await(0,import_promises6.pipeline)(body,limitBytes(declared+1,n3=>{written+=n3}),import_node_fs7.default.createWriteStream(filePath,{flags:"w",mode:384}))}catch(error2){throw await import_node_fs7.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_fs7.default.promises.rm(filePath,{force:!0}),new SizeMismatchError(written,declared);let current=this.slots.get(ref);if(current===void 0||this.now()>current.expiresAtMs)throw await import_node_fs7.default.promises.rm(filePath,{force:!0}),new SlotUnknownError;current.uploaded=!0}async consume(ref){let slot=this.slots.get(ref);if(slot===void 0||this.now()>slot.expiresAtMs)throw new SlotUnknownError;if(!slot.uploaded)throw new SlotEmptyError;this.slots.delete(ref);let filePath=this.stagePath(ref);try{return await import_node_fs7.default.promises.readFile(filePath)}catch(error2){throw new Error(`failed to read staged artifact: ${error2 instanceof Error?error2.message:String(error2)}`)}finally{await import_node_fs7.default.promises.rm(filePath,{force:!0})}}sweep(){let nowMs=this.now();for(let[ref,slot]of this.slots)nowMs>slot.expiresAtMs&&(this.slots.delete(ref),import_node_fs7.default.rmSync(this.stagePath(ref),{force:!0}))}stagedFileName(ref){return`${ref}.zip`}stagePath(ref){return import_node_path12.default.join(this.stagingDir,this.stagedFileName(ref))}};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}}}function uploadUrl(baseUrl,ref){return`${trimTrailingSlash(baseUrl)}${SKILL_ARTIFACTS_PATH_PREFIX}${UPLOADS_SEGMENT}${ref}`}function downloadUrl(baseUrl,storageKey){return`${trimTrailingSlash(baseUrl)}${SKILL_ARTIFACTS_PATH_PREFIX}/${storageKey}`}function trimTrailingSlash(url){return url.endsWith("/")?url.slice(0,-1):url}function newSkillTransferLane(slots,artifacts,logger2){return(request,response)=>{let pathOnly=(request.url??"").split("?")[0]??"";if(!pathOnly.startsWith(SKILL_ARTIFACTS_PATH_PREFIX)){writeText(response,404,"404 page not found");return}let rest=pathOnly.slice(SKILL_ARTIFACTS_PATH_PREFIX.length),logDetachedFailure=arm=>error2=>{logger2.error(`skill transfer lane ${arm} handler failed`,{error:error2 instanceof Error?error2.message:String(error2)})};if(rest.startsWith(UPLOADS_SEGMENT)){let ref=rest.slice(UPLOADS_SEGMENT.length);handleUpload(request,response,slots,ref,logger2).catch(logDetachedFailure("upload"));return}handleDownload(request,response,artifacts,rest.replace(/^\//,""),logger2).catch(logDetachedFailure("download"))}}async function handleUpload(request,response,slots,ref,logger2){if(request.method!=="PUT"){response.setHeader("Allow","PUT"),writeText(response,405,"method not allowed");return}try{await slots.receive(ref,request),response.statusCode=204,response.end()}catch(error2){error2 instanceof SlotUnknownError?writeText(response,404,"upload reference unknown or expired \u2014 request a new upload URL"):error2 instanceof SlotConsumedError?writeText(response,409,"upload reference already used \u2014 request a new upload URL"):error2 instanceof SizeMismatchError?writeText(response,400,`${error2.message} \u2014 the upload must match the size declared to createArtifactUploadUrl`):(logger2.error("skill artifact upload failed",{ref,error:error2 instanceof Error?error2.message:String(error2)}),writeText(response,500,"failed to stage upload"))}}async function handleDownload(request,response,artifacts,key,logger2){if(request.method!=="GET"){response.setHeader("Allow","GET"),writeText(response,405,"method not allowed");return}if(!key.startsWith(DOWNLOAD_KEY_PREFIX)){writeText(response,404,"404 page not found");return}let data;try{data=await artifacts.get(key)}catch(error2){if(error2 instanceof ArtifactNotFoundError){writeText(response,404,"404 page not found");return}logger2.error("skill artifact download failed",{storageKey:key,error:error2 instanceof Error?error2.message:String(error2)}),writeText(response,500,"failed to load artifact");return}response.setHeader("Content-Type","application/zip"),response.setHeader("Content-Length",String(data.length)),response.statusCode=200,response.end(Buffer.from(data))}function writeText(response,status,body){response.statusCode=status,response.setHeader("Content-Type","text/plain; charset=utf-8"),response.end(`${body}
489
489
  `)}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_CONFIGURED2="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 text=decoder3.decode(bytes);return text.charCodeAt(0)===65279?text.slice(1):text}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 parseJsonObject(text,path14,kind,findings){let value;try{value=JSON.parse(text)}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,field2,path14,findings){let value=object[field2];if(value!==void 0){if(typeof value!="string"){findings.error("manifest-field-type",{path:path14,subject:field2,detail:"a string"});return}return value}}function optionalStringArray(object,field2,path14,findings){let value=object[field2];if(value!==void 0){if(!isStringArray(value)){findings.error("manifest-field-type",{path:path14,subject:field2,detail:"an array of strings"});return}return value}}function stringOrStringArray(object,field2,path14,findings){let value=object[field2];if(value!==void 0){if(typeof value=="string")return[value];if(isStringArray(value))return value;findings.error("manifest-field-type",{path:path14,subject:field2,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,field2,path14,findings){let values=stringOrStringArray(object,field2,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,field2,path14,dialect,findings){let value=object[field2];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:field2,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 text=readText(index2,path14,"manifest",findings);return text===void 0?void 0:parseJsonObject(text,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(`
490
490
  `),body:lines.slice(i6+1).join(`
491
491
  `)};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 text=readText(index2,path14,"subAgent",findings);if(text===void 0)return;let extracted=extractFrontmatter(text),fieldsMap={},body=text;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 field2 of Object.keys(fieldsMap))READ_FIELDS.has(field2)||findings.warn("sub-agent-field-ignored",{path:path14,subject:name,detail:field2});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 list11 of lists)for(let component of list11){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 text=readText(index2,source.path,"mcpConfig",findings);if(text===void 0)return;let object=parseJsonObject(text,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[field2,value]of fields(raw))if(!known.has(field2))if(open)findings.error("mcp-server-field-unknown",{...ctx,detail:field2}),valid=!1;else if(field2==="auth"){findings.warn("mcp-server-auth-ignored",ctx);for(let text of stringsWithin(value))collectReferences(text,references)}else findings.warn("mcp-server-field-ignored",{...ctx,detail:field2});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(text,into){for(let name of referencedVariables(text))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),text=readText(index2,path14,"skillMd",findings);if(text===void 0)return;let extracted=extractFrontmatter(text);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_crypto23=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=trimTrailingSlash2(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 trimTrailingSlash2(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_crypto23.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(`