@mistralai-capabilities/backend-agents 0.0.0-stage → 0.1.88
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.
- package/.templateignore +27 -0
- package/CHANGELOG.md +235 -0
- package/LICENSE +201 -0
- package/capability.json +41 -0
- package/package/py/LICENSE +201 -0
- package/package/py/pyproject.toml +28 -0
- package/package/py/src/mistralai_capabilities/agents/__init__.py +2 -0
- package/package/py/src/mistralai_capabilities/agents/assembly.py +171 -0
- package/package/py/src/mistralai_capabilities/agents/hook_chain.py +184 -0
- package/package/py/src/mistralai_capabilities/agents/tools.py +16 -0
- package/package.json +7 -4
- package/template/apps/agent/project.json +29 -0
- package/template/apps/agent/pyproject.toml +54 -0
- package/template/apps/agent/src/agent/__init__.py +2 -0
- package/template/apps/agent/src/agent/connectors/__init__.py +9 -0
- package/template/apps/agent/src/agent/hooks/__init__.py +13 -0
- package/template/apps/agent/src/agent/instructions/README.md +1 -0
- package/template/apps/agent/src/agent/instructions.md +7 -0
- package/template/apps/agent/src/agent/main.py +30 -0
- package/template/apps/agent/src/agent/mcps/__init__.py +7 -0
- package/template/apps/agent/src/agent/skills/README.md +1 -0
- package/template/apps/agent/src/agent/subagents/__init__.py +7 -0
- package/template/apps/agent/src/agent/tools/__init__.py +7 -0
- package/template/apps/agent/tests/test_agent.py +111 -0
- package/template/deploy/docker/Dockerfile.agent +61 -0
- package/template/main.py +13 -0
- package/template/packages/py/env/src/env/agents.py +48 -0
- package/README.md +0 -3
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Mistral AI
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "mistralai-capabilities-backend-agents"
|
|
3
|
+
version = "0.1.88"
|
|
4
|
+
description = "Agents capability: assembles the app agent from the files its installed capabilities contribute."
|
|
5
|
+
requires-python = ">=3.12,<3.15"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
dependencies = [
|
|
9
|
+
# Exact-pinned in lockstep with the app's agent project (`apps/agent/pyproject.toml`), so the
|
|
10
|
+
# toolkit assembles the agent with the SDK the agent runs on.
|
|
11
|
+
"mistralai-agents==1.1.3",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
[build-system]
|
|
16
|
+
# uv_build 0.8 skips a `license-files` glob that matches nothing, while 0.13 fails on it. An app that
|
|
17
|
+
# vendors this package builds it from source, where the root LICENSE is not staged.
|
|
18
|
+
requires = ["uv_build>=0.8.22,<0.9.0"]
|
|
19
|
+
build-backend = "uv_build"
|
|
20
|
+
|
|
21
|
+
[tool.uv.build-backend]
|
|
22
|
+
# The dist name is fixed by the CLI convention (= `<registry id>-<kind>-<capability id>`);
|
|
23
|
+
# `module-name` keeps the IMPORT path unchanged so no vendored app file has to
|
|
24
|
+
# be edited.
|
|
25
|
+
# `namespace = true` makes this a PEP-420 portion so the sibling capability
|
|
26
|
+
# dists can each ship their own slice of `mistralai_capabilities`.
|
|
27
|
+
module-name = "mistralai_capabilities.agents"
|
|
28
|
+
namespace = true
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Assemble the app's agent from the files its installed capabilities contribute.
|
|
2
|
+
|
|
3
|
+
The agent is one `agents.Agent` whose fields absorb every installed capability's contributions. The
|
|
4
|
+
app passes its agent package in (``assemble(agent_package)``) and spreads the result onto
|
|
5
|
+
`agents.Agent` (``agents.Agent(..., **assemble(...))``). Each contribution is a file in a kind
|
|
6
|
+
directory of that package; a Python contribution is ONE module exposing a single module-level object::
|
|
7
|
+
|
|
8
|
+
tools/<tool>.py tool: agents.PythonTool # an @agents.tool the model calls
|
|
9
|
+
connectors/<key>.py connector: agents.Connector # an agents.connector("<key>") slot
|
|
10
|
+
hooks/<hook>.py hook: agents.Hook # a lifecycle hook
|
|
11
|
+
mcps/<name>.py mcp: agents.RemoteMCP # a remote HTTP MCP server, keyed by the module name
|
|
12
|
+
subagents/<name>.py subagent: agents.Subagent # a child agent the model can spawn
|
|
13
|
+
skills/<name>/SKILL.md # a skill folder, loaded as an agents.LocalSkillBundle
|
|
14
|
+
instructions/<name>.md # a fragment appended to the agent's instructions
|
|
15
|
+
|
|
16
|
+
A kind directory may be absent. A module may set its slot to ``None`` to opt out (e.g. a connector
|
|
17
|
+
gated behind a setting); a ``_``-prefixed module, skill folder or fragment is a private helper and
|
|
18
|
+
skipped, as is a kind directory's ``README.md``. Nothing here names a capability: a file is present only
|
|
19
|
+
when its capability is installed. A module missing its kind's slot, exporting the wrong type, a skill
|
|
20
|
+
folder without ``SKILL.md``, a file in ``skills/`` or a non-``.md`` entry in ``instructions/``, or two
|
|
21
|
+
contributions colliding on a tool/connector/MCP/subagent name fail assembly loudly rather than vanishing from the agent.
|
|
22
|
+
|
|
23
|
+
The fields also carry the sandbox the contributions need: skills are files the model reads, so an agent
|
|
24
|
+
with skills gets a sandbox with file access (Bashkit's, in this process). An agent that needs a shell or
|
|
25
|
+
Python replaces it in the returned fields before spreading them (passing ``environment=`` beside
|
|
26
|
+
``**assemble(...)`` is a duplicate keyword)::
|
|
27
|
+
|
|
28
|
+
fields = assemble(package)
|
|
29
|
+
fields["environment"] = agents.MistralSandbox(access="full")
|
|
30
|
+
agent = agents.Agent(..., **fields)
|
|
31
|
+
|
|
32
|
+
Hooks run each stage in contribution (module name) order, except ``post_agent_turn``: when several
|
|
33
|
+
hooks handle it, they are composed into one chain so each sees the answer with the earlier hooks'
|
|
34
|
+
replacements applied, in their declared ``post_agent_turn_order`` (see ``hook_chain``).
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import importlib
|
|
40
|
+
import pkgutil
|
|
41
|
+
from collections.abc import Callable, Iterator
|
|
42
|
+
from dataclasses import dataclass
|
|
43
|
+
from pathlib import Path
|
|
44
|
+
from types import ModuleType
|
|
45
|
+
from typing import Any, TypedDict
|
|
46
|
+
|
|
47
|
+
import mistralai.agents as agents
|
|
48
|
+
from mistralai_capabilities.agents.hook_chain import compose_post_agent_turn
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class _Kind:
|
|
53
|
+
package: str
|
|
54
|
+
slot: str
|
|
55
|
+
type: type
|
|
56
|
+
# How the error message names the expected type (the SDK classes behind the aliases differ).
|
|
57
|
+
label: str
|
|
58
|
+
# The name a contribution must be unique by, from `(module_name, item)`.
|
|
59
|
+
key: Callable[[str, Any], str]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
_TOOL = _Kind("tools", "tool", agents.PythonTool, "an @agents.tool", lambda _module, tool: tool.name)
|
|
63
|
+
_CONNECTOR = _Kind(
|
|
64
|
+
"connectors", "connector", agents.Connector, "an agents.connector() slot", lambda _module, slot: slot.connector_name
|
|
65
|
+
)
|
|
66
|
+
# Hooks carry no name; the module name is unique by construction, so any number may compose.
|
|
67
|
+
_HOOK = _Kind("hooks", "hook", agents.Hook, "an agents.Hook", lambda module, _hook: module)
|
|
68
|
+
_MCP = _Kind("mcps", "mcp", agents.RemoteMCP, "an agents.RemoteMCP", lambda module, _mcp: module.rsplit(".", 1)[-1])
|
|
69
|
+
_SUBAGENT = _Kind(
|
|
70
|
+
"subagents", "subagent", agents.Subagent, "an agents.Subagent", lambda _module, subagent: subagent.name
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _contributions(root: ModuleType, kind: _Kind) -> Iterator[tuple[str, Any]]:
|
|
75
|
+
"""Yield `(key, item)` for each module in `root`'s `kind` package, validated against `kind`.
|
|
76
|
+
|
|
77
|
+
Modules are walked in name order. A missing kind package contributes nothing.
|
|
78
|
+
"""
|
|
79
|
+
try:
|
|
80
|
+
package = importlib.import_module(f"{root.__name__}.{kind.package}")
|
|
81
|
+
except ModuleNotFoundError as error:
|
|
82
|
+
if error.name != f"{root.__name__}.{kind.package}":
|
|
83
|
+
raise
|
|
84
|
+
return
|
|
85
|
+
seen: set[str] = set()
|
|
86
|
+
for module_info in sorted(pkgutil.iter_modules(package.__path__), key=lambda info: info.name):
|
|
87
|
+
if module_info.name.startswith("_"):
|
|
88
|
+
continue
|
|
89
|
+
module_name = f"{package.__name__}.{module_info.name}"
|
|
90
|
+
module = importlib.import_module(module_name)
|
|
91
|
+
if not hasattr(module, kind.slot):
|
|
92
|
+
raise TypeError(
|
|
93
|
+
f"{module_name} is a {kind.slot} contribution but does not expose `{kind.slot}`; each "
|
|
94
|
+
f"contribution module declares one `{kind.slot}` (or `{kind.slot} = None` to opt out)."
|
|
95
|
+
)
|
|
96
|
+
item = getattr(module, kind.slot)
|
|
97
|
+
if item is None:
|
|
98
|
+
continue
|
|
99
|
+
if not isinstance(item, kind.type):
|
|
100
|
+
raise TypeError(f"{module_name}: `{kind.slot}` must be {kind.label}, got {type(item).__name__}")
|
|
101
|
+
key = kind.key(module_name, item)
|
|
102
|
+
if key in seen:
|
|
103
|
+
raise ValueError(f"{module_name}: duplicate {kind.slot} {key!r}")
|
|
104
|
+
seen.add(key)
|
|
105
|
+
yield key, item
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _public_entries(directory: Path) -> list[Path]:
|
|
109
|
+
"""`directory`'s entries in name order, without private (`_`), hidden (`.`) and README ones."""
|
|
110
|
+
if not directory.is_dir():
|
|
111
|
+
return []
|
|
112
|
+
return sorted(
|
|
113
|
+
entry
|
|
114
|
+
for entry in directory.iterdir()
|
|
115
|
+
if not entry.name.startswith(("_", ".")) and entry.name.lower() != "readme.md"
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _skills(root: Path) -> list[agents.LocalSkillBundle]:
|
|
120
|
+
"""One `LocalSkillBundle` per `skills/<name>/` folder; each must hold a `SKILL.md`."""
|
|
121
|
+
bundles: list[agents.LocalSkillBundle] = []
|
|
122
|
+
for folder in _public_entries(root / "skills"):
|
|
123
|
+
if not folder.is_dir():
|
|
124
|
+
raise ValueError(f"{folder} is in skills/ but is not a skill folder")
|
|
125
|
+
if not (folder / "SKILL.md").is_file():
|
|
126
|
+
raise ValueError(f"{folder} is a skill contribution but has no SKILL.md")
|
|
127
|
+
bundles.append(agents.LocalSkillBundle.from_directory(folder))
|
|
128
|
+
return bundles
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _instructions(root: Path) -> str:
|
|
132
|
+
"""`instructions.md`, then each `instructions/<name>.md` fragment, separated by a blank line."""
|
|
133
|
+
parts = [(root / "instructions.md").read_text(encoding="utf-8").strip()]
|
|
134
|
+
for fragment in _public_entries(root / "instructions"):
|
|
135
|
+
if fragment.suffix != ".md" or not fragment.is_file():
|
|
136
|
+
raise ValueError(f"{fragment} is in instructions/ but is not a .md fragment")
|
|
137
|
+
parts.append(fragment.read_text(encoding="utf-8").strip())
|
|
138
|
+
return "\n\n".join(part for part in parts if part) + "\n"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class AgentFields(TypedDict):
|
|
142
|
+
"""The `agents.Agent` keyword arguments the contributions fill."""
|
|
143
|
+
|
|
144
|
+
instructions: str
|
|
145
|
+
tools: list[agents.PythonTool]
|
|
146
|
+
connectors: list[agents.Connector]
|
|
147
|
+
hooks: list[agents.Hook]
|
|
148
|
+
mcps: dict[str, agents.RemoteMCP]
|
|
149
|
+
subagents: list[agents.Subagent]
|
|
150
|
+
skills: list[agents.LocalSkillBundle]
|
|
151
|
+
environment: agents.Sandbox | None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def assemble(root: ModuleType) -> AgentFields:
|
|
155
|
+
"""Merge every contribution in the agent package `root` into `agents.Agent` keyword arguments.
|
|
156
|
+
|
|
157
|
+
`root` is the agent's package (its `__init__.py` sits beside `instructions.md` and the kind
|
|
158
|
+
directories).
|
|
159
|
+
"""
|
|
160
|
+
directory = Path(next(iter(root.__path__)))
|
|
161
|
+
skills = _skills(directory)
|
|
162
|
+
return AgentFields(
|
|
163
|
+
instructions=_instructions(directory),
|
|
164
|
+
tools=[tool for _, tool in _contributions(root, _TOOL)],
|
|
165
|
+
connectors=[connector for _, connector in _contributions(root, _CONNECTOR)],
|
|
166
|
+
hooks=compose_post_agent_turn([hook for _, hook in _contributions(root, _HOOK)]),
|
|
167
|
+
mcps=dict(_contributions(root, _MCP)),
|
|
168
|
+
subagents=[subagent for _, subagent in _contributions(root, _SUBAGENT)],
|
|
169
|
+
skills=skills,
|
|
170
|
+
environment=agents.BashkitSandbox(access="files") if skills else None,
|
|
171
|
+
)
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Compose the installed hooks' ``post_agent_turn`` handlers into one chain.
|
|
2
|
+
|
|
3
|
+
The SDK's agent runtime runs every ``post_agent_turn`` hook on the ORIGINAL candidate and keeps the
|
|
4
|
+
LAST ``Accept``: a hook that accepts as is erases an earlier hook's ``ReplaceAssistantContent``, and a
|
|
5
|
+
gate judges the model's answer instead of the one the reader would get (the pinned SDK's
|
|
6
|
+
``execute_hook_action``). So when more than one installed hook handles ``post_agent_turn``,
|
|
7
|
+
``compose_post_agent_turn`` routes that stage through ONE hook, a ``PostAgentTurnChain``, which:
|
|
8
|
+
|
|
9
|
+
- runs the hooks in ``post_agent_turn_order`` (lower first; ties keep the contribution, i.e. module
|
|
10
|
+
name, order), each on the candidate with every earlier replacement applied;
|
|
11
|
+
- accepts with the last replacement, or as is when no hook replaced anything.
|
|
12
|
+
|
|
13
|
+
``post_agent_turn`` may only accept (``None`` accepts as is): the SDK refuses a ``Retry`` or
|
|
14
|
+
``Reject`` there, and so does the chain. A hook that retries or rejects the model's answer does it
|
|
15
|
+
in ``post_llm_call``.
|
|
16
|
+
|
|
17
|
+
The chain calls each member as ``post_agent_turn(ctx, result)``, without the SDK's session inputs: a
|
|
18
|
+
member whose ``post_agent_turn`` declares session-input parameters is not supported in the chain.
|
|
19
|
+
|
|
20
|
+
A hook declares its place with the class attribute ``post_agent_turn_order``: answer-shaping hooks
|
|
21
|
+
(citation checks, trims) keep the default ``ANSWER``; a gate that must judge the final answer
|
|
22
|
+
(an output guardrail, for one) declares ``SAFETY`` so it runs last.
|
|
23
|
+
|
|
24
|
+
The SDK routes a stage to a hook when its class overrides that stage's method. Each original hook is
|
|
25
|
+
therefore mounted as a subclass that does not override ``post_agent_turn`` (same name, same state), so
|
|
26
|
+
it keeps serving its other stages (``pre_agent_turn``, ``pre_tool_call``, ``post_tool_call``) where it
|
|
27
|
+
always did, and the chain is the stage's only route. The SDK rebuilds a hook from the import path of
|
|
28
|
+
its class and its saved fields; members are hooks, not fields, so the chain carries them on the class.
|
|
29
|
+
The derived classes are created once per hook class (per member list for the chain), when the agent's
|
|
30
|
+
module assembles its fields at import, and published in their module under a plain name (the hook's
|
|
31
|
+
module for a mounted hook, this one for a chain) so that path leads back to them.
|
|
32
|
+
|
|
33
|
+
``post_llm_call`` folds the same way in the SDK, but no installed hook handles it, so there is nothing
|
|
34
|
+
to compose there.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import copy
|
|
40
|
+
import hashlib
|
|
41
|
+
import sys
|
|
42
|
+
from collections.abc import Sequence
|
|
43
|
+
from typing import ClassVar
|
|
44
|
+
|
|
45
|
+
from mistralai.agents import agents
|
|
46
|
+
from mistralai.vibe.harness.core import protocol as core_protocol
|
|
47
|
+
from mistralai.vibe.harness.runtime.content import to_session_content
|
|
48
|
+
|
|
49
|
+
ORDER_ATTRIBUTE = "post_agent_turn_order"
|
|
50
|
+
"""The class attribute a hook declares its ``post_agent_turn`` place with (an ``int``, lower first)."""
|
|
51
|
+
|
|
52
|
+
ANSWER = 0
|
|
53
|
+
"""The default place: hooks that shape the answer (check citations, trim prose) run first."""
|
|
54
|
+
|
|
55
|
+
SAFETY = 100
|
|
56
|
+
"""The last place: gates that must judge the answer the reader will get (an output guardrail)."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def handles_post_agent_turn(hook: agents.Hook) -> bool:
|
|
60
|
+
"""Whether the SDK routes ``post_agent_turn`` to ``hook``: its class overrides the method."""
|
|
61
|
+
return type(hook).post_agent_turn is not agents.Hook.post_agent_turn
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def post_agent_turn_order(hook: agents.Hook) -> int:
|
|
65
|
+
return getattr(type(hook), ORDER_ATTRIBUTE, ANSWER)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class PostAgentTurnChain(agents.Hook):
|
|
69
|
+
"""The single ``post_agent_turn`` route over several hooks (see the module docstring).
|
|
70
|
+
|
|
71
|
+
Never instantiated directly: ``compose_post_agent_turn`` derives one subclass per member list.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
members: ClassVar[tuple[agents.Hook, ...]] = ()
|
|
75
|
+
|
|
76
|
+
async def post_agent_turn(
|
|
77
|
+
self, ctx: agents.HookCallbackContext, result: agents.hook.PostAgentTurn
|
|
78
|
+
) -> agents.hook.PostAgentTurnHookAccept:
|
|
79
|
+
replaced: list[core_protocol.ContentBlock] | None = None
|
|
80
|
+
current = result
|
|
81
|
+
for member in self.members:
|
|
82
|
+
outcome: object = await member.post_agent_turn(ctx, current)
|
|
83
|
+
if outcome is None:
|
|
84
|
+
continue
|
|
85
|
+
if not isinstance(outcome, agents.hook.PostAgentTurnHookAccept):
|
|
86
|
+
# The SDK reports a raising hook as a failed hook call, as it would this hook's own result.
|
|
87
|
+
raise TypeError(f"{type(member).__name__}.post_agent_turn returned {type(outcome).__name__}")
|
|
88
|
+
# The harness's class: `agents.hook.ReplaceAssistantContent` subclasses it, and a hook may return either.
|
|
89
|
+
if isinstance(outcome.acceptance, core_protocol.ReplaceAssistantContent):
|
|
90
|
+
replaced = list(outcome.acceptance.content)
|
|
91
|
+
current = _with_content(current, replaced)
|
|
92
|
+
if replaced is None:
|
|
93
|
+
return agents.hook.PostAgentTurnHookAccept()
|
|
94
|
+
return agents.hook.PostAgentTurnHookAccept(acceptance=agents.hook.ReplaceAssistantContent(content=replaced))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _with_content(
|
|
98
|
+
result: agents.hook.PostAgentTurn, content: list[core_protocol.ContentBlock]
|
|
99
|
+
) -> agents.hook.PostAgentTurn:
|
|
100
|
+
"""``result`` whose answer is ``content``, as the harness would commit it: the replacement is the
|
|
101
|
+
whole message, so it carries no tool calls nor reasoning."""
|
|
102
|
+
return result.model_copy(
|
|
103
|
+
update={
|
|
104
|
+
# `keep_origin`: a block the next member hands back unchanged reaches the model as it came.
|
|
105
|
+
"content": to_session_content(content, keep_origin=True),
|
|
106
|
+
"text": "".join(block.text for block in content if isinstance(block, core_protocol.TextContentBlock)),
|
|
107
|
+
"tool_calls": (),
|
|
108
|
+
"reasoning": "",
|
|
109
|
+
}
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
_STRIPPED: dict[type[agents.Hook], type[agents.Hook]] = {}
|
|
114
|
+
_CHAINS: dict[tuple[type[agents.Hook], ...], type[PostAgentTurnChain]] = {}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _type_key(hook_type: type) -> str:
|
|
118
|
+
return f"{hook_type.__module__}:{hook_type.__qualname__}"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _published[T: type](derived: T) -> T:
|
|
122
|
+
"""``derived``, set in its module under its ``__qualname__`` so the SDK can import it again."""
|
|
123
|
+
setattr(sys.modules[derived.__module__], derived.__qualname__, derived)
|
|
124
|
+
return derived
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _without_post_agent_turn(hook: agents.Hook) -> agents.Hook:
|
|
128
|
+
"""``hook`` mounted without its ``post_agent_turn``: same class name, state and other stages."""
|
|
129
|
+
hook_type = type(hook)
|
|
130
|
+
stripped = _STRIPPED.get(hook_type)
|
|
131
|
+
if stripped is None:
|
|
132
|
+
name = f"{hook_type.__qualname__.replace('.', '_')}__post_agent_turn_chained"
|
|
133
|
+
stripped = _published(
|
|
134
|
+
type(
|
|
135
|
+
hook_type.__name__,
|
|
136
|
+
(hook_type,),
|
|
137
|
+
{
|
|
138
|
+
"post_agent_turn": agents.Hook.post_agent_turn,
|
|
139
|
+
"__module__": hook_type.__module__,
|
|
140
|
+
"__qualname__": name,
|
|
141
|
+
"__doc__": hook_type.__doc__,
|
|
142
|
+
},
|
|
143
|
+
)
|
|
144
|
+
)
|
|
145
|
+
_STRIPPED[hook_type] = stripped
|
|
146
|
+
mounted = copy.copy(hook)
|
|
147
|
+
mounted.__class__ = stripped
|
|
148
|
+
return mounted
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _chain_of(members: Sequence[agents.Hook]) -> PostAgentTurnChain:
|
|
152
|
+
key = tuple(type(member) for member in members)
|
|
153
|
+
chain = _CHAINS.get(key)
|
|
154
|
+
if chain is None:
|
|
155
|
+
# Named by a digest of its members' paths: stable across processes, so a saved chain finds its
|
|
156
|
+
# class again in the agent's worker that assembled the same hooks.
|
|
157
|
+
digest = hashlib.sha256(" ".join(map(_type_key, key)).encode()).hexdigest()[:12]
|
|
158
|
+
chain = _published(
|
|
159
|
+
type(
|
|
160
|
+
PostAgentTurnChain.__name__,
|
|
161
|
+
(PostAgentTurnChain,),
|
|
162
|
+
{
|
|
163
|
+
"members": tuple(members),
|
|
164
|
+
"__module__": __name__,
|
|
165
|
+
"__qualname__": f"{PostAgentTurnChain.__qualname__}_{digest}",
|
|
166
|
+
"__doc__": f"The post_agent_turn chain of {', '.join(map(_type_key, key))}.",
|
|
167
|
+
},
|
|
168
|
+
)
|
|
169
|
+
)
|
|
170
|
+
_CHAINS[key] = chain
|
|
171
|
+
return chain()
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def compose_post_agent_turn(hooks: Sequence[agents.Hook]) -> list[agents.Hook]:
|
|
175
|
+
"""``hooks`` with their ``post_agent_turn`` handlers composed into one ``PostAgentTurnChain``.
|
|
176
|
+
|
|
177
|
+
With at most one such handler there is nothing to fold, and ``hooks`` is returned unchanged.
|
|
178
|
+
"""
|
|
179
|
+
handlers = [hook for hook in hooks if handles_post_agent_turn(hook)]
|
|
180
|
+
if len(handlers) < 2:
|
|
181
|
+
return list(hooks)
|
|
182
|
+
ordered = sorted(handlers, key=post_agent_turn_order) # stable: ties keep contribution order
|
|
183
|
+
mounted = [_without_post_agent_turn(hook) if handles_post_agent_turn(hook) else hook for hook in hooks]
|
|
184
|
+
return [*mounted, _chain_of(ordered)]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""What a hook can tell about the tool a call is to."""
|
|
2
|
+
|
|
3
|
+
from mistralai.agents import agents
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def is_builtin(call: agents.hook.PreToolCall) -> bool:
|
|
7
|
+
"""Whether ``call`` is to one of the sandbox's built-in tools (``file_system.bash``, ...), not to a
|
|
8
|
+
provided tool (an authored tool, or one served through a connector).
|
|
9
|
+
|
|
10
|
+
The view carries no kind, but its ``tool_id`` tells them apart: a provided tool's ID is
|
|
11
|
+
``<group>.<tool_name>``, its group never empty, while a built-in's ID is its own name. Only a
|
|
12
|
+
built-in's ID therefore equals its ``tool_name``. ``test_tools`` pins this against the SDK's own
|
|
13
|
+
view, so an SDK that names tools another way fails there first. A ``PostToolCall`` is a
|
|
14
|
+
``PreToolCall``, so a ``post_tool_call`` hook asks the same.
|
|
15
|
+
"""
|
|
16
|
+
return call.tool_id == call.tool_name
|
package/package.json
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mistralai-capabilities/backend-agents",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.88",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "restricted"
|
|
8
|
+
}
|
|
9
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "../../node_modules/nx/schemas/project-schema.json",
|
|
3
|
+
"name": "agent",
|
|
4
|
+
"projectType": "application",
|
|
5
|
+
"targets": {
|
|
6
|
+
"typecheck": {
|
|
7
|
+
"executor": "nx:run-commands",
|
|
8
|
+
"options": {
|
|
9
|
+
"command": "bash tools/uv.sh run --no-sync ty check --project apps/agent apps/agent/src",
|
|
10
|
+
"cwd": "{workspaceRoot}"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"test": {
|
|
14
|
+
"executor": "nx:run-commands",
|
|
15
|
+
"options": {
|
|
16
|
+
"command": "bash tools/uv.sh run --no-sync pytest apps/agent/tests",
|
|
17
|
+
"cwd": "{workspaceRoot}"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"check": {
|
|
21
|
+
"executor": "nx:run-commands",
|
|
22
|
+
"dependsOn": ["typecheck", "test"],
|
|
23
|
+
"options": {
|
|
24
|
+
"command": "echo \"[check] agent gate passed\"",
|
|
25
|
+
"cwd": "{workspaceRoot}"
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|