跳转至

app

feishu.agent.app

开箱即用的 Feishu agent 应用入口:Agent(config)。

Agent

基于配置开箱即用地装配并运行 Feishu agent。

Agent(config) 只接收已经加载好的 mapping / config object,不负责读取 yaml、toml 或环境变量。产品层可以用 chanfig.load(...)、环境变量或自己的配置系统得到配置后传入。

seen_store 可注入共享的事件去重存储;event_job_store 可将已验证的普通 Webhook 事件在 ACK 前持久化, 并由 EventJobRunner 在后台执行。设置持久事件收件箱时,使用 event_partition_key 为每条事件返回会话分区键,以保持同一会话的 FIFO 顺序。

示例:

Python Console Session
1
2
3
>>> config = {"model": {"model": "gpt-4o", "api_key": "k", "base_url": "https://api.example/v1"}}
>>> agent = Agent(config)
>>> agent.run(backend="ws")
源代码位于: feishu/agent/app.py
Python
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
class Agent:
    r"""
    基于配置开箱即用地装配并运行 Feishu agent。

    `Agent(config)` 只接收已经加载好的 mapping / config object,不负责读取 yaml、toml 或环境变量。产品层可以用
    `chanfig.load(...)`、环境变量或自己的配置系统得到配置后传入。

    `seen_store` 可注入共享的事件去重存储;`event_job_store` 可将已验证的普通 Webhook 事件在 ACK 前持久化,
    并由 [EventJobRunner][feishu.events.job_runner.EventJobRunner] 在后台执行。设置持久事件收件箱时,使用
    `event_partition_key` 为每条事件返回会话分区键,以保持同一会话的 FIFO 顺序。

    Examples:
        >>> config = {"model": {"model": "gpt-4o", "api_key": "k", "base_url": "https://api.example/v1"}}
        >>> agent = Agent(config)  # doctest:+SKIP
        >>> agent.run(backend="ws")  # doctest:+SKIP
    """

    def __init__(
        self,
        config: Mapping[str, Any] | None = None,
        *,
        engine: AgentEngine | None = None,
        client: Any | None = None,
        model_client: Any | None = None,
        backend: Any | None = None,
        registry: ToolRegistry | None = None,
        seen_store: SeenStore | None = None,
        event_job_store: EventJobStore | None = None,
        event_partition_key: Callable[[Event], str] | None = None,
        durable_callbacks: Any | None = None,
        user_tokens: Any | None = None,
        authorize_url_builder: Any | None = None,
        describe_analyzer: Any | None = None,
        progress_summarizer: Any | None = None,
        text_summarizer: Any | None = None,
        **engine_overrides: Any,
    ) -> None:
        injected = {
            name
            for name, dependency in (
                ("engine", engine),
                ("client", client),
                ("backend", backend),
                ("model_client", model_client),
                ("progress_summarizer", progress_summarizer),
                ("text_summarizer", text_summarizer),
            )
            if dependency is not None
        }
        if registry is not None:
            injected.add("registry")
        if engine_overrides.get("memory_store") is not None:
            injected.add("memory_store")
        issues = self.validate_config(config, injected=injected)
        if issues:
            raise AgentConfigurationError(issues)
        self.config = config or {}
        self._lifecycle_state = "created"
        self._shutdown_deadline: float | None = None
        self._owns_engine = engine is None
        self._owned_resources: list[Any] = []
        self._owned_resource_ids: set[int] = set()
        self._closed_resource_ids: set[int] = set()
        self._asgi_application: Any | None = None
        self._injected_seen_store = seen_store
        self._resolved_seen_store: Any = _UNSET
        if durable_callbacks is not None and (event_job_store is not None or event_partition_key is not None):
            raise ValueError("durable callbacks own their event store and session partitioning")
        self._durable_callbacks = durable_callbacks
        self._event_job_store = durable_callbacks if durable_callbacks is not None else event_job_store
        self._event_partition_key = event_partition_key
        self._scheduled_runner: Any | None = None
        if engine is not None:
            self.client = client if client is not None else getattr(engine, "client", None)
            self.model_client = model_client
            self.backend = backend
            self.progress_summarizer = progress_summarizer
            self.text_summarizer = text_summarizer
            self.extractor = SandboxedAttachmentExtractor()
            self.provider = user_tokens
            self.signer = None
            self.oauth_callback_path = normalize_oauth_callback_path(
                self._get("oauth.callback_path", "/oauth/callback")
            )
            self.oauth_redirect_uri = None
            self.authorize_url_builder = authorize_url_builder
            self.describe_analyzer = describe_analyzer
            self.engine = engine
            if durable_callbacks is not None and self._get("oauth.public_url"):
                if authorize_url_builder is not None or engine.authorize_url_builder is not None:
                    raise ValueError("durable OAuth with an injected engine requires the Agent-managed URL builder")
                self.signer = self._oauth_state_signer()
                self.oauth_redirect_uri = build_oauth_redirect_uri(
                    self._get("oauth.public_url"), self.oauth_callback_path
                )
                self.authorize_url_builder = self._authorize_url_builder()
                if self.authorize_url_builder is None:
                    raise ValueError("durable OAuth requires a state secret and token provider")
                engine.authorize_url_builder = self.authorize_url_builder
            self._configure_scheduling()
            self._configure_durable_callbacks()
            return
        self.client = client if client is not None else self._own_resource(self._client_from_config())
        self.model_client = model_client
        self.backend = backend
        self.progress_summarizer = progress_summarizer
        self.text_summarizer = text_summarizer
        self.extractor = SandboxedAttachmentExtractor()
        self.provider = user_tokens or UserTokenProvider(
            self.client,
            SqliteOAuthTokenStore(self.db_path),
        )
        self.signer = self._oauth_state_signer()
        self.oauth_callback_path = normalize_oauth_callback_path(self._get("oauth.callback_path", "/oauth/callback"))
        self.oauth_redirect_uri = build_oauth_redirect_uri(self._get("oauth.public_url"), self.oauth_callback_path)
        self.authorize_url_builder = authorize_url_builder or self._authorize_url_builder()
        self.describe_analyzer = describe_analyzer
        if engine is not None:
            self.engine = engine
            return
        if self.backend is None and self.model_client is None:
            self.model_client = self._own_resource(self._openai_client_from_config())
        if self.backend is None:
            self.backend = self._model_backend_from_config(self.model_client)
        if self.progress_summarizer is None:
            self.progress_summarizer = self._progress_summarizer_from_config()
        if self.text_summarizer is None:
            self.text_summarizer = self._text_summarizer_from_config()
        if self.describe_analyzer is None and self.model_client is not None:
            self.describe_analyzer = self._describe_analyzer()
        self.engine = self._engine(registry=registry, **engine_overrides)
        self._configure_scheduling()
        self._configure_durable_callbacks()

    def _configure_durable_callbacks(self) -> None:
        if self._durable_callbacks is None:
            return
        from ..auth import SqliteOAuthTokenStore
        from .durable_callbacks import SqliteDurableCallbacks, _same_file

        inbox = self._durable_callbacks
        if not isinstance(inbox, SqliteDurableCallbacks) or inbox.approvals is None:
            raise ValueError("durable callbacks require a configured SQLite callback inbox")
        if not (self._get("feishu.encrypt_key") or self._get("feishu.verification_token")):
            raise ValueError("durable callbacks require Feishu event authentication")
        if not isinstance(getattr(self.provider, "store", None), SqliteOAuthTokenStore):
            raise ValueError("durable callbacks require a SQLite OAuth token provider")
        if self.engine.user_tokens is not self.provider:
            raise ValueError("durable callbacks require the Agent and engine to share a token provider")
        if getattr(self.provider, "client", None) is not self.engine.client:
            raise ValueError("durable callbacks require the Agent and OAuth provider to share a Feishu client")
        if (
            not isinstance(self.engine.approvals, SqlitePendingApprovalStore)
            or not isinstance(self.engine.authorizations, SqlitePendingAuthorizationStore)
            or not isinstance(self.engine._store, SqliteSessionStore)
        ):
            raise ValueError("durable callbacks require SQLite session, approval and authorization stores")
        if not _same_file(
            inbox.jobs._db,
            getattr(getattr(self.provider, "store", None), "_db", None),
            getattr(self.engine.approvals, "_db", None),
            getattr(self.engine.authorizations, "_db", None),
            getattr(self.engine._store, "_db", None),
        ):
            raise ValueError("durable callbacks require Agent session, authorization and token stores in one database")
        self._event_partition_key = self.engine._session_id_for_event

    def _configure_scheduling(self) -> None:
        """Assemble the optional scheduler around this Agent's existing stores."""
        scheduling = self._section("scheduling")
        enabled = scheduling.get("enabled")
        if enabled is None:
            enabled = False
        if not isinstance(enabled, bool):
            raise ValueError("scheduling.enabled must be a boolean")
        if not enabled:
            return
        from .scheduled import (
            ScheduledAgentAdapter,
            ScheduledTaskRunner,
            ScheduledTaskStore,
            ScheduledTimezoneResolver,
        )
        from .scheduled_session import validate_fenced_stores
        from .session import InMemoryPendingApprovalStore, InMemoryPendingAuthorizationStore, InMemorySessionStore
        from .toolkit.scheduled import register_scheduled_tools

        if (
            isinstance(self.engine.store, InMemorySessionStore)
            or isinstance(self.engine.approvals, InMemoryPendingApprovalStore)
            or isinstance(self.engine.authorizations, InMemoryPendingAuthorizationStore)
        ):
            raise ValueError("scheduling requires persistent session, approval, and authorization stores")
        store = getattr(self.engine, "scheduled_store", None)
        if store is None:
            store = ScheduledTaskStore(str(scheduling.get("path") or self.db_path))
            self.engine.scheduled_store = store
        validate_fenced_stores(self.engine.store, store)
        expire_approval = getattr(self.engine.approvals, "expire_if_pending", None)
        expire_authorization = getattr(self.engine.authorizations, "expire_if_pending", None)
        if not callable(expire_approval) or not callable(expire_authorization):
            raise ValueError("scheduling requires approval and authorization stores with expiry support")
        base_registry = self.engine.registry
        scheduled_names = {
            "create_scheduled_task",
            "list_scheduled_tasks",
            "pause_scheduled_task",
            "resume_scheduled_task",
            "delete_scheduled_task",
        }
        if scheduled_names.intersection(spec.name for spec in base_registry.specs()):
            raise ValueError("scheduling tool names already exist in the supplied registry")
        registry = _OverlayRegistry(base_registry)
        register_scheduled_tools(registry, store)
        self.engine.registry = registry
        adapter = ScheduledAgentAdapter(self.engine)
        self._scheduled_runner = ScheduledTaskRunner(
            store,
            adapter.execute,
            adapter.notify,
            timezone_for=ScheduledTimezoneResolver(self.engine.user_tokens, self.engine.client),
            expire_approval=lambda approval_id, now: expire_approval(approval_id, now=now),
            expire_authorization=lambda authorization_id, now: expire_authorization(authorization_id, now=now),
            poll_interval=float(scheduling.get("poll_interval", 5)),
        )

    @staticmethod
    def validate_config(
        config: Mapping[str, Any] | None,
        *,
        injected: Iterable[str] = (),
    ) -> tuple[ConfigurationIssue, ...]:
        """Check known config fields and default assembly requirements without creating resources."""
        return validate_agent_config(config, injected=injected)

    @property
    def db_path(self) -> str:
        storage = self._section("storage")
        path = storage.get("path") or storage.get("db_path") or ".agent/agent.db"
        return str(path)

    @property
    def audit_path(self) -> str:
        storage = self._section("storage")
        return str(storage.get("audit_path") or str(Path(self.db_path).with_name("audit.jsonl")))

    @property
    def status(self) -> str:
        """Current runtime state: created, ready, draining, or stopped."""
        return self._lifecycle_state

    @property
    def is_ready(self) -> bool:
        """Whether startup completed and the runtime is accepting new work."""
        return self._lifecycle_state == "ready"

    async def start(self) -> None:
        """Mark the assembled runtime ready; ASGI and WebSocket runners share this lifecycle."""
        if self._lifecycle_state == "ready":
            return
        if self._lifecycle_state != "created":
            raise RuntimeError(f"cannot start agent while runtime is {self._lifecycle_state}")
        if self._scheduled_runner is not None:
            await self._scheduled_runner.start()
        self._lifecycle_state = "ready"

    def _begin_shutdown(self, *, stop_engine: bool = True) -> float:
        if self._shutdown_deadline is None:
            loop = asyncio.get_running_loop()
            timeout = float(self._get("runtime.shutdown_timeout_seconds", 30.0))
            self._shutdown_deadline = loop.time() + timeout
        if self._lifecycle_state != "stopped":
            self._lifecycle_state = "draining"
        if stop_engine and self._owns_engine and hasattr(self.engine, "stop_accepting_events"):
            self.engine.stop_accepting_events()
        return self._shutdown_deadline

    def _on_ws_connection_state(self, connected: bool) -> None:
        if self._lifecycle_state in {"draining", "stopped"}:
            return
        self._lifecycle_state = "ready" if connected else "reconnecting"

    async def aclose(self) -> None:
        """Drain active work and close only resources created by this Agent."""
        if self._lifecycle_state == "stopped":
            return
        deadline = self._begin_shutdown()
        if self._scheduled_runner is not None:
            drained = await self._scheduled_runner.aclose(deadline=deadline)
            if not drained:
                logger.error("scheduled work did not stop before the shutdown deadline; leaving resources open")
                return
        drained = True
        if self._owns_engine and hasattr(self.engine, "aclose"):
            drained = await self.engine.aclose(deadline=deadline)
        if not drained:
            logger.error("agent shutdown timed out; leaving resources open while work is still running")
            return
        resources_closed = await self._close_owned_resources(deadline)
        if not resources_closed:
            logger.error("agent shutdown did not close every owned resource before its deadline")
            return
        self._lifecycle_state = "stopped"

    async def __aenter__(self) -> Agent:
        await self.start()
        return self

    async def __aexit__(self, *_exc: Any) -> None:
        await self.aclose()

    def _own_resource(self, resource: Any) -> Any:
        if resource is not None and id(resource) not in self._owned_resource_ids:
            self._owned_resource_ids.add(id(resource))
            self._owned_resources.append(resource)
        return resource

    def _own_sqlite_store(self, store: Any) -> Any:
        connection = getattr(store, "_db", None)
        if connection is not None:
            self._own_resource(connection)
        return store

    async def _close_owned_resources(self, deadline: float) -> bool:
        loop = asyncio.get_running_loop()
        closed = True
        for resource in reversed(self._owned_resources):
            resource_id = id(resource)
            if resource_id in self._closed_resource_ids:
                continue
            close = getattr(resource, "aclose", None) or getattr(resource, "close", None)
            if not callable(close):
                self._closed_resource_ids.add(resource_id)
                continue
            try:
                result = close()
                if inspect.isawaitable(result):
                    remaining = deadline - loop.time()
                    if remaining <= 0:
                        logger.error("agent shutdown deadline expired before all resources closed")
                        return False
                    await asyncio.wait_for(result, timeout=remaining)
            except asyncio.TimeoutError:
                logger.error("timed out closing an Agent-owned resource")
                return False
            except Exception:  # noqa: BLE001 - close every owned resource even if one close fails
                logger.exception("failed to close an Agent-owned resource")
                closed = False
            else:
                self._closed_resource_ids.add(resource_id)
        return closed

    def run(self, *, backend: Literal["ws", "http"] = "ws") -> None:
        r"""启动 agent。`backend="ws"` 运行飞书长连接,`backend="http"` 运行 HTTP webhook 服务。"""
        if backend == "ws":
            asyncio.run(self.run_ws())
            return
        if backend == "http":
            self.run_http()
            return
        raise ValueError(f"unknown agent run backend: {backend!r}")

    async def run_ws(self) -> None:
        r"""运行飞书 WebSocket 长连接服务。"""
        if self._durable_callbacks is not None:
            raise ValueError("durable callback intake currently requires the HTTP backend")
        feishu = self._section("feishu")
        app_id = str(feishu.get("app_id") or "")
        app_secret = str(feishu.get("app_secret") or "")
        if not (app_id and app_secret):
            raise RuntimeError("feishu.app_id / feishu.app_secret are required for ws backend")
        if self.signer is not None and self.oauth_redirect_uri:
            logger.warning(
                "ws backend does not serve OAuth callback; run http backend to handle %s", self.oauth_callback_path
            )
        ws = WsClient(
            app_id,
            app_secret,
            self.dispatcher(),
            region=str(feishu.get("region") or "feishu"),
            card_ack_timeout=self._card_ack_timeout_seconds(),
            background_dispatch_drain_timeout=float(self._get("runtime.shutdown_timeout_seconds", 30.0)),
            shutdown_deadline=lambda: self._shutdown_deadline,
            on_connection_state=self._on_ws_connection_state,
        )
        await self.start()
        self._lifecycle_state = "starting"
        loop = asyncio.get_running_loop()
        stop_task: asyncio.Task[Any] | None = None

        def stop() -> None:
            nonlocal stop_task
            logger.info("shutdown signal received; closing the ws connection gracefully")
            self._begin_shutdown(stop_engine=False)
            if stop_task is None:
                stop_task = asyncio.create_task(ws.aclose())

        installed_signals: list[signal.Signals] = []
        try:
            for sig in (signal.SIGTERM, signal.SIGINT):
                with suppress(NotImplementedError, RuntimeError, ValueError):
                    loop.add_signal_handler(sig, stop)
                    installed_signals.append(sig)
            await ws.start()
        finally:
            for installed_signal in installed_signals:
                with suppress(NotImplementedError, RuntimeError, ValueError):
                    loop.remove_signal_handler(installed_signal)
            try:
                if stop_task is not None:
                    await stop_task
            finally:
                await self.aclose()

    def run_http(self) -> None:
        r"""运行 HTTP webhook 服务。"""
        import uvicorn

        server = self._section("server")
        shutdown_timeout = float(self._get("runtime.shutdown_timeout_seconds", 30.0))
        uvicorn.run(
            self.asgi_app(),
            host=str(server.get("host") or "127.0.0.1"),
            port=int(server.get("port") or 5654),
            log_level=str(server.get("log_level") or "info").lower(),
            lifespan="on",
            timeout_graceful_shutdown=max(1, math.ceil(shutdown_timeout)),
        )

    def asgi_app(self) -> Any:
        r"""返回可交给 ASGI server 的 Starlette app。"""
        from starlette.applications import Starlette
        from starlette.responses import JSONResponse
        from starlette.routing import Route

        if self._asgi_application is not None:
            return self._asgi_application

        server = self._section("server")

        async def health(_request: Any) -> Any:
            return JSONResponse({"ok": True, "service": str(server.get("service") or "feishu-agent")})

        async def ready(_request: Any) -> Any:
            is_ready = self.is_ready
            return JSONResponse(
                {"ready": is_ready, "status": self.status},
                status_code=200 if is_ready else 503,
            )

        @asynccontextmanager
        async def lifespan(_app: Any) -> AsyncIterator[None]:
            await self.start()
            try:
                yield
            finally:
                await self.aclose()

        dispatcher = self.dispatcher()
        event_path = str(server.get("event_path") or "/feishu/event")
        routes = [
            Route(str(server.get("health_path") or "/health"), health, methods=["GET"]),
            Route(str(server.get("ready_path") or "/ready"), ready, methods=["GET"]),
            create_event_route(
                dispatcher,
                path=event_path,
                encrypt_key=self._get("feishu.encrypt_key"),
                verification_token=self._get("feishu.verification_token"),
                **self._event_route_options(),
            ),
        ]
        card_path = server.get("card_path", "/feishu/card")
        if card_path and str(card_path) != event_path:
            routes.append(
                create_event_route(
                    dispatcher,
                    path=str(card_path),
                    encrypt_key=self._get("feishu.encrypt_key"),
                    verification_token=self._get("feishu.verification_token"),
                    **self._event_route_options(),
                )
            )
        routes.extend(self.extra_routes())
        if self.signer is not None and self.oauth_redirect_uri and self.provider is not None:
            handler = oauth_callback_handler(
                self.provider,
                self.signer,
                self.oauth_redirect_uri,
                on_authorized=self.engine.resume_authorization,
                durable_receiver=self._durable_callbacks,
                track_task=getattr(self.engine, "track_background_task", None),
                success_message=self.oauth_success_message(),
                success_title=self.oauth_success_title(),
            )
            routes.append(Route(self.oauth_callback_path, handler, methods=["GET"]))
        self._asgi_application = Starlette(routes=routes, lifespan=lifespan)
        return self._asgi_application

    def extra_routes(self) -> list[Any]:
        r"""返回产品层追加的 Starlette routes。"""
        return []

    def oauth_success_message(self) -> str:
        r"""OAuth 成功页正文。"""
        return str(self._get("oauth.success_message", "授权成功,正在回到飞书继续处理。"))

    def oauth_success_title(self) -> str:
        r"""OAuth 成功页标题。"""
        return str(self._get("oauth.success_title", "授权完成"))

    def dispatcher(self) -> Any:
        r"""创建并返回绑定了当前 engine 的事件 dispatcher。"""
        return create_agent_dispatcher(self.engine, seen_store=self._seen_store_config())

    def _seen_store_config(self) -> Any | None:
        if self._injected_seen_store is not None:
            return self._injected_seen_store
        if self._resolved_seen_store is not _UNSET:
            return self._resolved_seen_store
        mode_value = self._get("server.seen_store")
        if mode_value is None:
            self._resolved_seen_store = None
            return None
        mode = str(mode_value).strip().lower()
        if mode in {"", "none", "off", "false", "0", "disabled"}:
            self._resolved_seen_store = None
            return None
        if mode == "sqlite":
            from ..events.idempotency import SqliteSeenStore

            path = self._get("server.seen_db_path") or self.db_path
            ttl = float(self._get("server.seen_ttl_seconds", 7 * 24 * 3600) or 7 * 24 * 3600)
            self._resolved_seen_store = SqliteSeenStore(str(path), ttl=ttl)
            return self._resolved_seen_store
        raise ValueError(f"unknown server.seen_store mode: {mode_value!r}")

    def _event_route_options(self) -> dict[str, Any]:
        options: dict[str, Any] = {}
        seen_store = self._seen_store_config()
        if seen_store is not None:
            options["seen_store"] = seen_store
        if self._event_job_store is not None:
            options["job_store"] = self._event_job_store
        if self._durable_callbacks is not None:
            options["card_handler"] = self._durable_callbacks.card_handler(self.engine)
        if self._event_partition_key is not None:
            options["partition_key"] = self._event_partition_key
        return options

    def _card_ack_timeout_seconds(self) -> float | None:
        value = self._get("ws.card_ack_timeout_seconds", self._get("server.card_ack_timeout_seconds", 1.5))
        return None if value is None else float(value)

    async def handle_event(self, event: Any) -> None:
        r"""直接处理一条消息事件。"""
        await self.engine.run(event)

    async def handle_card_action(self, event: Any) -> dict[str, Any]:
        r"""直接处理一条卡片回调事件。"""
        return await self.engine.handle_card_action(event)

    async def resume_authorization(self, authorization_id: str, *, user: Mapping[str, Any] | None = None) -> str:
        r"""在 OAuth 回调保存用户 token 后恢复挂起授权。"""
        return await self.engine.resume_authorization(authorization_id, user=user)

    def _engine(self, *, registry: ToolRegistry | None = None, **overrides: Any) -> AgentEngine:
        approvals = overrides.pop("approvals", None)
        if approvals is None:
            approvals = self._own_sqlite_store(SqlitePendingApprovalStore(self.db_path))
        authorizations = overrides.pop("authorizations", None)
        if authorizations is None:
            authorizations = self._own_sqlite_store(
                SqlitePendingAuthorizationStore(
                    self.db_path,
                    ttl_seconds=int(self._get("oauth.authorization_ttl_seconds", 3600) or 3600),
                )
            )
        shared_files_store = overrides.pop("shared_files_store", None)
        if shared_files_store is None:
            shared_files_store = self._own_sqlite_store(SqliteSharedFileStore(self.db_path))
        shared_files = overrides.pop("shared_files", None)
        if shared_files is None:
            shared_files = SharedFileResolver(
                shared_files_store,
                self.client,
                max_materialize_bytes=int(self._get("shared_files.max_bytes", 20 * 1024 * 1024) or 20 * 1024 * 1024),
            )
        memory = self._section("memory")
        memory_store = overrides.pop("memory_store", None)
        if memory_store is None and bool(memory.get("enabled", False)):
            memory_store = self._own_sqlite_store(SqliteMemoryStore(self.db_path))
        timezone_resolver = overrides.pop("timezone", None) or self._timezone_resolver()
        if self.backend is None:
            raise RuntimeError("agent backend is not configured")
        store = overrides.pop("store", None)
        if store is None:
            store = self._own_sqlite_store(
                SqliteSessionStore(self.db_path, max_messages=int(self._get("session.max_messages", 0) or 0))
            )
        approval_engine = overrides.pop("approval_engine", None)
        if approval_engine is None:
            approval_engine = DefaultApprovalEngine(
                approvals=approvals,
                executions=self._own_sqlite_store(SqliteExecutionResultStore(self.db_path)),
                audit=JsonlAuditLog(self.audit_path),
                outcome_status=overrides.pop("outcome_status", None),
                idempotency_namespace=str(self._get("approval.idempotency_namespace", "agent") or "agent"),
            )
        return AgentEngine(
            backend=self.backend,
            registry=registry or self._registry(),
            client=self.client,
            store=store,
            approvals=approvals,
            authorizations=authorizations,
            approval_engine=approval_engine,
            progress_summarizer=self.progress_summarizer,
            progress_summary_interval_seconds=float(self._get("reply.progress_summary_interval_seconds", 2.0) or 0),
            user_tokens=self.provider,
            authorize_url_builder=self.authorize_url_builder,
            shared_files=shared_files,
            shared_files_store=shared_files_store,
            shared_file_ttl_seconds=int(self._get("shared_files.ttl_seconds", 7 * 24 * 3600) or 7 * 24 * 3600),
            payment_accounts=overrides.pop("payment_accounts", None) or PaymentAccountResolver(self.client),
            memory_store=memory_store,
            memory_namespace=str(memory.get("namespace") or "default") if memory_store is not None else None,
            system=overrides.pop("system", None) or self._system_prompt(timezone_resolver),
            turn_context=overrides.pop("turn_context", None) or self._turn_context(timezone_resolver),
            timezone=timezone_resolver,
            trusted_tenant_key=overrides.pop("trusted_tenant_key", None) or self._get("feishu.tenant_key"),
            summarize_threshold_tokens=int(self._get("session.summarize_threshold_tokens", 0) or 0),
            summarize_keep_recent=int(self._get("session.summarize_keep_recent", 12) or 12),
            idle_session_timeout_seconds=float(self._get("session.idle_session_timeout_seconds", 0) or 0),
            stream=bool(self._get("reply.stream", True)),
            **overrides,
        )

    def _registry(self) -> ToolRegistry:
        toolkits = _string_tuple(self._get("toolkits", ("feishu.workplace",)))
        bundle = self._section("bundle")
        context = BundleContext(
            locale=str(self._get("locale", "zh-CN") or "zh-CN"),
            timezone=str(self._get("timezone", "Asia/Shanghai") or "Asia/Shanghai"),
            describe_analyzer=self.describe_analyzer,
            text_summarizer=self.text_summarizer,
            mail_summary_max_messages=int(bundle.get("mail_summary_max_messages") or 10),
            mail_summary_max_body_chars=int(bundle.get("mail_summary_max_body_chars") or 4000),
            mail_summary_max_chars=int(bundle.get("mail_summary_max_chars") or 2000),
            extra=dict(bundle.get("extra") or {}),
        )
        return build_tool_registry(toolkits, context)

    def _client_from_config(self) -> FeishuClient:
        feishu = self._section("feishu")
        app_id = str(feishu.get("app_id") or "")
        app_secret = str(feishu.get("app_secret") or "")
        if not (app_id and app_secret):
            raise RuntimeError("feishu.app_id / feishu.app_secret are required")
        return FeishuClient(app_id, app_secret, region=str(feishu.get("region") or "feishu"))

    def _openai_client_from_config(self) -> Any:
        model = self._section("model")
        api_key = model.get("api_key")
        base_url = model.get("base_url")
        if not (api_key and base_url):
            raise RuntimeError("model.api_key / model.base_url are required for the OpenAI-compatible backend")
        return create_openai_client(str(api_key), str(base_url))

    def _model_backend_from_config(self, client: Any) -> Any:
        model = self._section("model")
        model_name = model.get("model") or model.get("name")
        if not model_name:
            raise RuntimeError("model.model is required")
        return create_openai_backend(
            client=client,
            model=str(model_name),
            base_url=model.get("base_url"),
            thinking_enabled=model.get("thinking_enabled"),
            thinking_budget=model.get("thinking_budget"),
        )

    def _fast_backend_from_config(self) -> Any | None:
        fast = self._section("fast_model")
        model_name = fast.get("model") or fast.get("name")
        if not model_name:
            return None
        model = self._section("model")
        api_key = fast.get("api_key") or model.get("api_key")
        base_url = fast.get("base_url") or model.get("base_url")
        if not (api_key and base_url):
            raise RuntimeError("fast_model.model requires fast_model.api_key/base_url or model fallback values")
        client = create_openai_client(str(api_key), str(base_url))
        self._own_resource(client)
        return create_openai_backend(
            client=client,
            model=str(model_name),
            base_url=str(base_url),
            force_non_thinking=True,
        )

    def _progress_summarizer_from_config(self) -> Any | None:
        backend = self._fast_backend_from_config()
        if backend is None:
            return None
        fast = self._section("fast_model")
        return build_progress_summarizer(
            backend,
            timeout_seconds=float(fast.get("timeout_seconds") or 3.0),
            max_chars=int(fast.get("max_chars") or 60),
        )

    def _text_summarizer_from_config(self) -> Any | None:
        backend = self._fast_backend_from_config()
        if backend is None:
            return None
        fast = self._section("fast_model")
        return build_fast_text_summarizer(
            backend,
            timeout_seconds=float(fast.get("summary_timeout_seconds") or 12.0),
            default_max_chars=int(fast.get("summary_max_chars") or 2000),
        )

    def _timezone_resolver(self) -> Any:
        return build_timezone_resolver(
            str(self._get("timezone", "Asia/Shanghai") or "Asia/Shanghai"),
            user_tokens=self.provider,
            client=self.client,
            trusted_tenant_key=self._get("feishu.tenant_key"),
        )

    def _system_prompt(self, timezone_resolver: Any) -> Any:
        system = self._get("system")
        if system is None:
            path = self._get("system_path")
            system = Path(path).read_text(encoding="utf-8") if path else None
        if system is None:
            return None
        if callable(system):
            return system
        return str(system)

    def _turn_context(self, timezone_resolver: Any) -> Any:
        if bool(self._get("time_aware_system", True)):
            return build_time_context(timezone_resolver)
        return None

    def _describe_analyzer(self) -> Any:
        model_name = self._section("model").get("model") or self._section("model").get("name")
        if not model_name:
            return None

        async def analyzer(data: bytes, *, media_type: str | None, name: str | None) -> str:
            analysis = await analyze_attachment(
                data,
                {"name": name, "mime_type": media_type},
                extractor=self.extractor,
                openai_client=self.model_client,
                model=str(model_name),
            )
            return json.dumps(analysis, ensure_ascii=False)

        return analyzer

    def _oauth_state_signer(self) -> OAuthStateSigner | None:
        secret = self._get("oauth.state_secret")
        if not secret:
            secret = self._get("feishu.app_secret")
            if secret:
                secret = hmac.new(str(secret).encode(), b"feishu-agent-oauth-state-v1", hashlib.sha256).hexdigest()
                logger.warning(
                    "oauth.state_secret is not set; deriving the OAuth state key from feishu.app_secret. "
                    "Set a dedicated oauth.state_secret in production."
                )
        if not secret:
            return None
        return OAuthStateSigner(str(secret), ttl_seconds=int(self._get("oauth.state_ttl_seconds", 3600) or 3600))

    def _authorize_url_builder(self) -> Any | None:
        if self.signer is not None and self.oauth_redirect_uri and self.provider is not None:
            return build_authorize_url_builder(self.provider, self.signer, self.oauth_redirect_uri)
        if not self.oauth_redirect_uri:
            logger.warning("oauth.public_url is not set; user-scoped tools cannot offer an authorize link")
        return None

    def _section(self, name: str) -> Mapping[str, Any]:
        value = self.config.get(name) if isinstance(self.config, Mapping) else None
        return value if isinstance(value, Mapping) else {}

    def _get(self, path: str, default: Any = None) -> Any:
        node: Any = self.config
        for part in path.split("."):
            if not isinstance(node, Mapping) or part not in node:
                return default
            node = node[part]
        return node

