zero-agent-core 0.2.0__py3-none-any.whl

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 (104) hide show
  1. agent_core/__init__.py +525 -0
  2. agent_core/access/__init__.py +6 -0
  3. agent_core/access/context.py +45 -0
  4. agent_core/access/guard.py +40 -0
  5. agent_core/acp/README.md +236 -0
  6. agent_core/acp/__init__.py +20 -0
  7. agent_core/acp/server.py +351 -0
  8. agent_core/acp/types.py +86 -0
  9. agent_core/callbacks/__init__.py +17 -0
  10. agent_core/callbacks/manager.py +105 -0
  11. agent_core/checkpoint/__init__.py +19 -0
  12. agent_core/checkpoint/naming.py +93 -0
  13. agent_core/checkpoint/store.py +186 -0
  14. agent_core/checkpoint/travel.py +448 -0
  15. agent_core/compaction/__init__.py +57 -0
  16. agent_core/compaction/middleware.py +428 -0
  17. agent_core/compaction/prompts.py +32 -0
  18. agent_core/compaction/pruner.py +121 -0
  19. agent_core/compaction/region.py +145 -0
  20. agent_core/compaction/spill.py +81 -0
  21. agent_core/compaction/spill_tool.py +42 -0
  22. agent_core/compaction/summarizer.py +95 -0
  23. agent_core/compaction/token_limit.py +74 -0
  24. agent_core/compaction/types.py +93 -0
  25. agent_core/docs.py +15 -0
  26. agent_core/documents/__init__.py +23 -0
  27. agent_core/documents/loaders.py +79 -0
  28. agent_core/documents/splitters.py +94 -0
  29. agent_core/documents/types.py +197 -0
  30. agent_core/errors.py +81 -0
  31. agent_core/guardrails/__init__.py +19 -0
  32. agent_core/guardrails/core.py +186 -0
  33. agent_core/hitl/__init__.py +15 -0
  34. agent_core/hitl/core.py +517 -0
  35. agent_core/mcp/__init__.py +14 -0
  36. agent_core/mcp/client.py +212 -0
  37. agent_core/mcp/errors.py +26 -0
  38. agent_core/middleware/__init__.py +26 -0
  39. agent_core/middleware/base.py +283 -0
  40. agent_core/model/__init__.py +73 -0
  41. agent_core/model/catalog.py +73 -0
  42. agent_core/model/core.py +179 -0
  43. agent_core/model/governance.py +317 -0
  44. agent_core/model/providers/__init__.py +43 -0
  45. agent_core/model/providers/anthropic.py +294 -0
  46. agent_core/model/providers/common.py +28 -0
  47. agent_core/model/providers/factory.py +107 -0
  48. agent_core/model/providers/gemini.py +273 -0
  49. agent_core/model/providers/ollama.py +80 -0
  50. agent_core/model/providers/openai_compatible.py +526 -0
  51. agent_core/model/structured.py +200 -0
  52. agent_core/observability/__init__.py +21 -0
  53. agent_core/observability/core.py +311 -0
  54. agent_core/ports/__init__.py +31 -0
  55. agent_core/ports/memory.py +130 -0
  56. agent_core/ports/model_selection.py +64 -0
  57. agent_core/ports/storage.py +114 -0
  58. agent_core/prompts/__init__.py +19 -0
  59. agent_core/prompts/registry.py +236 -0
  60. agent_core/prompts/templates.py +166 -0
  61. agent_core/protocol/__init__.py +31 -0
  62. agent_core/protocol/capabilities.py +49 -0
  63. agent_core/protocol/messages.py +100 -0
  64. agent_core/protocol/runtime.py +293 -0
  65. agent_core/py.typed +1 -0
  66. agent_core/retrieval/__init__.py +40 -0
  67. agent_core/retrieval/_common.py +121 -0
  68. agent_core/retrieval/chroma.py +269 -0
  69. agent_core/retrieval/core.py +63 -0
  70. agent_core/retrieval/factory.py +72 -0
  71. agent_core/retrieval/memory.py +232 -0
  72. agent_core/retrieval/pgvector.py +239 -0
  73. agent_core/retrieval/types.py +95 -0
  74. agent_core/runtime/__init__.py +28 -0
  75. agent_core/runtime/compat.py +98 -0
  76. agent_core/runtime/react.py +888 -0
  77. agent_core/runtime/service.py +557 -0
  78. agent_core/runtime/store.py +55 -0
  79. agent_core/serialization/__init__.py +21 -0
  80. agent_core/serialization/registry.py +318 -0
  81. agent_core/skills/__init__.py +24 -0
  82. agent_core/skills/errors.py +27 -0
  83. agent_core/skills/loader.py +258 -0
  84. agent_core/skills/registry.py +205 -0
  85. agent_core/skills/types.py +56 -0
  86. agent_core/storage/__init__.py +107 -0
  87. agent_core/storage/_sqlite_utils.py +92 -0
  88. agent_core/storage/context.py +382 -0
  89. agent_core/storage/lease.py +435 -0
  90. agent_core/storage/memory.py +604 -0
  91. agent_core/storage/model_selection.py +360 -0
  92. agent_core/storage/runtime.py +899 -0
  93. agent_core/storage/session.py +904 -0
  94. agent_core/storage/workflow.py +411 -0
  95. agent_core/tools/__init__.py +5 -0
  96. agent_core/tools/executor.py +306 -0
  97. agent_core/workflow/__init__.py +25 -0
  98. agent_core/workflow/durable.py +175 -0
  99. agent_core/workflow/state_machine.py +427 -0
  100. zero_agent_core-0.2.0.dist-info/METADATA +237 -0
  101. zero_agent_core-0.2.0.dist-info/RECORD +104 -0
  102. zero_agent_core-0.2.0.dist-info/WHEEL +4 -0
  103. zero_agent_core-0.2.0.dist-info/entry_points.txt +3 -0
  104. zero_agent_core-0.2.0.dist-info/licenses/LICENSE +201 -0
