magimoire 0.3.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 (277) hide show
  1. magimoire/__init__.py +272 -0
  2. magimoire/acp/__init__.py +1 -0
  3. magimoire/acp/codec.py +22 -0
  4. magimoire/acp/mcp.py +164 -0
  5. magimoire/acp/protocol.py +43 -0
  6. magimoire/acp/server.py +608 -0
  7. magimoire/acp/startup.py +97 -0
  8. magimoire/agent/__init__.py +120 -0
  9. magimoire/agent/agent_loop.py +1002 -0
  10. magimoire/agent/archive_admission.py +38 -0
  11. magimoire/agent/assistant_stream.py +160 -0
  12. magimoire/agent/cancellation.py +235 -0
  13. magimoire/agent/constants.py +7 -0
  14. magimoire/agent/consumed_work.py +58 -0
  15. magimoire/agent/contracts.py +257 -0
  16. magimoire/agent/default_model.py +61 -0
  17. magimoire/agent/dispatch.py +111 -0
  18. magimoire/agent/inbox.py +248 -0
  19. magimoire/agent/model_selection.py +261 -0
  20. magimoire/agent/preset.py +258 -0
  21. magimoire/agent/preset_projection.py +38 -0
  22. magimoire/agent/projection.py +97 -0
  23. magimoire/agent/react_loop.py +1027 -0
  24. magimoire/agent/registry.py +423 -0
  25. magimoire/agent/runtime_context.py +111 -0
  26. magimoire/agent/system_prompt.py +89 -0
  27. magimoire/agent_instructions/__init__.py +8 -0
  28. magimoire/agent_instructions/config.py +122 -0
  29. magimoire/agent_instructions/digest.py +18 -0
  30. magimoire/agent_instructions/files.py +238 -0
  31. magimoire/agent_instructions/render.py +271 -0
  32. magimoire/agent_instructions/service.py +178 -0
  33. magimoire/agent_instructions/state.py +153 -0
  34. magimoire/approval/__init__.py +9 -0
  35. magimoire/approval/guard.py +56 -0
  36. magimoire/approval/service.py +244 -0
  37. magimoire/attachments/__init__.py +1 -0
  38. magimoire/attachments/service.py +143 -0
  39. magimoire/cli.py +887 -0
  40. magimoire/commands/__init__.py +20 -0
  41. magimoire/commands/service.py +385 -0
  42. magimoire/commands/types.py +130 -0
  43. magimoire/compaction/__init__.py +5 -0
  44. magimoire/compaction/image_offload.py +216 -0
  45. magimoire/compaction/pruner.py +250 -0
  46. magimoire/compaction/service.py +98 -0
  47. magimoire/components/__init__.py +12 -0
  48. magimoire/components/discovery.py +35 -0
  49. magimoire/components/layers.py +124 -0
  50. magimoire/components/manifest.py +38 -0
  51. magimoire/components/service.py +228 -0
  52. magimoire/context/__init__.py +5 -0
  53. magimoire/context/service.py +76 -0
  54. magimoire/context/settings.py +173 -0
  55. magimoire/context/user_questions.py +398 -0
  56. magimoire/credentials/__init__.py +35 -0
  57. magimoire/credentials/engine.py +287 -0
  58. magimoire/feedback/__init__.py +18 -0
  59. magimoire/feedback/service.py +108 -0
  60. magimoire/feedback/types.py +70 -0
  61. magimoire/fs/__init__.py +88 -0
  62. magimoire/fs/local.py +978 -0
  63. magimoire/fs/observation_policy.py +161 -0
  64. magimoire/fs/patch.py +422 -0
  65. magimoire/fs/service.py +309 -0
  66. magimoire/fs/types.py +185 -0
  67. magimoire/fs/workspace_path.py +93 -0
  68. magimoire/goal/__init__.py +33 -0
  69. magimoire/goal/command.py +140 -0
  70. magimoire/goal/projection.py +244 -0
  71. magimoire/goal/round_driver.py +506 -0
  72. magimoire/goal/service.py +470 -0
  73. magimoire/goal/tools.py +489 -0
  74. magimoire/goal/types.py +545 -0
  75. magimoire/headless_json.py +250 -0
  76. magimoire/jobs/__init__.py +76 -0
  77. magimoire/jobs/archive_admission.py +63 -0
  78. magimoire/jobs/events.py +112 -0
  79. magimoire/jobs/local.py +756 -0
  80. magimoire/jobs/pump.py +87 -0
  81. magimoire/jobs/ring.py +116 -0
  82. magimoire/jobs/service.py +84 -0
  83. magimoire/jobs/types.py +244 -0
  84. magimoire/llm/__init__.py +585 -0
  85. magimoire/llm/adapter_failure.py +208 -0
  86. magimoire/llm/api_key.py +40 -0
  87. magimoire/llm/assembler.py +184 -0
  88. magimoire/llm/assistant_stream.py +518 -0
  89. magimoire/llm/attribution.py +35 -0
  90. magimoire/llm/brand.py +20 -0
  91. magimoire/llm/call_config.py +88 -0
  92. magimoire/llm/conduit/__init__.py +5 -0
  93. magimoire/llm/conduit/adapter.py +184 -0
  94. magimoire/llm/conduit/catalog.py +404 -0
  95. magimoire/llm/conduit/component.py +211 -0
  96. magimoire/llm/conduit/config.py +203 -0
  97. magimoire/llm/conduit/data/anthropic.json +1 -0
  98. magimoire/llm/conduit/data/google.json +1 -0
  99. magimoire/llm/conduit/data/groq.json +1 -0
  100. magimoire/llm/conduit/data/openai.json +1 -0
  101. magimoire/llm/conduit/data/opencode.json +1 -0
  102. magimoire/llm/conduit/data/openrouter.json +1 -0
  103. magimoire/llm/conduit/data/pollinations.json +35 -0
  104. magimoire/llm/conduit/data/xai.json +1 -0
  105. magimoire/llm/conduit/protocols/__init__.py +31 -0
  106. magimoire/llm/conduit/protocols/anthropic_messages.py +274 -0
  107. magimoire/llm/conduit/protocols/common.py +342 -0
  108. magimoire/llm/conduit/protocols/google_generative_ai.py +271 -0
  109. magimoire/llm/conduit/protocols/openai_completions.py +247 -0
  110. magimoire/llm/conduit/protocols/openai_responses.py +289 -0
  111. magimoire/llm/conduit/provider_data.py +236 -0
  112. magimoire/llm/content.py +474 -0
  113. magimoire/llm/error.py +207 -0
  114. magimoire/llm/listing_cache.py +288 -0
  115. magimoire/llm/listing_config.py +75 -0
  116. magimoire/llm/message.py +146 -0
  117. magimoire/llm/retry.py +519 -0
  118. magimoire/llm/retry_policy.py +195 -0
  119. magimoire/llm/scripted.py +112 -0
  120. magimoire/llm/service.py +1819 -0
  121. magimoire/llm/slug.py +37 -0
  122. magimoire/llm/token_meter.py +1633 -0
  123. magimoire/llm/types.py +346 -0
  124. magimoire/llm/values.py +347 -0
  125. magimoire/mcp/client.py +43 -0
  126. magimoire/permission/__init__.py +27 -0
  127. magimoire/permission/service.py +669 -0
  128. magimoire/plan/__init__.py +8 -0
  129. magimoire/plan/fold.py +72 -0
  130. magimoire/plan/service.py +268 -0
  131. magimoire/plan/tools.py +256 -0
  132. magimoire/plan/types.py +76 -0
  133. magimoire/profiles/__init__.py +5 -0
  134. magimoire/profiles/base.yaml +309 -0
  135. magimoire/profiles/launcher.py +317 -0
  136. magimoire/profiles/merge.py +94 -0
  137. magimoire/profiles/templates/acp/animas.patch.yaml +4 -0
  138. magimoire/profiles/templates/acp/pyproject.toml +7 -0
  139. magimoire/profiles/templates/base/animas.patch.yaml +1 -0
  140. magimoire/profiles/templates/base/pyproject.toml +7 -0
  141. magimoire/profiles/templates/headless/animas.patch.yaml +1 -0
  142. magimoire/profiles/templates/headless/pyproject.toml +7 -0
  143. magimoire/profiles/templates/sdk/animas.patch.yaml +17 -0
  144. magimoire/profiles/templates/sdk/pyproject.toml +7 -0
  145. magimoire/profiles/templates/sdk-minimal/animas.patch.yaml +227 -0
  146. magimoire/profiles/templates/sdk-minimal/pyproject.toml +7 -0
  147. magimoire/profiles/templates/web/animas.patch.yaml +11 -0
  148. magimoire/profiles/templates/web/pyproject.toml +7 -0
  149. magimoire/profiles/translate.py +290 -0
  150. magimoire/ptc/__init__.py +1 -0
  151. magimoire/ptc/protocol.py +39 -0
  152. magimoire/ptc/run_code.py +156 -0
  153. magimoire/ptc/runtime.py +415 -0
  154. magimoire/ptc/worker.js +232 -0
  155. magimoire/ptc/workflow.py +310 -0
  156. magimoire/py.typed +0 -0
  157. magimoire/remote/__init__.py +1 -0
  158. magimoire/remote/controllers.py +1807 -0
  159. magimoire/runtime/__init__.py +1 -0
  160. magimoire/runtime/carrier.py +232 -0
  161. magimoire/sandbox/escalation.py +180 -0
  162. magimoire/sandbox/policy.py +249 -0
  163. magimoire/sandbox/roots.py +67 -0
  164. magimoire/sandbox/service.py +183 -0
  165. magimoire/sandbox/types.py +116 -0
  166. magimoire/schedule/__init__.py +35 -0
  167. magimoire/schedule/engine.py +327 -0
  168. magimoire/scope/__init__.py +64 -0
  169. magimoire/scope/_core.py +458 -0
  170. magimoire/scope/store.py +244 -0
  171. magimoire/sdk/__init__.py +1 -0
  172. magimoire/sdk/client.py +486 -0
  173. magimoire/sdk/launch.py +91 -0
  174. magimoire/sdk/process_events.py +140 -0
  175. magimoire/sdk/protocol.py +483 -0
  176. magimoire/sdk/query_activity.py +183 -0
  177. magimoire/sdk/server.py +1079 -0
  178. magimoire/session/__init__.py +215 -0
  179. magimoire/session/checkpoint_policy.py +135 -0
  180. magimoire/session/events.py +302 -0
  181. magimoire/session/fork.py +34 -0
  182. magimoire/session/format.py +5959 -0
  183. magimoire/session/lists.py +105 -0
  184. magimoire/session/messages.py +86 -0
  185. magimoire/session/pairing.py +66 -0
  186. magimoire/session/persistence.py +296 -0
  187. magimoire/session/persistence_jsonl.py +1903 -0
  188. magimoire/session/projection_cache.py +784 -0
  189. magimoire/session/projection_registry.py +680 -0
  190. magimoire/session/projections.py +799 -0
  191. magimoire/session/repair.py +250 -0
  192. magimoire/session/request_header.py +144 -0
  193. magimoire/session/service.py +585 -0
  194. magimoire/session/store.py +1477 -0
  195. magimoire/session/surface.py +874 -0
  196. magimoire/session/title.py +1031 -0
  197. magimoire/session/title_first_prompt.py +326 -0
  198. magimoire/session/tool_history.py +149 -0
  199. magimoire/session/working_directory.py +260 -0
  200. magimoire/session_query/__init__.py +90 -0
  201. magimoire/session_query/engine.py +678 -0
  202. magimoire/session_query/errors.py +183 -0
  203. magimoire/session_query/extraction.py +142 -0
  204. magimoire/session_query/filters.py +414 -0
  205. magimoire/session_query/service.py +74 -0
  206. magimoire/session_query/tracing.py +250 -0
  207. magimoire/session_query/types.py +432 -0
  208. magimoire/shell/__init__.py +76 -0
  209. magimoire/shell/_subprocess_base.py +552 -0
  210. magimoire/shell/bash_local.py +45 -0
  211. magimoire/shell/bash_sandbox.py +117 -0
  212. magimoire/shell/executor.py +90 -0
  213. magimoire/shell/pwsh_local.py +129 -0
  214. magimoire/shell/render.py +34 -0
  215. magimoire/shell/service.py +165 -0
  216. magimoire/shell/terminal.py +170 -0
  217. magimoire/shell/types.py +160 -0
  218. magimoire/shell_env/__init__.py +37 -0
  219. magimoire/shell_env/service.py +271 -0
  220. magimoire/spill/__init__.py +45 -0
  221. magimoire/spill/local.py +103 -0
  222. magimoire/spill/notice.py +106 -0
  223. magimoire/spill/policy.py +291 -0
  224. magimoire/spill/retention.py +93 -0
  225. magimoire/spill/service.py +125 -0
  226. magimoire/spill/store.py +119 -0
  227. magimoire/subagent/__init__.py +31 -0
  228. magimoire/subagent/manager.py +440 -0
  229. magimoire/subagent/providers.py +103 -0
  230. magimoire/subagent/service.py +526 -0
  231. magimoire/subagent/tools.py +449 -0
  232. magimoire/subagent/types.py +77 -0
  233. magimoire/subprocess/__init__.py +107 -0
  234. magimoire/subprocess/local.py +691 -0
  235. magimoire/subprocess/output.py +188 -0
  236. magimoire/subprocess/retention.py +320 -0
  237. magimoire/subprocess/service.py +100 -0
  238. magimoire/subprocess/types.py +163 -0
  239. magimoire/system_prompt/__init__.py +67 -0
  240. magimoire/system_prompt/service.py +856 -0
  241. magimoire/team/__init__.py +8 -0
  242. magimoire/team/fold.py +235 -0
  243. magimoire/team/service.py +517 -0
  244. magimoire/team/task_graph.py +97 -0
  245. magimoire/team/tools.py +334 -0
  246. magimoire/team/types.py +119 -0
  247. magimoire/telemetry/__init__.py +32 -0
  248. magimoire/telemetry/engine.py +193 -0
  249. magimoire/tools/__init__.py +162 -0
  250. magimoire/tools/bash_tool.py +242 -0
  251. magimoire/tools/contracts.py +357 -0
  252. magimoire/tools/fs.py +689 -0
  253. magimoire/tools/fs_apply_patch.py +768 -0
  254. magimoire/tools/fs_observations.py +274 -0
  255. magimoire/tools/fs_presentation.py +917 -0
  256. magimoire/tools/fs_search.py +302 -0
  257. magimoire/tools/jobs.py +299 -0
  258. magimoire/tools/json_schema.py +511 -0
  259. magimoire/tools/native_executor.py +81 -0
  260. magimoire/tools/path_guard.py +28 -0
  261. magimoire/tools/pipeline.py +1323 -0
  262. magimoire/tools/presentation.py +219 -0
  263. magimoire/tools/pwsh_tool.py +296 -0
  264. magimoire/tools/repeat_guard.py +143 -0
  265. magimoire/tools/schema.py +559 -0
  266. magimoire/tools/service.py +636 -0
  267. magimoire/tools/timeout_guard.py +61 -0
  268. magimoire/tools/todo.py +248 -0
  269. magimoire/web/__init__.py +23 -0
  270. magimoire/web/service.py +476 -0
  271. magimoire/web/tools.py +266 -0
  272. magimoire-0.3.0.dist-info/METADATA +112 -0
  273. magimoire-0.3.0.dist-info/RECORD +277 -0
  274. magimoire-0.3.0.dist-info/WHEEL +4 -0
  275. magimoire-0.3.0.dist-info/entry_points.txt +4 -0
  276. magimoire-0.3.0.dist-info/licenses/LICENSE +21 -0
  277. magimoire-0.3.0.dist-info/licenses/NOTICE +58 -0