status property

Python
status: str

Current runtime state: created, ready, draining, or stopped.

is_ready property

Python
is_ready: bool

Whether startup completed and the runtime is accepting new work.

validate_config staticmethod

Python
validate_config(config: Mapping[str, Any] | None, *, injected: Iterable[str] = ()) -> tuple[ConfigurationIssue, ...]

Check known config fields and default assembly requirements without creating resources.

源代码位于: feishu/agent/app.py
Python
@staticmethod
def validate_config(
    config: Mapping[str, Any] | None,
    *,
    injected: Iterable[str] = (),
) -> tuple[ConfigurationIssue, ...]:
    """Check known config fields and default assembly requirements without creating resources."""
    return validate_agent_config(config, injected=injected)

start async

Python
start() -> None

Mark the assembled runtime ready; ASGI and WebSocket runners share this lifecycle.

源代码位于: feishu/agent/app.py
Python
async def start(self) -> None:
    """Mark the assembled runtime ready; ASGI and WebSocket runners share this lifecycle."""
    if self._lifecycle_state == "ready":
        return
    if self._lifecycle_state != "created":
        raise RuntimeError(f"cannot start agent while runtime is {self._lifecycle_state}")
    if self._scheduled_runner is not None:
        await self._scheduled_runner.start()
    self._lifecycle_state = "ready"

