deepclause-sdk 0.0.89 → 0.1.0

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 (292) hide show
  1. package/README.md +417 -948
  2. package/dist/agent.d.ts +18 -2
  3. package/dist/agent.d.ts.map +1 -1
  4. package/dist/agent.js +74 -21
  5. package/dist/agent.js.map +1 -1
  6. package/dist/cli/config.d.ts +323 -176
  7. package/dist/cli/config.d.ts.map +1 -1
  8. package/dist/cli/config.js +146 -188
  9. package/dist/cli/config.js.map +1 -1
  10. package/dist/cli/index.d.ts +3 -2
  11. package/dist/cli/index.d.ts.map +1 -1
  12. package/dist/cli/index.js +61 -425
  13. package/dist/cli/index.js.map +1 -1
  14. package/dist/cli/login.d.ts +29 -0
  15. package/dist/cli/login.d.ts.map +1 -0
  16. package/dist/cli/login.js +184 -0
  17. package/dist/cli/login.js.map +1 -0
  18. package/dist/cli/readline.d.ts +6 -0
  19. package/dist/cli/readline.d.ts.map +1 -0
  20. package/dist/cli/readline.js +15 -0
  21. package/dist/cli/readline.js.map +1 -0
  22. package/dist/cli/repl-bin.d.ts +9 -0
  23. package/dist/cli/repl-bin.d.ts.map +1 -0
  24. package/dist/cli/repl-bin.js +16 -0
  25. package/dist/cli/repl-bin.js.map +1 -0
  26. package/dist/cli/repl.d.ts +191 -0
  27. package/dist/cli/repl.d.ts.map +1 -0
  28. package/dist/cli/repl.js +1232 -0
  29. package/dist/cli/repl.js.map +1 -0
  30. package/dist/cli/run.d.ts +17 -18
  31. package/dist/cli/run.d.ts.map +1 -1
  32. package/dist/cli/run.js +196 -183
  33. package/dist/cli/run.js.map +1 -1
  34. package/dist/cli/set-backend.d.ts +53 -0
  35. package/dist/cli/set-backend.d.ts.map +1 -0
  36. package/dist/cli/set-backend.js +259 -0
  37. package/dist/cli/set-backend.js.map +1 -0
  38. package/dist/cli/visualize.d.ts +38 -0
  39. package/dist/cli/visualize.d.ts.map +1 -0
  40. package/dist/cli/visualize.js +125 -0
  41. package/dist/cli/visualize.js.map +1 -0
  42. package/dist/compiler.d.ts +5 -52
  43. package/dist/compiler.d.ts.map +1 -1
  44. package/dist/compiler.js +4 -768
  45. package/dist/compiler.js.map +1 -1
  46. package/dist/index.d.ts +27 -2
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +18 -2
  49. package/dist/index.js.map +1 -1
  50. package/dist/prolog/bridge.d.ts +3 -1
  51. package/dist/prolog/bridge.d.ts.map +1 -1
  52. package/dist/prolog/bridge.js +8 -1
  53. package/dist/prolog/bridge.js.map +1 -1
  54. package/dist/prolog-src/deepclause_analysis.pl +10 -2
  55. package/dist/prolog-src/deepclause_mi.pl +2245 -41
  56. package/dist/repl/agent.d.ts +72 -0
  57. package/dist/repl/agent.d.ts.map +1 -0
  58. package/dist/repl/agent.js +366 -0
  59. package/dist/repl/agent.js.map +1 -0
  60. package/dist/repl/auth.d.ts +45 -0
  61. package/dist/repl/auth.d.ts.map +1 -0
  62. package/dist/repl/auth.js +116 -0
  63. package/dist/repl/auth.js.map +1 -0
  64. package/dist/repl/backend.d.ts +290 -0
  65. package/dist/repl/backend.d.ts.map +1 -0
  66. package/dist/repl/backend.js +370 -0
  67. package/dist/repl/backend.js.map +1 -0
  68. package/dist/repl/compaction.d.ts +122 -0
  69. package/dist/repl/compaction.d.ts.map +1 -0
  70. package/dist/repl/compaction.js +318 -0
  71. package/dist/repl/compaction.js.map +1 -0
  72. package/dist/repl/export.d.ts +30 -0
  73. package/dist/repl/export.d.ts.map +1 -0
  74. package/dist/repl/export.js +23 -0
  75. package/dist/repl/export.js.map +1 -0
  76. package/dist/repl/frames.d.ts +21 -0
  77. package/dist/repl/frames.d.ts.map +1 -0
  78. package/dist/repl/frames.js +79 -0
  79. package/dist/repl/frames.js.map +1 -0
  80. package/dist/repl/harness-tools.d.ts +74 -0
  81. package/dist/repl/harness-tools.d.ts.map +1 -0
  82. package/dist/repl/harness-tools.js +121 -0
  83. package/dist/repl/harness-tools.js.map +1 -0
  84. package/dist/repl/highlight.d.ts +30 -0
  85. package/dist/repl/highlight.d.ts.map +1 -0
  86. package/dist/repl/highlight.js +285 -0
  87. package/dist/repl/highlight.js.map +1 -0
  88. package/dist/repl/history.d.ts +234 -0
  89. package/dist/repl/history.d.ts.map +1 -0
  90. package/dist/repl/history.js +661 -0
  91. package/dist/repl/history.js.map +1 -0
  92. package/dist/repl/index.d.ts +120 -0
  93. package/dist/repl/index.d.ts.map +1 -0
  94. package/dist/repl/index.js +107 -0
  95. package/dist/repl/index.js.map +1 -0
  96. package/dist/repl/judge.d.ts +51 -0
  97. package/dist/repl/judge.d.ts.map +1 -0
  98. package/dist/repl/judge.js +58 -0
  99. package/dist/repl/judge.js.map +1 -0
  100. package/dist/repl/markdown.d.ts +25 -0
  101. package/dist/repl/markdown.d.ts.map +1 -0
  102. package/dist/repl/markdown.js +103 -0
  103. package/dist/repl/markdown.js.map +1 -0
  104. package/dist/repl/picker.d.ts +34 -0
  105. package/dist/repl/picker.d.ts.map +1 -0
  106. package/dist/repl/picker.js +81 -0
  107. package/dist/repl/picker.js.map +1 -0
  108. package/dist/repl/project-context.d.ts +16 -0
  109. package/dist/repl/project-context.d.ts.map +1 -0
  110. package/dist/repl/project-context.js +23 -0
  111. package/dist/repl/project-context.js.map +1 -0
  112. package/dist/repl/render.d.ts +160 -0
  113. package/dist/repl/render.d.ts.map +1 -0
  114. package/dist/repl/render.js +715 -0
  115. package/dist/repl/render.js.map +1 -0
  116. package/dist/repl/session.d.ts +356 -0
  117. package/dist/repl/session.d.ts.map +1 -0
  118. package/dist/repl/session.js +1275 -0
  119. package/dist/repl/session.js.map +1 -0
  120. package/dist/repl/status.d.ts +100 -0
  121. package/dist/repl/status.d.ts.map +1 -0
  122. package/dist/repl/status.js +218 -0
  123. package/dist/repl/status.js.map +1 -0
  124. package/dist/repl/tools.d.ts +53 -0
  125. package/dist/repl/tools.d.ts.map +1 -0
  126. package/dist/repl/tools.js +307 -0
  127. package/dist/repl/tools.js.map +1 -0
  128. package/dist/repl/toolset.d.ts +32 -0
  129. package/dist/repl/toolset.d.ts.map +1 -0
  130. package/dist/repl/toolset.js +82 -0
  131. package/dist/repl/toolset.js.map +1 -0
  132. package/dist/repl/tui/editor.d.ts +17 -0
  133. package/dist/repl/tui/editor.d.ts.map +1 -0
  134. package/dist/repl/tui/editor.js +39 -0
  135. package/dist/repl/tui/editor.js.map +1 -0
  136. package/dist/repl/tui/status-bar.d.ts +26 -0
  137. package/dist/repl/tui/status-bar.d.ts.map +1 -0
  138. package/dist/repl/tui/status-bar.js +47 -0
  139. package/dist/repl/tui/status-bar.js.map +1 -0
  140. package/dist/repl/tui/theme.d.ts +30 -0
  141. package/dist/repl/tui/theme.d.ts.map +1 -0
  142. package/dist/repl/tui/theme.js +81 -0
  143. package/dist/repl/tui/theme.js.map +1 -0
  144. package/dist/repl/tui/transcript.d.ts +39 -0
  145. package/dist/repl/tui/transcript.d.ts.map +1 -0
  146. package/dist/repl/tui/transcript.js +123 -0
  147. package/dist/repl/tui/transcript.js.map +1 -0
  148. package/dist/runner.d.ts +132 -13
  149. package/dist/runner.d.ts.map +1 -1
  150. package/dist/runner.js +434 -277
  151. package/dist/runner.js.map +1 -1
  152. package/dist/sdk.d.ts.map +1 -1
  153. package/dist/sdk.js +0 -32
  154. package/dist/sdk.js.map +1 -1
  155. package/dist/system/assets/docs/AGENT_PROMPT.md +1373 -0
  156. package/dist/system/assets/docs/DML_AUTHORING.md +195 -0
  157. package/dist/system/assets/docs/DML_REFERENCE.md +312 -72
  158. package/dist/system/assets/docs/HARNESS_EXAMPLES.md +172 -0
  159. package/dist/system/assets/docs/HARNESS_PATTERNS.md +562 -0
  160. package/dist/system/assets/docs/META_PROMPT.md +68 -0
  161. package/dist/system/assets/docs/PROLOG_SNIPPETS.md +117 -0
  162. package/dist/system/assets/index.d.ts +9 -17
  163. package/dist/system/assets/index.d.ts.map +1 -1
  164. package/dist/system/assets/index.js +26 -85
  165. package/dist/system/assets/index.js.map +1 -1
  166. package/dist/system/runtime/agentvm-manager.d.ts +9 -2
  167. package/dist/system/runtime/agentvm-manager.d.ts.map +1 -1
  168. package/dist/system/runtime/agentvm-manager.js +70 -44
  169. package/dist/system/runtime/agentvm-manager.js.map +1 -1
  170. package/dist/system/runtime/media.d.ts +23 -0
  171. package/dist/system/runtime/media.d.ts.map +1 -0
  172. package/dist/system/runtime/media.js +55 -0
  173. package/dist/system/runtime/media.js.map +1 -0
  174. package/dist/system/runtime/shell-limits.d.ts +21 -0
  175. package/dist/system/runtime/shell-limits.d.ts.map +1 -0
  176. package/dist/system/runtime/shell-limits.js +39 -0
  177. package/dist/system/runtime/shell-limits.js.map +1 -0
  178. package/dist/system/runtime/shell-manager.d.ts +8 -3
  179. package/dist/system/runtime/shell-manager.d.ts.map +1 -1
  180. package/dist/system/runtime/shell-manager.js +56 -39
  181. package/dist/system/runtime/shell-manager.js.map +1 -1
  182. package/dist/system/runtime/shell-tool-events.js +5 -0
  183. package/dist/system/runtime/shell-tool-events.js.map +1 -1
  184. package/dist/system/runtime/token-usage.d.ts +2 -0
  185. package/dist/system/runtime/token-usage.d.ts.map +1 -1
  186. package/dist/system/runtime/token-usage.js +7 -0
  187. package/dist/system/runtime/token-usage.js.map +1 -1
  188. package/dist/tools.d.ts +3 -21
  189. package/dist/tools.d.ts.map +1 -1
  190. package/dist/tools.js +14 -168
  191. package/dist/tools.js.map +1 -1
  192. package/dist/types.d.ts +80 -118
  193. package/dist/types.d.ts.map +1 -1
  194. package/dist/validate.d.ts +19 -0
  195. package/dist/validate.d.ts.map +1 -0
  196. package/dist/validate.js +338 -0
  197. package/dist/validate.js.map +1 -0
  198. package/dist/visualize/index.d.ts +52 -0
  199. package/dist/visualize/index.d.ts.map +1 -0
  200. package/dist/visualize/index.js +189 -0
  201. package/dist/visualize/index.js.map +1 -0
  202. package/package.json +17 -15
  203. package/src/prolog-src/deepclause_analysis.pl +10 -2
  204. package/src/prolog-src/deepclause_mi.pl +2245 -41
  205. package/dist/cli/commands.d.ts +0 -42
  206. package/dist/cli/commands.d.ts.map +0 -1
  207. package/dist/cli/commands.js +0 -246
  208. package/dist/cli/commands.js.map +0 -1
  209. package/dist/cli/compile.d.ts +0 -99
  210. package/dist/cli/compile.d.ts.map +0 -1
  211. package/dist/cli/compile.js +0 -363
  212. package/dist/cli/compile.js.map +0 -1
  213. package/dist/cli/default-skills.d.ts +0 -10
  214. package/dist/cli/default-skills.d.ts.map +0 -1
  215. package/dist/cli/default-skills.js +0 -206
  216. package/dist/cli/default-skills.js.map +0 -1
  217. package/dist/cli/interactive.d.ts +0 -2
  218. package/dist/cli/interactive.d.ts.map +0 -1
  219. package/dist/cli/interactive.js +0 -20
  220. package/dist/cli/interactive.js.map +0 -1
  221. package/dist/cli/mcp.d.ts +0 -56
  222. package/dist/cli/mcp.d.ts.map +0 -1
  223. package/dist/cli/mcp.js +0 -138
  224. package/dist/cli/mcp.js.map +0 -1
  225. package/dist/cli/prompt.d.ts +0 -2
  226. package/dist/cli/prompt.d.ts.map +0 -1
  227. package/dist/cli/prompt.js +0 -2
  228. package/dist/cli/prompt.js.map +0 -1
  229. package/dist/cli/search.d.ts +0 -19
  230. package/dist/cli/search.d.ts.map +0 -1
  231. package/dist/cli/search.js +0 -189
  232. package/dist/cli/search.js.map +0 -1
  233. package/dist/cli/tool-args.d.ts +0 -2
  234. package/dist/cli/tool-args.d.ts.map +0 -1
  235. package/dist/cli/tool-args.js +0 -39
  236. package/dist/cli/tool-args.js.map +0 -1
  237. package/dist/cli/tools.d.ts +0 -36
  238. package/dist/cli/tools.d.ts.map +0 -1
  239. package/dist/cli/tools.js +0 -229
  240. package/dist/cli/tools.js.map +0 -1
  241. package/dist/cli/tui/index.d.ts +0 -22
  242. package/dist/cli/tui/index.d.ts.map +0 -1
  243. package/dist/cli/tui/index.js +0 -29
  244. package/dist/cli/tui/index.js.map +0 -1
  245. package/dist/cli/tui.d.ts +0 -167
  246. package/dist/cli/tui.d.ts.map +0 -1
  247. package/dist/cli/tui.js +0 -5228
  248. package/dist/cli/tui.js.map +0 -1
  249. package/dist/compiler_prompt.d.ts +0 -20
  250. package/dist/compiler_prompt.d.ts.map +0 -1
  251. package/dist/compiler_prompt.js +0 -870
  252. package/dist/compiler_prompt.js.map +0 -1
  253. package/dist/deepclause-cli.skill +0 -0
  254. package/dist/prolog-src/deepclause_mi.pl.bak +0 -570
  255. package/dist/system/assets/docs/CONDUCTOR_PROMPT.md +0 -105
  256. package/dist/system/assets/docs/DML_COMPILER_PROMPT.md +0 -700
  257. package/dist/system/assets/docs/TUI.md +0 -150
  258. package/dist/system/assets/recipes/deepclause-coding-workflow/SKILL.md +0 -100
  259. package/dist/system/assets/skills/conductor.dml +0 -76
  260. package/dist/system/assets/skills/deep-planner.dml +0 -412
  261. package/dist/system/assets/skills/plan.dml +0 -429
  262. package/dist/system/assets/skills/security-planner.dml +0 -337
  263. package/dist/system/assets/skills/skill-creator.dml +0 -187
  264. package/dist/system/runtime/catalog-recipes.d.ts +0 -24
  265. package/dist/system/runtime/catalog-recipes.d.ts.map +0 -1
  266. package/dist/system/runtime/catalog-recipes.js +0 -273
  267. package/dist/system/runtime/catalog-recipes.js.map +0 -1
  268. package/dist/system/runtime/catalog-skills.d.ts +0 -50
  269. package/dist/system/runtime/catalog-skills.d.ts.map +0 -1
  270. package/dist/system/runtime/catalog-skills.js +0 -152
  271. package/dist/system/runtime/catalog-skills.js.map +0 -1
  272. package/dist/system/runtime/conductor.d.ts +0 -105
  273. package/dist/system/runtime/conductor.d.ts.map +0 -1
  274. package/dist/system/runtime/conductor.js +0 -732
  275. package/dist/system/runtime/conductor.js.map +0 -1
  276. package/dist/system/runtime/console-capture.d.ts +0 -9
  277. package/dist/system/runtime/console-capture.d.ts.map +0 -1
  278. package/dist/system/runtime/console-capture.js +0 -67
  279. package/dist/system/runtime/console-capture.js.map +0 -1
  280. package/dist/system/runtime/dml-executor.d.ts +0 -52
  281. package/dist/system/runtime/dml-executor.d.ts.map +0 -1
  282. package/dist/system/runtime/dml-executor.js +0 -203
  283. package/dist/system/runtime/dml-executor.js.map +0 -1
  284. package/dist/system/runtime/runtime-tools.d.ts +0 -31
  285. package/dist/system/runtime/runtime-tools.d.ts.map +0 -1
  286. package/dist/system/runtime/runtime-tools.js +0 -312
  287. package/dist/system/runtime/runtime-tools.js.map +0 -1
  288. package/dist/system/runtime/skill-creator.d.ts +0 -38
  289. package/dist/system/runtime/skill-creator.d.ts.map +0 -1
  290. package/dist/system/runtime/skill-creator.js +0 -763
  291. package/dist/system/runtime/skill-creator.js.map +0 -1
  292. package/src/prolog-src/deepclause_mi.pl.bak +0 -570