magimoire/__init__.py ADDED
@@ -0,0 +1,272 @@
1
+ """Magimoire: Composable Agent Runtime by Magitech."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.3.0"
6
+
7
+ import asyncio
8
+ import os
9
+ from collections.abc import Callable, Sequence
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from animas import Context, FiberState
14
+ from animas.loader import LoaderService
15
+ from animas.profile_yaml import load_yaml
16
+
17
+ from magimoire.agent.agent_loop import AgentLoop, FactoryOwnership
18
+ from magimoire.agent.assistant_stream import AssistantStreamAttempt
19
+ from magimoire.agent.cancellation import AbortController, AbortError, AbortSignal
20
+ from magimoire.agent.constants import DEFAULT_MAX_PARALLEL_TOOL_CALLS
21
+ from magimoire.agent.react_loop import ReactLoopAgent
22
+ from magimoire.agent.registry import AgentRegistry
23
+ from magimoire.agent.runtime_context import RuntimeContextProjection
24
+ from magimoire.approval.service import (
25
+ ApprovalRequest,
26
+ ApprovalService,
27
+ calculate_argument_digest,
28
+ )
29
+ from magimoire.compaction.service import CompactionService
30
+ from magimoire.components.layers import ConfigLayer, LayerResolutionService
31
+ from magimoire.components.manifest import ComponentManifest
32
+ from magimoire.components.service import ComponentService
33
+ from magimoire.context.service import ContextService
34
+ from magimoire.fs.local import LocalFileSystem
35
+ from magimoire.fs.service import FileSystem
36
+ from magimoire.jobs.local import LocalJobRegistry
37
+ from magimoire.jobs.service import JobRegistry
38
+ from magimoire.llm.service import (
39
+ LLMProvider,
40
+ LLMService,
41
+ MockLLMProvider,
42
+ NoProviderError,
43
+ )
44
+ from magimoire.llm.slug import parse_model_slug
45
+ from magimoire.llm.types import ModelChunk, ModelResponse, UsageData
46
+ from magimoire.profiles.launcher import is_standalone
47
+ from magimoire.profiles.merge import merge_bundle_rows, profile_rows_from_source
48
+ from magimoire.session.events import (
49
+ EventType,
50
+ SessionEvent,
51
+ ToolCallData,
52
+ ToolResultData,
53
+ )
54
+ from magimoire.session.pairing import is_tool_pairing_balanced
55
+ from magimoire.session.service import SessionService
56
+ from magimoire.session.store import Session, derive_messages
57
+ from magimoire.session.working_directory import WorkingDirectoryService
58
+ from magimoire.shell.bash_local import LocalBashExecutor
59
+ from magimoire.shell.executor import ShellExecutor
60
+ from magimoire.shell.pwsh_local import LocalPwshExecutor
61
+ from magimoire.shell.service import LocalShellService, ShellResult
62
+ from magimoire.shell_env.service import ShellEnvRegistry
63
+ from magimoire.subprocess.local import LocalSubprocessRuntime
64
+ from magimoire.subprocess.service import SubprocessRuntime
65
+ from magimoire.system_prompt.service import SystemPromptService
66
+ from magimoire.tools.native_executor import NativeToolExecutor
67
+ from magimoire.tools.pipeline import ToolExecutionPipeline
68
+ from magimoire.tools.schema import define_tool
69
+ from magimoire.tools.service import ToolRuntime, ToolService, ToolsService
70
+
71
+ _BASE_BUNDLE_PATH = Path(__file__).resolve().parent / "profiles" / "base.yaml"
72
+
73
+
74
+ def _check_bundle_entries(loader: LoaderService) -> None:
75
+ """Fail loud if any enabled bundle row did not mount.
76
+
77
+ A row that fails to mount never raises through load or flush: the
78
+ failure is visible only on the entry fiber's state, so it is
79
+ checked here. Zero entries (e.g. auditing before flushing a running
80
+ event loop) also fails loud instead of passing vacuously. Disabled
81
+ rows are intentionally unmounted and skipped.
82
+ """
83
+ entries = list(loader.entries())
84
+ if not entries:
85
+ raise RuntimeError("default bundle failed to mount: no bundle entries loaded")
86
+ problems: list[str] = []
87
+ for entry in entries:
88
+ if entry.disabled:
89
+ continue
90
+ fiber = entry.fiber
91
+ if fiber is None:
92
+ problems.append(f"{entry.id}: no fiber mounted")
93
+ elif fiber.state is not FiberState.ACTIVE:
94
+ detail = f": {fiber.error}" if fiber.error is not None else ""
95
+ problems.append(f"{entry.id}: fiber {fiber.state.value}{detail}")
96
+ if problems:
97
+ raise RuntimeError("default bundle failed to mount: " + "; ".join(problems))
98
+
99
+
100
+ def check_bundle_entries(ctx: Context) -> None:
101
+ """Fail loud if any enabled default-bundle row did not activate.
102
+
103
+ Call after the bundle rows have settled -- after ``ctx.flush()`` when
104
+ a loop is running, as the CLI does after its own flush. The loader is
105
+ reachable from the context: loading the bundle registers it under
106
+ ``loader``, and its entries carry the per-row fiber states.
107
+ """
108
+ loader = ctx.get("loader", None, strict=False)
109
+ if not isinstance(loader, LoaderService):
110
+ raise TypeError("default bundle failed to mount: no loader on context")
111
+ _check_bundle_entries(loader)
112
+
113
+
114
+ def _settle_default_bundle(ctx: Context, loader: LoaderService) -> None:
115
+ """Settle the default bundle rows and fail loud on any row that did not mount.
116
+
117
+ With no running event loop the rows settle here, so the returned
118
+ context has every bundle slot and the fiber check runs. With a running
119
+ loop the rows settle on the caller's flush, following the loader's
120
+ established load/flush contract; the caller then runs
121
+ :func:`check_bundle_entries` after that flush.
122
+ """
123
+ try:
124
+ asyncio.get_running_loop()
125
+ except RuntimeError:
126
+ asyncio.run(ctx.flush())
127
+ _check_bundle_entries(loader)
128
+
129
+
130
+ def create_harness(
131
+ storage_dir: Path | str | None = None,
132
+ *,
133
+ profile: Path | str | list[Any] | dict[str, Any] | None = None,
134
+ prepare: Callable[[Context], None] | None = None,
135
+ patches: Sequence[Path | str | list[Any] | dict[str, Any]] | None = None,
136
+ ) -> Context:
137
+ """Factory creating a standard Context populated with core Harness services.
138
+
139
+ Every service mounts from the default bundle file: the six leaf
140
+ services (system prompt, tools, LLM, shell, approvals, layers),
141
+ components, sessions, the session internals, the agent loop, and
142
+ the first-prompt title provider. The sessions row reads its
143
+ storage dir from ``MAGITECH_SESSIONS_DIR`` in the environment
144
+ passed to the loader: ``storage_dir`` sets it, and
145
+ ``storage_dir=None`` removes it, so an ambient value cannot turn a
146
+ memory-only boot into a persisted one. The persistence and
147
+ projection-cache rows read the same variable for their roots.
148
+
149
+ The optional ``prepare`` hook runs after the loader installs and
150
+ before the bundle loads: no bundle slot is reachable inside it, and
151
+ no direct mount has happened yet. With no running loop the rows
152
+ settle inside this call and a row that did not mount raises here;
153
+ with a running loop the rows settle on the caller's flush and the
154
+ caller fails loud by running :func:`check_bundle_entries` after it.
155
+
156
+ Args:
157
+ storage_dir: Optional base directory to persist session JSONL files.
158
+ profile: Optional profile overlay applied after the base bundle.
159
+ patches: Extra overlay sources applied after the profile, in order.
160
+ prepare: Optional host setup called with the context after the
161
+ loader installs and before the bundle loads, so before any
162
+ row activates.
163
+
164
+ Returns:
165
+ A configured Context instance.
166
+ """
167
+ ctx = Context()
168
+
169
+ base_path = Path(storage_dir) if storage_dir else None
170
+
171
+ # The sessions row reads its storage dir from the environment: the
172
+ # loader interpolates ${MAGITECH_SESSIONS_DIR} from the mapping
173
+ # passed here, which replaces os.environ as the interpolation
174
+ # source for the bundle. A missing storage dir removes the
175
+ # variable, so an ambient value cannot persist a memory-only boot.
176
+ env = dict(os.environ)
177
+ if base_path is not None:
178
+ env["MAGITECH_SESSIONS_DIR"] = str(base_path)
179
+ else:
180
+ env.pop("MAGITECH_SESSIONS_DIR", None)
181
+
182
+ # Mount the default bundle rows. The loader installs here; the
183
+ # bundle loads after prepare, so the hook runs before any row
184
+ # activates on either the sync or the loop path. No service mounts
185
+ # directly: the kernel is the bare context, the loader, and the
186
+ # bundle.
187
+ loader = LoaderService(ctx, {"filename": _BASE_BUNDLE_PATH})
188
+ if prepare is not None:
189
+ prepare(ctx)
190
+ with open(_BASE_BUNDLE_PATH, encoding="utf-8") as base_stream:
191
+ base_rows = load_yaml(base_stream)
192
+ if profile is not None:
193
+ profile_rows = profile_rows_from_source(profile)
194
+ if is_standalone(profile_rows):
195
+ base_rows = []
196
+ base_rows = merge_bundle_rows(
197
+ base_rows,
198
+ [
199
+ row
200
+ for row in profile_rows
201
+ if not (isinstance(row, dict) and row.get("id") == "__standalone__")
202
+ ],
203
+ )
204
+ # Extra patch overlays apply after the profile, in argv order: the
205
+ # default bundle -> profile -> --patch layers resolve deterministically.
206
+ for patch in patches or ():
207
+ base_rows = merge_bundle_rows(base_rows, profile_rows_from_source(patch))
208
+ loader.load(base_rows, env=env)
209
+ _settle_default_bundle(ctx, loader)
210
+
211
+ return ctx
212
+
213
+
214
+ __all__ = [
215
+ "DEFAULT_MAX_PARALLEL_TOOL_CALLS",
216
+ "AbortController",
217
+ "AbortError",
218
+ "AbortSignal",
219
+ "AgentLoop",
220
+ "AgentRegistry",
221
+ "ApprovalRequest",
222
+ "ApprovalService",
223
+ "AssistantStreamAttempt",
224
+ "CompactionService",
225
+ "ComponentManifest",
226
+ "ComponentService",
227
+ "ConfigLayer",
228
+ "ContextService",
229
+ "EventType",
230
+ "FactoryOwnership",
231
+ "FileSystem",
232
+ "JobRegistry",
233
+ "LLMProvider",
234
+ "LLMService",
235
+ "LayerResolutionService",
236
+ "LocalBashExecutor",
237
+ "LocalFileSystem",
238
+ "LocalJobRegistry",
239
+ "LocalPwshExecutor",
240
+ "LocalShellService",
241
+ "LocalSubprocessRuntime",
242
+ "MockLLMProvider",
243
+ "ModelChunk",
244
+ "ModelResponse",
245
+ "NativeToolExecutor",
246
+ "NoProviderError",
247
+ "ReactLoopAgent",
248
+ "RuntimeContextProjection",
249
+ "Session",
250
+ "SessionEvent",
251
+ "SessionService",
252
+ "ShellEnvRegistry",
253
+ "ShellExecutor",
254
+ "ShellResult",
255
+ "SubprocessRuntime",
256
+ "SystemPromptService",
257
+ "ToolCallData",
258
+ "ToolExecutionPipeline",
259
+ "ToolResultData",
260
+ "ToolRuntime",
261
+ "ToolService",
262
+ "ToolsService",
263
+ "UsageData",
264
+ "WorkingDirectoryService",
265
+ "calculate_argument_digest",
266
+ "check_bundle_entries",
267
+ "create_harness",
268
+ "define_tool",
269
+ "derive_messages",
270
+ "is_tool_pairing_balanced",
271
+ "parse_model_slug",
272
+ ]
@@ -0,0 +1 @@
1
+ """Automation-only Agent Client Protocol surface."""
magimoire/acp/codec.py ADDED
@@ -0,0 +1,22 @@
1
+ """Pure turn-ending to ACP stop-reason mapping."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ _STOP_REASONS = {
8
+ "completed": "end_turn",
9
+ "max-tokens": "max_tokens",
10
+ "aborted": "end_turn",
11
+ "interrupted": "cancelled",
12
+ "blocked": "end_turn",
13
+ "error": "end_turn",
14
+ }
15
+
16
+
17
+ def turn_end_to_stop_reason(reason: Any) -> str:
18
+ """Map one committed harness turn reason to the ACP stop-reason vocabulary."""
19
+ kind = reason.get("kind") if isinstance(reason, dict) else None
20
+ if not isinstance(kind, str):
21
+ return "end_turn"
22
+ return _STOP_REASONS.get(kind, "end_turn")
magimoire/acp/mcp.py ADDED
@@ -0,0 +1,164 @@
1
+ """Validation and mount seam for per-session ACP MCP servers.
2
+
3
+ Ports dsh's ``packages/acp/acp/src/mcp.ts``: stable stdio/HTTP declarations
4
+ are validated, normalized into unique client names, and mounted into the
5
+ unpublished Agent scope before publication.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import re
12
+ from typing import Any
13
+ from urllib.parse import urlsplit
14
+
15
+ VALID_NAME = re.compile(r"^[A-Za-z0-9_-]{1,32}$")
16
+ CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]")
17
+
18
+
19
+ class McpConfigError(ValueError):
20
+ """Caller-correctable MCP declaration failure."""
21
+
22
+ def __init__(self, message: str) -> None:
23
+ super().__init__(f"MCP_CONFIG: {message}")
24
+
25
+
26
+ def normalize_name(name: Any) -> str:
27
+ """Produce a stable tool namespace from a human-readable server name."""
28
+ if not isinstance(name, str) or not name.strip() or CONTROL_CHARS.search(name):
29
+ raise McpConfigError("invalid server name")
30
+ if VALID_NAME.fullmatch(name):
31
+ return name
32
+ slug = re.sub(r"[^A-Za-z0-9_-]+", "_", name, flags=re.UNICODE)
33
+ slug = re.sub(r"^_+|_+$", "", slug)[:20] or "server"
34
+ digest = hashlib.sha256(name.encode("utf-8")).hexdigest()[:8]
35
+ return f"{slug}_{digest}"
36
+
37
+
38
+ def _entries(raw: Any, field: str, kind: str) -> dict[str, str]:
39
+ if raw is None:
40
+ return {}
41
+ if not isinstance(raw, list):
42
+ raise McpConfigError(f"{field} must be an array of name/value entries")
43
+ result: dict[str, str] = {}
44
+ seen: set[str] = set()
45
+ for entry in raw:
46
+ if not isinstance(entry, dict):
47
+ raise McpConfigError(f"{field} contains an invalid entry")
48
+ name, value = entry.get("name"), entry.get("value")
49
+ if not isinstance(name, str) or not isinstance(value, str):
50
+ raise McpConfigError(f"{field} entries require string name and value")
51
+ if kind == "header":
52
+ if (
53
+ not name
54
+ or not name.isascii()
55
+ or any(char in name for char in ":\t ")
56
+ or name != name.strip()
57
+ or CONTROL_CHARS.search(name)
58
+ or CONTROL_CHARS.search(value)
59
+ ):
60
+ raise McpConfigError(f"{field} contains an invalid header entry")
61
+ identity = name.lower()
62
+ else:
63
+ if not name or "=" in name or "\x00" in name or "\x00" in value:
64
+ raise McpConfigError(f"{field} contains an invalid environment entry")
65
+ identity = name
66
+ if identity in seen:
67
+ raise McpConfigError(f"{field} contains duplicate name: {name}")
68
+ seen.add(identity)
69
+ result[name] = value
70
+ return result
71
+
72
+
73
+ def resolve_configs(servers: Any, cwd: str) -> list[dict[str, Any]]:
74
+ """Validate ordered ACP server declarations into client configs."""
75
+ if servers is None:
76
+ return []
77
+ if not isinstance(servers, list):
78
+ raise McpConfigError("mcpServers must be an array")
79
+ names: set[str] = set()
80
+ configs: list[dict[str, Any]] = []
81
+ for index, server in enumerate(servers):
82
+ if not isinstance(server, dict):
83
+ raise McpConfigError(f"mcpServers[{index}] must be an object")
84
+ name = normalize_name(server.get("name"))
85
+ if name in names:
86
+ raise McpConfigError(f"duplicate normalized name: {name}")
87
+ names.add(name)
88
+ transport = server.get("type")
89
+ if transport is None:
90
+ command = server.get("command")
91
+ if not isinstance(command, str) or not command.startswith("/"):
92
+ raise McpConfigError(f"mcpServers[{index}].command must be absolute")
93
+ raw_args = server.get("args") or []
94
+ if not isinstance(raw_args, list) or not all(
95
+ isinstance(item, str) for item in raw_args
96
+ ):
97
+ raise McpConfigError(
98
+ f"mcpServers[{index}].args must be an array of strings"
99
+ )
100
+ configs.append(
101
+ {
102
+ "transport": "stdio",
103
+ "serverName": name,
104
+ "command": command,
105
+ "args": list(raw_args),
106
+ "env": _entries(
107
+ server.get("env"), f"mcpServers[{index}].env", "env"
108
+ ),
109
+ "cwd": cwd,
110
+ "failOnStartupError": True,
111
+ }
112
+ )
113
+ elif transport == "http":
114
+ url = server.get("url")
115
+ parts = urlsplit(url) if isinstance(url, str) else None
116
+ if (
117
+ parts is None
118
+ or parts.scheme not in ("http", "https")
119
+ or not parts.netloc
120
+ ):
121
+ raise McpConfigError(f"mcpServers[{index}].url must be HTTP(S)")
122
+ configs.append(
123
+ {
124
+ "transport": "streamable-http",
125
+ "serverName": name,
126
+ "url": url,
127
+ "headers": _entries(
128
+ server.get("headers"),
129
+ f"mcpServers[{index}].headers",
130
+ "header",
131
+ ),
132
+ "failOnStartupError": True,
133
+ }
134
+ )
135
+ else:
136
+ raise McpConfigError(
137
+ f"mcpServers[{index}] transport {transport} is not supported"
138
+ )
139
+ return configs
140
+
141
+
142
+ async def mount_servers(
143
+ ctx: Any,
144
+ servers: Any,
145
+ cwd: str,
146
+ on_mount: Any = None,
147
+ session_id: str = "",
148
+ ) -> list[dict[str, Any]]:
149
+ """Resolve and mount all declarations into the caller's Agent scope."""
150
+ configs = resolve_configs(servers, cwd)
151
+ mount = on_mount or ctx.get("mcpClient", None, strict=False)
152
+ if configs and mount is None:
153
+ raise McpConfigError("no MCP client seam is configured for this session")
154
+ if mount is not None:
155
+ registrar = getattr(mount, "mount_client", mount)
156
+ for config in configs:
157
+ result = (
158
+ registrar(config, session_id)
159
+ if registrar is not mount
160
+ else registrar(config)
161
+ )
162
+ if hasattr(result, "__await__"):
163
+ await result
164
+ return configs
@@ -0,0 +1,43 @@
1
+ """ACP v1 wire vocabulary for the Python server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ PROTOCOL_VERSION = 1
8
+ AGENT_NAME = "deepseek-harness-acp"
9
+ AGENT_VERSION = "0.0.1"
10
+
11
+ METHODS = {
12
+ "initialize": "initialize",
13
+ "authenticate": "authenticate",
14
+ "session/new": "session/new",
15
+ "session/list": "session/list",
16
+ "session/resume": "session/resume",
17
+ "session/close": "session/close",
18
+ "session/set_config_option": "session/set_config_option",
19
+ "session/prompt": "session/prompt",
20
+ "session/cancel": "session/cancel",
21
+ "session/update": "session/update",
22
+ "session/request_permission": "session/request_permission",
23
+ }
24
+
25
+ CONFIG_OPTIONS = ("model", "reasoning_effort")
26
+
27
+
28
+ def capabilities(image: bool = False) -> dict[str, Any]:
29
+ """Advertised agent capabilities, with only mounted surfaces included."""
30
+ return {
31
+ "protocolVersion": PROTOCOL_VERSION,
32
+ "agentInfo": {"name": AGENT_NAME, "version": AGENT_VERSION},
33
+ "agentCapabilities": {
34
+ "mcpCapabilities": {"http": False},
35
+ "promptCapabilities": {
36
+ "image": image,
37
+ "audio": False,
38
+ "embeddedContext": False,
39
+ },
40
+ "sessionCapabilities": {"close": {}, "list": {}, "resume": {}},
41
+ },
42
+ "authMethods": [],
43
+ }