aclose async

Python
aclose() -> None

Drain active work and close only resources created by this Agent.

源代码位于: feishu/agent/app.py
Python
async def aclose(self) -> None:
    """Drain active work and close only resources created by this Agent."""
    if self._lifecycle_state == "stopped":
        return
    deadline = self._begin_shutdown()
    if self._scheduled_runner is not None:
        drained = await self._scheduled_runner.aclose(deadline=deadline)
        if not drained:
            logger.error("scheduled work did not stop before the shutdown deadline; leaving resources open")
            return
    drained = True
    if self._owns_engine and hasattr(self.engine, "aclose"):
        drained = await self.engine.aclose(deadline=deadline)
    if not drained:
        logger.error("agent shutdown timed out; leaving resources open while work is still running")
        return
    resources_closed = await self._close_owned_resources(deadline)
    if not resources_closed:
        logger.error("agent shutdown did not close every owned resource before its deadline")
        return
    self._lifecycle_state = "stopped"

run

Python
run(*, backend: Literal['ws', 'http'] = 'ws') -> None

启动 agent。backend="ws" 运行飞书长连接,backend="http" 运行 HTTP webhook 服务。

源代码位于: feishu/agent/app.py
Python
def run(self, *, backend: Literal["ws", "http"] = "ws") -> None:
    r"""启动 agent。`backend="ws"` 运行飞书长连接,`backend="http"` 运行 HTTP webhook 服务。"""
    if backend == "ws":
        asyncio.run(self.run_ws())
        return
    if backend == "http":
        self.run_http()
        return
    raise ValueError(f"unknown agent run backend: {backend!r}")

