Coverage for apps / backend / src / orcheo_backend / app / factory.py: 99%

260 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2026-11-16 14:04 +0000

1"""Application factory for the Orcheo FastAPI service.""" 

2 

3from __future__ import annotations 

4import json 

5import mimetypes 

6import os 

7from collections.abc import AsyncIterator 

8from contextlib import asynccontextmanager 

9from pathlib import Path 

10from typing import cast 

11from dotenv import load_dotenv 

12from fastapi import APIRouter, Depends, FastAPI, Request, Response 

13from fastapi.exception_handlers import http_exception_handler 

14from fastapi.middleware.cors import CORSMiddleware 

15from fastapi.middleware.gzip import GZipMiddleware 

16from fastapi.responses import PlainTextResponse 

17from fastapi.staticfiles import StaticFiles 

18from starlette.concurrency import run_in_threadpool 

19from starlette.datastructures import Headers 

20from starlette.exceptions import HTTPException as StarletteHTTPException 

21from starlette.types import ASGIApp, Receive, Scope, Send 

22from orcheo.agentensor.checkpoints import AgentensorCheckpointStore 

23from orcheo.plugins import load_enabled_plugins 

24from orcheo.vault.oauth import OAuthCredentialService 

25from orcheo_backend.app.authentication import ( 

26 AuthenticationError, 

27 authenticate_request, 

28 load_auth_settings, 

29) 

30from orcheo_backend.app.chatkit_runtime import ( 

31 cancel_chatkit_cleanup_task, 

32 ensure_chatkit_cleanup_task, 

33 get_chatkit_server, 

34 sensitive_logging_enabled, 

35) 

36from orcheo_backend.app.cron_scheduler import ( 

37 CronSchedulerService, 

38 inprocess_cron_enabled, 

39) 

40from orcheo_backend.app.database_errors import ( 

41 DATABASE_UNAVAILABLE_ERRORS, 

42 database_unavailable_handler, 

43) 

44from orcheo_backend.app.dependencies import ( 

45 ListenerRuntimeStore, 

46 _create_repository, 

47 _repository_ref, 

48 get_checkpoint_store, 

49 get_credential_service, 

50 get_history_store, 

51 get_listener_runtime_store, 

52 get_plugin_installation_store, 

53 get_repository, 

54 get_vault, 

55 set_checkpoint_store, 

56 set_credential_service, 

57 set_history_store, 

58 set_listener_runtime_store, 

59 set_plugin_installation_store, 

60 set_repository, 

61 set_vault, 

62) 

63from orcheo_backend.app.history import RunHistoryStore 

64from orcheo_backend.app.history.retention import ( 

65 cancel_trace_retention_task, 

66 ensure_trace_retention_task, 

67) 

68from orcheo_backend.app.hosted_apps import ( 

69 auth_router as hosted_apps_auth_router, 

70) 

71from orcheo_backend.app.hosted_apps import ( 

72 internal_router as hosted_apps_internal_router, 

73) 

74from orcheo_backend.app.hosted_apps import reset_app_bundle_store 

75from orcheo_backend.app.identity.passkey_router import ( 

76 router as passkey_api_router, 

77) 

78from orcheo_backend.app.identity.router import router as identity_api_router 

79from orcheo_backend.app.listener_runtime_service import ListenerRuntimeService 

80from orcheo_backend.app.local_execution import drain_inprocess_runs 

81from orcheo_backend.app.logging_config import configure_logging 

82from orcheo_backend.app.managed_workflows import ensure_managed_vibe_workflow 

83from orcheo_backend.app.mcp_server import mcp_lifespan 

84from orcheo_backend.app.oauth import router as oauth_router 

85from orcheo_backend.app.oauth import well_known_router as oauth_well_known_router 

86from orcheo_backend.app.pending_run_reconciler import pending_run_reconciliation 

87from orcheo_backend.app.plugin_installation_store import PluginInstallationStore 

88from orcheo_backend.app.repository import WorkflowRepository 

