dap-runtimes 0.3.0__tar.gz

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.
@@ -0,0 +1,87 @@
1
+ # --- Python ---
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ .venv/
8
+ venv/
9
+ env/
10
+ *.egg-info/
11
+ *.egg
12
+ dist/
13
+ build/
14
+ .eggs/
15
+ pip-log.txt
16
+ pip-delete-this-directory.txt
17
+
18
+ # uv
19
+ .uv-cache/
20
+
21
+ # Type checkers / linters
22
+ .mypy_cache/
23
+ .ruff_cache/
24
+ .pyright/
25
+ .pytype/
26
+
27
+ # pytest / coverage
28
+ .pytest_cache/
29
+ .coverage
30
+ .coverage.*
31
+ htmlcov/
32
+ .tox/
33
+ .nox/
34
+ coverage.xml
35
+ *.cover
36
+
37
+ # --- Node (dashboard) ---
38
+ node_modules/
39
+ .pnpm-store/
40
+ .next/
41
+ out/
42
+ *.tsbuildinfo
43
+ .turbo/
44
+
45
+ # --- Environment ---
46
+ .env
47
+ .env.local
48
+ .env.*.local
49
+
50
+ # --- DAP local state ---
51
+ .dap/
52
+ *.db
53
+ *.db-journal
54
+ *.db-wal
55
+ *.db-shm
56
+
57
+ # --- Logs ---
58
+ logs/
59
+ *.log
60
+ npm-debug.log*
61
+ pnpm-debug.log*
62
+
63
+ # --- IDE / Agents ---
64
+ .vscode/
65
+ .idea/
66
+ *.swp
67
+ *.swo
68
+ .claude/
69
+
70
+ # --- OS ---
71
+ .DS_Store
72
+ Thumbs.db
73
+
74
+ # --- Cache ---
75
+ .cache/
76
+ .eslintcache
77
+
78
+ # --- Built artefacts ---
79
+ # Dashboard bundle staged into the dap-cli wheel by
80
+ # scripts/build-dashboard-bundle.sh — regenerated on demand from
81
+ # apps/dashboard/.next. The ``.gitkeep`` is retained so hatchling's
82
+ # ``force-include`` always finds the directory; dev wheels built
83
+ # without running the bundle script ship an effectively-empty
84
+ # ``_dashboard/`` and ``dap start`` falls back to "dashboard not
85
+ # bundled".
86
+ apps/cli/src/dap_cli/_dashboard/*
87
+ !apps/cli/src/dap_cli/_dashboard/.gitkeep
@@ -0,0 +1,345 @@
1
+ Metadata-Version: 2.4
2
+ Name: dap-runtimes
3
+ Version: 0.3.0
4
+ Summary: Runtime adapters for DAP (claude-code, gemini-cli, codex, aider, api-call, bash, http)
5
+ Requires-Python: >=3.13
6
+ Requires-Dist: anthropic>=0.40.0
7
+ Requires-Dist: anyio>=4.6.0
8
+ Requires-Dist: dap-schemas
9
+ Requires-Dist: google-genai>=0.3.0
10
+ Requires-Dist: httpx>=0.27.2
11
+ Requires-Dist: jinja2>=3.1.4
12
+ Requires-Dist: jsonpath-ng>=1.6.1
13
+ Requires-Dist: openai>=1.55.0
14
+ Description-Content-Type: text/markdown
15
+
16
+ # dap-runtimes
17
+
18
+ Runtime adapters dla DAP. Każdy adapter deleguje zadanie do konkretnego executora (CLI agent, SDK, shell, HTTP).
19
+
20
+ Stan: `api-call` (multi-provider: Anthropic + OpenAI + OpenAI-compat + Gemini), `bash`, `claude-code`, `codex`, `gemini-cli` i `http` są w pełni zaimplementowane; `aider` — stub (przyjdzie później).
21
+
22
+ ```python
23
+ import asyncio
24
+ from dap_runtimes import create_default_registry
25
+
26
+ async def main() -> None:
27
+ registry = create_default_registry()
28
+ adapter = registry.get("bash")
29
+ health = await adapter.healthcheck()
30
+ print(health)
31
+
32
+ asyncio.run(main())
33
+ ```
34
+
35
+ ## api-call
36
+
37
+ Wywołanie LLM przez SDK — single-shot, bez tool use, bez streamowania.
38
+ Provider wybierany przez `runtime_config.provider`; każdy provider ma
39
+ własne pricing + token extraction w module pod `_providers/`.
40
+
41
+ | `provider` | SDK | Wymagany env | Pricing |
42
+ | ----------------- | ---------------------------------- | ----------------------------------------------- | -------------------------------------------------------- |
43
+ | `anthropic` (default) | `anthropic.AsyncAnthropic` | `ANTHROPIC_API_KEY` | Pełne (Claude 4.x rodzina + cache mnożniki) |
44
+ | `openai` | `openai.AsyncOpenAI` | `OPENAI_API_KEY` | Pełne (gpt-5, o-series) |
45
+ | `openai-compat` | `openai.AsyncOpenAI(base_url=…)` | env nazwany w `runtime_config.api_key_env` | None (nie znamy cen third-party) |
46
+ | `gemini` | `google.genai.Client` | `GEMINI_API_KEY` | Pełne (Gemini 2.x / 3.x) |
47
+
48
+ `runtime_config` (wspólne):
49
+
50
+ | key | type | description |
51
+ | ------------------ | -------------- | ---------------------------------------------------------------------------- |
52
+ | `provider` | `str` | `anthropic` (domyślnie) / `openai` / `openai-compat` / `gemini` |
53
+ | `model_id` | `str` | ID modelu (np. `claude-haiku-4-5`, `gpt-5-mini`, `gemini-3.0-flash`) |
54
+ | `max_tokens` | `int` | Domyślnie 4096 |
55
+ | `system_prompt` | `str?` | Prepend przed `prompt_xml` w roli system |
56
+
57
+ Specyficzne dla `anthropic`:
58
+
59
+ | key | type | description |
60
+ | ----------------- | --------------------------------------------------- | ---------------------------------------- |
61
+ | `prompt_cache` | `bool` | Włącza ephemeral cache control |
62
+ | `enable_thinking` | `bool` | Adaptive thinking |
63
+ | `effort` | `low`/`medium`/`high`/`xhigh`/`max` | Reasoning effort |
64
+
65
+ Specyficzne dla `openai-compat`:
66
+
67
+ | key | type | required | description |
68
+ | -------------- | ------ | :------: | -------------------------------------------------------------------- |
69
+ | `base_url` | `str` | tak | OpenAI-compat endpoint (np. `https://api.z.ai/api/coding/paas/v4`) |
70
+ | `api_key_env` | `str` | tak | Nazwa env var trzymającej klucz (np. `GLM_API_KEY`) |
71
+
72
+ Specyficzne dla `gemini`:
73
+
74
+ | key | type | description |
75
+ | ------------------ | ------ | ------------------------------------------------- |
76
+ | `temperature` | `float`| Domyślnie SDK default |
77
+ | `thinking_budget` | `int` | Limit tokenów na reasoning |
78
+
79
+ ### Przykłady
80
+
81
+ **DeveloperJr (GLM przez OpenAI-compat):**
82
+
83
+ ```json
84
+ {
85
+ "provider": "openai-compat",
86
+ "model_id": "glm-5-flash",
87
+ "base_url": "https://api.z.ai/api/coding/paas/v4",
88
+ "api_key_env": "GLM_API_KEY",
89
+ "max_tokens": 4096
90
+ }
91
+ ```
92
+
93
+ **DeveloperFrontend (Gemini API):**
94
+
95
+ ```json
96
+ {
97
+ "provider": "gemini",
98
+ "model_id": "gemini-3.0-pro",
99
+ "max_tokens": 8192,
100
+ "temperature": 0.2
101
+ }
102
+ ```
103
+
104
+ ## bash
105
+
106
+ Wykonuje pojedynczą komendę shellową w `task.working_directory`, z timeoutem
107
+ z `task.timeout_ms`. Zwraca `success=False` przy non-zero exit / timeout;
108
+ stdout trafia do `output`, stderr i exit_code do `structured`.
109
+
110
+ `runtime_config`:
111
+
112
+ | key | type | required | description |
113
+ | --------- | ---------------- | :------: | ----------------------------------------------------------------- |
114
+ | `command` | `str` | no | Komenda do uruchomienia. Pierwszeństwo nad `<command>` w prompcie. |
115
+ | `shell` | `str` | no | Domyślnie `/bin/bash`. Override też przez `DAP_BASH_SHELL`. |
116
+ | `env` | `dict[str, str]` | no | Dodatkowe zmienne środowiskowe (zlewane na proces.env). |
117
+
118
+ Jeśli `command` nie jest ustawione, adapter wyciąga zawartość pierwszego
119
+ `<command>...</command>` z `prompt_xml` — pozwala to na komendy wyliczane
120
+ z `PipelineState` przez Jinja w template'cie agenta.
121
+
122
+ ### Model bezpieczeństwa (v0.1)
123
+
124
+ **Single-user, local-trust.** Komenda działa z uprawnieniami procesu engine'a
125
+ w skonfigurowanym `working_directory` — **bez sandboxa, bez izolacji sieci,
126
+ bez confinementu plików**. Każda definicja agenta używającego runtime'u `bash`
127
+ ma faktyczną kontrolę nad maszyną. Multi-user setup wymaga najpierw auth
128
+ (#38) i dodatkowej warstwy izolacji (firejail / Docker / nsjail) zanim ten
129
+ runtime można wystawić niezaufanym definicjom agentów.
130
+
131
+ ## Env layering (v0.6)
132
+
133
+ Subprocess-spawning adapters (`bash`, `claude-code`, `codex`, `gemini-cli`)
134
+ budują env subprocesa w trzech warstwach. Wyższa warstwa wygrywa nad niższą:
135
+
136
+ 1. **Engine process env** (najniższa) — env, w którym działa `dap-engine`.
137
+ Trzymaj tu sekrety (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`).
138
+ 2. **Project `env_vars`** (overlay) — `Project.env_vars` projektu związanego z
139
+ runem (#65). Wartości wyższe od engine env, niższe od per-agent. Convenience
140
+ dla nie-sekretnych zmiennych typu `WORKSPACE_NAME`, feature flagów, ścieżek
141
+ per-projekt.
142
+ 3. **Per-agent `runtime_config.env`** (najwyższa) — wprost w agent definition.
143
+ Ostatnia szansa na override per-call.
144
+
145
+ Ad-hoc runs (bez `project_id`) widzą tylko warstwy 1 + 3 — warstwa 2 jest pustym
146
+ dictem. `api-call` adapter nie spawnuje subprocesów, więc env layering go nie
147
+ dotyczy (klucz API czyta SDK z `os.environ` bezpośrednio).
148
+
149
+ ## claude-code
150
+
151
+ Wywołuje Claude Code CLI w trybie `--print --output-format json`. Prompt
152
+ XML idzie przez stdin, odpowiedź to structured JSON (`result`, `usage`,
153
+ `total_cost_usd`, `session_id`, `num_turns`). Cost i token usage
154
+ populują `RuntimeResult` automatycznie.
155
+
156
+ Kiedy `claude-code` zamiast `api-call` (Anthropic):
157
+
158
+ | Potrzeba | Użyj |
159
+ | ----------------------------------------------------- | ------------------- |
160
+ | Single-shot LLM, deterministycznie, bez tooli | `api-call` |
161
+ | Agentic loop z file edits, bashem, MCP tools | `claude-code` |
162
+
163
+ `runtime_config`:
164
+
165
+ | key | type | required | description |
166
+ | -------------- | ----------- | :------: | ------------------------------------------------------------------------ |
167
+ | `model_id` | `str` | tak | Anthropic model (np. `claude-opus-4-7`, `claude-sonnet-4-6`) |
168
+ | `binary_path` | `str` | no | Domyślnie `claude` na PATH. Override przy wielu instalacjach. |
169
+ | `extra_args` | `list[str]` | no | Dopisane do CLI invocation, np. `["--allowed-tools","Read,Edit,Bash"]` |
170
+
171
+ Klucz API: `ANTHROPIC_API_KEY` w env engine'a — Claude Code CLI czyta go
172
+ sam, adapter nie wstrzykuje.
173
+
174
+ Process lifecycle identyczny jak w `bash`: POSIX session group +
175
+ `asyncio.shield(wait)` cleanup + obsługa `CancelledError`. Engine
176
+ pause/abort zabija całą grupę procesów (CLI + jego subprocessy), bez
177
+ zombie.
178
+
179
+ ## codex
180
+
181
+ Wywołuje OpenAI Codex CLI w trybie `exec --json --model {model_id}`.
182
+ Prompt XML idzie przez stdin, wynik to structured JSON. Token usage
183
+ wyciągamy z `usage` z fallbackami nazw (snake_case z OpenAI SDK,
184
+ camelCase z niektórych buildów, oraz wariant `prompt_tokens` /
185
+ `completion_tokens`). Tekst odpowiedzi szukamy kolejno w
186
+ `output_text` → `result` → `response` → `text` → `output`. Cost
187
+ zwracany jako `None` (CLI nie raportuje; jeśli chcesz pricing — użyj
188
+ `api-call` z `provider="openai"`).
189
+
190
+ Kiedy `codex` zamiast `api-call` (OpenAI):
191
+
192
+ | Potrzeba | Użyj |
193
+ | ----------------------------------------------------- | ------------------- |
194
+ | Single-shot LLM, deterministycznie, bez tooli | `api-call` |
195
+ | Agentic loop z file edits, bashem, MCP tools | `codex` |
196
+
197
+ `runtime_config`:
198
+
199
+ | key | type | required | description |
200
+ | -------------- | ----------- | :------: | ------------------------------------------------------------------------ |
201
+ | `model_id` | `str` | tak | OpenAI model (np. `gpt-5-codex`, `gpt-5`, `o3`) |
202
+ | `binary_path` | `str` | no | Domyślnie `codex` na PATH. Override przy wielu instalacjach. |
203
+ | `extra_args` | `list[str]` | no | Dopisane do CLI invocation, np. `["--sandbox","workspace-write"]` |
204
+
205
+ Klucz API: `OPENAI_API_KEY` w env engine'a — Codex CLI czyta go sam,
206
+ adapter nie wstrzykuje.
207
+
208
+ Process lifecycle identyczny jak w `bash` / `claude-code`. Cały payload
209
+ JSON z CLI ląduje w `RuntimeResult.structured.payload` — pozwala
210
+ debugować shape drift między releasami CLI bez zmian adaptera.
211
+
212
+ ## gemini-cli
213
+
214
+ Wywołuje Google Gemini CLI z `-m {model_id} -o json`, prompt XML idzie
215
+ przez stdin, wynik to structured JSON. Token usage wyciągamy z
216
+ `usage_metadata` (snake_case z SDK lub camelCase z niektórych buildów —
217
+ adapter próbuje obu). Cost zwracany jako `None` (CLI nie raportuje;
218
+ jeśli chcesz pricing — użyj `api-call` z `provider="gemini"`).
219
+
220
+ `runtime_config`:
221
+
222
+ | key | type | required | description |
223
+ | ------------------ | ------ | :------: | ------------------------------------------------------------------------ |
224
+ | `model_id` | `str` | tak | Gemini model (np. `gemini-3.0-pro`, `gemini-3.0-flash`) |
225
+ | `binary_path` | `str` | no | Domyślnie `gemini` na PATH |
226
+ | `thinking_budget` | `int` | no | Limit tokenów na reasoning (mappowany do `--thinking-budget`) |
227
+
228
+ Klucz API: `GEMINI_API_KEY` w env engine'a — albo `GOOGLE_API_KEY` jako
229
+ fallback (Gemini CLI akceptuje oba). Adapter nie wstrzykuje, CLI czyta
230
+ sam.
231
+
232
+ Process lifecycle identyczny jak w `bash` / `claude-code`.
233
+
234
+ ## http
235
+
236
+ Generic POST do dowolnego JSON-speaking serwisu — Ollama, llama.cpp,
237
+ custom gatewaye, OpenAI/Anthropic-compatible proxy, własne API teamu.
238
+ Request body to Jinja2 template (sandboxed) renderowany ze scope'm
239
+ `{prompt_xml, runtime_config}`; response parsowany przez JSONPath.
240
+
241
+ `runtime_config`:
242
+
243
+ | key | type | required | description |
244
+ | -------------------- | --------------- | :------: | ---------------------------------------------------------------------------- |
245
+ | `url` | `str` | tak | Endpoint (http:// lub https://) |
246
+ | `method` | `str` | no | `POST` (default) lub `PUT` |
247
+ | `request_template` | `dict`/`list`/`str` | tak | Template z Jinja2 placeholders. Stringi templatowane, inne typy as-is. |
248
+ | `response_extractor` | `dict[str, str]` | tak | Mapa nazw → JSONPath. **Musi zawierać `output`**. Np. `{"output":"$.response"}` |
249
+ | `auth` | `dict` | no | `{"type":"bearer","env":"OLLAMA_API_KEY"}` / `{"type":"header","name":"...","env":"..."}` / `{"type":"basic","user_env":"...","pass_env":"..."}` |
250
+ | `headers` | `dict[str,str]` | no | Dodatkowe statyczne headery |
251
+
252
+ Klucze API: zawsze przez env vary nazwane w `auth.env` / `auth.user_env`
253
+ / `auth.pass_env` — nigdy nie persystowane w bazie.
254
+
255
+ Przykład Ollama:
256
+
257
+ ```json
258
+ {
259
+ "url": "http://localhost:11434/api/generate",
260
+ "request_template": {
261
+ "model": "{{ runtime_config.model_id }}",
262
+ "prompt": "{{ prompt_xml }}",
263
+ "stream": false
264
+ },
265
+ "response_extractor": {
266
+ "output": "$.response",
267
+ "tokens_used": "$.eval_count"
268
+ },
269
+ "model_id": "llama3.2"
270
+ }
271
+ ```
272
+
273
+ Cancellation: httpx connection cancel'owane przez context manager
274
+ (`async with`); engine pause/abort kończy request bez residue.
275
+
276
+ ## python-func
277
+
278
+ Wykonuje dowolny Python callable (sync lub async) jako agenta DAP.
279
+ Entrypoint rozwiązywany w momencie wywołania — instalacja pakietu
280
+ nie wymaga restartu engine'a.
281
+
282
+ ### Sygnatura funkcji
283
+
284
+ ```python
285
+ async def run(state: dict, config: dict) -> dict:
286
+ """
287
+ state — dict budowany z pól przełączanych przez pass_prompt / pass_context.
288
+ config — runtime_config z definicji agenta.
289
+ returns — dict pól do scalenia z PipelineState.
290
+ Zarezerwowany klucz __audit: dict jest wyciągany przez adapter
291
+ i trafia do RuntimeResult.structured["audit"] (NIE do state_delta).
292
+ """
293
+ return {
294
+ "output_field": result_text,
295
+ "__audit": {"tokens_used": 1240, "cost_usd": 0.003},
296
+ }
297
+ ```
298
+
299
+ Sync `def run(state, config)` też działa — adapter owija w `loop.run_in_executor(None, ...)`.
300
+
301
+ `runtime_config`:
302
+
303
+ | key | type | required | description |
304
+ | --------------- | ------ | :------: | ----------------------------------------------------------------------------------- |
305
+ | `callable_path` | `str` | tak | `"package.module:func_name"`. Pakiet musi być zainstalowany w venv engine'a. |
306
+ | `pass_prompt` | `bool` | no | Czy wstrzyknąć `prompt_xml` do `state["prompt_xml"]`. Domyślnie `True`. |
307
+ | `pass_context` | `bool` | no | Czy wstrzyknąć `RuntimeContext` do `state["context"]`. Domyślnie `False`. |
308
+
309
+ `RuntimeResult.structured`:
310
+
311
+ | key | type | description |
312
+ | ------------- | ------ | -------------------------------------------------------------------- |
313
+ | `state_delta` | `dict` | Zwrot funkcji po usunięciu `__audit` — gotowy do scalenia ze statem. |
314
+ | `audit` | `dict` | Zawartość `__audit` z returna (tokeny, koszt, custom pola). |
315
+
316
+ ### Przykład
317
+
318
+ ```json
319
+ {
320
+ "runtime_id": "python-func",
321
+ "runtime_config": {
322
+ "callable_path": "cortex.nodes.mockup:run",
323
+ "pass_prompt": true
324
+ }
325
+ }
326
+ ```
327
+
328
+ ### Instalacja pakietów
329
+
330
+ > **Note**: The package containing the callable must be installed in the
331
+ > engine's venv separately. It is not a build dependency of `dap-engine`.
332
+ >
333
+ > The `python-func` adapter resolves `callable_path` with `importlib` at
334
+ > invocation time — the engine starts fine without the package and only
335
+ > fails when that specific node runs. Install the package in the engine's
336
+ > venv on the host where `dap-engine` runs (e.g. `uv pip install -e
337
+ > /path/to/cortex-project`).
338
+
339
+ ### Model bezpieczeństwa (v0.1)
340
+
341
+ **Single-user, local-trust.** Ten sam poziom zaufania co `bash` — callable
342
+ działa z uprawnieniami procesu engine'a, **bez sandboxa, bez izolacji importów,
343
+ bez confinementu sieci**. Pakiet musi być zainstalowany w venv engine'a.
344
+ Multi-user setup wymaga najpierw auth (#38) i dodatkowej warstwy izolacji
345
+ zanim ten runtime można wystawić niezaufanym definicjom agentów.