run_ws async

Python
run_ws() -> None

运行飞书 WebSocket 长连接服务。

源代码位于: feishu/agent/app.py
Python
async def run_ws(self) -> None:
    r"""运行飞书 WebSocket 长连接服务。"""
    if self._durable_callbacks is not None:
        raise ValueError("durable callback intake currently requires the HTTP backend")
    feishu = self._section("feishu")
    app_id = str(feishu.get("app_id") or "")
    app_secret = str(feishu.get("app_secret") or "")
    if not (app_id and app_secret):
        raise RuntimeError("feishu.app_id / feishu.app_secret are required for ws backend")
    if self.signer is not None and self.oauth_redirect_uri:
        logger.warning(
            "ws backend does not serve OAuth callback; run http backend to handle %s", self.oauth_callback_path
        )
    ws = WsClient(
        app_id,
        app_secret,
        self.dispatcher(),
        region=str(feishu.get("region") or "feishu"),
        card_ack_timeout=self._card_ack_timeout_seconds(),
        background_dispatch_drain_timeout=float(self._get("runtime.shutdown_timeout_seconds", 30.0)),
        shutdown_deadline=lambda: self._shutdown_deadline,
        on_connection_state=self._on_ws_connection_state,
    )
    await self.start()
    self._lifecycle_state = "starting"
    loop = asyncio.get_running_loop()
    stop_task: asyncio.Task[Any] | None = None

    def stop() -> None:
        nonlocal stop_task
        logger.info("shutdown signal received; closing the ws connection gracefully")
        self._begin_shutdown(stop_engine=False)
        if stop_task is None:
            stop_task = asyncio.create_task(ws.aclose())

    installed_signals: list[signal.Signals] = []
    try:
        for sig in (signal.SIGTERM, signal.SIGINT):
            with suppress(NotImplementedError, RuntimeError, ValueError):
                loop.add_signal_handler(sig, stop)
                installed_signals.append(sig)
        await ws.start()
    finally:
        for installed_signal in installed_signals:
            with suppress(NotImplementedError, RuntimeError, ValueError):
                loop.remove_signal_handler(installed_signal)
        try:
            if stop_task is not None:
                await stop_task
        finally:
            await self.aclose()