89from orcheo_backend.app.routers import ( 

90 agentensor, 

91 auth, 

92 candidates, 

93 chatkit_assets, 

94 credential_alerts, 

95 credential_health, 

96 credential_templates, 

97 credentials, 

98 listeners, 

99 mcp, 

100 nodes, 

101 runs, 

102 system, 

103 teams, 

104 triggers, 

105 websocket, 

106 workflows, 

107) 

108from orcheo_backend.app.routers import apps as hosted_apps_router 

109from orcheo_backend.app.routers import apps_platform as hosted_apps_platform_router 

110from orcheo_backend.app.routers import ( 

111 chatkit as chatkit_router, 

112) 

113from orcheo_backend.app.routers import ( 

114 workspaces as workspaces_router, 

115) 

116from orcheo_backend.app.service_token_endpoints import router as service_token_router 

117from orcheo_backend.app.workflow_execution import configure_sensitive_logging 

118from orcheo_backend.app.workspace import ( 

119 get_workspace_service, 

120 resolve_workspace_context, 

121) 

122 

123 

124load_dotenv() 

125configure_logging() 

126 

127configure_sensitive_logging( 

128 enable_sensitive_debug=sensitive_logging_enabled(), 

129) 

130 

131 

132async def _authentication_error_handler(request: Request, exc: Exception) -> Response: 

133 """Translate AuthenticationError instances into structured HTTP responses.""" 

134 auth_error = cast(AuthenticationError, exc) 2ebdbhbibjbkbfb2f

135 http_exc = auth_error.as_http_exception() 2ebdbhbibjbkbfb2f

136 return await http_exception_handler(request, http_exc) 2ebdbhbibjbkbfb2f

137 

138 

139async def _robots_txt() -> PlainTextResponse: 

140 """Expose crawl policy for public backend deployments.""" 

141 return PlainTextResponse("User-agent: *\nDisallow: /\n") 25c/f

142 

143 

144# Backend namespaces mounted outside the API router (see _configure_application) 

145# that a request path might fall through to without matching a literal route. 

146# These must 404 as themselves rather than silently serving the SPA shell. 

147_RESERVED_BACKEND_PREFIXES = ("api/", "internal/", "hooks/", "assets/ck1/", "ws/") 

148 

149 

150def _is_reserved_backend_path(path: str) -> bool: 

151 """Return True for paths that belong to a backend namespace, not the SPA.""" 

152 return path == "robots.txt" or path.startswith(_RESERVED_BACKEND_PREFIXES) 2:fc b : ;

153 

154 

155def _accepts_gzip(scope: Scope) -> bool: 

156 """Honor explicit gzip quality values before a wildcard encoding.""" 

157 encodings: dict[str, float] = {} 1cb@[:;{=?]}^|`~

158 for entry in Headers(scope=scope).get("accept-encoding", "").split(","): 1cb@[:;{=?]}^|`~

159 name, *parameters = entry.strip().lower().split(";") 1cb@[:;{=?]}^|`~

160 quality = 1.0 1cb@[:;{=?]}^|`~

161 for parameter in parameters: 1cb@[:;{=?]}^|`~

162 if parameter.strip().startswith("q="): 162 ↛ 161line 162 didn't jump to line 161 because the condition on line 162 was always true1|`

163 try: 1|`

164 quality = float(parameter.strip()[2:]) 1|`

165 except ValueError: 1`

166 quality = 0.0 1`

167 encodings[name] = quality 1cb@[:;{=?]}^|`~

168 return encodings.get("gzip", encodings.get("*", 0.0)) > 0 1cb@[:;{=?]}^|`~

169 

170 

171class _ApiGZipMiddleware: 

172 """Gzip REST API responses such as execution traces and run histories. 

173 

174 These are large, repetitive JSON payloads. Compression is scoped to the 

175 REST API: internal routes stream raw bytes to the app gateway, Studio 

176 assets are pre-compressed, and the MCP endpoint is left untouched. 

177 Starlette already skips ``text/event-stream`` and compressed media types. 

178 """ 

179 

180 def __init__(self, app: ASGIApp) -> None: 