agent_core/__init__.py ADDED
@@ -0,0 +1,525 @@
1
+ """零外部平台绑定的 Python Agent 运行时内核。"""
2
+
3
+ from agent_core.access import AccessContext
4
+ from agent_core.acp import (
5
+ AcpBackend,
6
+ AcpProtocolError,
7
+ AcpSession,
8
+ AcpSessionNotFoundError,
9
+ AcpStdioServer,
10
+ AcpUpdate,
11
+ run_acp_stdio,
12
+ )
13
+ from agent_core.callbacks import (
14
+ BaseCallbackHandler,
15
+ CallableCallbackHandler,
16
+ CallbackFailure,
17
+ CallbackHandler,
18
+ CallbackManager,
19
+ )
20
+ from agent_core.checkpoint import (
21
+ Checkpointer,
22
+ CheckpointVersion,
23
+ FileCheckpointer,
24
+ MemoryCheckpointer,
25
+ TimeTravelCheckpointer,
26
+ )
27
+ from agent_core.compaction import (
28
+ DEFAULT_COMPACTION_INSTRUCTION,
29
+ DEFAULT_SUMMARY_SECTIONS,
30
+ CompactionConfig,
31
+ CompactionError,
32
+ CompactionMiddleware,
33
+ CompactionResult,
34
+ PruneConfig,
35
+ SpillStore,
36
+ build_spill_tool,
37
+ )
38
+ from agent_core.documents import (
39
+ Blob,
40
+ BlobParser,
41
+ Document,
42
+ DocumentChunk,
43
+ DocumentLoader,
44
+ DocumentLocator,
45
+ RecursiveCharacterTextSplitter,
46
+ TextBlobParser,
47
+ TextLoader,
48
+ TextSplitter,
49
+ )
50
+ from agent_core.errors import (
51
+ AgentError,
52
+ CheckpointError,
53
+ ConfigurationError,
54
+ DocumentError,
55
+ DocumentParsingError,
56
+ DocumentServiceError,
57
+ MemoryConflictError,
58
+ MiddlewareError,
59
+ ModelInvocationError,
60
+ ModelOutputValidationError,
61
+ ModelRateLimitError,
62
+ ModelTimeoutError,
63
+ ModelUnavailableError,
64
+ SerializationError,
65
+ StateMachineError,
66
+ ToolExecutionError,
67
+ UnknownSerializedTypeError,
68
+ UnsupportedSchemaVersionError,
69
+ )
70
+ from agent_core.guardrails import (
71
+ BlockedKeywordsGuard,
72
+ Guard,
73
+ GuardrailsMiddleware,
74
+ LengthGuard,
75
+ OutputFormatGuard,
76
+ PIIRedactionGuard,
77
+ )
78
+ from agent_core.hitl import (
79
+ ApprovalQueue,
80
+ ApprovalRequest,
81
+ ApprovalStatus,
82
+ HumanInTheLoopMiddleware,
83
+ )
84
+ from agent_core.mcp import (
85
+ JsonObject,
86
+ McpConnectionError,
87
+ McpError,
88
+ McpTimeoutError,
89
+ McpToolCaller,
90
+ McpToolClient,
91
+ McpToolError,
92
+ )
93
+ from agent_core.middleware import (
94
+ LoggingMiddleware,
95
+ Middleware,
96
+ MiddlewareAction,
97
+ MiddlewareContext,
98
+ MiddlewareManager,
99
+ MiddlewareResult,
100
+ RetryMiddleware,
101
+ TokenLimitMiddleware,
102
+ )
103
+ from agent_core.model import (
104
+ MODEL_PROVIDER_REGISTRY,
105
+ AnthropicProvider,
106
+ ContextUsage,
107
+ GeminiProvider,
108
+ GovernedModelAdapter,
109
+ ModelAdapter,
110
+ ModelExecutionPolicy,
111
+ ModelOption,
112
+ ModelProviderFactory,
113
+ ModelProviderRegistry,
114
+ OllamaProvider,
115
+ OpenAIProvider,
116
+ SlidingWindowRateLimiter,
117
+ StreamChunk,
118
+ StructuredOutputResult,
119
+ StructuredOutputSpec,
120
+ build_tool_definition,
121
+ catalog_payload,
122
+ chat_structured,
123
+ create_llm_provider,
124
+ create_model_provider,
125
+ default_model_catalog,
126
+ default_model_provider_registry,
127
+ known_context_window,
128
+ model_execution_scope,
129
+ parse_structured_output,
130
+ register_model_provider,
131
+ validate_json_schema,
132
+ )
133
+ from agent_core.observability import (
134
+ AgentStats,
135
+ CallRecord,
136
+ ObservabilityMiddleware,
137
+ ThreadStats,
138
+ ToolRecord,
139
+ agent_stats,
140
+ setup_tracing,
141
+ )
142
+ from agent_core.ports import (
143
+ ApprovalStore,
144
+ ContextStore,
145
+ EventSink,
146
+ MemoryRecord,
147
+ MemorySearchResult,
148
+ MemoryStore,
149
+ ModelSelection,
150
+ ModelSelectionScope,
151
+ ModelSelectionStore,
152
+ RunStore,
153
+ SessionStore,
154
+ WorkflowStore,
155
+ )
156
+ from agent_core.prompts import (
157
+ ChatPromptTemplate,
158
+ MessagesPlaceholder,
159
+ MessageTemplate,
160
+ PromptEntry,
161
+ PromptRegistry,
162
+ PromptTemplate,
163
+ PromptVersion,
164
+ )
165
+ from agent_core.protocol import (
166
+ AgentCapabilities,
167
+ ApprovalRecord,
168
+ Message,
169
+ RunContext,
170
+ RunEvent,
171
+ RunStatus,
172
+ ToolResult,
173
+ assistant_message,
174
+ system_message,
175
+ tool_message,
176
+ user_message,
177
+ )
178
+ from agent_core.retrieval import (
179
+ ChromaVectorStore,
180
+ EmbeddingRetriever,
181
+ Embeddings,
182
+ InMemoryVectorStore,
183
+ KeywordRetriever,
184
+ PgVectorStore,
185
+ Reranker,
186
+ RetrievalQuery,
187
+ RetrievalResult,
188
+ Retriever,
189
+ SearchType,
190
+ VectorQuery,
191
+ VectorRecord,
192
+ VectorSearchResult,
193
+ VectorStore,
194
+ VectorStoreBackend,
195
+ create_vector_store,
196
+ )
197
+ from agent_core.runtime import (
198
+ AgentRuntime,
199
+ MemoryEventSink,
200
+ MemoryRunStore,
201
+ ReActAgent,
202
+ RunExecutor,
203
+ RunRecord,
204
+ RuntimeRun,
205
+ ThreadRecord,
206
+ content_text,
207
+ extract_prompt,
208
+ message_json,
209
+ now_iso,
210
+ )
211
+ from agent_core.serialization import (
212
+ SerializedEnvelope,
213
+ SerializerRegistry,
214
+ default_serializer_registry,
215
+ dumpd,
216
+ dumps,
217
+ load,
218
+ loads,
219
+ )
220
+ from agent_core.skills import (
221
+ SkillActivation,
222
+ SkillBindingError,
223
+ SkillError,
224
+ SkillLoader,
225
+ SkillLoadError,
226
+ SkillRegistrationError,
227
+ SkillRegistry,
228
+ SkillSpec,
229
+ SkillToolKind,
230
+ SkillToolSpec,
231
+ )
232
+ from agent_core.storage import (
233
+ BaseSessionStore,
234
+ InMemoryMemoryStore,
235
+ MemoryContextStore,
236
+ MemoryModelSelectionStore,
237
+ MemoryRunLeaseStore,
238
+ MemoryRuntimeStore,
239
+ MemorySessionStore,
240
+ MemoryWorkflowExecutionStore,
241
+ PostgresContextStore,
242
+ PostgresMemoryStore,
243
+ PostgresModelSelectionStore,
244
+ PostgresRunLeaseStore,
245
+ PostgresRuntimeStore,
246
+ PostgresSessionStore,
247
+ PostgresWorkflowExecutionStore,
248
+ RunLease,
249
+ RunLeaseStore,
250
+ RuntimeConcurrencyError,
251
+ RuntimeStore,
252
+ SessionManager,
253
+ SqliteContextStore,
254
+ SqliteMemoryStore,
255
+ SqliteModelSelectionStore,
256
+ SqliteRunLeaseStore,
257
+ SqliteRuntimeStore,
258
+ SqliteSessionStore,
259
+ SqliteWorkflowExecutionStore,
260
+ WorkflowConcurrencyError,
261
+ WorkflowExecution,
262
+ WorkflowExecutionStore,
263
+ create_context_store,
264
+ create_memory_store,
265
+ create_model_selection_store,
266
+ create_run_lease_store,
267
+ create_runtime_store,
268
+ create_session_store,
269
+ create_workflow_execution_store,
270
+ )
271
+ from agent_core.tools import ToolExecutor, ToolRegistry, ToolSpec
272
+ from agent_core.workflow import (
273
+ END,
274
+ START,
275
+ DurableWorkflowRunner,
276
+ NodeExecutionContext,
277
+ NodeExecutionPolicy,
278
+ StateMachine,
279
+ StateMachineBuilder,
280
+ WorkflowPause,
281
+ current_node_execution,
282
+ )
283
+
284
+ __all__ = [
285
+ "DEFAULT_COMPACTION_INSTRUCTION",
286
+ "DEFAULT_SUMMARY_SECTIONS",
287
+ "END",
288
+ "MODEL_PROVIDER_REGISTRY",
289
+ "START",
290
+ "AccessContext",
291
+ "AcpBackend",
292
+ "AcpProtocolError",
293
+ "AcpSession",
294
+ "AcpSessionNotFoundError",
295
+ "AcpStdioServer",
296
+ "AcpUpdate",
297
+ "AgentCapabilities",
298
+ "AgentError",
299
+ "AgentRuntime",
300
+ "AgentStats",
301
+ "AnthropicProvider",
302
+ "ApprovalQueue",
303
+ "ApprovalRecord",
304
+ "ApprovalRequest",
305
+ "ApprovalStatus",
306
+ "ApprovalStore",
307
+ "BaseCallbackHandler",
308
+ "BaseSessionStore",
309
+ "Blob",
310
+ "BlobParser",
311
+ "BlockedKeywordsGuard",
312
+ "CallRecord",
313
+ "CallableCallbackHandler",
314
+ "CallbackFailure",
315
+ "CallbackHandler",
316
+ "CallbackManager",
317
+ "ChatPromptTemplate",
318
+ "CheckpointError",
319
+ "CheckpointVersion",
320
+ "Checkpointer",
321
+ "ChromaVectorStore",
322
+ "CompactionConfig",
323
+ "CompactionError",
324
+ "CompactionMiddleware",
325
+ "CompactionResult",
326
+ "ConfigurationError",
327
+ "ContextStore",
328
+ "ContextUsage",
329
+ "Document",
330
+ "DocumentChunk",
331
+ "DocumentError",
332
+ "DocumentLoader",
333
+ "DocumentLocator",
334
+ "DocumentParsingError",
335
+ "DocumentServiceError",
336
+ "DurableWorkflowRunner",
337
+ "EmbeddingRetriever",
338
+ "Embeddings",
339
+ "EventSink",
340
+ "FileCheckpointer",
341
+ "GeminiProvider",
342
+ "GovernedModelAdapter",
343
+ "Guard",
344
+ "GuardrailsMiddleware",
345
+ "HumanInTheLoopMiddleware",
346
+ "InMemoryMemoryStore",
347
+ "InMemoryVectorStore",
348
+ "JsonObject",
349
+ "KeywordRetriever",
350
+ "LengthGuard",
351
+ "LoggingMiddleware",
352
+ "McpConnectionError",
353
+ "McpError",
354
+ "McpTimeoutError",
355
+ "McpToolCaller",
356
+ "McpToolClient",
357
+ "McpToolError",
358
+ "MemoryCheckpointer",
359
+ "MemoryConflictError",
360
+ "MemoryContextStore",
361
+ "MemoryEventSink",
362
+ "MemoryModelSelectionStore",
363
+ "MemoryRecord",
364
+ "MemoryRunLeaseStore",
365
+ "MemoryRunStore",
366
+ "MemoryRuntimeStore",
367
+ "MemorySearchResult",
368
+ "MemorySessionStore",
369
+ "MemoryStore",
370
+ "MemoryWorkflowExecutionStore",
371
+ "Message",
372
+ "MessageTemplate",
373
+ "MessagesPlaceholder",
374
+ "Middleware",
375
+ "MiddlewareAction",
376
+ "MiddlewareContext",
377
+ "MiddlewareError",
378
+ "MiddlewareManager",
379
+ "MiddlewareResult",
380
+ "ModelAdapter",
381
+ "ModelExecutionPolicy",
382
+ "ModelInvocationError",
383
+ "ModelOption",
384
+ "ModelOutputValidationError",
385
+ "ModelProviderFactory",
386
+ "ModelProviderRegistry",
387
+ "ModelRateLimitError",
388
+ "ModelSelection",
389
+ "ModelSelectionScope",
390
+ "ModelSelectionStore",
391
+ "ModelTimeoutError",
392
+ "ModelUnavailableError",
393
+ "NodeExecutionContext",
394
+ "NodeExecutionPolicy",
395
+ "ObservabilityMiddleware",
396
+ "OllamaProvider",
397
+ "OpenAIProvider",
398
+ "OutputFormatGuard",
399
+ "PIIRedactionGuard",
400
+ "PgVectorStore",
401
+ "PostgresContextStore",
402
+ "PostgresMemoryStore",
403
+ "PostgresModelSelectionStore",
404
+ "PostgresRunLeaseStore",
405
+ "PostgresRuntimeStore",
406
+ "PostgresSessionStore",
407
+ "PostgresWorkflowExecutionStore",
408
+ "PromptEntry",
409
+ "PromptRegistry",
410
+ "PromptTemplate",
411
+ "PromptVersion",
412
+ "PruneConfig",
413
+ "ReActAgent",
414
+ "RecursiveCharacterTextSplitter",
415
+ "Reranker",
416
+ "RetrievalQuery",
417
+ "RetrievalResult",
418
+ "Retriever",
419
+ "RetryMiddleware",
420
+ "RunContext",
421
+ "RunEvent",
422
+ "RunExecutor",
423
+ "RunLease",
424
+ "RunLeaseStore",
425
+ "RunRecord",
426
+ "RunStatus",
427
+ "RunStore",
428
+ "RuntimeConcurrencyError",
429
+ "RuntimeRun",
430
+ "RuntimeStore",
431
+ "SearchType",
432
+ "SerializationError",
433
+ "SerializedEnvelope",
434
+ "SerializerRegistry",
435
+ "SessionManager",
436
+ "SessionStore",
437
+ "SkillActivation",
438
+ "SkillBindingError",
439
+ "SkillError",
440
+ "SkillLoadError",
441
+ "SkillLoader",
442
+ "SkillRegistrationError",
443
+ "SkillRegistry",
444
+ "SkillSpec",
445
+ "SkillToolKind",
446
+ "SkillToolSpec",
447
+ "SlidingWindowRateLimiter",
448
+ "SpillStore",
449
+ "SqliteContextStore",
450
+ "SqliteMemoryStore",
451
+ "SqliteModelSelectionStore",
452
+ "SqliteRunLeaseStore",
453
+ "SqliteRuntimeStore",
454
+ "SqliteSessionStore",
455
+ "SqliteWorkflowExecutionStore",
456
+ "StateMachine",
457
+ "StateMachineBuilder",
458
+ "StateMachineError",
459
+ "StreamChunk",
460
+ "StructuredOutputResult",
461
+ "StructuredOutputSpec",
462
+ "TextBlobParser",
463
+ "TextLoader",
464
+ "TextSplitter",
465
+ "ThreadRecord",
466
+ "ThreadStats",
467
+ "TimeTravelCheckpointer",
468
+ "TokenLimitMiddleware",
469
+ "ToolExecutionError",
470
+ "ToolExecutor",
471
+ "ToolRecord",
472
+ "ToolRegistry",
473
+ "ToolResult",
474
+ "ToolSpec",
475
+ "UnknownSerializedTypeError",
476
+ "UnsupportedSchemaVersionError",
477
+ "VectorQuery",
478
+ "VectorRecord",
479
+ "VectorSearchResult",
480
+ "VectorStore",
481
+ "VectorStoreBackend",
482
+ "WorkflowConcurrencyError",
483
+ "WorkflowExecution",
484
+ "WorkflowExecutionStore",
485
+ "WorkflowPause",
486
+ "WorkflowStore",
487
+ "agent_stats",
488
+ "assistant_message",
489
+ "build_spill_tool",
490
+ "build_tool_definition",
491
+ "catalog_payload",
492
+ "chat_structured",
493
+ "content_text",
494
+ "create_context_store",
495
+ "create_llm_provider",
496
+ "create_memory_store",
497
+ "create_model_provider",
498
+ "create_model_selection_store",
499
+ "create_run_lease_store",
500
+ "create_runtime_store",
501
+ "create_session_store",
502
+ "create_vector_store",
503
+ "create_workflow_execution_store",
504
+ "current_node_execution",
505
+ "default_model_catalog",
506
+ "default_model_provider_registry",
507
+ "default_serializer_registry",
508
+ "dumpd",
509
+ "dumps",
510
+ "extract_prompt",
511
+ "known_context_window",
512
+ "load",
513
+ "loads",
514
+ "message_json",
515
+ "model_execution_scope",
516
+ "now_iso",
517
+ "parse_structured_output",
518
+ "register_model_provider",
519
+ "run_acp_stdio",
520
+ "setup_tracing",
521
+ "system_message",
522
+ "tool_message",
523
+ "user_message",
524
+ "validate_json_schema",
525
+ ]
@@ -0,0 +1,6 @@
1
+ """访问上下文公共导出。"""
2
+
3
+ from agent_core.access.context import AccessContext
4
+ from agent_core.access.guard import enforce_access
5
+
6
+ __all__ = ["AccessContext", "enforce_access"]
@@ -0,0 +1,45 @@
1
+ """通用访问上下文。
2
+
3
+ Core 只表达一次运行所携带的用户、租户和角色边界,不负责 JWT 校验、HTTP
4
+ Header 解析或具体认证系统。存储适配器可以使用 ``can_access`` 做资源归属检查。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+ from typing import Any
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class AccessContext:
15
+ """一次请求的访问身份。"""
16
+
17
+ user_id: str = "anonymous"
18
+ tenant_id: str = "default"
19
+ roles: frozenset[str] = field(default_factory=lambda: frozenset({"user"}))
20
+
21
+ @property
22
+ def is_admin(self) -> bool:
23
+ """判断是否拥有当前租户范围内的管理权限。"""
24
+ return bool({"admin", "tenant_admin"} & self.roles)
25
+
26
+ def can_access(
27
+ self,
28
+ owner_user_id: str | None,
29
+ owner_tenant_id: str | None,
30
+ ) -> bool:
31
+ """判断当前身份是否可以访问资源。"""
32
+ if self.is_admin and owner_tenant_id in (None, self.tenant_id):
33
+ return True
34
+ return owner_user_id in (None, self.user_id) and owner_tenant_id in (None, self.tenant_id)
35
+
36
+ def to_dict(self) -> dict[str, Any]:
37
+ """转换为可持久化或写入事件的字典。"""
38
+ return {
39
+ "user_id": self.user_id,
40
+ "tenant_id": self.tenant_id,
41
+ "roles": sorted(self.roles),
42
+ }
43
+
44
+
45
+ __all__ = ["AccessContext"]
@@ -0,0 +1,40 @@
1
+ """访问校验的共享实现。
2
+
3
+ ``AgentRuntime`` 与 ``DurableWorkflowRunner`` 都在读取/恢复入口执行同一套
4
+ 三类校验:严格模式必须提供身份、资源必须绑定归属、访问者必须有权。
5
+ 这里把判定顺序与错误文案固定在唯一实现处,避免两份拷贝各自漂移。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from agent_core.access.context import AccessContext
11
+
12
+
13
+ def enforce_access(
14
+ *,
15
+ strict: bool,
16
+ accessor: str,
17
+ subject: str,
18
+ owner_user_id: str | None,
19
+ owner_tenant_id: str | None,
20
+ access: AccessContext | None,
21
+ ) -> None:
22
+ """统一执行三类访问校验,任一不通过时抛出 ``PermissionError``。
23
+
24
+ Args:
25
+ strict: 严格模式开关(``require_access``)。
26
+ accessor: 严格模式错误文案中的执行体名称,如 "AgentRuntime"。
27
+ subject: 资源对象文案,如 "run" / "工作流执行实例"。
28
+ owner_user_id: 资源绑定的用户 ID。
29
+ owner_tenant_id: 资源绑定的租户 ID。
30
+ access: 调用方身份;None 表示匿名访问(严格模式下不允许)。
31
+ """
32
+ if strict and access is None:
33
+ raise PermissionError(f"该 {accessor} 要求提供 AccessContext")
34
+ if strict and (owner_user_id is None or owner_tenant_id is None):
35
+ raise PermissionError(f"该 {subject} 尚未绑定用户和租户")
36
+ if access is not None and not access.can_access(owner_user_id, owner_tenant_id):
37
+ raise PermissionError(f"无权访问该 {subject}")
38
+
39
+
40
+ __all__ = ["enforce_access"]