run_http

Python
run_http() -> None

运行 HTTP webhook 服务。

源代码位于: feishu/agent/app.py
Python
def run_http(self) -> None:
    r"""运行 HTTP webhook 服务。"""
    import uvicorn

    server = self._section("server")
    shutdown_timeout = float(self._get("runtime.shutdown_timeout_seconds", 30.0))
    uvicorn.run(
        self.asgi_app(),
        host=str(server.get("host") or "127.0.0.1"),
        port=int(server.get("port") or 5654),
        log_level=str(server.get("log_level") or "info").lower(),
        lifespan="on",
        timeout_graceful_shutdown=max(1, math.ceil(shutdown_timeout)),
    )

asgi_app

Python
asgi_app() -> Any

返回可交给 ASGI server 的 Starlette app。

源代码位于: feishu/agent/app.py
Python
def asgi_app(self) -> Any:
    r"""返回可交给 ASGI server 的 Starlette app。"""
    from starlette.applications import Starlette
    from starlette.responses import JSONResponse
    from starlette.routing import Route

    if self._asgi_application is not None:
        return self._asgi_application

    server = self._section("server")

    async def health(_request: Any) -> Any:
        return JSONResponse({"ok": True, "service": str(server.get("service") or "feishu-agent")})

    async def ready(_request: Any) -> Any:
        is_ready = self.is_ready
        return JSONResponse(
            {"ready": is_ready, "status": self.status},
            status_code=200 if is_ready else 503,
        )

    @asynccontextmanager
    async def lifespan(_app: Any) -> AsyncIterator[None]:
        await self.start()
        try:
            yield
        finally:
            await self.aclose()

    dispatcher = self.dispatcher()
    event_path = str(server.get("event_path") or "/feishu/event")
    routes = [
        Route(str(server.get("health_path") or "/health"), health, methods=["GET"]),
        Route(str(server.get("ready_path") or "/ready"), ready, methods=["GET"]),
        create_event_route(
            dispatcher,
            path=event_path,
            encrypt_key=self._get("feishu.encrypt_key"),
            verification_token=self._get("feishu.verification_token"),
            **self._event_route_options(),
        ),
    ]
    card_path = server.get("card_path", "/feishu/card")
    if card_path and str(card_path) != event_path:
        routes.append(
            create_event_route(
                dispatcher,
                path=str(card_path),
                encrypt_key=self._get("feishu.encrypt_key"),
                verification_token=self._get("feishu.verification_token"),
                **self._event_route_options(),
            )
        )
    routes.extend(self.extra_routes())
    if self.signer is not None and self.oauth_redirect_uri and self.provider is not None:
        handler = oauth_callback_handler(
            self.provider,
            self.signer,
            self.oauth_redirect_uri,
            on_authorized=self.engine.resume_authorization,
            durable_receiver=self._durable_callbacks,
            track_task=getattr(self.engine, "track_background_task", None),
            success_message=self.oauth_success_message(),
            success_title=self.oauth_success_title(),
        )
        routes.append(Route(self.oauth_callback_path, handler, methods=["GET"]))
    self._asgi_application = Starlette(routes=routes, lifespan=lifespan)
    return self._asgi_application