181 self._app = app 2Mbg d e Nb6b7bObPbQbRblbmbnbobpbqbdbrbsbtbgbubvbwbxbybzbAbBbCbDbEbFbGbHbSbx y f m n o h i l k j c b p q r s t u v TbUbVbWbXbYbw Zb0b1b2b3b4b5b

182 self._gzip = GZipMiddleware(app, minimum_size=1024) 2Mbg d e Nb6b7bObPbQbRblbmbnbobpbqbdbrbsbtbgbubvbwbxbybzbAbBbCbDbEbFbGbHbSbx y f m n o h i l k j c b p q r s t u v TbUbVbWbXbYbw Zb0b1b2b3b4b5b

183 

184 async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: 

185 path = scope.get("path", "") if scope["type"] == "http" else "" 26cMb7c8c9c!c#c$c%c'c(c)c*c+cg ,c-c.c/c:c;c=c?c3f@c[c]c^c_c`c{c|c}c~cadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzdAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd0d1d2d3d4d5d6d7d8d9d!d#d$d%d'd(dd e 8b9b!b#b4f5f6f$b7f8f9f!f%b'b(b)b*b+b,b-b.b/b#f)d*d+d:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchc$ficjckclcmcncocpcqcrcebsc%ftc'fucvcwcxcyczc(fAcBcCc)fDc*f+fEcFcGcHcIcJc,d-d.d/d:d;d=d?d@d[d]d^d_d`d{d|d}d~daebecedeeefegeheiejekelemeneoepeqereseteuevewexeyezeAeBeCeDe,fEeFeGeHeIeJeKeLeMeNeOePeQeReSeTeUeVeWeXeYeZe0e1e2e3e4e5e6e7e8e9e!e#e$e%e'e(e)e*eNb6b7bObPbQbRblbmbnbobpbqbdbrbsbtbgbubvbwbxbybzbAbBbCbDbEbFbGbHb+eSbx ,e-e.e/e:e;e=e?e@e[e]e^e_e`e{e|e}e~eafbfcfdfefffgfhfifjfkfhblfmfnfofpfqfrfsftfufvfibjbkbwfxfyfzfAfBfKcCfLcMcDfNcEfFfOcGfHfPcQcRcScTcUcVcWcXcYcIf-fZc0c1c2cJfKf3cLfMfNfOfPfQfRfSfTf4cfb5cUfVfWfXfy YfZf0f1ff m n o h i l k j c b p q r s t u v TbUbVbWbXbYbw Zb0b1b2b3b4b5b

186 if path.startswith("/api/") and not path.startswith("/api/mcp"): 26cMb7c8c9c!c#c$c%c'c(c)c*c+cg ,c-c.c/c:c;c=c?c3f@c[c]c^c_c`c{c|c}c~cadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzdAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd0d1d2d3d4d5d6d7d8d9d!d#d$d%d'd(dd e 8b9b!b#b4f5f6f$b7f8f9f!f%b'b(b)b*b+b,b-b.b/b#f)d*d+d:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchc$ficjckclcmcncocpcqcrcebsc%ftc'fucvcwcxcyczc(fAcBcCc)fDc*f+fEcFcGcHcIcJc,d-d.d/d:d;d=d?d@d[d]d^d_d`d{d|d}d~daebecedeeefegeheiejekelemeneoepeqereseteuevewexeyezeAeBeCeDe,fEeFeGeHeIeJeKeLeMeNeOePeQeReSeTeUeVeWeXeYeZe0e1e2e3e4e5e6e7e8e9e!e#e$e%e'e(e)e*eNb6b7bObPbQbRblbmbnbobpbqbdbrbsbtbgbubvbwbxbybzbAbBbCbDbEbFbGbHb+eSbx ,e-e.e/e:e;e=e?e@e[e]e^e_e`e{e|e}e~eafbfcfdfefffgfhfifjfkfhblfmfnfofpfqfrfsftfufvfibjbkbwfxfyfzfAfBfKcCfLcMcDfNcEfFfOcGfHfPcQcRcScTcUcVcWcXcYcIf-fZc0c1c2cJfKf3cLfMfNfOfPfQfRfSfTf4cfb5cUfVfWfXfy YfZf0f1ff m n o h i l k j c b p q r s t u v TbUbVbWbXbYbw Zb0b1b2b3b4b5b