package/README.md CHANGED
@@ -1,1097 +1,566 @@
1
- # DeepClause TUI Agent, CLI and SDK
1
+ # DeepClause SDK
2
+
3
+ DeepClause is a **Prolog-based runtime for self-modifying agent harnesses**. A
4
+ harness created with DeepClause is a self contained library in the form of a **DML** module. DML (DeepClause Meta Language) is a Prolog DSL with added functionality for LLM model calls, semantic
5
+ judgments (Jev-type models), and constraints. An LLM agent embedded in the runtime reads, extends, and tests code in a live module a turn by
6
+ turn. You drive it from an interactive **REPL**. Using the REPL once can successively build a custom harness that is optimized for a specific use case.
7
+
8
+ DML runs on **SWI-Prolog compiled to WebAssembly** — the whole language runtime
9
+ is in-process and portable, with no native Prolog to install.
10
+
11
+ Most agent stacks contain a lot of separate moving parts: tools in one place,
12
+ prompts in another, memory in a third, and the workflow as a graph or a chain
13
+ somewhere else. DML folds them into one idea — a **predicate**. A skill is a
14
+ clause, a tool is a clause, memory and state are clauses, control flow and
15
+ retries are clause order and backtracking, and a workflow is simply predicates
16
+ calling predicates. Because it is one language in one self-contained file, the
17
+ parts can read, reuse, and extend one another, and a whole harness can be
18
+ inspected, versioned, and moved as a unit.
19
+
20
+ ## Dependencies and acknowledgements
21
+
22
+ DeepClause stands on other people's work, and is grateful for it:
23
+
24
+ - **[Pi](https://pi.dev)** (`@earendil-works/pi-coding-agent` and
25
+ `@earendil-works/pi-ai`) — the `pi` backend reuses Pi's model catalog,
26
+ credential store, streaming, cancellation, and usage accounting, and the
27
+ interactive REPL TUI is built on Pi's terminal UI library
28
+ (`@earendil-works/pi-tui`). Thanks to the **Pi developers** for building and
29
+ sharing it.
30
+ - **[SWI-Prolog](https://www.swi-prolog.org/)** — the Prolog engine that DML
31
+ runs on, compiled to WebAssembly so the whole runtime is in-process and
32
+ portable. SWI-Prolog is created and maintained by **Jan Wielemaker** and the
33
+ SWI-Prolog community.
34
+ - **[Markus Triska](https://www.metalevel.at/)** — his work on
35
+ meta-interpreters, constraint logic programming, and the
36
+ `library(clpfd)`/`library(clpq)` libraries underpins DML's executable
37
+ meta-interpreter and constraint layer.
38
+
39
+ DML, the REPL, and the SDK are original work; these projects are used as
40
+ dependencies and as conceptual foundations.
41
+
42
+ ## Why would I use this?
43
+
44
+ - **Reproducibility.** Control flow, retries, and validation are Prolog clauses
45
+ you can read and re-run, so a DML harness tends to produce the same result shape
46
+ across sessions and machines. The model is consulted only at the points you
47
+ choose, and its outputs are typed where that helps.
48
+ - **Auditability.** Each turn is a transaction: the module is snapshotted, the
49
+ change is committed replace-by-predicate, and the session, event trace, and
50
+ harness versions are recorded and remain queryable. It is possible to see what
51
+ changed, when, and in response to what.
52
+ - **Regulated and high-stakes settings.** Where a workflow has to be reviewed,
53
+ versioned, and reproduced — and where it helps to keep deterministic logic
54
+ separate from model judgment — a small, inspectable harness is easier to
55
+ scrutinise than a prompt. The transaction record and `rollback.` are meant to
56
+ support that kind of review, not replace it.
57
+ - **Research in neurosymbolic AI.** DML offers a concrete substrate for
58
+ combining symbolic reasoning (Prolog, CLP, backtracking) with LLM calls and
59
+ semantic judgments in one program, and for studying how such a system behaves
60
+ as an agent edits it over time (transactions, history, rollback).
61
+
62
+ It is likely not worth it when a single prompt or a short script is enough, or
63
+ when there is no structure you would want to reuse, review, or reproduce.
64
+
65
+ ## The REPL: a living, self-modifying harness
66
+
67
+ The REPL keeps a persistent DML module ("the harness"). You talk to it in two ways:
68
+
69
+ | Input | Mode |
70
+ |---|---|
71
+ | `<plain English>` (default) | **author** — the agent writes, tests, and commits DML |
72
+ | `/goal <dml>` | **run** — query the current harness |
2
73
 
3
- *Update (09/2026): Now also available as an extension for the pi coding agent: [https://github.com/deepclause/deepclause-pi](https://github.com/deepclause/deepclause-pi).*
4
-
5
- Compile markdown specs into executable logic programs. Guaranteed execution semantics for agentic workflows. Comes with a minimal coding agent incl. a nostalgic Borland-style TUI.
6
-
7
- ![docs/overview.png](docs/DeepClause_AI_Logic_Framework_Overview.png)
8
- ![docs/tui.png](docs/tui.png)
9
-
10
-
11
- ## What This Is
12
-
13
- AI skills and tools are everywhere, but most are still just prompts. When a prompt fails, you tweak it. When you need branching logic, you write wrapper code. When you want retry behavior, you build it yourself.
14
-
15
- DeepClause takes a different approach: **compile task descriptions into DML programs** - a Prolog-based language that handles control flow, error recovery, and tool orchestration automatically.
16
-
17
- The three main ways to use DeepClause are:
18
-
19
- 1. Coding Agent
20
- - Specialty: Create executable plans from specs and prompts
21
- 2. General Purpose Automation
22
- - Compile recurring tasks into skills, small logic programs that orchestrate agents, prompts, and deterministic code
23
- 3. Testbed for LLM+Prolog
24
- - Explore how constrained logic, tool calls, and model output interact in a reproducible runtime
25
-
26
- ## Host-provided LLM backend
27
-
28
- DeepClause can run on a model supplied by an embedding host instead of configuring an SDK provider. Pass an `LLMBackend` to `createDeepClause()`:
29
-
30
- ```ts
31
- import { createDeepClause, type LLMBackend } from "deepclause-sdk";
32
-
33
- const llmBackend: LLMBackend = {
34
- async complete(request) {
35
- const response = await hostModel.complete({
36
- messages: request.messages,
37
- tools: request.tools,
38
- signal: request.signal,
39
- });
40
-
41
- return {
42
- text: response.text,
43
- toolCalls: response.toolCalls,
44
- usage: response.usage,
45
- };
46
- },
47
- };
48
-
49
- const deepclause = await createDeepClause({
50
- model: "host-active-model",
51
- llmBackend,
52
- });
53
- ```
54
-
55
- The backend receives model messages, DML task tools, cancellation, token limits, and an optional `onText` callback. It returns text, structured tool calls, usage, and optional opaque `providerData` for replaying provider-native assistant state across agent-loop iterations. When a backend is supplied, DeepClause does not require provider credentials.
56
-
57
- DML-defined tool predicates remain available to `task/N` loops under a runtime tool whitelist. Calls made by those predicates through `exec/2` are still checked against the host policy, so an embedding can expose high-level DML tools without exposing its complete runtime tool registry.
58
-
59
-
60
- ## Benchmark: DeepPlanning Travel Planning
61
-
62
- DeepClause was evaluated on the [DeepPlanning](https://arxiv.org/abs/2601.18137) travel planning benchmark, which tests long-horizon agentic planning with verifiable constraints (time, budget, geography). The benchmark requires agents to gather information via tool calls, reason about local constraints, and produce globally coherent multi-day itineraries evaluated across 8 commonsense dimensions and personalized hard constraints.
63
-
64
- | Agent | Plan Model | Run Model | Composite | Case Acc | Delivery |
65
- |-------|-----------|-----------|-----------|----------|----------|
66
- | Qwen-Agent baseline (paper) | qwen3.6-35b-a3b | qwen3.6-35b-a3b | 22.2% | 0.0% | 82.5% |
67
- | DeepClause DML (direct) | qwen3.6-35b-a3b | qwen3.6-35b-a3b | 36.5% | 0.0% | **98.3%** |
68
- | DeepClause DML (plan-execute) | qwen3.6-plus | qwen3.6-35b-a3b | **42.9%** | 0.0% | 96.7% |
69
-
70
- Full comparison with frontier models from the DeepPlanning paper (travel planning only):
71
-
72
- | Model | CS | PS | Comp | Case Acc |
73
- |-------|-----|-----|------|----------|
74
- | **Non-Reasoning Models** | | | | |
75
- | Anthropic/Claude-4.5-Opus (w/o thinking) | 67.5 | 58.8 | 63.1 | 6.7 |
76
- | Anthropic/Claude-4.5-Sonnet (w/o thinking) | 53.4 | 42.8 | 48.1 | 1.1 |
77
- | Alibaba/Qwen3-Max (w/o thinking) | 36.7 | 30.7 | 31.8 | 0.8 |
78
- | ByteDance/Seed-1.8-minimal | 43.0 | 47.5 | 45.3 | 0.0 |
79
- | Alibaba/Qwen-Plus (w/o thinking) | 37.3 | 13.0 | 25.1 | 0.0 |
80
- | Z.ai/GLM-4.7 (w/o thinking) | 38.9 | 22.5 | 30.7 | 0.0 |
81
- | DeepSeek-AI/DeepSeek-V3.2 (w/o thinking) | 37.4 | 12.1 | 24.7 | 0.0 |
82
- | OpenAI/GPT-5.2-none | 54.3 | 29.9 | 42.1 | 0.4 |
83
- | xAI/Grok-4.1-Fast (non-reasoning) | 39.6 | 19.7 | 29.6 | 0.0 |
84
- | **Reasoning Models** | | | | |
85
- | OpenAI/GPT-5.2-high | 88.5 | 83.3 | 85.8 | 35.0 |
86
- | Anthropic/Claude-4.5-Opus (w/ thinking) | 79.3 | 70.9 | 75.1 | 22.7 |
87
- | OpenAI/GPT-5-high | 78.7 | 65.9 | 72.3 | 18.9 |
88
- | Google/Gemini-3-Flash-Preview | 67.1 | 57.7 | 62.4 | 5.9 |
89
- | Alibaba/Qwen3-Max (w/ thinking) | 64.0 | 61.7 | 62.8 | 13.8 |
90
- | Anthropic/Claude-4.5-Sonnet (w/ thinking) | 65.2 | 58.4 | 61.8 | 7.6 |
91
- | OpenAI/o3 | 76.5 | 55.6 | 66.1 | 11.3 |
92
- | Google/Gemini-3-Pro-Preview | 58.4 | 25.1 | 41.8 | 0.7 |
93
- | Deepseek-AI/DeepSeek-V3.2 (w/ thinking) | 47.4 | 35.0 | 41.2 | 0.7 |
94
- | ByteDance/Seed-1.8-high | 43.6 | 56.7 | 50.1 | 0.0 |
95
- | xAI/Grok-4.1-Fast (reasoning) | 57.1 | 37.7 | 47.4 | 2.7 |
96
- | Alibaba/Qwen-Plus (w/ thinking) | 35.4 | 22.4 | 28.9 | 0.0 |
97
- | Google/Gemini-2.5-Pro | 62.3 | 42.0 | 52.2 | 3.2 |
98
- | Z.ai/GLM-4.7 (w/ thinking) | 44.0 | 44.6 | 44.3 | 0.4 |
99
- | OpenAI/o4-mini | 58.0 | 36.6 | 47.2 | 3.0 |
100
- | Moonshot-AI/Kimi-K2-Thinking | 45.2 | 32.5 | 38.9 | 0.0 |
101
- | qwen3.6-35b-a3b baseline | 44.5 | 0.0 | 22.2 | 0.0 |
102
- | **DeepClause** | | | | |
103
- | DeepClause plan-execute (qwen3.6-35b-a3b) | 32.9 | 40.0 | 36.5 | 0.0 |
104
- | DeepClause plan-execute (plan: qwen3.6-plus, run: qwen3.6-35b-a3b) | 34.1 | 51.7 | **42.9** | 0.0 |
105
-
106
- CS = Commonsense Score, PS = Personalized Score, Comp = Composite Score. Results from the DeepPlanning paper (Table 2, travel planning only) are averaged over four runs across Chinese and English variants; DeepClause results are on the English subset. The DeepClause plan-execute variant outperforms the Qwen-Agent baseline by +93% on composite score (42.9% vs 22.2%) using the same execution model, and matches or exceeds several frontier reasoning models (DeepSeek-V3.2 w/ thinking: 41.2%, Gemini-3-Pro-Preview: 41.8%) — without any internal reasoning capability.
107
-
108
- The plan-execute variant runs in two phases. In the **plan phase**, a stronger model (qwen3.6-plus) analyzes the travel request and generates a self-contained DML file: it derives a system prompt, decomposes the request into 3-6 focused gathering tasks, and assembles DML program that includes all tool definitions and the execution logic. In the **execute phase**, a cheaper model (qwen3.6-35b-a3b) runs the generated DML.
109
-
110
- Example for a generated plan:
74
+ ```text
75
+ dml> add a research(Question, Answer) skill that answers with task/2 and cites sources
76
+ dml> run research on "why is the sky blue?"
77
+ A = "Rayleigh scattering scatters short wavelengths more strongly..."
111
78
 
79
+ dml> /goal research("why is the sky blue?", A). % the same skill, run directly
112
80
  ```
113
- :- use_module(library(http/json)).
114
-
115
- % --- Travel Tool Bridge ---
116
-
117
- run_tool(ToolName, ArgsDict, Result) :-
118
- param(db_path, DbPath),
119
- param(bridge_dir, BridgeDir),
120
- param(bench_dir, BenchDir),
121
- param(python_path, PythonPath),
122
- (var(PythonPath) -> PythonPath = 'python3' ; true),
123
- atom_json_dict(ArgsJson, ArgsDict, []),
124
- format(string(ArgsFile), ".dc_bridge_~w.json", [ToolName]),
125
- exec(write_file(path: ArgsFile, content: ArgsJson), _),
126
- format(string(Cmd), "~w '~w/python-bridge.py' --domain travel --db-path '~w' --bench-dir '~w' --tool ~w --args-file '~w'", [PythonPath, BridgeDir, DbPath, BenchDir, ToolName, ArgsFile]),
127
- exec(bash(command: Cmd), Raw),
128
- parse_bridge_result(Raw, Result).
129
-
130
- tool(query_train_info(Origin, Dest, Date, Result),
131
- "Search for train tickets between two cities on a given date. Returns train number, times, stations, duration, seat class, remaining seats, price.") :-
132
- run_tool(query_train_info, _{origin: Origin, destination: Dest, depDate: Date}, Result).
133
-
134
-
135
- [ ... more tool definitions ...]
136
-
137
- agent_main(Request) :-
138
- system("You are a travel planning agent creating a detailed itinerary for 4 travelers from Zhengzhou to Quanzhou (Nov 12-15, 2025). Execute the planned gathering steps autonomously without asking for user input.\n\nRULES:\n- All information must come from tool results — never fabricate names, prices, or details\n- Restaurant names must be EXACT matches from recommend_restaurants/query_restaurant_details results\n- Use recommend_restaurants with attraction/hotel coordinates passed as STRINGS, not restaurant coordinates\n- Current City on intercity travel days must use 'from CityA to CityB' format (literal 'from' and 'to')\n- Budget: all prices are per-unit; multiply by number of travelers/rooms in the final summary\n- Schedule times must be continuous with no gaps; do not schedule breakfast; full days require lunch+dinner\n- Last day (Nov 15) must end at the departure airport/station for the return journey\n- Select the shortest-duration direct outbound flight, a 4-star hotel with free parking, the 3 highest-rated attractions, and the cheapest restaurant in Donghai Bay area\n\nProceed through all gathering steps, then compile the complete itinerary with continuous daily schedules, exact venue names, and accurate budget calculations."),
139
- user(Request),
140
- task("Search for direct flights from Zhengzhou to Quanzhou on November 12, 2025, and return flights from Quanzhou to Zhengzhou on November 15, 2025, for 4 passengers, identif
141
- ying the shortest-duration direct flight option for the outbound journey."),
142
- task("Search for four-star hotels in Quanzhou with free parking available for check-in on November 12, 2025 and check-out on November 15, 2025, accommodating 4 guests."),
143
- task("Search for and recommend top-rated attractions in Quanzhou, then retrieve details to identify the three highest-rated attractions."),
144
- task("Search for restaurants in the Donghai Bay area of Quanzhou and find the one with the lowest average spending per person."),
145
- task('Based on all gathered information, generate the complete travel itinerary inside <plan></plan> tags. Include day-by-day schedule with times, Current City, attractions,
146
- meals with EXACT restaurant names from tool results, transport details, and a budget summary where per-unit costs are multiplied by number of travelers/rooms.', string(DraftPlan)
147
- ),
148
- task('Review this travel plan for errors and fix them. Check ALL of the following:
149
- 1. BUDGET: Is total cost (per-person costs * travelers, per-room costs * rooms) within budget?
150
- 2. TIME CONTINUITY: Are times continuous with no gaps or overlaps? Each activity end time = next start time.
151
- 3. MEAL RULES: Full sightseeing days need lunch AND dinner. No breakfast. Meals 1-2 hours. At least 2 hours between lunch and dinner.
152
- 4. DAILY STRUCTURE: Every day except last ends at hotel. Last day ends at departure airport/station.
153
- 5. GEOSPATIAL: No teleportation — travel_city between different locations.
154
- 6. DIVERSITY: No repeating restaurants or attractions across days.
155
- 7. NAMES: All names EXACTLY match tool results — no abbreviations or renames.
156
- 8. CURRENT CITY: Intercity days must say "from CityA to CityB".
157
-
158
- Plan to review:
159
- {DraftPlan}
160
-
161
- If the plan has errors, output the CORRECTED plan inside <plan></plan> tags. If it is already correct, output it unchanged inside <plan></plan> tags. Store the final verified plan in VerifiedPlan.', string(VerifiedPlan)),
162
- answer(VerifiedPlan).
163
-
164
- agent_main(Request) :-
165
- system('You are a travel planning assistant. Create a travel plan using the available tools. Output inside <plan></plan> tags with budget summary.'),
166
- user(Request),
167
- task('Create a complete travel plan using all available tools. Output inside <plan></plan> tags.', string(Plan)),
168
- answer(Plan).
169
- ```
170
-
171
-
172
81
 
173
- ## Install and Run
82
+ The default mode is the interesting one: describe what you want and the
83
+ authoring agent edits the module for you through tools, testing as it goes. Ask
84
+ for anything — add a skill, add a tool, change existing logic, run or test code
85
+ in the living module, or just ask a question about the harness.
174
86
 
175
- DeepClause requires Node.js 18+.
87
+ ### A worked session
176
88
 
177
- ### Global install
89
+ A full pass: create a skill, watch the transaction, run it, export it, and load
90
+ it again as a new harness.
178
91
 
179
- ```bash
180
- npm install -g deepclause-sdk
181
-
182
- # Pick one provider and export its API key
183
- export OPENAI_API_KEY="sk-..."
184
- # or: export ANTHROPIC_API_KEY="..."
185
- # or: export GOOGLE_GENERATIVE_AI_API_KEY="..."
186
- # or: export OPENROUTER_API_KEY="..."
187
-
188
- # Initialize the current workspace
189
- deepclause init --model openai:gpt-4o
92
+ **1. Create (one transaction)**
190
93
 
191
- # Inspect the configured slots
192
- deepclause show-model
193
-
194
- # Start the fullscreen conductor TUI
195
- deepclause
196
-
197
- # Or run one headless conductor turn
198
- deepclause -p "Summarize the repository architecture"
199
- ```
94
+ ```text
95
+ dml> add a research(Question, Answer) skill that answers with task/2
200
96
 
201
- ### One-off usage with npx
97
+ ⚙ begin_turn
98
+ ✔ begin_turn · 2ms
99
+ ⚙ assert_many(clauses=module_doc("…"), research(Question, Answer) :- task(…), doc(research/2, …))
100
+ ✔ assert_many · 11ms
101
+ ⚙ execute
102
+ research("Why is the sky blue?", A).
103
+ ▸ Task Answer this research question: Why is the sky blue?
104
+ ✔ Task done
105
+ A = "Rayleigh scattering…"
106
+ ✔ execute · 3.7s
107
+ ⚙ end_turn(summary=Add research/2)
108
+ ✔ end_turn · 4ms — {"committed":true,"changed":["+research/2","+module_doc/1","+doc/2"]}
202
109
 
203
- ```bash
204
- npx deepclause-sdk@latest init --model openai:gpt-4o
205
- npx deepclause-sdk@latest show-model
206
- npx deepclause-sdk@latest
110
+ Added research/2 — a one-call task/2 research skill.
207
111
  ```
208
112
 
209
- All commands except `init`, `help`, `--help`, `--version`, and `-V` expect a `.deepclause/` directory in the current workspace.
210
-
211
- `deepclause init` creates:
212
-
213
- - `.deepclause/config.json`
214
- - `.deepclause/tools/`
215
- - `.deepclause/docs/`
216
- - `.deepclause/docs/TUI.md`
217
- - `.deepclause/system/`
218
- - `.deepclause/system/recipes/`
219
- - `.deepclause/.gitignore`
220
- - seeded local skills: `deep-research` and `research-search-reader`
221
- - seeded example recipe: `deepclause-coding-workflow`
222
- - editable system overrides:
223
- - `conductor.dml`
224
- - `skill-creator.dml`
225
- - `CONDUCTOR_PROMPT.md`
226
- - `DML_COMPILER_PROMPT.md`
227
- - `TASK_PROMPT.md`
228
-
229
- The default recipe is created at `.deepclause/system/recipes/deepclause-coding-workflow/SKILL.md`. It is a real example, not a placeholder: it teaches the conductor how to approach local repository changes with small edits and focused validation. You can edit it, remove it, or add your own recipes next to it.
230
-
231
- Recipes are plain markdown guidance, not executable DML. If you want to add or update one, edit `.deepclause/system/recipes/<slug>/SKILL.md` directly. The conductor can search those recipe files on future turns via `consult_recipes`.
232
-
233
- ## TUI Agent
234
-
235
- Running `deepclause` with no subcommand starts the fullscreen TUI.
236
-
237
- - Session list on the left
238
- - Messages in the center
239
- - Execution log and context summary on the right
240
- - Slash commands such as `/new`, `/sessions`, `/set-model <model> [--slot <slot>]`, `/compile <spec>`, `/skill-creator <spec>`, `/cancel`, and `/<skill> [args]`
241
- - Direct shell commands with `!<command>`, streamed live in the execution pane and cancelled with `/cancel`
242
- - Persistent shell commands with `!!<command>`, which also append the command and its output to the active session transcript so the conductor can see them on the next turn
243
-
244
- Use `!<command>` when you just want an ephemeral shell escape in the execution pane. Use `!!<command>` when the shell result should become part of the conversation state for later conductor turns.
245
-
246
- For non-interactive use, `deepclause -p "..."` runs a single headless conductor turn with a fresh session.
247
-
248
- ### Basic Structure
249
-
250
- The TUI is the interface around a single built-in agent: the conductor.
251
-
252
- - The TUI itself is just the UI shell: session browser, messages pane, execution log, and context view.
253
- - The conductor is the actual agent that receives your prompt each turn and decides what to do.
254
- - The conductor is implemented as a system DML skill plus a system prompt.
255
- - The conductor can answer directly, call an existing local skill, consult the recipe library for workflow guidance, invoke the skill creator to make a new skill, use shell tools, or do web research.
256
-
257
- Conceptually, a TUI turn works like this:
258
-
259
- 1. Load the current session from `.deepclause/sessions/<session-id>/`.
260
- 2. Build the conductor prompt from the resolved conductor prompt template, the current skill catalog, the recipe library, assistant memory, task memory, and session transcript.
261
- 3. Run the conductor DML with the `gateway` model slot.
262
- 4. Stream the conductor's own activity and any child-skill events into the execution log on the right.
263
- 5. Persist the final user/assistant messages, structured `execution-log.jsonl`, and updated usage counters back into the session directory.
264
-
265
- The conductor is the router and orchestrator for the CLI runtime. Normal compiled skills are the workers it delegates to. When the conductor launches a normal skill, that skill runs with the `run` model slot. When it launches the skill creator, that child run uses the `compile` model slot instead.
266
-
267
- ### Skills, Recipes, and the Conductor
268
-
269
- DeepClause separates three things that other agent systems often collapse into one prompt surface.
270
-
271
- - **Conductor**: the built-in router. It owns the conversation, inspects the workspace context, and decides whether to solve directly, run a skill, consult a recipe, or create a new skill.
272
- - **Skills**: executable DML workers stored in `.deepclause/tools/`. These are compiled programs with explicit tool calls, branching, retries, recursion, and parameters.
273
- - **Recipes**: markdown guidance stored in `.deepclause/system/recipes/`. These are instruction packs for workflows, conventions, checklists, and examples. They are searched via `consult_recipes`, not executed as child workers.
274
- - **Skill creator**: the built-in compiler/orchestrator that turns a natural-language spec into a tested local skill.
275
-
276
- That distinction matters in practice:
277
-
278
- - Use a **recipe** when you need to know how to approach a task.
279
- - Use a **skill** when you need a reusable automation that should actually execute.
280
- - Use the **conductor** when you want the system to choose between those options for the current turn.
281
-
282
- If the task is to create or refine workflow guidance itself, add or edit a recipe markdown file under `.deepclause/system/recipes/<slug>/SKILL.md`. Do not send recipe authoring through `deepclause compile` unless you actually want an executable skill instead of a guidance document.
283
-
284
- Minimal recipe example:
113
+ The agent opened a transaction (`begin_turn`), wrote the predicates
114
+ (`assert_many`), tested them with `execute`, and committed with `end_turn` — which
115
+ printed the predicates it changed and recorded a version. Had the turn failed,
116
+ the host would have rolled the module back to exactly its prior state.
285
117
 
286
- ```md
287
- ---
288
- name: DeepClause Coding Workflow
289
- description: Guidance for implementing and validating local repository changes.
290
- tags: [coding, tests, docs]
291
- when_to_use:
292
- - implementing a feature or bug fix in the current repository
293
- priority: high
294
- ---
295
-
296
- # Workflow
297
-
298
- 1. Start from a concrete anchor.
299
- 2. Make the smallest grounded edit.
300
- 3. Run the narrowest validation that can falsify it.
301
- ```
302
-
303
- Minimal skill example:
118
+ **2. Inspect, run, undo**
304
119
 
305
120
  ```text
306
- deepclause compile fix-imports.md
307
- deepclause run .deepclause/tools/fix-imports.dml src/index.ts
308
- ```
309
-
310
- The recipe is guidance. The skill is an executable worker.
311
-
312
- ### The `/plan` Command
313
-
314
- `plan` is a built-in system command that turns a request into a standalone DML plan file under `plans/` in the workspace.
315
-
316
- How it works:
317
-
318
- 1. You provide a request, for example from the TUI as `/plan ...` or through the command listing interface.
319
- 2. DeepClause uses the packaged or workspace-overridden `src/system/assets/skills/plan.dml` implementation to classify the request, collect any needed recipe guidance, and draft a numbered task list.
320
- 3. The plan generator derives a system prompt for the resulting plan, includes the DeepClause coding workflow recipe, and assembles a deterministic `.dml` file.
321
- 4. The generated file is written to `plans/<name>.dml`, validated, and then available to run like any other plan or skill.
322
- 5. In the TUI, `/<plan> [args]` runs a plan from `plans/` when no compiled skill with the same name exists.
323
-
324
- The important design point is that `plan` does not try to invent a whole new agent architecture each time. It produces a small executable plan file from the request, with the runtime and recipes providing the reusable behavior.
325
-
326
- ### How This Differs From Other Agent Systems
121
+ dml> /listing
122
+ skill: Research a question and return a written answer.
327
123
 
328
- Systems like `AGENTS.md`, Cursor rules, Claude Skills, or other instruction-pack formats are mostly about giving the model reusable context. DeepClause supports that same need through **recipes**, but it does not stop there.
124
+ doc/2
125
+ doc(research/2,"Answer a question in one model call. research(+Question, -Answer). …").
329
126
 
330
- What is different here:
127
+ module_doc/1
128
+ module_doc("Research a question and return a written answer. …").
331
129
 
332
- - DeepClause keeps **guidance** and **execution** separate. Recipes are markdown guidance; skills are compiled programs.
333
- - A DeepClause skill is not just a saved prompt. It is a DML program that the runtime executes with Prolog semantics.
334
- - The conductor can decide between **consulting a recipe**, **running a compiled skill**, or **creating a new skill**.
335
- - Model choice is split by role: `gateway` for orchestration, `run` for worker execution, and `compile` for skill creation.
336
- - The compiled `.dml` is inspectable and versionable, so the automation logic is explicit instead of hidden in a long prompt.
130
+ research/2
131
+ research(A,B) :-
132
+ task("Answer this question: {A}",B).
337
133
 
338
- ### Memory Tools
134
+ dml> /goal research("Why is the sky blue?", A).
135
+ A = "Rayleigh scattering…"
339
136
 
340
- The memory tools are there so the conductor can keep durable technical notes across turns instead of re-deriving everything from scratch every time.
137
+ dml> /rollback
138
+ rolled back harness: version 1 → 0
341
139
 
342
- - `messages.jsonl` is the conversation transcript. This is the raw history of user and assistant messages.
343
- - `assistant-memory.md` is long-lived assistant context that gets injected into the conductor prompt each turn.
344
- - `task-memory.md` is technical working memory: commands that worked, failure modes, local architecture notes, repair strategies, and other distilled learnings.
345
-
346
- In the current conductor, memory updates are produced as part of the main `task(...)` call. The conductor asks the model for two outputs:
347
-
348
- - `FinalAnswer`: the user-facing reply
349
- - `MemoryUpdate`: the complete updated task-memory markdown, or `NONE`
350
-
351
- When `MemoryUpdate` contains actual content, the runtime persists it through `update_memory`, which replaces `task-memory.md` with the complete updated memory contents.
352
-
353
- That distinction matters:
354
-
355
- - use the transcript for exact conversation history
356
- - use task memory for compressed technical learnings that should help future turns
357
- - use assistant memory for stable higher-level context, tone, or persistent instructions
358
-
359
- In the current CLI runtime, task memory is the main writable memory channel exposed to the conductor. Assistant memory is loaded and shown in the TUI, but it is not automatically updated by a built-in conductor tool in the same way.
140
+ dml> /goal research("Why is the sky blue?", A).
141
+ false. % the skill is gone
142
+ ```
360
143
 
361
- ### Session and Memory Files
144
+ `end_turn` is the only commit point, and `/rollback` moves the harness back one
145
+ committed version (here, to the baseline) — so nothing is committed silently.
362
146
 
363
- Each TUI session lives under `.deepclause/sessions/<session-id>/`:
147
+ **3. Export**
364
148
 
365
149
  ```text
366
- .deepclause/
367
- sessions/
368
- <session-id>/
369
- session.json
370
- messages.jsonl
371
- execution-log.jsonl
372
- assistant-memory.md
373
- task-memory.md
374
- usage.json
375
- specs/
150
+ dml> /export research.dml
151
+ exported 3 clauses, 0 tools, 0 scripts → research.dml
376
152
  ```
377
153
 
378
- - `session.json` stores the session title and timestamps.
379
- - `messages.jsonl` is the append-only user/assistant transcript that gets replayed into future conductor turns.
380
- - `execution-log.jsonl` stores structured JSONL records for conductor turns, direct `/skill` runs, direct `/skill-creator` runs, child-skill events, tool calls, streamed model output, errors, and completion summaries.
381
- - `assistant-memory.md` is loaded into the conductor prompt as stable assistant context.
382
- - `task-memory.md` is loaded into the conductor prompt as technical working memory.
383
- - `usage.json` stores token usage summaries by model.
384
- - `specs/` is used when the conductor invokes the skill creator and saves generated spec drafts for that session.
385
-
386
- When a task fails, looks stuck, or needs to be retried, `execution-log.jsonl` is the first file to inspect. It gives you the concrete failing tool call, streamed model behavior, and any successful prior pattern in the same session instead of forcing you to guess from the final transcript alone.
387
-
388
- In the CLI runtime today, task memory is the actively updated memory channel: the conductor can emit a `MemoryUpdate`, which persists through `update_memory` into `task-memory.md`. `assistant-memory.md` is still loaded every turn, but it is primarily something you inspect or edit manually unless you build additional tooling around it.
389
-
390
- ### Hacking the Conductor and Skill Creator
391
-
392
- There are two levels of customization.
393
-
394
- #### 1. Workspace-local system overrides
154
+ `research.dml` is a plain DML file: commit it, diff it, mail it. Use a `.zip`
155
+ target to bundle linked `script_file/2` scripts.
395
156
 
396
- If you want to customize behavior for one workspace without modifying the package, place override files here:
397
-
398
- - `.deepclause/system/conductor.dml`
399
- - `.deepclause/system/skill-creator.dml`
400
- - `.deepclause/system/CONDUCTOR_PROMPT.md`
401
- - `.deepclause/system/DML_COMPILER_PROMPT.md`
402
- - `.deepclause/system/TASK_PROMPT.md`
403
- - `.deepclause/system/recipes/<recipe-slug>/SKILL.md`
404
-
405
- When present, the CLI runtime prefers those files over the packaged system DML and system prompt markdown. For recipes, workspace files override packaged recipes with the same slug.
406
-
407
- `.deepclause/system/TASK_PROMPT.md` is the markdown template used for `task(...)` and `prompt(...)` harness calls. `deepclause init` seeds it into the workspace, and the runtime resolves that workspace copy before falling back to the packaged default.
408
-
409
- #### 2. Source-level hacking in this repository
410
-
411
- If you are developing DeepClause itself, these are the main files to edit:
412
-
413
- - `src/system/assets/skills/conductor.dml` - the conductor's DML logic
414
- - `src/system/assets/skills/skill-creator.dml` - the skill creator's DML logic
415
- - `src/system/assets/docs/CONDUCTOR_PROMPT.md` - the conductor system prompt template
416
- - `src/system/assets/docs/DML_COMPILER_PROMPT.md` - the skill creator/compiler system prompt template
417
- - `src/system/assets/docs/TASK_PROMPT.md` - the `task(...)` / `prompt(...)` harness template
418
- - `src/system/assets/recipes/` - packaged default recipes copied into new workspaces
419
- - `src/system/runtime/conductor.ts` - session loading, memory injection, tool registration, child-skill routing
420
- - `src/system/runtime/skill-creator.ts` - compile-slot execution, skill-creator tool registration, validation/testing/deploy flow
421
- - `src/system/runtime/catalog-recipes.ts` - recipe discovery, frontmatter parsing, and query matching
422
-
423
- Notes:
424
-
425
- - The conductor uses the `gateway` model slot.
426
- - Normal compiled skills use the `run` model slot.
427
- - The skill creator uses the `compile` model slot.
428
- - The TUI context pane shows the resolved source paths for the conductor DML/prompt, skill creator DML/prompt, and task prompt template.
429
- - Changes to those `.deepclause/system/` files are picked up on the next conductor turn, skill-creator run, or `task(...)` / `prompt(...)` execution; a dedicated TUI reload is not required.
430
-
431
- After source-level changes, rebuild the package:
157
+ **4. Load it elsewhere (a harness from somewhere else)**
432
158
 
433
159
  ```bash
434
- npm install
435
- npm run build
160
+ deepclause repl -l research.dml
436
161
  ```
437
162
 
438
- If you want to run the CLI from a source checkout while hacking on it:
163
+ Loading a file targets the harness named after it (`research`), creating it if
164
+ needed. The file becomes that harness's **baseline**, so it works with no prior
165
+ history: `/rollback` floors at the loaded file, never at empty.
166
+
167
+ **5. Several harnesses in one project**
439
168
 
440
169
  ```bash
441
- npm install
442
- npm run build
443
- npm run cli -- init
444
- npm run cli --
170
+ deepclause repl # harness `main`
171
+ deepclause repl --harness support # harness `support`
172
+ deepclause repl -l research.dml # harness `research`
445
173
  ```
446
174
 
447
- ## Model and Provider Configuration
448
-
449
- DeepClause separates model choice into three slots:
175
+ Each harness has its own content and version history under
176
+ `.deepclause/repl/harnesses/<name>/`. A fresh session loads its harness's current
177
+ content (the agent continues what is there instead of re-creating it), and
178
+ `/rollback` never crosses harnesses.
450
179
 
451
- - `gateway` - conductor and orchestration turns
452
- - `run` - compiled skill execution
453
- - `compile` - skill compilation and `_skill-creator`
180
+ ### Example: build a coding agent
454
181
 
455
- The canonical model id format is `provider:model`, but the CLI also accepts `provider/model` and, for common built-ins, bare model names that it can infer.
182
+ You can ask for a whole **capability**, not just a one-off answer:
456
183
 
457
- Example `.deepclause/config.json`:
184
+ ```text
185
+ dml> build me a coding agent harness for this repo
186
+
187
+ ⚙ listing
188
+ ✔ listing · 1ms
189
+ ⚙ begin_turn
190
+ ✔ begin_turn · 2ms
191
+ ⚙ define(head=run_shell(Command, Output), clauses=run_shell(Command, Output) :- exec(bash(…), Result), …)
192
+ ✔ define · 31ms
193
+ ⚙ define(head=fs_read(Path, Text), clauses=fs_read(Path, Text) :- read_file(Path, Text).)
194
+ ✔ define · 6ms
195
+ ⚙ define(head=fs_write(Path, Content), clauses=fs_write(Path, Content) :- write_file(Path, Content).)
196
+ ✔ define · 5ms
197
+ ⚙ define(head=fs_grep(Pattern, Path, Matches), clauses=fs_grep(Pattern, Path, Matches) :- …)
198
+ ✔ define · 7ms
199
+ ⚙ assert_many(clauses=tool(run_shell(…)) :- run_shell(…). tool(fs_read(…)) :- …. …)
200
+ ✔ assert_many · 4ms
201
+ ⚙ define(head=explain(Question, Answer), clauses=explain(Question, Answer) :- system(…), with_tools(…).)
202
+ ✔ define · 8ms
203
+ ⚙ define(head=patch(File, Issue, Summary), clauses=patch(File, Issue, Summary) :- system(…), with_tools(…).)
204
+ ✔ define · 9ms
205
+ ⚙ execute
206
+ fs_read("package.json", T), run_shell("npm test", R).
207
+ ✔ execute · 1.4s
208
+ ⚙ end_turn(summary=Add coding-agent skills: run_shell/fs_read/fs_write/fs_grep + explain/patch)
209
+ ✔ end_turn · 12ms — {"committed":true,"changed":["+run_shell/2","+fs_read/2","+fs_write/2","+fs_grep/3","+explain/2","+patch/3"]}
210
+
211
+ A coding-agent harness is ready: a small shell/file toolset exposed to `task/N`, plus
212
+ `explain/2` and `patch/3` skills that scope those tools per task.
213
+ ```
214
+
215
+ The harness it built (trimmed):
458
216
 
459
- ```json
460
- {
461
- "models": {
462
- "gateway": "openai:gpt-4o",
463
- "run": "openrouter:google/gemini-2.5-flash",
464
- "compile": "anthropic:claude-sonnet-4-20250514"
465
- },
466
- "temperatures": {
467
- "gateway": 0.7,
468
- "run": 0.7,
469
- "compile": 0.4
470
- },
471
- "providers": {
472
- "openai": {
473
- "apiKey": "${OPENAI_API_KEY}"
474
- },
475
- "anthropic": {
476
- "apiKey": "${ANTHROPIC_API_KEY}"
477
- },
478
- "google": {
479
- "apiKey": "${GOOGLE_GENERATIVE_AI_API_KEY}"
480
- },
481
- "openrouter": {
482
- "apiKey": "${OPENROUTER_API_KEY}",
483
- "baseUrl": "https://openrouter.ai/api/v1"
484
- }
485
- },
486
- "agentvm": {
487
- "network": false
488
- },
489
- "workspace": "./workspace",
490
- "dmlBase": ".deepclause/tools"
491
- }
492
- ```
217
+ ```prolog
218
+ module_doc("Coding agent: read, search, and edit a repository and run its tests.").
493
219
 
494
- Configuration values support `${ENV_VAR}` and `$ENV_VAR` interpolation.
220
+ run_shell(Command, Output) :-
221
+ exec(bash(command: Command), Result),
222
+ ( get_dict(stdout, Result, Out) -> Output = Out ; Output = "" ).
495
223
 
496
- ### Setting Models from the CLI
224
+ fs_read(Path, Text) :- read_file(Path, Text).
225
+ fs_write(Path, Content) :- write_file(Path, Content).
497
226
 
498
- ```bash
499
- # Update all three slots
500
- deepclause set-model openai:gpt-4o
227
+ fs_grep(Pattern, Path, Matches) :-
228
+ format(atom(Cmd), "grep -rn -- ~w ~w", [Pattern, Path]),
229
+ exec(bash(command: Cmd), Result),
230
+ ( get_dict(stdout, Result, Out) -> Matches = Out ; Matches = "" ).
501
231
 
502
- # Only change the compile slot
503
- deepclause set-model anthropic:claude-sonnet-4-20250514 --slot compile
232
+ % `tool/2` only exposes the predicates above to the nested agent in task/N.
233
+ tool(run_shell(Command, Output), "Run a shell command; returns stdout.") :- run_shell(Command, Output).
234
+ tool(fs_read(Path, Text), "Read a workspace file.") :- fs_read(Path, Text).
235
+ tool(fs_write(Path, Content), "Write a workspace file.") :- fs_write(Path, Content).
236
+ tool(fs_grep(Pattern, Path, Matches), "Search a path; returns matching lines.") :- fs_grep(Pattern, Path, Matches).
504
237
 
505
- # Use OpenRouter for the conductor only
506
- deepclause set-model openrouter:google/gemini-2.5-flash --slot gateway
238
+ doc(explain/2, "Explain code relevant to a question. explain(+Question, -Answer).").
239
+ explain(Question, Answer) :-
240
+ system("You are a coding assistant working in a repository. Cite file paths and line numbers."),
241
+ with_tools([run_shell, fs_read, fs_grep],
242
+ task("Answer this question about the repository: {Question}", Answer)).
507
243
 
508
- # Inspect the resolved slot values
509
- deepclause show-model
244
+ doc(patch/3, "Apply a minimal fix and run the tests. patch(+File, +Issue, -Summary).").
245
+ patch(File, Issue, Summary) :-
246
+ system("Make the smallest change that fixes the issue. Run the project's tests and report the result."),
247
+ with_tools([run_shell, fs_read, fs_write, fs_grep],
248
+ task("Fix this issue in {File}: {Issue}. Then run the tests and report what changed.", Summary)).
510
249
  ```
511
250
 
512
- ### Provider Notes
513
-
514
- | Provider | Canonical example | API key env var | Notes |
515
- |----------|-------------------|-----------------|-------|
516
- | OpenAI | `openai:gpt-4o` | `OPENAI_API_KEY` | You can also set `providers.openai.baseUrl` for an OpenAI-compatible endpoint. |
517
- | Anthropic | `anthropic:claude-sonnet-4-20250514` | `ANTHROPIC_API_KEY` | Native Anthropic adapter. |
518
- | Google | `google:gemini-2.5-flash` | `GOOGLE_GENERATIVE_AI_API_KEY` | Native Google Generative AI adapter. |
519
- | OpenRouter | `openrouter:anthropic/claude-sonnet-4` | `OPENROUTER_API_KEY` | Use any OpenRouter model path. |
520
- | Custom | `custom:local:qwen3-32b` | `LLM_PROVIDER_LOCAL_API_KEY` | Uses the OpenAI-compatible transport with a custom base URL. |
521
-
522
- ### Custom Provider
251
+ Use it:
523
252
 
524
- `custom:` is for OpenAI-compatible endpoints that you want to name explicitly instead of pretending they are one of the built-in providers.
253
+ ```text
254
+ dml> /goal explain("where are the CLI entry points?", A).
255
+ A = "…"
525
256
 
526
- Format:
257
+ dml> /goal patch("src/cli.ts", "the --help flag is missing", S).
258
+ S = "…"
527
259
 
528
- ```text
529
- custom:<provider-name>:<model-name>
260
+ dml> /export coding_agent.dml
530
261
  ```
531
262
 
532
- Example:
533
-
534
263
  ```bash
535
- export LLM_PROVIDER_LOCAL_BASE_URL="http://localhost:11434/v1"
536
- export LLM_PROVIDER_LOCAL_API_KEY="dummy"
537
-
538
- deepclause set-model custom:local:qwen3-32b --slot run
539
- deepclause show-model
264
+ deepclause repl -l coding_agent.dml # harness `coding_agent`
265
+ deepclause run coding_agent.dml --goal 'explain("…", A)' # one-shot
540
266
  ```
541
267
 
542
268
  Notes:
543
269
 
544
- - `custom:local:qwen3-32b` reads `LLM_PROVIDER_LOCAL_BASE_URL` and `LLM_PROVIDER_LOCAL_API_KEY`.
545
- - The provider name is uppercased and normalized when constructing env vars, so `custom:my-lab:model-x` becomes `LLM_PROVIDER_MY_LAB_BASE_URL` and `LLM_PROVIDER_MY_LAB_API_KEY`.
546
- - `custom:` providers are not configured under the `providers` object in `config.json`; they are resolved from env vars.
547
- - Internally, `custom:` uses the OpenAI-compatible transport, so your endpoint must speak an OpenAI-style chat/completions API.
548
-
549
- ## Runtime Model
550
-
551
- DeepClause executes DML in a local CLI runtime:
552
-
553
- - **Prolog runtime in WASM**: The DML logic engine runs in SWI-Prolog compiled to WebAssembly.
554
- - **Host shell by default**: Shell tools run in the active local workspace shell.
555
- - **AgentVM on demand**: Pass `--sandbox` when you want shell tools to run inside [AgentVM](https://github.com/deepclause/agentvm) instead.
556
-
557
- This keeps the default workflow simple for local development while still supporting an isolated shell backend when needed.
558
-
559
- The active shell backend also appears in the TUI and runtime events with labels such as `host[bwrap]`, `host[clean-room]`, `host[bwrap strict]`, and `sandbox[agentvm]`.
270
+ - `tool/2` is only an annotation; the *capabilities* are the predicates above, so
271
+ they are reachable from `execute` / `/goal` **and** from `task/N`.
272
+ - `with_tools/2` scopes which tools a `task/N` turn may call — `explain` cannot
273
+ edit files, `patch` can.
274
+ - Because a `task/N` turn can call these tools (and itself), the module is an
275
+ RLM-style harness, not a fixed script.
560
276
 
561
- Host-shell isolation details:
277
+ ### Sessions
562
278
 
563
- - `shell.wrapper: "auto"` prefers `bwrap` on Linux and `sandbox-exec` on macOS when available, then falls back to `clean-room`.
564
- - `shell.wrapper` can also force `clean-room`, `bwrap`, or `sandbox-exec` when you want deterministic behavior across machines.
565
- - `shell.strictIsolation: true` requests stricter host-shell isolation. On Linux with `bwrap`, that adds `--unshare-net` so shell commands lose outbound network access.
566
- - The Linux `bwrap` path preserves common DNS setups where `/etc/resolv.conf` is a symlink into `/run`, so resolver lookups continue to work on `systemd-resolved` hosts.
279
+ The REPL also records sessions, turns, and harness versions under
280
+ `.deepclause/repl/`, so you can pick a conversation back up later. Its harness,
281
+ conversation memory, and turn count are restored:
567
282
 
568
- Linux note: when `bubblewrap` is available, DeepClause will prefer it for host-shell isolation. On some Ubuntu/AppArmor systems, `kernel.apparmor_restrict_unprivileged_userns=1` blocks the unprivileged user-namespace path that `bwrap` needs, which surfaces as `bwrap: setting up uid map: Permission denied`. In that case DeepClause correctly falls back to the clean-room host shell. If you want `bwrap` on those hosts, you need a permitted AppArmor/userns configuration, a setuid-capable `bwrap` install, or `--sandbox` with AgentVM instead.
569
-
570
- ## Beyond Markdown: Why Logic Programming?
571
-
572
- Markdown skills are great for simple, linear workflows. But real-world tasks often need:
573
-
574
- - **Branching logic** - Try approach A, fall back to B if it fails
575
- - **Iteration** - Process a list of items one by one
576
- - **State management** - Isolate context between sub-tasks
577
- - **Error recovery** - Handle failures gracefully
578
- - **Composition** - Build complex skills from simpler ones
283
+ ```bash
284
+ deepclause repl --session last # resume the most recent session
285
+ deepclause repl --session repl_m9x1_1 # …or one by id
286
+ ```
579
287
 
580
- When you give markdown instructions to a typical agentic loop, there's no guarantee these requirements will actually be followed—the LLM might ignore the fallback logic or skip items in a list.
288
+ ### Why Prolog/DML for a self-modifying harness
581
289
 
582
- By compiling to Prolog, you get **guaranteed execution semantics**: backtracking ensures fallbacks happen, recursion processes every item, and unification binds variables correctly. You define *what* should happen—the runtime guarantees *how*.
290
+ An RLM-style harness works best when the harness *is* the program the model
291
+ edits. DML makes that literal:
583
292
 
293
+ - **The harness is data = code.** Skills are predicates, data is facts
294
+ (`city(ch, "Zürich").`). The model reads it (`listing`), queries it
295
+ (`/goal`), extends it, and reuses it — no separate plugin format and no
296
+ recompile step.
297
+ - **One language for logic and language.** Recursion, backtracking, and CLP
298
+ constraints sit next to LLM calls (`task/N`) and typed semantic judgments
299
+ (`choose`, `verify`, `rate`, `probability`) in the same clause.
300
+ - **Composable skills.** A `task/N` call runs a bounded agentic turn that may
301
+ itself call other skills, so the library grows by composition and reuse.
302
+ - **Small and inspectable.** Everything a harness can do is visible in the
303
+ module and the host tool catalog (by default `bash`, plus the human-in-the-loop
304
+ `ask_user` / `input/2`).
584
305
 
306
+ ### Transactions
585
307
 
586
- ## Spec-Driven Development That Compiles
308
+ A prompt turn is an **edit transaction**:
587
309
 
588
- [Spec-driven development](https://martinfowler.com/articles/exploring-gen-ai/sdd-3-tools.html) proposes writing specifications before code, with the spec becoming the source of truth. Current SDD tools (Kiro, spec-kit, Tessl) generate elaborate markdown artifacts that are then fed to coding agents—but the output is still non-deterministic, and you end up reviewing both specs *and* generated code.
310
+ 1. the living module is snapshotted;
311
+ 2. the authoring agent edits predicates with tools (`define`/`assert`/`assert_many`/
312
+ `retract`/`delete`) and tests them with `execute`;
313
+ 3. `end_turn` validates and commits the change, recording a version;
314
+ 4. `rollback` — or a failed turn — restores the harness unchanged.
589
315
 
590
- DeepClause offers a different approach: **specs that compile to actual programs**.
316
+ For anything larger than a couple of predicates the agent is instructed to commit
317
+ working pieces as it goes (`execute` → `end_turn` → `begin_turn`), so a late
318
+ failure does not lose earlier progress.
591
319
 
592
- ```bash
593
- # Your spec
594
- cat > api-client.md << 'EOF'
595
- # API Client Generator
596
- Generate a TypeScript API client from an OpenAPI spec URL.
597
-
598
- ## Arguments
599
- - SpecUrl: URL to an OpenAPI/Swagger JSON specification
600
-
601
- ## Behavior
602
- - Fetch the OpenAPI spec from SpecUrl
603
- - Extract endpoints and types
604
- - Generate typed client code
605
- - Write to output file
606
- EOF
607
-
608
- # Compile it once
609
- deepclause compile api-client.md
610
-
611
- # Run it deterministically, forever
612
- deepclause run api-client.dml "https://api.example.com/openapi.json"
613
- ```
320
+ ### Auditability
614
321
 
615
- The compiled `.dml` is inspectable logic—you can see exactly what it does:
322
+ Every session, turn, event trace, and harness version is written under
323
+ `.deepclause/repl/` — per harness under `harnesses/<name>/` (`harness.dml`,
324
+ `baseline.dml`, `HEAD.json`, `changes.jsonl`, `versions/`) — and exposed to DML
325
+ as queryable `harness_*` facts (`harness_session/5`, `harness_turn/5`,
326
+ `harness_change/5`, `harness_changed/4`, `harness_head/4`, `harness_trace/3`).
327
+ `rollback.` restores the previous version, step by step, and a harness can query
328
+ its own past:
616
329
 
617
330
  ```prolog
618
- tool(fetch_spec(Url, Spec), "Fetch OpenAPI specification") :-
619
- exec(web_fetch(url: Url), Spec).
620
-
621
- agent_main(SpecUrl) :-
622
- system("You are an API client generator..."),
623
- fetch_spec(SpecUrl, Spec),
624
- task("Extract endpoints from: {Spec}", Endpoints),
625
- task("Generate TypeScript client for: {Endpoints}", Code),
626
- exec(vm_exec(command: "cat > client.ts"), Code),
627
- answer("Generated client.ts").
628
- ```
629
-
630
- Unlike traditional SDD where specs guide but don't control, DeepClause specs **become** the executable. The spec *is* the code—just at a higher abstraction level.
631
-
632
- ## Compile and Run a Skill
633
-
634
- ```bash
635
- # Create a task description
636
- cat > .deepclause/tools/explain.md << 'EOF'
637
- # Code Explainer
638
-
639
- Explain what a piece of code does in plain English.
640
-
641
- ## Arguments
642
- - Code: The source code to explain
643
-
644
- ## Behavior
645
- - Break down the code into logical sections
646
- - Explain each section's purpose
647
- - Note any potential issues
648
- EOF
649
-
650
- # Compile to executable DML
651
- deepclause compile .deepclause/tools/explain.md
652
-
653
- # Run it
654
- deepclause run .deepclause/tools/explain.dml "function fib(n) { return n < 2 ? n : fib(n-1) + fib(n-2) }"
655
-
656
- # Or trigger skill creation directly from the TUI with:
657
- # /compile <spec>
658
- # /skill-creator <spec>
659
- # Or update the configured model selection from the TUI with:
660
- # /set-model openai:gpt-4.1 --slot run
661
- # Or run a direct workspace shell command with:
662
- # !npm test
331
+ recent_changes(N, Changes) :-
332
+ findall(Version-Timestamp, harness_change(Version, Timestamp, commit, _, _), All),
333
+ last_n(All, N, Changes).
663
334
  ```
664
335
 
665
- Compilation now runs two security-oriented checks on the generated DML:
336
+ See [`docs/REPL.md`](docs/REPL.md) and
337
+ [`docs/DML_REPL_SESSION_HISTORY.md`](docs/DML_REPL_SESSION_HISTORY.md).
666
338
 
667
- - Prolog static analysis for taint flow, dangerous tool usage, and capability extraction
668
- - An LLM security audit that reviews the generated DML and returns a short Markdown report
339
+ ### Commands
669
340
 
670
- The LLM audit runs by default for `deepclause compile`, `deepclause compile-all`, and one-shot `deepclause run -p ...`. Use `--no-audit` if you want to skip only the LLM review. Static analysis still runs either way.
341
+ `/goal <dml>`, `/listing [filter]`, `/help`, `/reset`, `/rollback`,
342
+ `/compact [notes]`, `/export [file]`, `/model [id]`, `/freeze`/`/unfreeze`,
343
+ `/params`, `/trace`/`/notrace`, `/halt` (aliases `/exit`, `/quit`). The legacy
344
+ `goal:`/`listing.` dotted forms still work.
671
345
 
672
- ## Use Cases
673
-
674
- ### Reliable tools for coding agents
675
-
676
- Give your AI coding assistant more deterministic, inspectable tools instead of hoping prompts work:
346
+ ## Install
677
347
 
678
348
  ```bash
679
- # Define a tool the agent can use
680
- cat > .deepclause/tools/api-docs.md << 'EOF'
681
- # API Documentation Lookup
682
- Search for API documentation and summarize usage patterns.
683
-
684
- ## Arguments
685
- - Query: The API or library name to look up
686
-
687
- ## Tools needed
688
- - web_search
689
-
690
- ## Behavior
691
- - Search for official documentation
692
- - Summarize usage patterns and examples
693
- EOF
694
-
695
- # Compile it once
696
- deepclause compile .deepclause/tools/api-docs.md
697
-
698
- # Now your coding agent can run it reliably
699
- deepclause run .deepclause/tools/api-docs.dml "Stripe PaymentIntent"
349
+ npm install deepclause-sdk
700
350
  ```
701
351
 
702
- The compiled `.dml` files execute the same way every time—no prompt variance, no skipped steps. Build up a library of tools your agent can trust.
703
-
704
- ### Automation pipelines
705
-
706
- Chain compiled programs together:
352
+ ## Quick start
707
353
 
708
354
  ```bash
709
- deepclause run review-code.dml src/handler.ts > review.md
710
- deepclause run summarize.dml review.md
711
- ```
712
-
713
- ### Shareable, versionable task logic
714
-
715
- Check `.dml` files into version control. The logic is inspectable—you can see exactly what the program does, not just what prompt it sends.
716
-
717
- ## Example Task Descriptions
718
-
719
- ### Web Research
720
- ```markdown
721
- # Web Research
722
- Search the web and synthesize findings into a report.
723
-
724
- ## Arguments
725
- - Question: The research question to investigate
726
-
727
- ## Tools needed
728
- - web_search
729
-
730
- ## Behavior
731
- - Search for 3-5 authoritative sources on the Question
732
- - Extract key findings from each
733
- - Write a summary with inline citations
734
- ```
735
-
736
- ### Code Review
737
- ```markdown
738
- # Code Review
739
- Review code for bugs, security issues, and style.
740
-
741
- ## Arguments
742
- - FilePath: Path to the file to review
743
-
744
- ## Tools needed
745
- - vm_exec (to read files)
746
-
747
- ## Behavior
748
- - Read the file at FilePath
749
- - Check for common bugs and anti-patterns
750
- - Identify security concerns
751
- - Suggest improvements
752
- - Be concise and actionable
355
+ deepclause init # write .deepclause/config.json
356
+ deepclause login # sign in to provider, then pick a model
357
+ deepclause repl # interactive
358
+ deepclause repl --session last # resume the most recent session
359
+ deepclause run skill.dml "arg" # one-shot
753
360
  ```
754
361
 
755
- ### Data Analysis
756
- ```markdown
757
- # CSV Analyzer
758
- Analyze a CSV file and describe its contents.
759
-
760
- ## Arguments
761
- - FilePath: Path to the CSV file to analyze
362
+ ### Backends
762
363
 
763
- ## Tools needed
764
- - vm_exec (to run Python)
364
+ `pi` is the default: it reuses pi's model catalog and credential store. `env`
365
+ uses the SDK's own provider/API keys.
765
366
 
766
- ## Behavior
767
- - Load the CSV at FilePath with pandas
768
- - Describe the schema (columns, types, row count)
769
- - Identify interesting patterns
770
- - Generate summary statistics
367
+ ```bash
368
+ deepclause login [--provider <id>] [--api-key <key>|--oauth] [--model provider/model] [--thinking <level>]
369
+ deepclause logout [provider]
370
+ deepclause set-backend status
371
+ deepclause set-backend env # switch to provider API keys
771
372
  ```
772
373
 
773
- ## Available Tools
374
+ For reasoning-capable models, `deepclause login`/`set-backend`/`set-model` prompt
375
+ for a thinking level (`off|minimal|low|medium|high|xhigh|max`); pass `--thinking`
376
+ to skip the picker. It is stored as `backend.thinkingLevel` and forwarded to pi
377
+ only for models that support it.
774
378
 
775
- Common built-in runtime tools:
379
+ Credentials live in pi's agent dir (`~/.pi/agent`) unless `backend.agentDir`
380
+ overrides it. Existing pi installations stay untouched.
776
381
 
777
- | Tool | Description |
778
- |------|-------------|
779
- | `web_search` | Search the web using Brave Search (requires `BRAVE_API_KEY`) |
780
- | `news_search` | Search recent news |
781
- | `url_fetch` | Fetch a URL or save it into the workspace |
782
- | `bash` | Run shell commands in the active workspace shell |
783
- | `vm_exec` | Alias of `bash`; with `--sandbox`, runs in AgentVM |
382
+ ## run
784
383
 
785
- Some tools are runtime-role specific rather than globally available to every skill. For example:
786
-
787
- - the conductor adds tools such as `run_skill`, `create_skill`, and `update_memory`
788
- - the skill creator adds tools such as `list_skills`, `write_file`, `validate_dml`, `test_dml`, and `deploy_skill`
789
-
790
- Additional tools can come from configured MCP servers. Use `deepclause list-tools` to see the built-ins plus anything exposed by your configured MCP servers.
791
-
792
- ## CLI Reference
384
+ `run` uses the **same engine as the REPL**: it opens a module, loads the
385
+ DML file (`.dml` or a `.zip` bundle), runs one entry, and renders events through
386
+ the REPL renderer. The entry is `agent_main/N` (chosen by the number of
387
+ positional arguments) or an explicit `--goal`.
793
388
 
794
389
  ```bash
795
- deepclause init # Set up .deepclause/ folder
796
- deepclause compile <file.md> # Compile Markdown to DML
797
- deepclause compile-all <dir> # Compile all .md files in directory
798
- deepclause run <file.dml> [args] # Execute a compiled skill
799
- deepclause # Start the interactive conductor TUI
800
- deepclause -p <text> # Run one headless conductor turn
801
- deepclause list-commands # List available compiled skills
802
- deepclause list-tools # Show available tools
803
- deepclause show-model # Show gateway/run/compile slots
804
- deepclause set-model <model> # Change all slots or one slot with --slot
390
+ deepclause run <file.dml> [args...] # call agent_main/N
391
+ deepclause run <file.dml> --goal '<dml>' # explicit entry goal
392
+ deepclause run <file.dml> --dry-run # print the resolved entry
393
+ deepclause run <file.dml> --trace t.json --usage u.json
394
+ deepclause run <file.dml> --no-stream --no-events # only outputs/answers
805
395
  ```
806
396
 
807
- ### Run Options
397
+ ## Runtime and sandboxing
808
398
 
809
- ```bash
810
- deepclause run skill.dml "input" \
811
- --model google:gemini-2.5-flash \ # Override the run model for this execution
812
- --stream \ # Stream output
813
- --verbose \ # Show tool calls
814
- --workspace ./data \ # Set working directory
815
- --sandbox # Use AgentVM instead of the local shell
816
- ```
399
+ **Engine.** DML is executed by **SWI-Prolog compiled to WebAssembly**
400
+ (`vendor/swipl-wasm`, loaded through `src/prolog/`). It runs in-process — no
401
+ native Prolog install, no external server — with the standard SWI libraries
402
+ available (constraint solving via `clpfd`, `clpq`, `clpr`; plus regex, dicts,
403
+ and DCGs). Validation runs on the same engine.
817
404
 
818
- ### Compile Options
405
+ **Workspace confinement.** DML file predicates and `bash` all run against the
406
+ active **workspace** (`.` or `--workspace <path>`) using workspace-relative
407
+ paths; harness paths cannot escape it.
819
408
 
820
- `deepclause compile` and `deepclause compile-all` use the `compile` model slot. They accept `--model`, `--provider`, `--temperature`, `--max-attempts`, `--sandbox`, and `--no-audit`.
409
+ **Shell execution.** `bash` is the only capability tool, with two backends:
821
410
 
822
- Static analysis always runs. `--no-audit` disables only the LLM security audit.
411
+ | Backend | When | Notes |
412
+ |---|---|---|
413
+ | host shell | default | isolated by a wrapper: `clean-room`, `bwrap` (bubblewrap), or `sandbox-exec` (macOS); `auto` picks the best available |
414
+ | AgentVM | `--sandbox` | WASM micro-VM; network disabled by default |
823
415
 
824
- One-shot prompt mode uses the same compile pipeline before execution, so `deepclause run -p "..." --no-audit` disables the LLM audit there as well.
416
+ Network access is **off by default** (`agentvm.network: false`), and `bwrap`
417
+ with `shell.strictIsolation: true` also disables it. `--no-tools` registers no
418
+ capability tool at all; `ask_user` / `input/2` remain the human-in-the-loop
419
+ channel.
825
420
 
826
421
  ```bash
827
- deepclause compile skill.md \
828
- --model claude-sonnet-4-20250514 \
829
- --provider anthropic \
830
- --temperature 0.2 \
831
- --max-attempts 4
832
-
833
- deepclause compile-all ./specs \
834
- --model claude-sonnet-4-20250514 \
835
- --provider anthropic \
836
- --no-audit
422
+ deepclause repl --sandbox # run bash inside the AgentVM micro-VM
423
+ deepclause repl --no-tools # no capability host tools
837
424
  ```
838
425
 
839
- ## Configuration
840
-
841
- The main configuration surface is `.deepclause/config.json`.
842
-
843
- The most important fields are covered above in:
844
-
845
- - [Install and Run](#install-and-run)
846
- - [TUI Conductor](#tui-conductor)
847
- - [Model and Provider Configuration](#model-and-provider-configuration)
848
-
849
- Other useful config fields:
850
-
851
426
  ```json
852
427
  {
853
- "agentvm": {
854
- "network": false
855
- },
856
- "shell": {
857
- "wrapper": "auto",
858
- "strictIsolation": false
859
- },
860
- "compaction": {
861
- "enabled": true,
862
- "bindings": [
863
- {
864
- "name": "default-session",
865
- "scope": "session",
866
- "trigger": "before_user_message",
867
- "compactor": {
868
- "source": ".deepclause/system/default-session-compactor.dml",
869
- "sourceType": "file",
870
- "timeoutMs": 15000,
871
- "inheritTools": false
872
- }
873
- },
874
- {
875
- "name": "default-loop",
876
- "scope": "loop",
877
- "trigger": "before_model_call",
878
- "compactor": {
879
- "source": ".deepclause/system/default-loop-compactor.dml",
880
- "sourceType": "file",
881
- "timeoutMs": 15000,
882
- "inheritTools": false
883
- }
884
- }
885
- ]
886
- },
887
- "workspace": "./workspace",
888
- "dmlBase": ".deepclause/tools",
889
- "mcp": {
890
- "servers": {
891
- "filesystem": {
892
- "command": "npx",
893
- "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
894
- }
895
- }
896
- }
428
+ "agentvm": { "network": false },
429
+ "shell": { "wrapper": "auto", "strictIsolation": false }
897
430
  }
898
431
  ```
899
432
 
900
- - `agentvm.network` controls whether shell commands in `--sandbox` mode get outbound network access.
901
- - `shell.wrapper` chooses the host-shell isolation backend: `auto`, `clean-room`, `bwrap`, or `sandbox-exec`.
902
- - `shell.strictIsolation` requests stricter host execution. On Linux with `bwrap`, that disables network access with a separate network namespace.
903
- - `compaction.enabled` toggles the compaction system for session and loop memory.
904
- - `compaction.bindings` attaches DML compactors to runtime hook points such as `before_user_message` and `before_model_call`.
905
- - `workspace` sets the default working directory used by shell/file tools.
906
- - `dmlBase` changes where compiled local skills are written.
907
- - `mcp.servers` registers MCP servers that then appear in `deepclause list-tools`.
908
-
909
- ### Compaction Is Hackable
433
+ ## visualize
910
434
 
911
- The default compaction bindings point at seeded DML files in `.deepclause/system/default-session-compactor.dml` and `.deepclause/system/default-loop-compactor.dml`. Those are ordinary workspace files, so you can edit them directly instead of treating compaction as a black box.
435
+ Turn a harness into a diagram: `visualize` reads the harness `listing`
436
+ (source + `doc/2` annotations) and asks the active model for a Mermaid chart of
437
+ one entry, then renders it.
912
438
 
913
- At the moment, the packaged defaults are intentionally conservative: they skip compaction until the history is at least `8`/`12` messages and roughly `50000` estimated tokens for session/loop history respectively.
914
-
915
- For example, the default session compactor currently gates on:
916
-
917
- ```prolog
918
- should_skip_session_compaction(_MessageCount, EstimatedTokens) :-
919
- EstimatedTokens < 50000.
439
+ ```bash
440
+ deepclause visualize skill.dml -g router/2 --presentation -o router.png
441
+ deepclause visualize skill.dml -g router/2 --spec -o router.spec.png
920
442
  ```
921
443
 
922
- If you want compaction to kick in earlier or later, you have two straightforward options:
923
-
924
- - Edit the seeded DML compactor files in `.deepclause/system/` and change the heuristics directly.
925
- - Repoint `compaction.bindings` in `.deepclause/config.json` to a different file, an inline compactor, or a binding with its own `model`, `provider`, `gasLimit`, `timeoutMs`, `inheritTools`, or `toolPolicy` settings.
444
+ `-g/--goal` names the entry predicate to document. `--presentation` (default) is
445
+ an audience-facing overview (inputs, steps, answer); `--spec` shows engineering
446
+ detail (decisions, `task`/`exec` calls, branches, fallbacks). A `.mmd` output
447
+ writes the Mermaid source; a `.png`/`.svg` output renders it via
448
+ `@mermaid-js/mermaid-cli` (fetched with `npx` on first use) and always writes the
449
+ `.mmd` beside the image.
926
450
 
927
- ## Understanding DML
451
+ ## Media (images)
928
452
 
929
- The compiled `.dml` files use DML (DeepClause Meta Language), a dialect of Prolog designed for AI workflows.
453
+ Images are workspace files referenced by a `media(Path, Mime)` term; the bytes
454
+ never enter Prolog or conversation memory. Read a reference and attach it, and the
455
+ next `task/N` sends it to a vision-capable model:
930
456
 
931
457
  ```prolog
932
- % Generated from research.md
933
- tool(search(Query, Results), "Search the web") :-
934
- exec(web_search(query: Query), Results).
935
-
936
- agent_main(Topic) :-
937
- system("You are a research assistant..."),
938
- task("Research {Topic} and summarize findings."),
939
- answer("Done").
458
+ agent_main :-
459
+ read_media("photos/fox.png", Image),
460
+ attach_media(Image),
461
+ task("Describe the image in one sentence.", Description),
462
+ answer(Description).
940
463
  ```
941
464
 
942
- You can edit DML directly for fine-grained control. See the [DML Reference](./docs/DML_REFERENCE.md) for the full language spec.
943
-
465
+ Only PNG/JPEG/GIF/WebP are accepted, and judgments stay text-only. Image
466
+ generation and video are not implemented — see [`docs/DML_MEDIA.md`](docs/DML_MEDIA.md).
944
467
 
945
- ### Backtracking: Automatic Retry Logic
468
+ ## TypeScript SDK
946
469
 
947
- Prolog's backtracking means you can define multiple approaches. If one fails, execution automatically tries the next:
470
+ ```ts
471
+ import { createDeepClause } from 'deepclause-sdk';
948
472
 
949
- ```prolog
950
- % Try fast approach first, fall back to thorough approach
951
- agent_main(Question) :-
952
- system("Answer concisely."),
953
- task("Answer: {Question}"),
954
- validate_answer, % Fails if answer is inadequate
955
- answer("Done").
956
-
957
- agent_main(Question) :-
958
- system("Be thorough and detailed."),
959
- task("Research and answer: {Question}"),
960
- answer("Done").
473
+ const dc = await createDeepClause({ model: 'gpt-4o', provider: 'openai' });
474
+ for await (const event of dc.runDML(dmlSource, { args: ['topic'] })) {
475
+ if (event.type === 'answer') console.log(event.answer ?? event.content);
476
+ }
477
+ await dc.dispose();
961
478
  ```
962
479
 
963
- If `validate_answer` fails, Prolog backtracks and tries the second clause. No explicit if/else needed. Backtracking resets the execution state (including LLM context) to the original choice point!
964
-
965
- ### Recursion: Processing Lists
480
+ To reuse pi's model and credentials from a host, pass an injected `LLMBackend`
481
+ (`createPiBackend`) and judgment backends (`createLLMJudgeBackend`,
482
+ `createJevJudgeBackend`).
966
483
 
967
- Handle variable-length inputs naturally:
484
+ The REPL is embeddable too:
968
485
 
969
- ```prolog
970
- % Process each file in a list
971
- process_files([]).
972
- process_files([File|Rest]) :-
973
- task("Review {File} for issues."),
974
- process_files(Rest).
975
-
976
- agent_main(Files) :-
977
- process_files(Files),
978
- answer("All files reviewed.").
979
- ```
980
-
981
- ### Memory Isolation: Independent Sub-tasks
982
-
983
- Use `prompt/N` for LLM calls that shouldn't share context:
486
+ ```ts
487
+ import { createHarnessRepl } from 'deepclause-sdk';
984
488
 
985
- ```prolog
986
- agent_main(Topic) :-
987
- system("You are a researcher."),
988
- task("Research {Topic} deeply.", Findings),
989
-
990
- % Independent critique - fresh context, no bias from main research
991
- prompt("As a skeptic, critique: {Findings}", Critique),
992
-
993
- % Back to main context
994
- task("Address this critique: {Critique}"),
995
- answer("Done").
489
+ const repl = await createHarnessRepl({ model: 'gpt-4o', provider: 'openai' });
490
+ for await (const event of repl.query('fact(5, F)')) {
491
+ if (event.type === 'solution') console.log(event.solution?.bindings);
492
+ }
493
+ await repl.dispose();
996
494
  ```
997
495
 
998
- ### Tool Scoping: Controlled Capabilities
496
+ ## Validation
999
497
 
1000
- Limit what tools are available to specific sub-tasks:
498
+ ```ts
499
+ import { validateWithProlog } from 'deepclause-sdk/validate';
1001
500
 
1002
- ```prolog
1003
- tool(dangerous_action(X, Result), "Do something risky") :-
1004
- exec(vm_exec(command: X), Result).
1005
-
1006
- agent_main(Task) :-
1007
- % Main task has all tools
1008
- task("Plan how to: {Task}", Plan),
1009
-
1010
- % Execute with restricted tools - no dangerous_action allowed
1011
- without_tools([dangerous_action], (
1012
- task("Execute this plan safely: {Plan}")
1013
- )),
1014
- answer("Done").
501
+ const { valid, errors, warnings } = await validateWithProlog(dmlSource);
1015
502
  ```
1016
503
 
1017
- ### Composition: Building Blocks
504
+ ## Configuration
1018
505
 
1019
- Define reusable predicates and compose them:
506
+ `.deepclause/config.json` (created by `init`):
1020
507
 
1021
- ```prolog
1022
- % Reusable building blocks
1023
- search_and_summarize(Query, Summary) :-
1024
- exec(web_search(query: Query), Results),
1025
- task("Summarize: {Results}", Summary).
1026
-
1027
- verify_facts(Text, Verified) :-
1028
- task("Fact-check this text: {Text}", Issues),
1029
- (Issues = "none" -> Verified = Text ; fix_issues(Text, Issues, Verified)).
1030
-
1031
- % Compose into a skill
1032
- agent_main(Topic) :-
1033
- search_and_summarize(Topic, Draft),
1034
- verify_facts(Draft, Final),
1035
- answer(Final).
508
+ ```json
509
+ {
510
+ "backend": { "kind": "pi", "model": "anthropic/claude-sonnet-4" },
511
+ "temperatures": { "run": 0.7 },
512
+ "providers": { "openai": { "apiKey": "..." } },
513
+ "agentvm": { "network": false },
514
+ "shell": { "wrapper": "auto", "strictIsolation": false, "timeoutMs": 0, "idleTimeoutMs": 180000 },
515
+ "repl": {
516
+ "tui": "auto",
517
+ "harness": "main",
518
+ "showReasoning": "summary",
519
+ "maxModelCalls": 100,
520
+ "compaction": { "enabled": true, "auto": true },
521
+ "history": { "enabled": true, "dir": ".deepclause/repl", "trace": "summary" }
522
+ },
523
+ "judgment": { "default": "llm", "jev": { "enabled": false } }
524
+ }
1036
525
  ```
1037
526
 
1038
- ### Shared Predicates Across DML Files
527
+ ## Repository layout
1039
528
 
1040
- When a skill grows beyond one file, move reusable predicates into helper files and load them at the top of the main DML. This is useful for shared search helpers, validation predicates, common formatting logic, or domain-specific utilities that multiple skills reuse.
529
+ ```text
530
+ src/
531
+ ├── repl/ # the living-module REPL (session, frames, renderer, auth, history)
532
+ ├── cli/ # init, run, repl, login, set-backend
533
+ ├── system/ # shell/AgentVM, config, bundled docs
534
+ ├── judge/ # semantic judgment backends (llm, jev, mock)
535
+ ├── prolog/ # SWI-Prolog-WASM loader/bridge
536
+ ├── prolog-src/ # deepclause_mi.pl, deepclause_analysis.pl, …
537
+ ├── agent.ts # task/agent loop
538
+ ├── runner.ts # DML execution
539
+ ├── sdk.ts # createDeepClause
540
+ └── validate.ts # DML validation/linting
1041
541
 
1042
- ```prolog
1043
- % .deepclause/tools/repo-review/helpers/search_helpers.dml
1044
- normalize_query(Query, Normalized) :-
1045
- format(string(Normalized), "site:github.com ~w", [Query]).
1046
-
1047
- search_and_summarize(Query, Summary) :-
1048
- normalize_query(Query, Normalized),
1049
- exec(web_search(query: Normalized), Results),
1050
- task("Summarize these results: {Results}", Summary).
542
+ vendor/
543
+ └── swipl-wasm/ # SWI-Prolog compiled to WebAssembly (the DML engine)
1051
544
  ```
1052
545
 
1053
- ```prolog
1054
- % .deepclause/tools/repo-review.dml
1055
- :- use_module(library(lists)).
1056
- :- use_module(library(clpfd)).
1057
- :- consult('.deepclause/tools/repo-review/helpers/search_helpers.dml').
1058
-
1059
- agent_main(Topic) :-
1060
- search_and_summarize(Topic, Summary),
1061
- answer(Summary).
1062
- ```
546
+ Bundled prompt assets: `AGENT_PROMPT.md` (the authoring agent's contract),
547
+ `DML_REFERENCE.md` (language), `DML_AUTHORING.md` (guide),
548
+ `HARNESS_EXAMPLES.md` (idiomatic shapes), `HARNESS_PATTERNS.md` (harness shapes
549
+ by use case), `PROLOG_SNIPPETS.md` (tested building blocks).
1063
550
 
1064
- - Use `:- use_module(library(...)).` for standard SWI-Prolog libraries such as `lists`, `clpfd`, `clpq`, and `clpr`.
1065
- - Use `:- consult('workspace-relative/path.dml').` for local shared DML helpers inside the workspace.
1066
- - Local `:- use_module('.deepclause/tools/repo-review/helpers/search_helpers.dml').` also works as a convenience alias, but today it has consult-style loading semantics rather than full SWI module export filtering.
1067
- - When a helper belongs to one skill, keep it in a dedicated subfolder such as `.deepclause/tools/<skill-slug>/helpers/` so the skill and its shared predicates stay together.
551
+ ## Development
1068
552
 
1069
- ## Using as a Library
1070
-
1071
- Embed DeepClause in your own applications:
1072
-
1073
- ```typescript
1074
- import { createDeepClause } from 'deepclause-sdk';
1075
-
1076
- const dc = await createDeepClause({
1077
- model: 'gpt-4o',
1078
- apiKey: process.env.OPENAI_API_KEY,
1079
- });
1080
-
1081
- for await (const event of dc.runDML(code)) {
1082
- console.log(event.type, event.content);
1083
- }
1084
-
1085
- await dc.dispose();
553
+ ```bash
554
+ npm run build # tsc + copy prolog + assets
555
+ npm test # vitest
556
+ npm run repl # deepclause repl via tsx
1086
557
  ```
1087
558
 
1088
- See [sdk-examples/](./sdk-examples/) for more.
1089
-
1090
- ## More Resources
1091
-
1092
- - [DML Reference](./docs/DML_REFERENCE.md) - Full language documentation
1093
- - [Examples](./dml-examples/) - Sample DML programs
1094
- - [Architecture](./ARCHITECTURE.md) - How it works
559
+ See [`docs/`](docs/): [`STATUS.md`](docs/STATUS.md) (current state),
560
+ [`REPL.md`](docs/REPL.md),
561
+ [`DML_REPL_PROPOSAL.md`](docs/DML_REPL_PROPOSAL.md),
562
+ [`DML_REPL_SESSION_HISTORY.md`](docs/DML_REPL_SESSION_HISTORY.md),
563
+ [`JUDGMENT_BACKENDS.md`](docs/JUDGMENT_BACKENDS.md).
1095
564
 
1096
565
  ## License
1097
566