extra_routes

Python
extra_routes() -> list[Any]

返回产品层追加的 Starlette routes。

源代码位于: feishu/agent/app.py
Python
def extra_routes(self) -> list[Any]:
    r"""返回产品层追加的 Starlette routes。"""
    return []

oauth_success_message

Python
oauth_success_message() -> str

OAuth 成功页正文。

源代码位于: feishu/agent/app.py
Python
def oauth_success_message(self) -> str:
    r"""OAuth 成功页正文。"""
    return str(self._get("oauth.success_message", "授权成功,正在回到飞书继续处理。"))

oauth_success_title

Python
oauth_success_title() -> str

OAuth 成功页标题。

源代码位于: feishu/agent/app.py
Python
def oauth_success_title(self) -> str:
    r"""OAuth 成功页标题。"""
    return str(self._get("oauth.success_title", "授权完成"))

dispatcher

Python
dispatcher() -> Any

创建并返回绑定了当前 engine 的事件 dispatcher。

源代码位于: feishu/agent/app.py
Python
def dispatcher(self) -> Any:
    r"""创建并返回绑定了当前 engine 的事件 dispatcher。"""
    return create_agent_dispatcher(self.engine, seen_store=self._seen_store_config())

handle_event async

Python
handle_event(event: Any) -> None

直接处理一条消息事件。

源代码位于: feishu/agent/app.py
Python
async def handle_event(self, event: Any) -> None:
    r"""直接处理一条消息事件。"""
    await self.engine.run(event)

handle_card_action async

Python
handle_card_action(event: Any) -> dict[str, Any]

直接处理一条卡片回调事件。

源代码位于: feishu/agent/app.py
Python
async def handle_card_action(self, event: Any) -> dict[str, Any]:
    r"""直接处理一条卡片回调事件。"""
    return await self.engine.handle_card_action(event)

resume_authorization async

Python
resume_authorization(authorization_id: str, *, user: Mapping[str, Any] | None = None) -> str

在 OAuth 回调保存用户 token 后恢复挂起授权。

源代码位于: feishu/agent/app.py
Python
async def resume_authorization(self, authorization_id: str, *, user: Mapping[str, Any] | None = None) -> str:
    r"""在 OAuth 回调保存用户 token 后恢复挂起授权。"""
    return await self.engine.resume_authorization(authorization_id, user=user)