187 await self._gzip(scope, receive, send) 26cMb7c8c9c!c#c$c%c'c(c)c*c+c,c-c.c/c:c;c=c?c@c[c]c^c_c`c{c|c}c~cadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzdAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd0d1d2d3d4d5d6d7d8d9d!d#d$d%d'd(dd e 8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b)d*d+d:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcebsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJc,d-d.d/d:d;d=d?d@d[d]d^d_d`d{d|d}d~daebecedeeefegeheiejekelemeneoepeqereseteuevewexeyezeAeBeCeDeEeFeGeHeIeJeKeLeMeNeOePeQeReSeTeUeVeWeXeYeZe0e1e2e3e4e5e6e7e8e9e!e#e$e%e'e(e)e*eNbObPbQbRblbmbnbobpbqbdbrbsbtbgbubvbwbxbybzbAbBbCbDbEbFbGbHb+eSbx ,e-e.e/e:e;e=e?e@e[e]e^e_e`e{e|e}e~eafbfcfdfefffgfhfifjfkfhblfmfnfofpfqfrfsftfufvfibjbkbwfxfyfzfAfBfKcCfLcMcDfNcEfFfOcGfHfPcQcRcScTcUcVcWcXcYcIfZc0c1c2cJfKf3cLfMfNfOfPfQfRfSfTf4cfbUfVfWfXfy YfZf0f1ff m n o c p q r s t u v TbUbVbWbXbYbw Zb0b1b2b3b4b5b

188 return 26cMb7c8c9c!c#c$c%c'c(c)c*c+c,c-c.c/c:c;c=c?c@c[c]c^c_c`c{c|c}c~cadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzdAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd0d1d2d3d4d5d6d7d8d9d!d#d$d%d'd(dd e 8b9b!b#b$b%b'b(b)b*b+b,b-b.b/b)d*d+d:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcebsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJc,d-d.d/d:d;d=d?d@d[d]d^d_d`d{d|d}d~daebecedeeefegeheiejekelemeneoepeqereseteuevewexeyezeAeBeCeDeEeFeGeHeIeJeKeLeMeNeOePeQeReSeTeUeVeWeXeYeZe0e1e2e3e4e5e6e7e8e9e!e#e$e%e'e(e)e*eNbObPbQbRblbmbnbobpbqbdbrbsbtbgbubvbwbxbybzbAbBbCbDbEbFbGbHb+eSbx ,e-e.e/e:e;e=e?e@e[e]e^e_e`e{e|e}e~eafbfcfdfefffgfhfifjfkfhblfmfnfofpfqfrfsftfufvfibjbkbwfxfyfzfAfBfKcCfLcMcDfNcEfFfOcGfHfPcQcRcScTcUcVcWcXcYcIfZc0c1c2cJfKf3cLfMfNfOfPfQfRfSfTf4cfbUfVfWfXfy YfZf0f1ff m n o c p q r s t u v TbUbVbWbXbYbw Zb0b1b2b3b4b5b

189 await self._app(scope, receive, send) 2g 3fd e 8b9b!b#b4f5f6f$b7f8f9f!f%b'b(b)b*b+b,b-b.b/b#f:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchc$ficjckclcmcncocpcqcrcebsc%ftc'fucvcwcxcyczc(fAcBcCc)fDc*f+fEcFcGcHcIcJc,f6b7bKcLcMcNcOcPcQcRcScTcUcVcWcXcYc-fZc0c1c2c3c4cfb5cf h i l k j c b

190 

191 

192class _StudioStaticFiles(StaticFiles): 

193 """Serve a Vite SPA bundle and fall back to index.html for app routes.""" 

194 

195 async def get_response(self, path: str, scope: Scope) -> Response: 

196 try: 2c b @ [ : ; { = ? ] } ^ | ` IbJbKbLb

197 response = await self._get_asset_response(path, scope) 2c b @ [ : ; { = ? ] } ^ | ` IbJbKbLb

198 except StarletteHTTPException as exc: 1cb:;

199 if exc.status_code != 404 or _is_reserved_backend_path(path): 1cb:;

200 raise 1c;

201 response = await self._get_asset_response("index.html", scope) 1b:;

202 # Runtime substitutions can change JS content while retaining Vite names. 

203 response.headers["Cache-Control"] = "public, max-age=0, must-revalidate" 2b @ [ : ; { = ? ] } ^ | ` IbJbKbLb

204 response.headers["Vary"] = "Accept-Encoding" 2b @ [ : ; { = ? ] } ^ | ` IbJbKbLb

205 return response 2b @ [ : ; { = ? ] } ^ | ` IbJbKbLb

206 

207 async def _get_asset_response(self, path: str, scope: Scope) -> Response: 

208 """Negotiate an asset, including the index selected for an SPA route.""" 

209 # FileResponse's multipart ranges contain uncompressed MIME boundaries. 

210 # Serve identity for ranges so Content-Encoding describes the whole body. 

211 if "range" not in Headers(scope=scope) and _accepts_gzip(scope): 2c b @ [ : ; { = ? ] } ^ | ` IbJbKbLb~

212 asset_path = "index.html" if path == "." else path 1cb@[:;{=?]^~

213 try: 1cb@[:;{=?]^~

214 response = await super().get_response(asset_path + ".gz", scope) 1cb@[:;{=?]^~

215 except StarletteHTTPException as exc: 1cb:;~

216 if exc.status_code != 404: 1cb:;~

217 raise 1~

218 else: 

219 # HTML mode can return an uncompressed custom 404 response. 

220 if response.status_code in {200, 304}: 1@[:{=?]^

221 response.headers["Content-Encoding"] = "gzip" 1@[:=?]^

222 response.headers["Content-Type"] = ( 1@[:=?]^

223 mimetypes.guess_type(asset_path)[0] 

224 or "application/octet-stream" 

225 ) 

226 return response 1@[:=?]^

227 return await super().get_response(path, scope) 2c b : ; { = ? } | ` IbJbKbLb

228 

229 

230@asynccontextmanager 

231async def _app_lifespan(app: FastAPI) -> AsyncIterator[None]: 

232 """Manage application lifespan with startup and shutdown logic.""" 

233 from orcheo.graph.ir.definition_mode import log_active_definition_mode 1gdef,hilkjcb

234 from orcheo.tracing import configure_tracing 1gdef,hilkjcb

235 

236 if not _repository_ref.get("repository"): 1gdef,hilkjcb

237 _create_repository() 1,

238 configure_tracing() 1gdef,hilkjcb

239 log_active_definition_mode(force=True) 1gdef,hilkjcb

240 load_auth_settings(refresh=True) 1gdef,hilkjcb

241 load_enabled_plugins(force=True) 1gdef,hikjcb

242 workspace_service = await run_in_threadpool(get_workspace_service) 1gdef,hikjcb

243 workspaces = await run_in_threadpool( 1gdef,hikjcb

244 workspace_service.list_workspaces, include_inactive=False 

245 ) 

246 for workspace in workspaces: 1gdef,hikjcb

247 try: 1def,

248 await ensure_managed_vibe_workflow(get_repository(), workspace) 1def,

249 except (RuntimeError, Exception): 1def

250 # Managed vibe workflow may not exist in production / fresh deployments. 

251 # The check is a no-op when not applicable. 

252 pass 1def

253 listener_runtime = ListenerRuntimeService( 1gdef,hikjcb

254 repository=get_repository(), 

255 vault=get_vault(), 

256 runtime_store=get_listener_runtime_store(), 

257 ) 

258 app.state.listener_runtime = listener_runtime 1gdef,hikjcb

259 cron_scheduler: CronSchedulerService | None = None 1gdef,hikjcb

260 if inprocess_cron_enabled(): 1gdef,hikjcb

261 cron_scheduler = CronSchedulerService(repository=get_repository()) 1gdef,hijcb

262 app.state.cron_scheduler = cron_scheduler 1gdef,hikjcb

263 try: 1gdef,hikjcb

264 get_chatkit_server() 1gdef,hikjcb

265 await ensure_chatkit_cleanup_task() 1def,ikjcb

266 except Exception: 1gh

267 pass 1gh

268 await ensure_trace_retention_task() 1gdef,hikjcb

269 await listener_runtime.start() 1gdef,hikjcb

270 if cron_scheduler is not None: 1gdef,hikjcb

271 await cron_scheduler.start() 1gdef,hijcb

272 try: 1gdef,hikjcb

273 async with pending_run_reconciliation(get_repository()): 1gdef,hikjcb

274 async with mcp_lifespan(app): 1gdef,hikjcb

275 yield 1gdef,hikjcb

276 finally: 

277 # Stop dispatching before draining, so the drain is not racing a 

278 # scheduler that keeps handing it new runs. 

279 if cron_scheduler is not None: 1gdef,hikjcb

280 await cron_scheduler.stop() 1gdef,hijcb

281 await drain_inprocess_runs() 1gdef,hikjcb

282 await listener_runtime.stop() 1gdef,hikjcb

283 await cancel_chatkit_cleanup_task() 1gdef,hikjcb

284 await cancel_trace_retention_task() 1gdef,hikjcb

285 reset_app_bundle_store() 1gdef,hikjcb

286 

287 

288def _build_api_router() -> APIRouter: 

289 router = APIRouter(prefix="/api") 

290 

291 protected_router = APIRouter( 

292 dependencies=[ 

293 Depends(authenticate_request), 

294 Depends(resolve_workspace_context), 

295 ] 

296 ) 

297 protected_router.include_router(service_token_router) 

298 protected_router.include_router(workflows.router) 

299 protected_router.include_router(teams.router) 

300 protected_router.include_router(credentials.router) 

301 protected_router.include_router(credential_templates.router) 

302 protected_router.include_router(credential_alerts.router) 

303 protected_router.include_router(credential_health.router) 

304 protected_router.include_router(listeners.router) 

305 protected_router.include_router(runs.router) 

306 protected_router.include_router(triggers.router) 

307 protected_router.include_router(nodes.router) 

308 protected_router.include_router(agentensor.router) 

309 protected_router.include_router(system.router) 

310 protected_router.include_router(workspaces_router.admin_router) 

311 protected_router.include_router(workspaces_router.router) 

312 protected_router.include_router(hosted_apps_router.router) 

313 

314 router.include_router(workflows.public_router) 

315 router.include_router(candidates.router) 

316 router.include_router(chatkit_router.router) 

317 router.include_router(auth.router) 

318 router.include_router(identity_api_router) 

319 router.include_router(passkey_api_router) 

320 router.include_router(system.public_router) 

321 # Authenticates on its own route; tools re-enter the protected API above. 

322 router.include_router(mcp.router) 

323 # OAuth endpoints authenticate clients themselves; consent routes require 

324 # the signed-in Studio user. 

325 router.include_router(oauth_router) 

326 router.include_router(workspaces_router.self_service_router) 

327 # Public webhook invocation routes - external services (Slack, GitHub, etc.) 

328 # cannot provide Orcheo auth tokens. Security is enforced via webhook-level 

329 # validation (HMAC signatures, shared secrets) configured per workflow. 

330 router.include_router(triggers.public_webhook_router) 

331 router.include_router(hosted_apps_platform_router.router) 

332 router.include_router(hosted_apps_platform_router.operations_router) 

333 router.include_router(hosted_apps_auth_router) 

334 router.include_router(protected_router) 

335 return router 

336 

337 

338api_router = _build_api_router() 

339 

340 

341_DEFAULT_ALLOWED_ORIGINS = [ 

342 "http://localhost:2026", 

343 "http://127.0.0.1:2026", 

344] 

345 

346 

347def _load_allowed_origins() -> list[str]: 

348 """Return the list of CORS-allowed origins based on environment configuration.""" 

349 raw = os.getenv("ORCHEO_CORS_ALLOW_ORIGINS") 2a - g d e z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 x . y f m n o 4 5 h i l k j bb.fabcb3 c b p q r s t u v / 6 7 8 9 ! # w $ % ' ( ) * +

350 if not raw: 2a - g d e z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 x . y f m n o 4 5 h i l k j bb.fabcb3 c b p q r s t u v / 6 7 8 9 ! # w $ % ' ( ) * +

351 return list(_DEFAULT_ALLOWED_ORIGINS) 2a - g d e z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 x . y f m n o 4 5 h i l k j .f3 c b p q r s t u v / 6 7 8 9 ! # w $ % ' ( ) * +

352 candidates: list[str] = [] 2bbabcb

353 parsed: list[str] | str | None 

354 try: 2bbabcb

355 parsed = json.loads(raw) 2bbabcb

356 except json.JSONDecodeError: 2ab

357 parsed = raw 2ab

358 

359 if isinstance(parsed, str): 2bbabcb

360 candidates = [entry.strip() for entry in parsed.split(",")] 2ab

361 elif isinstance(parsed, list): 2bbcb

362 candidates = [str(entry).strip() for entry in parsed] 2bbcb

363 

364 origins = [origin for origin in candidates if origin] # pragma: no cover 2bbabcb

365 return origins or list(_DEFAULT_ALLOWED_ORIGINS) 2bbabcb

366 

367 

368def _configure_dependency_overrides( 

369 application: FastAPI, 

370 repository: WorkflowRepository | None = None, 

371 *, 

372 history_store: RunHistoryStore | None = None, 

373 checkpoint_store: AgentensorCheckpointStore | None = None, 

374 plugin_installation_store: PluginInstallationStore | None = None, 

375 credential_service: OAuthCredentialService | None = None, 

376) -> ListenerRuntimeStore: 

377 """Apply optional dependency overrides used by tests and integrations.""" 

378 if repository is not None: 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno_45hilkj3cbpqrstuv/6789!#w$%'()*+

379 set_repository(repository) # pragma: no mutate - override for tests 1gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012fmno_45hilkj3cbpqrstuv6789!#w$%'()*+

380 application.dependency_overrides[get_repository] = lambda: repository 2g d e z A B C D lbE mbF nbG obH pbI qbJ K rbL sbM tbN gbO ubP vbQ wbR xbS ybT zbU AbV BbW CbX DbY EbZ Fb0 Gb1 Hb2 f m n o _ 4 5 h i l k j 3 c b p q r s t u v 6 7 8 9 ! # w $ % ' ( ) * +

381 if history_store is not None: 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno_45hilkj3cbpqrstuv/6789!#w$%'()*+

382 set_history_store(history_store) 1ABCDEFGHIJKLMNOPQRSTUVWXYZ012mno_

383 application.dependency_overrides[get_history_store] = lambda: history_store 2A B C D E F G H I J K L M N gbO P Q R S T U V W X Y Z 0 1 2 m n o _

384 if checkpoint_store is not None: 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno_45hilkj3cbpqrstuv/6789!#w$%'()*+

385 set_checkpoint_store(checkpoint_store) 1_

386 application.dependency_overrides[get_checkpoint_store] = ( 1_

387 lambda: checkpoint_store 

388 ) 

389 if plugin_installation_store is not None: 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno_45hilkj3cbpqrstuv/6789!#w$%'()*+

390 set_plugin_installation_store(plugin_installation_store) 1_

391 application.dependency_overrides[get_plugin_installation_store] = ( 1_

392 lambda: plugin_installation_store 

393 ) 

394 

395 listener_runtime_store = get_listener_runtime_store() 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno_45hilkj3cbpqrstuv/6789!#w$%'()*+

396 set_listener_runtime_store(listener_runtime_store) 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno_45hilkj3cbpqrstuv/6789!#w$%'()*+

397 

398 if credential_service is not None: 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno_45hilkj3cbpqrstuv/6789!#w$%'()*+

399 set_credential_service(credential_service) 1gde_

400 set_vault(getattr(credential_service, "_vault", None)) 1gde_

401 application.dependency_overrides[get_credential_service] = lambda: ( 1gde_

402 credential_service 

403 ) 

404 elif repository is not None: 1a-zABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

405 inferred_service = getattr(repository, "_credential_service", None) 1zABCDEFGHIJKLMNOPQRSTUVWXYZ012fmno45hilkj3cbpqrstuv6789!#w$%'()*+

406 if inferred_service is not None: 1zABCDEFGHIJKLMNOPQRSTUVWXYZ012fmno45hilkj3cbpqrstuv6789!#w$%'()*+

407 set_credential_service(inferred_service) 1z

408 application.dependency_overrides[get_credential_service] = lambda: ( 1z

409 inferred_service 

410 ) 

411 

412 application.state.listener_runtime_store = listener_runtime_store 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno_45hilkj3cbpqrstuv/6789!#w$%'()*+

413 return listener_runtime_store 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno_45hilkj3cbpqrstuv/6789!#w$%'()*+

414 

415 

416def _configure_application(application: FastAPI) -> None: 

417 """Install routes, handlers, and middleware on the FastAPI app.""" 

418 application.include_router(api_router) 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

419 # RFC 8414 / RFC 9728 discovery documents live at the origin root. 

420 application.include_router(oauth_well_known_router) 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

421 application.include_router(hosted_apps_internal_router) 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

422 # Workspace-slug-prefixed webhook routes at /hooks/{workspace_slug}/{trigger_id}. 

423 # Mounted at the application root (not under /api) so external services 

424 # can reach them without an /api prefix. 

425 application.include_router(triggers.workspace_webhook_router) 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

426 application.include_router(chatkit_assets.router) 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

427 application.include_router(websocket.router) 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

428 application.add_exception_handler( 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

429 AuthenticationError, _authentication_error_handler 

430 ) 

431 for error_type in DATABASE_UNAVAILABLE_ERRORS: 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

432 application.add_exception_handler(error_type, database_unavailable_handler) 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

433 _configure_studio_static(application) 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

434 

435 

436def _configure_studio_static(application: FastAPI) -> None: 

437 """Mount built Studio assets when ORCHEO_STUDIO_DIST_DIR is configured.""" 

438 studio_dist_dir = os.getenv("ORCHEO_STUDIO_DIST_DIR", "").strip() 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

439 if not studio_dist_dir: 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

440 return 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkjpqrstuv/6789!#w$%'()*+

441 

442 studio_dist_path = Path(studio_dist_dir).expanduser().resolve() 13cb

443 if not studio_dist_path.joinpath("index.html").is_file(): 13cb

444 raise RuntimeError( 13

445 "ORCHEO_STUDIO_DIST_DIR must point to a built Studio directory " 

446 "containing index.html." 

447 ) 

448 

449 application.mount( 1cb

450 "/", 

451 _StudioStaticFiles(directory=studio_dist_path, html=True), 

452 name="studio", 

453 ) 

454 

455 

456def create_app( 

457 repository: WorkflowRepository | None = None, 

458 *, 

459 history_store: RunHistoryStore | None = None, 

460 checkpoint_store: AgentensorCheckpointStore | None = None, 

461 plugin_installation_store: PluginInstallationStore | None = None, 

462 credential_service: OAuthCredentialService | None = None, 

463) -> FastAPI: 

464 """Instantiate and configure the FastAPI application.""" 

465 application = FastAPI(lifespan=_app_lifespan) 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

466 application.add_api_route("/robots.txt", _robots_txt, include_in_schema=False) 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

467 allowed_origins = _load_allowed_origins() 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

468 application.add_middleware( 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

469 CORSMiddleware, 

470 allow_origins=allowed_origins, 

471 allow_credentials=True, 

472 allow_methods=["*"], 

473 allow_headers=["*"], 

474 ) 

475 application.add_middleware(_ApiGZipMiddleware) 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

476 _configure_dependency_overrides( 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

477 application, 

478 repository, 

479 history_store=history_store, 

480 checkpoint_store=checkpoint_store, 

481 plugin_installation_store=plugin_installation_store, 

482 credential_service=credential_service, 

483 ) 

484 _configure_application(application) 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkj3cbpqrstuv/6789!#w$%'()*+

485 return application 1a-gdezABCDEFGHIJKLMNOPQRSTUVWXYZ012x.yfmno45hilkjcbpqrstuv/6789!#w$%'()*+

486 

487 

488__all__ = ["create_app"]