deepclause-sdk 0.4.0 → 0.6.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.
- package/README.md +134 -2
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +154 -28
- package/dist/agent.js.map +1 -1
- package/dist/cli/config.d.ts +150 -140
- package/dist/cli/config.d.ts.map +1 -1
- package/dist/cli/config.js +3 -0
- package/dist/cli/config.js.map +1 -1
- package/dist/cli/login.d.ts +2 -1
- package/dist/cli/login.d.ts.map +1 -1
- package/dist/cli/login.js +15 -2
- package/dist/cli/login.js.map +1 -1
- package/dist/cli/repl.d.ts +54 -1
- package/dist/cli/repl.d.ts.map +1 -1
- package/dist/cli/repl.js +437 -54
- package/dist/cli/repl.js.map +1 -1
- package/dist/cli/set-backend.d.ts +2 -2
- package/dist/cli/set-backend.d.ts.map +1 -1
- package/dist/cli/set-backend.js +54 -8
- package/dist/cli/set-backend.js.map +1 -1
- package/dist/cli/work.d.ts +16 -0
- package/dist/cli/work.d.ts.map +1 -0
- package/dist/cli/work.js +45 -0
- package/dist/cli/work.js.map +1 -0
- package/dist/index.d.ts +8 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/prolog-src/deepclause_mi.pl +2426 -253
- package/dist/prolog-src/deepclause_strings.pl +36 -3
- package/dist/repl/agent.d.ts +5 -0
- package/dist/repl/agent.d.ts.map +1 -1
- package/dist/repl/agent.js +19 -7
- package/dist/repl/agent.js.map +1 -1
- package/dist/repl/auth.d.ts +6 -3
- package/dist/repl/auth.d.ts.map +1 -1
- package/dist/repl/auth.js +55 -5
- package/dist/repl/auth.js.map +1 -1
- package/dist/repl/backend.d.ts +24 -0
- package/dist/repl/backend.d.ts.map +1 -1
- package/dist/repl/backend.js +292 -12
- package/dist/repl/backend.js.map +1 -1
- package/dist/repl/compaction.d.ts +2 -0
- package/dist/repl/compaction.d.ts.map +1 -1
- package/dist/repl/compaction.js +9 -0
- package/dist/repl/compaction.js.map +1 -1
- package/dist/repl/event-history.d.ts +4 -0
- package/dist/repl/event-history.d.ts.map +1 -0
- package/dist/repl/event-history.js +33 -0
- package/dist/repl/event-history.js.map +1 -0
- package/dist/repl/harness-tools.d.ts +25 -18
- package/dist/repl/harness-tools.d.ts.map +1 -1
- package/dist/repl/harness-tools.js +103 -34
- package/dist/repl/harness-tools.js.map +1 -1
- package/dist/repl/history.d.ts +52 -2
- package/dist/repl/history.d.ts.map +1 -1
- package/dist/repl/history.js +113 -4
- package/dist/repl/history.js.map +1 -1
- package/dist/repl/index.d.ts +27 -5
- package/dist/repl/index.d.ts.map +1 -1
- package/dist/repl/index.js +27 -0
- package/dist/repl/index.js.map +1 -1
- package/dist/repl/reference.d.ts +31 -0
- package/dist/repl/reference.d.ts.map +1 -0
- package/dist/repl/reference.js +143 -0
- package/dist/repl/reference.js.map +1 -0
- package/dist/repl/render.d.ts +3 -1
- package/dist/repl/render.d.ts.map +1 -1
- package/dist/repl/render.js +7 -0
- package/dist/repl/render.js.map +1 -1
- package/dist/repl/session.d.ts +128 -23
- package/dist/repl/session.d.ts.map +1 -1
- package/dist/repl/session.js +895 -196
- package/dist/repl/session.js.map +1 -1
- package/dist/repl/tui/autocomplete.d.ts.map +1 -1
- package/dist/repl/tui/autocomplete.js +5 -1
- package/dist/repl/tui/autocomplete.js.map +1 -1
- package/dist/repl/tui/renderer.d.ts +2 -1
- package/dist/repl/tui/renderer.d.ts.map +1 -1
- package/dist/repl/tui/renderer.js +20 -3
- package/dist/repl/tui/renderer.js.map +1 -1
- package/dist/repl/tui/status-bar.d.ts +5 -2
- package/dist/repl/tui/status-bar.d.ts.map +1 -1
- package/dist/repl/tui/status-bar.js +8 -3
- package/dist/repl/tui/status-bar.js.map +1 -1
- package/dist/repl/tui/tool-pane.d.ts +1 -1
- package/dist/repl/tui/tool-pane.d.ts.map +1 -1
- package/dist/repl/tui/tool-pane.js +13 -7
- package/dist/repl/tui/tool-pane.js.map +1 -1
- package/dist/repl/tui/work-view.d.ts +10 -0
- package/dist/repl/tui/work-view.d.ts.map +1 -0
- package/dist/repl/tui/work-view.js +28 -0
- package/dist/repl/tui/work-view.js.map +1 -0
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +50 -19
- package/dist/runner.js.map +1 -1
- package/dist/runtime-identity.json +10 -0
- package/dist/system/assets/docs/AGENT_PROMPT.md +265 -3008
- package/dist/system/assets/docs/DML_AUTHORING.md +81 -299
- package/dist/system/assets/docs/DML_BASICS.md +93 -0
- package/dist/system/assets/docs/DML_DEBUGGING.md +73 -0
- package/dist/system/assets/docs/DML_FORMS.md +94 -728
- package/dist/system/assets/docs/DML_MEDIA.md +63 -0
- package/dist/system/assets/docs/DML_PROCESSES.md +100 -0
- package/dist/system/assets/docs/DML_PYTHON.md +74 -0
- package/dist/system/assets/docs/DML_REFERENCE.md +224 -1971
- package/dist/system/assets/docs/DML_SHELL.md +107 -0
- package/dist/system/assets/docs/DML_TASKS.md +112 -0
- package/dist/system/assets/docs/HARNESS_EXAMPLES.md +255 -179
- package/dist/system/assets/docs/HARNESS_PATTERNS.md +65 -538
- package/dist/system/assets/docs/LOCAL_AGENT_PROMPT.md +186 -0
- package/dist/system/assets/docs/PROLOG_SNIPPETS.md +61 -154
- package/dist/system/assets/index.d.ts +1 -1
- package/dist/system/assets/index.d.ts.map +1 -1
- package/dist/system/assets/index.js +7 -0
- package/dist/system/assets/index.js.map +1 -1
- package/dist/system/environment.d.ts +1 -1
- package/dist/system/environment.d.ts.map +1 -1
- package/dist/system/environment.js +10 -6
- package/dist/system/environment.js.map +1 -1
- package/dist/system/runtime/shell-manager.d.ts +1 -1
- package/dist/system/runtime/shell-manager.d.ts.map +1 -1
- package/dist/types.d.ts +49 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/work/index.d.ts +82 -0
- package/dist/work/index.d.ts.map +1 -0
- package/dist/work/index.js +232 -0
- package/dist/work/index.js.map +1 -0
- package/package.json +12 -3
- package/src/prolog-src/deepclause_mi.pl +2426 -253
- package/src/prolog-src/deepclause_strings.pl +36 -3
|
@@ -1,2024 +1,277 @@
|
|
|
1
|
-
# DML
|
|
1
|
+
# DML language API
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
DML is Prolog plus model, host, process, media and human-interaction handlers.
|
|
4
|
+
A harness is a library; it needs no agent_main unless used as a positional run.
|
|
5
|
+
Use focused topics (basics/tasks/shell/python/processes/media/forms) before an
|
|
6
|
+
unfamiliar feature. Topic-only calls give indexes; request a section id and follow
|
|
7
|
+
returned offsets. Runtime catalog/capabilities override generic examples.
|
|
4
8
|
|
|
5
|
-
##
|
|
9
|
+
## Program structure
|
|
6
10
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
- [Model Selection](#model-selection)
|
|
15
|
-
- [system/1, user/1](#memory-predicates)
|
|
16
|
-
- [output/1, yield/1, log/1](#output-predicates)
|
|
17
|
-
- [answer/1](#answer1)
|
|
18
|
-
- [Forms (structured human input)](#forms-structured-human-input)
|
|
19
|
-
- [Conversation: `chat/1` and `input/1`](#conversation-chat1-and-input1)
|
|
20
|
-
- [Processes and concurrency](#processes-and-concurrency)
|
|
21
|
-
- [Control Flow](#control-flow)
|
|
22
|
-
- [String Interpolation](#string-interpolation)
|
|
23
|
-
- [Backtracking](#backtracking)
|
|
24
|
-
- [Full Prolog Support](#full-prolog-support)
|
|
11
|
+
Facts and rules use Prolog syntax and end with periods. Predicates are identified
|
|
12
|
+
by name/arity (ALL inputs and outputs). `agent_main/N` is an OPTIONAL positional
|
|
13
|
+
run entry point; all its arguments are inputs. Libraries and explicit workflow
|
|
14
|
+
or goal calls can name any predicate. Normal Work conversation uses shell/1.
|
|
15
|
+
`doc(Name/Arity, Text)` describes modes and an example; `module_doc(Text)` describes
|
|
16
|
+
purpose; `schema/2` defines model data shapes; `script_file/2` links bundled files.
|
|
17
|
+
Use distinct script link/predicate names, e.g. extract_py versus extract/2.
|
|
25
18
|
|
|
26
|
-
|
|
19
|
+
## Harness modules
|
|
27
20
|
|
|
28
|
-
|
|
21
|
+
A harness can publish a small read-only API for other harnesses:
|
|
29
22
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
```prolog
|
|
33
|
-
% This is a single line comment
|
|
34
|
-
|
|
35
|
-
/*
|
|
36
|
-
This is a
|
|
37
|
-
multi-line comment
|
|
38
|
-
*/
|
|
39
|
-
|
|
40
|
-
% Define helper predicates
|
|
41
|
-
greet(Name, Greeting) :-
|
|
42
|
-
format(string(Greeting), "Hello, ~w!", [Name]).
|
|
43
|
-
|
|
44
|
-
% Main entry point
|
|
45
|
-
agent_main :-
|
|
46
|
-
greet("World", Msg),
|
|
47
|
-
answer(Msg).
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
---
|
|
51
|
-
|
|
52
|
-
## Entry Point
|
|
53
|
-
|
|
54
|
-
Every DML program must define `agent_main` as the entry point. It can have 0, 1, or 2 arguments:
|
|
55
|
-
|
|
56
|
-
### agent_main/0
|
|
57
|
-
```prolog
|
|
58
|
-
agent_main :-
|
|
59
|
-
task("Do something"),
|
|
60
|
-
answer("Done").
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
### agent_main/1
|
|
64
|
-
Receives the first argument:
|
|
65
|
-
```prolog
|
|
66
|
-
agent_main(Name) :-
|
|
67
|
-
format(string(Msg), "Hello, ~w!", [Name]),
|
|
68
|
-
answer(Msg).
|
|
69
|
-
```
|
|
70
|
-
|
|
71
|
-
### agent_main/2
|
|
72
|
-
Receives the first two arguments:
|
|
73
|
-
```prolog
|
|
74
|
-
agent_main(Name, Task) :-
|
|
75
|
-
system("You are a helpful assistant."),
|
|
76
|
-
task(Task),
|
|
77
|
-
answer("Complete").
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
---
|
|
81
|
-
|
|
82
|
-
## Core Predicates
|
|
83
|
-
|
|
84
|
-
### `sample_token(+Prompt, -Token)`
|
|
85
|
-
|
|
86
|
-
Run a fresh prompt and normalize the result down to a single raw token string.
|
|
87
|
-
This is useful when the model should emit one grammar symbol, label, or keyword
|
|
88
|
-
instead of a full sentence.
|
|
89
|
-
|
|
90
|
-
```prolog
|
|
91
|
-
agent_main :-
|
|
92
|
-
sample_token("Pick a SQL keyword for starting a query.", Token),
|
|
93
|
-
answer(Token).
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
### `sample_token(+Prompt, +Allowed, -Token)`
|
|
97
|
-
|
|
98
|
-
Same as `sample_token/2`, but constrains the result to an allowed token list.
|
|
99
|
-
If the model returns something outside that list, DML falls back deterministically
|
|
100
|
-
to the first allowed token. The runtime still samples just one model token, so
|
|
101
|
-
the prompt can stay terse and the grammar frontier can live in `Allowed`.
|
|
102
|
-
|
|
103
|
-
```prolog
|
|
104
|
-
agent_main :-
|
|
105
|
-
sample_token("Pick the next token for a query.", ["select", "update"], Token),
|
|
106
|
-
answer(Token).
|
|
107
|
-
```
|
|
108
|
-
|
|
109
|
-
### Task Predicates
|
|
110
|
-
|
|
111
|
-
Both `task/N` and `prompt/N` run an LLM step and bind typed outputs. They differ in
|
|
112
|
-
**what conversation the model sees**, which is the single most important thing to
|
|
113
|
-
know about them.
|
|
114
|
-
|
|
115
|
-
| | `task/N` | `prompt/N` |
|
|
116
|
-
|---|---|---|
|
|
117
|
-
| Memory | the accumulated conversation, **and it is written back** | **fresh** — empty; does not read or write it |
|
|
118
|
-
| Tools | the harness's `tool/2` predicates | **none** (plain text completion) |
|
|
119
|
-
| Use for | a step in a multi-step flow that should know what came before | classification, extraction, transformation, or a bounded question that must not be swayed by the conversation |
|
|
120
|
-
|
|
121
|
-
#### `task(+Description)`
|
|
122
|
-
|
|
123
|
-
Invoke an LLM to perform a task. The description is sent to the model.
|
|
124
|
-
|
|
125
|
-
```prolog
|
|
126
|
-
agent_main :-
|
|
127
|
-
system("You are a coding assistant."),
|
|
128
|
-
task("Write a function to calculate factorial in Python."),
|
|
129
|
-
answer("Code generated!").
|
|
130
|
-
```
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
Invoke an LLM to perform a task. The description is sent to the model.
|
|
134
|
-
|
|
135
|
-
```prolog
|
|
136
|
-
agent_main :-
|
|
137
|
-
system("You are a coding assistant."),
|
|
138
|
-
task("Write a function to calculate factorial in Python."),
|
|
139
|
-
answer("Code generated!").
|
|
140
|
-
```
|
|
141
|
-
|
|
142
|
-
#### `task(+Description, -Var1)`
|
|
143
|
-
|
|
144
|
-
Invoke LLM and bind output to a variable. Mention the variable name in the description:
|
|
145
|
-
|
|
146
|
-
```prolog
|
|
147
|
-
agent_main :-
|
|
148
|
-
task("Calculate 2 + 2 and store the result in Answer.", Answer),
|
|
149
|
-
format(string(Msg), "The answer is: ~w", [Answer]),
|
|
150
|
-
answer(Msg).
|
|
151
|
-
```
|
|
152
|
-
|
|
153
|
-
#### `task(+Description, -Var1, -Var2)`
|
|
154
|
-
|
|
155
|
-
Bind multiple variables:
|
|
156
|
-
|
|
157
|
-
```prolog
|
|
158
|
-
agent_main :-
|
|
159
|
-
task("Generate a name and age for a character. Store name in Name and age in Age.", Name, Age),
|
|
160
|
-
format(string(Msg), "Character: ~w, Age: ~w", [Name, Age]),
|
|
161
|
-
answer(Msg).
|
|
162
|
-
```
|
|
163
|
-
|
|
164
|
-
#### `task(+Description, -Var1, -Var2, -Var3)`
|
|
165
|
-
|
|
166
|
-
Bind up to three variables.
|
|
167
|
-
|
|
168
|
-
> **Note — `task/N` is load-time sugar.** `task/1,2,3,4` and `prompt/2,3,4` are
|
|
169
|
-
> rewritten by the DML loader into `task_named/3` / `prompt_named/3` with typed
|
|
170
|
-
> output variables. The rewrite runs whenever code is loaded (`deepclause run`,
|
|
171
|
-
> the REPL `-l` and commit paths, `consult`, and the REPL `assert`/`assert_many`
|
|
172
|
-
> tools). The untransformed form has no runtime handler,
|
|
173
|
-
> so code that somehow reaches the runtime without the rewrite raises
|
|
174
|
-
> `domain_error(unrewritten_task_form, Goal)` instead of failing silently.
|
|
175
|
-
> `task/1`/`prompt/1` are handled directly and are unaffected.
|
|
176
|
-
|
|
177
|
-
> **Internal note.** At load time `task/N`/`prompt/N` are rewritten to
|
|
178
|
-
> `task_named/3`/`prompt_named/3` (which carry the output-variable names) and
|
|
179
|
-
> `{Var}` descriptions are hoisted into a `format/3`. That is why a description
|
|
180
|
-
> like `task("Answer: {Question}", Answer)` sometimes *appears* as
|
|
181
|
-
> `format(string(C), "Answer: ~w", [Question]), task_named(C, [Answer], ...)`.
|
|
182
|
-
> `listing` and `export` reverse this, so you always read/write `task/N` and
|
|
183
|
-
> `prompt/N` — never author `task_named/3` yourself.
|
|
184
|
-
|
|
185
|
-
### Memory: what the model sees, and how it grows
|
|
186
|
-
|
|
187
|
-
A `task/N` call is **not** a fresh conversation. It is sent the memory the session
|
|
188
|
-
has accumulated, and the agent's full resulting memory is written back — so each
|
|
189
|
-
`task/N` sees every earlier one, plus its own prompt and reply:
|
|
190
|
-
|
|
191
|
-
```prolog
|
|
192
|
-
step(Text, Summary, Tags) :-
|
|
193
|
-
task("Summarise: {Text}", Summary), % sees: nothing yet
|
|
194
|
-
task("Tag this summary: {Summary}", Tags). % sees: the first task's prompt and reply
|
|
195
|
-
```
|
|
196
|
-
|
|
197
|
-
`system/1` and `user/1` add to that same memory, and **they are backtrackable** —
|
|
198
|
-
a `system/1` inside a branch that is later undone stops contributing:
|
|
199
|
-
|
|
200
|
-
```prolog
|
|
201
|
-
brief(Text, Out) :-
|
|
202
|
-
system("Answer in one sentence."),
|
|
203
|
-
task("Summarise: {Text}", Out).
|
|
204
|
-
```
|
|
205
|
-
|
|
206
|
-
Two consequences worth planning for:
|
|
207
|
-
|
|
208
|
-
- **Memory grows with every task.** A loop of `task/N` calls sends an ever longer
|
|
209
|
-
conversation, which costs tokens and eventually dilutes the instruction. Pass
|
|
210
|
-
values as explicit arguments rather than relying on the model to remember, and
|
|
211
|
-
start a fresh step when the history is no longer relevant.
|
|
212
|
-
- **A `task/N` inside a `tool/2` starts with empty memory.** Tool bodies run in
|
|
213
|
-
their own engine, which is created with no memory of the caller, so a nested
|
|
214
|
-
agent sees only what the *tool arguments* carry. Put the context in the argument,
|
|
215
|
-
or add it inside the tool body with `system/1`:
|
|
216
|
-
|
|
217
|
-
```prolog
|
|
218
|
-
summarise(Text, Summary) :-
|
|
219
|
-
task("Summarise this text in two sentences: {Text}", Summary).
|
|
220
|
-
|
|
221
|
-
tool(summarise(Text, Summary), "Summarise a passage.") :-
|
|
222
|
-
summarise(Text, Summary).
|
|
223
|
-
```
|
|
224
|
-
|
|
225
|
-
**A fresh context: `prompt/N`, or `with_fresh_memory/2`.** `prompt/N` takes the same
|
|
226
|
-
arguments as `task/N` but sends **no memory and no tools**, and leaves the memory
|
|
227
|
-
untouched. Use it when the step must answer from its own prompt alone — a
|
|
228
|
-
classifier, an extractor, a translation — or when a long history has started to
|
|
229
|
-
interfere:
|
|
230
|
-
|
|
231
|
-
```prolog
|
|
232
|
-
route(Message, Team) :-
|
|
233
|
-
prompt("Classify as billing, orders or account: {Message}", Team).
|
|
234
|
-
|
|
235
|
-
% The conversation so far cannot leak into the classification, and the
|
|
236
|
-
% classification cannot leak into it.
|
|
237
|
-
```
|
|
238
|
-
|
|
239
|
-
Because `prompt/N` has no tools, a step that must read a file or search an index
|
|
240
|
-
has to be a `task/N`. Choose by what the step needs: the harness's capabilities
|
|
241
|
-
(`task/N`) or an uncontaminated answer (`prompt/N`).
|
|
242
|
-
|
|
243
|
-
`prompt/N` isolates **one call**. To isolate a **group** of steps — several
|
|
244
|
-
`task/N` calls that share a fresh context with each other but nothing with the
|
|
245
|
-
caller — wrap them in `with_fresh_memory/1`:
|
|
246
|
-
|
|
247
|
-
```prolog
|
|
248
|
-
describe(Paper, Report) :-
|
|
249
|
-
with_fresh_memory((
|
|
250
|
-
task("Summarise the method of: {Paper}", Method),
|
|
251
|
-
task("Summarise the results of: {Paper}", Results),
|
|
252
|
-
task("Write a two-sentence abstract from {Method} and {Results}", Report)
|
|
253
|
-
)).
|
|
254
|
-
% The three steps see each other's turns, because they accumulate within the
|
|
255
|
-
% scope. Nothing the caller accumulated reaches them, and nothing they
|
|
256
|
-
% accumulate reaches the caller — the memory is restored on exit.
|
|
257
|
-
```
|
|
258
|
-
|
|
259
|
-
With `with_tools/2` / `without_tools/2` it composes into a scope that controls both
|
|
260
|
-
the conversation and the capabilities:
|
|
261
|
-
|
|
262
|
-
```prolog
|
|
263
|
-
audit(App, Finding) :-
|
|
264
|
-
with_fresh_memory(without_tools([apply_fix],
|
|
265
|
-
task("Review {App} against the checklist and report one finding.", Finding))).
|
|
266
|
-
```
|
|
267
|
-
|
|
268
|
-
### Declared Output Shapes: `schema/2`
|
|
269
|
-
|
|
270
|
-
A type says "a list of dicts"; a schema says what is *in* them. Declare the shape
|
|
271
|
-
once, name it in the `task/N` output, and every step gets a value that matches it —
|
|
272
|
-
defaults filled, and a missing required field or a wrong-typed field failing the
|
|
273
|
-
step instead of quietly yielding an empty result:
|
|
274
|
-
|
|
275
|
-
```prolog
|
|
276
|
-
schema(author, [
|
|
277
|
-
field(name, string, required),
|
|
278
|
-
field(affiliation, string, default("not stated")),
|
|
279
|
-
field(email, string, default("")),
|
|
280
|
-
field(country, string, default(""))
|
|
281
|
-
]).
|
|
282
|
-
|
|
283
|
-
extract_authors(Text, Authors) :-
|
|
284
|
-
task("From the front matter extract every author: {Text}",
|
|
285
|
-
list(schema(author, Authors))).
|
|
286
|
-
% Authors = [author{name:"Ashish Vaswani", affiliation:"Google Brain", email:"", country:""} …]
|
|
287
|
-
```
|
|
288
|
-
|
|
289
|
-
- An absent field with a `default(Value)` is filled.
|
|
290
|
-
- An absent `required` field **fails the step** with a message naming the field, so
|
|
291
|
-
the agent can correct it in the same turn.
|
|
292
|
-
- A field of the wrong type fails the same way. Types are `string`, `integer`,
|
|
293
|
-
`number`, `boolean`, `object`, `array`.
|
|
294
|
-
- An **undeclared** field is kept, not dropped: a model mistake stays visible
|
|
295
|
-
- The field list is **described to the model** in the step's own instructions, and a
|
|
296
|
-
missing required or wrong-typed field is reported by name inside the same turn,
|
|
297
|
-
so the agent usually fixes it before the step ends
|
|
298
|
-
rather than disappearing.
|
|
299
|
-
- `schema/2` is a fact, like `doc/2` — it appears in the listing and travels with
|
|
300
|
-
`export`.
|
|
301
|
-
|
|
302
|
-
For a single object rather than a list, use `schema(author, Author)` (no `list/1`).
|
|
303
|
-
You can also apply a schema by hand to any dict:
|
|
304
|
-
|
|
305
|
-
```prolog
|
|
306
|
-
schema_fill(author, Raw, Author), % fills defaults, validates
|
|
307
|
-
```
|
|
308
|
-
|
|
309
|
-
`end_turn` reports a `task/N` that names a schema which was never declared.
|
|
310
|
-
|
|
311
|
-
### Type-Safe Output Variables
|
|
312
|
-
|
|
313
|
-
You can wrap output variables with type specifiers to enforce strict validation on the LLM's output. The runtime will ensure the value matches the specified type.
|
|
314
|
-
|
|
315
|
-
| Wrapper | Description | Zod Equivalent |
|
|
316
|
-
|---------|-------------|----------------|
|
|
317
|
-
| `string(Var)` | Default string type | `z.string()` |
|
|
318
|
-
| `integer(Var)` | Integer number | `z.number().int()` |
|
|
319
|
-
| `number(Var)` | Any number (float or int) | `z.number()` |
|
|
320
|
-
| `float(Var)` | Alias for number | `z.number()` |
|
|
321
|
-
| `boolean(Var)` | Boolean value | `z.boolean()` |
|
|
322
|
-
| `list(Type(Var))` | Array of specified type | `z.array(Type)` |
|
|
323
|
-
| `object(Var)` | Dictionary/Object | `z.record(z.unknown())` |
|
|
324
|
-
|
|
325
|
-
**Examples:**
|
|
326
|
-
|
|
327
|
-
```prolog
|
|
328
|
-
% Enforce integer result
|
|
329
|
-
task("Calculate 10 + 5", integer(Result)).
|
|
330
|
-
|
|
331
|
-
% Enforce boolean result
|
|
332
|
-
task("Is this true?", boolean(IsTrue)).
|
|
333
|
-
|
|
334
|
-
% Enforce list of strings
|
|
335
|
-
task("List 3 colors", list(string(Colors))).
|
|
336
|
-
|
|
337
|
-
% Enforce object result
|
|
338
|
-
task("Extract user details", object(User)).
|
|
339
|
-
```
|
|
340
|
-
|
|
341
|
-
**Note:** The LLM during `task()` can only call tools defined in DML (see [Tool Definitions](#tool-definitions)). Registered TypeScript tools are not automatically available - this gives you control over what the LLM can do.
|
|
342
|
-
|
|
343
|
-
---
|
|
344
|
-
|
|
345
|
-
### `exec(+ToolCall, -Output)`
|
|
346
|
-
|
|
347
|
-
Execute a registered TypeScript tool directly and capture its output.
|
|
348
|
-
|
|
349
|
-
```prolog
|
|
350
|
-
% Assuming 'calculator' tool is registered in TypeScript
|
|
351
|
-
agent_main :-
|
|
352
|
-
exec(calculator(expression: "15 * 23"), Result),
|
|
353
|
-
format(string(Msg), "Calculation result: ~w", [Result]),
|
|
354
|
-
answer(Msg).
|
|
355
|
-
```
|
|
356
|
-
|
|
357
|
-
Tool arguments use `key: value` syntax:
|
|
358
|
-
|
|
359
|
-
```prolog
|
|
360
|
-
exec(fetch_url(url: "https://example.com"), Response)
|
|
361
|
-
```
|
|
362
|
-
|
|
363
|
-
Or positional if the tool supports it:
|
|
364
|
-
|
|
365
|
-
```prolog
|
|
366
|
-
exec(get_time, CurrentTime)
|
|
367
|
-
```
|
|
368
|
-
|
|
369
|
-
The `bash` tool takes exactly two inputs — `command` (a shell string) or `argv` (a
|
|
370
|
-
list, quoted by the runtime) — plus an optional wall-clock `timeoutMs`. There is
|
|
371
|
-
**no `stdin`**: pass data as an `argv` element, or write it to a workspace file and
|
|
372
|
-
name the file. stdin is `/dev/null`, so a command that reads it sees EOF rather
|
|
373
|
-
than waiting. It always returns the wall-clock duration as `timeMs`:
|
|
374
|
-
|
|
375
|
-
```prolog
|
|
376
|
-
exec(bash(command: "sleep 30", timeoutMs: 5000), R),
|
|
377
|
-
exec(bash(argv: ["python3", Script, Query]), R), % no quoting to write
|
|
378
|
-
get_dict(timeMs, R, Took),
|
|
379
|
-
( get_dict(exitCode, R, 124)
|
|
380
|
-
-> format(string(Msg), "timed out after ~w ms", [Took])
|
|
381
|
-
; format(string(Msg), "finished in ~w ms", [Took])
|
|
382
|
-
).
|
|
383
|
-
```
|
|
384
|
-
|
|
385
|
-
A command is also killed when it produces no output for `DC_HOST_SHELL_IDLE_TIMEOUT_MS`
|
|
386
|
-
(default 180 000 ms); `DC_HOST_SHELL_TIMEOUT_MS` sets a default wall-clock cap
|
|
387
|
-
(0 = disabled). Exit code `124` means a timeout.
|
|
388
|
-
|
|
389
|
-
**The host may refuse a tool.** A session can set a tool **policy** — a whitelist
|
|
390
|
-
or blacklist, by name or glob. A refused `exec/2` fails exactly as a tool that
|
|
391
|
-
returned failure, and the reason is reported to the operator. The policy applies
|
|
392
|
-
to *every* `exec/2`, including one inside a `tool/2` body, so a tool cannot reach
|
|
393
|
-
a capability the policy blocked. `ask_user` is exempt: it is the human channel,
|
|
394
|
-
not a capability.
|
|
395
|
-
|
|
396
|
-
---
|
|
397
|
-
|
|
398
|
-
### Tool Definitions
|
|
399
|
-
|
|
400
|
-
`tool/2` is an **annotation**, not an implementation. It exposes an existing
|
|
401
|
-
harness predicate to the nested agent that runs inside `task/N`. Define the
|
|
402
|
-
predicate normally, then add a `tool/2` clause that delegates to it:
|
|
403
|
-
|
|
404
|
-
```prolog
|
|
405
|
-
% 1. The capability: a normal predicate, callable from `execute` and `/goal`.
|
|
406
|
-
count_words(File, Count) :-
|
|
407
|
-
script_file(count_words, Script),
|
|
408
|
-
format(atom(Cmd), "python3 '~w' '~w'", [Script, File]),
|
|
409
|
-
exec(bash(command: Cmd), Result),
|
|
410
|
-
get_dict(stdout, Result, Count).
|
|
411
|
-
|
|
412
|
-
% 2. The annotation: exposes it to the nested agent. Thin body only.
|
|
413
|
-
tool(count_words(File, Count), "Count words in a workspace file.") :-
|
|
414
|
-
count_words(File, Count).
|
|
415
|
-
```
|
|
416
|
-
|
|
417
|
-
The tool head's **last argument is the output**; the ones before it are inputs. A
|
|
418
|
-
tool that needs more than one input therefore needs a **result argument**: a write
|
|
419
|
-
tool is `fs_write(Path, Content, Result)`, not `fs_write(Path, Content)` —
|
|
420
|
-
otherwise the content is taken for the output, the model is never offered a way
|
|
421
|
-
to pass it, and the write silently does nothing.
|
|
422
|
-
|
|
423
|
-
```prolog
|
|
424
|
-
fs_write(Path, Content, ok) :-
|
|
425
|
-
file_directory_name(Path, Dir),
|
|
426
|
-
( Dir == "." -> true ; make_directory_path(Dir) ),
|
|
427
|
-
write_file(Path, Content).
|
|
428
|
-
|
|
429
|
-
tool(fs_write(Path, Content, Result),
|
|
430
|
-
"Write a text file, creating parent directories.",
|
|
431
|
-
[string, string]) :-
|
|
432
|
-
fs_write(Path, Content, Result).
|
|
433
|
-
```
|
|
434
|
-
|
|
435
|
-
`tool/3` takes the **input types** after the description, in order, one per input
|
|
436
|
-
(`[string, string]` above); the last argument is still the output. A tool whose
|
|
437
|
-
output argument is left unbound fails with an explanation rather than reporting a
|
|
438
|
-
silent success.
|
|
439
|
-
|
|
440
|
-
`tool/2` and `tool/3` are **source annotations, not executable predicates**.
|
|
441
|
-
Never call or assert `tool/N` as a goal. The loader installs the implementation
|
|
442
|
-
as `tool(Head) :- Body` and registers its schema separately; nested agents call
|
|
443
|
-
the tool by the head's predicate name, while DML calls the underlying predicate
|
|
444
|
-
directly.
|
|
445
|
-
|
|
446
|
-
The head and its delegate must have the **same name and the same arity**. The
|
|
447
|
-
tool body is what runs when the nested agent calls the tool, so a body that
|
|
448
|
-
calls a different arity either calls nothing (`existence_error`) or calls the
|
|
449
|
-
tool again and recurses forever:
|
|
450
|
-
|
|
451
|
-
```prolog
|
|
452
|
-
% WRONG: declares /2 but calls /3, so the tool fails when a nested agent uses it.
|
|
453
|
-
tool(bibliography(Query, Max), "…") :-
|
|
454
|
-
bibliography(Query, Max, Entries).
|
|
455
|
-
|
|
456
|
-
% WRONG: calls itself; a nested agent recurses until the budget is gone.
|
|
457
|
-
tool(citations(Text, Citations), "…") :-
|
|
458
|
-
citations(Text, Citations).
|
|
459
|
-
```
|
|
460
|
-
|
|
461
|
-
Nothing is checked when the clause is loaded, so both mistakes look fine until a
|
|
462
|
-
nested agent calls the tool. `end_turn` reports them as contract warnings; treat
|
|
463
|
-
them as errors, not style notes.
|
|
464
|
-
|
|
465
|
-
A predicate defined *only* inside a `tool/2` clause is invisible to
|
|
466
|
-
`execute` / `/goal` — the loader asserts it as `tool(Head)`, never as `Head`. Split
|
|
467
|
-
the two so one implementation is reachable from both surfaces:
|
|
468
|
-
|
|
469
|
-
```prolog
|
|
470
|
-
/goal count_words("report.txt", C). % authoring agent
|
|
471
|
-
task("Count the words in report.txt.", N). % nested agent calls the tool
|
|
472
|
-
```
|
|
473
|
-
|
|
474
|
-
The only tools a nested agent can call are the harness's `tool/2` predicates;
|
|
475
|
-
registered host tools (for example `bash`) are reachable from DML code through
|
|
476
|
-
`exec/2`, not as tools by name. So a task description that says "use the
|
|
477
|
-
`fs_read` tool" works only if the module itself defines `fs_read/2` **and**
|
|
478
|
-
annotates it.
|
|
479
|
-
|
|
480
|
-
The tool head's **last argument is the output**; the description is shown to the
|
|
481
|
-
nested agent. Keep the `tool/2` body a single delegation — put no logic in it.
|
|
482
|
-
|
|
483
|
-
Logic lives in the predicate, not the annotation:
|
|
484
|
-
|
|
485
|
-
```prolog
|
|
486
|
-
safe_divide(A, B, Result) :-
|
|
487
|
-
( B =:= 0
|
|
488
|
-
-> Result = error("Division by zero")
|
|
489
|
-
; Result is A / B
|
|
490
|
-
).
|
|
491
|
-
|
|
492
|
-
tool(safe_divide(A, B, Result), "Safely divide two numbers.") :-
|
|
493
|
-
safe_divide(A, B, Result).
|
|
494
|
-
```
|
|
495
|
-
|
|
496
|
-
#### Using `task()` Inside Tools
|
|
497
|
-
|
|
498
|
-
Tools can use `task()` and `prompt()` internally to combine Prolog logic with LLM reasoning:
|
|
499
|
-
|
|
500
|
-
```prolog
|
|
501
|
-
% A predicate that computes then explains.
|
|
502
|
-
% The nested task is told to work from the given figures — it has no tools it
|
|
503
|
-
% needs, so it cannot try to re-enter this predicate.
|
|
504
|
-
explain_calculation(A, B, Explanation) :-
|
|
505
|
-
Sum is A + B, % Prolog computation
|
|
506
|
-
format(string(Desc),
|
|
507
|
-
"Explain ~w + ~w = ~w to a child, using only these figures.",
|
|
508
|
-
[A, B, Sum]),
|
|
509
|
-
task(Desc, Explanation).
|
|
510
|
-
|
|
511
|
-
tool(explain_calculation(A, B, Explanation), "Calculate and explain the result.") :-
|
|
512
|
-
explain_calculation(A, B, Explanation).
|
|
513
|
-
```
|
|
514
|
-
|
|
515
|
-
**Do not wrap an LLM step in a `tool/2` that advertises the same job.** The tool
|
|
516
|
-
is declared to the agent running *inside* that same `task/N`, so the description
|
|
517
|
-
invites the agent to do the very thing it was asked, by calling the tool:
|
|
518
|
-
|
|
519
|
-
```prolog
|
|
520
|
-
% WARNING: this shape self-delegates.
|
|
521
|
-
extract_authors(Text, Authors) :-
|
|
522
|
-
task("Extract every author and their affiliation(s) from: {Text}", list(object(Authors))).
|
|
523
|
-
|
|
524
|
-
tool(extract_authors(Text, Authors), "Extract every author and their affiliation(s).") :-
|
|
525
|
-
extract_authors(Text, Authors).
|
|
526
|
-
```
|
|
527
|
-
|
|
528
|
-
Called as a predicate (`/goal extract_authors(…, A)`, `execute`, or from another
|
|
529
|
-
predicate), `extract_authors` runs its `task/N`, and that agent is offered
|
|
530
|
-
`extract_authors` — a tool described as doing exactly its job. The runtime refuses
|
|
531
|
-
the re-entrant call (a tool whose predicate is already running is withheld, and a
|
|
532
|
-
call that slips through is refused with a reason), so it cannot recurse forever.
|
|
533
|
-
But the agent still spends a turn on it, is told the tool failed, and then does
|
|
534
|
-
the work by hand — a confusing transcript and a wasted call.
|
|
535
|
-
|
|
536
|
-
Two ways to avoid it, in order of preference:
|
|
537
|
-
|
|
538
|
-
**Keep the LLM step a skill, and give `tool/2` only to capabilities.** A skill is
|
|
539
|
-
called from DML (`/goal`, `execute`, another predicate) and does not need to be a
|
|
540
|
-
tool. Annotate the operations a nested agent should *use* — deterministic or
|
|
541
|
-
side-effecting work such as reading a PDF, searching an index, or shelling out:
|
|
542
|
-
|
|
543
|
-
```prolog
|
|
544
|
-
% Skill: an LLM step. Call it from DML; no tool/2.
|
|
545
|
-
extract_authors(Text, Authors) :-
|
|
546
|
-
task("Extract every author and their affiliation(s) from: {Text}", list(object(Authors))).
|
|
547
|
-
|
|
548
|
-
% Tools: capabilities for nested agents. No task/N, so no self-reference.
|
|
549
|
-
read_pdf(Path, Text) :-
|
|
550
|
-
script_file(pdf_to_text, Script),
|
|
551
|
-
format(atom(Cmd), "python3 '~w' '~w'", [Script, Path]),
|
|
552
|
-
exec(bash(command: Cmd), R), get_dict(stdout, R, Text).
|
|
553
|
-
|
|
554
|
-
tool(read_pdf(Path, Text), "Convert a workspace PDF to text.") :- read_pdf(Path, Text).
|
|
555
|
-
```
|
|
556
|
-
|
|
557
|
-
**Or scope the nested task's tools so the tool cannot be reached.** If a `task/N`
|
|
558
|
-
inside a predicate must not use a tool, say so with `without_tools/2` (or list
|
|
559
|
-
exactly what it may use with `with_tools/2`):
|
|
560
|
-
|
|
561
|
-
```prolog
|
|
562
|
-
extract_authors(Text, Authors) :-
|
|
563
|
-
without_tools([extract_authors],
|
|
564
|
-
task("Extract every author and their affiliation(s) from: {Text}",
|
|
565
|
-
list(object(Authors)))).
|
|
566
|
-
```
|
|
567
|
-
|
|
568
|
-
Scoping is the narrower fix: it keeps the tool advertised to *other* agents (which
|
|
569
|
-
is usually why it exists) while removing it from this one.
|
|
570
|
-
|
|
571
|
-
**Memory Isolation:** When `task()` or `prompt()` runs inside a tool, the nested agent starts with **fresh memory**. It does NOT inherit the parent's accumulated memory from `system()`, `user()`, or previous `task()` calls. If you need context in a nested task, pass it explicitly as a tool argument or add it with `system()` inside the tool body.
|
|
572
|
-
|
|
573
|
-
**Tool Access:** A nested agent's only callable tools are the harness's `tool/2`
|
|
574
|
-
predicates; host tools such as `bash` are reachable from DML code via `exec/2`,
|
|
575
|
-
never by name from a task description. A tool that is **already executing** cannot
|
|
576
|
-
be re-entered: a call to it from inside itself is refused with an explanation, so a
|
|
577
|
-
tool cannot recurse into itself. The refusal is deliberate and visible — the tool is
|
|
578
|
-
declared to the agent with the reason on its description, so the call comes back as
|
|
579
|
-
"already running further up the call chain" rather than as a missing tool, which
|
|
580
|
-
would invite a retry.
|
|
581
|
-
|
|
582
|
-
> The withholding is keyed on *tool* execution, and only that is guaranteed. Whether a
|
|
583
|
-
> running tool is also *removed* from the tool list presented to the agent inside it
|
|
584
|
-
> is not something the current test suite covers; the refusal above is what stops the
|
|
585
|
-
> recursion. Do not rely on the tool being absent from `task/N`'s tool list.
|
|
586
|
-
|
|
587
|
-
That keying has a consequence worth knowing: a predicate that is also a tool does
|
|
588
|
-
**not** count as "executing" when it is called as a predicate (`/goal`, `execute`,
|
|
589
|
-
or from another predicate). So for
|
|
590
|
-
|
|
591
|
-
```prolog
|
|
592
|
-
extract_authors(Text, Authors) :- task("…", list(object(Authors))).
|
|
593
|
-
tool(extract_authors(Text, Authors), "…") :- extract_authors(Text, Authors).
|
|
594
|
-
```
|
|
595
|
-
|
|
596
|
-
`/goal extract_authors(Text, A)` still offers `extract_authors` to the agent inside
|
|
597
|
-
`task/N`. Use `with_tools/2` / `without_tools/2` to scope it, or keep the LLM step
|
|
598
|
-
out of the tool set entirely (see **Using `task()` Inside Tools** above).
|
|
599
|
-
|
|
600
|
-
```prolog
|
|
601
|
-
% Example: passing context explicitly.
|
|
602
|
-
smart_grep(BuildContext, Pattern, Summary) :-
|
|
603
|
-
system(BuildContext), % add context to the nested task's memory
|
|
604
|
-
format(atom(Cmd), "grep -rn '~w' .", [Pattern]),
|
|
605
|
-
exec(bash(command: Cmd), Results),
|
|
606
|
-
format(string(Desc), "Summarize these matches: ~w", [Results]),
|
|
607
|
-
task(Desc, Summary).
|
|
608
|
-
|
|
609
|
-
tool(smart_grep(BuildContext, Pattern, Summary), "Grep with context.") :-
|
|
610
|
-
smart_grep(BuildContext, Pattern, Summary).
|
|
611
|
-
```
|
|
612
|
-
|
|
613
|
-
---
|
|
614
|
-
|
|
615
|
-
### Tool Scoping
|
|
616
|
-
|
|
617
|
-
You can control which tools are available to nested `task()` calls using `with_tools/2` and `without_tools/2`.
|
|
618
|
-
|
|
619
|
-
#### `with_tools(+ToolList, +Goal)`
|
|
620
|
-
|
|
621
|
-
Run Goal with only the specified tools available to nested tasks. `ToolList`
|
|
622
|
-
holds tool *names* (atoms), not predicates:
|
|
623
|
-
|
|
624
|
-
```prolog
|
|
625
|
-
% The implementation defines what the tool does; the annotation exposes it.
|
|
626
|
-
restricted_work(Input, Output) :-
|
|
627
|
-
with_tools([search_papers, read_paper], (
|
|
628
|
-
format(string(Desc), "Process '~w' using the available tools", [Input]),
|
|
629
|
-
task(Desc, Output)
|
|
630
|
-
)).
|
|
631
|
-
|
|
632
|
-
tool(restricted_task(Input, Output), "Runs with limited tools") :-
|
|
633
|
-
restricted_work(Input, Output).
|
|
634
|
-
```
|
|
635
|
-
|
|
636
|
-
#### `without_tools(+ToolList, +Goal)`
|
|
637
|
-
|
|
638
|
-
Run Goal with the specified tools excluded from nested tasks:
|
|
639
|
-
|
|
640
|
-
```prolog
|
|
641
|
-
cheap_work(Input, Output) :-
|
|
642
|
-
without_tools([expensive_tool], (
|
|
643
|
-
format(string(Desc), "Process '~w' cheaply", [Input]),
|
|
644
|
-
task(Desc, Output)
|
|
645
|
-
)).
|
|
646
|
-
|
|
647
|
-
tool(cheap_task(Input, Output), "Runs without expensive tools") :-
|
|
648
|
-
cheap_work(Input, Output).
|
|
649
|
-
```
|
|
650
|
-
|
|
651
|
-
#### Using Tool Scoping in `agent_main`
|
|
652
|
-
|
|
653
|
-
You can also use `with_tools/2` and `without_tools/2` directly in `agent_main`:
|
|
654
|
-
|
|
655
|
-
```prolog
|
|
656
|
-
agent_main :-
|
|
657
|
-
system("You are a safe assistant."),
|
|
658
|
-
|
|
659
|
-
% Run task with only safe tools
|
|
660
|
-
with_tools([search, fetch_page], (
|
|
661
|
-
task("Analyze the files in the workspace.", Analysis)
|
|
662
|
-
)),
|
|
663
|
-
|
|
664
|
-
output(Analysis),
|
|
665
|
-
answer("Done").
|
|
666
|
-
```
|
|
667
|
-
|
|
668
|
-
**Automatic call stack exclusion:** When a tool calls `task()`, the calling tool is automatically excluded from the nested agent's available tools to prevent infinite recursion. This happens in addition to any manual scoping via `with_tools/2` or `without_tools/2`.
|
|
669
|
-
|
|
670
|
-
---
|
|
671
|
-
|
|
672
|
-
### Model Selection
|
|
673
|
-
|
|
674
|
-
#### `with_model(+Spec, +Goal)`
|
|
675
|
-
|
|
676
|
-
Run `Goal` with a different model — and optionally a reasoning level — for every
|
|
677
|
-
`task/N`, `prompt/N` and `sample_token/N` call inside it. Judgments
|
|
678
|
-
(`choose/rate/verify/probability`) are not affected.
|
|
679
|
-
|
|
680
|
-
```prolog
|
|
681
|
-
% a cheap model for classification
|
|
682
|
-
with_model("openai:gpt-4o-mini",
|
|
683
|
-
prompt("Classify as billing/orders/account: {Message}", Team)).
|
|
684
|
-
|
|
685
|
-
% a strong model with high reasoning, only for the hard step
|
|
686
|
-
with_model("anthropic:claude-sonnet-4#high",
|
|
687
|
-
task("Review this diff and list defects:\n{Diff}", Notes)).
|
|
688
|
-
|
|
689
|
-
% full control with a dict
|
|
690
|
-
with_model(model{provider: "google", id: "gemini-2.5-pro",
|
|
691
|
-
temperature: 0.2, maxTokens: 8192}, Goal).
|
|
692
|
-
```
|
|
693
|
-
|
|
694
|
-
`Spec` is a string — `"provider:model"`, `"provider/model"`, `"model"`, each with
|
|
695
|
-
an optional `#reasoning` suffix (`off|minimal|low|medium|high|xhigh|max`) — or a
|
|
696
|
-
`model{provider, id, temperature, maxTokens, reasoning}` dict. The innermost
|
|
697
|
-
`with_model` wins, and a nested `with_reasoning/2` overrides the spec's reasoning.
|
|
698
|
-
The default is the session's active model. An unknown or unsigned-in model fails
|
|
699
|
-
with a clear error.
|
|
700
|
-
|
|
701
|
-
---
|
|
702
|
-
|
|
703
|
-
### Memory Predicates
|
|
704
|
-
|
|
705
|
-
Memory predicates build the conversation context sent to the LLM.
|
|
706
|
-
|
|
707
|
-
#### `system(+Text)`
|
|
708
|
-
|
|
709
|
-
Add a system message (instructions for the LLM):
|
|
710
|
-
|
|
711
|
-
```prolog
|
|
712
|
-
agent_main :-
|
|
713
|
-
system("You are a helpful cooking assistant."),
|
|
714
|
-
system("Always provide measurements in metric units."),
|
|
715
|
-
task("Suggest a recipe for pasta."),
|
|
716
|
-
answer("Done").
|
|
717
|
-
```
|
|
718
|
-
|
|
719
|
-
#### `user(+Text)`
|
|
720
|
-
|
|
721
|
-
Add a user message to the context:
|
|
722
|
-
|
|
723
|
-
```prolog
|
|
724
|
-
agent_main :-
|
|
725
|
-
system("You are a helpful assistant."),
|
|
726
|
-
user("I want to learn about machine learning."),
|
|
727
|
-
task("Explain the basics of machine learning."),
|
|
728
|
-
answer("Explained!").
|
|
729
|
-
```
|
|
730
|
-
|
|
731
|
-
#### `push_context` / `pop_context`
|
|
732
|
-
|
|
733
|
-
Save the current memory to a stack and restore it, which makes memory
|
|
734
|
-
**backtrackable**. `push_context(clear)` also empties the active memory.
|
|
735
|
-
|
|
736
|
-
```prolog
|
|
737
|
-
agent_main(Draft) :-
|
|
738
|
-
push_context(clear),
|
|
739
|
-
system("You are a terse reviewer."),
|
|
740
|
-
task("Review this in one line: {Draft}", string(Note)),
|
|
741
|
-
pop_context,
|
|
742
|
-
answer(Note).
|
|
743
|
-
```
|
|
744
|
-
|
|
745
|
-
#### `clear_memory`
|
|
746
|
-
|
|
747
|
-
Clear the active memory without saving it.
|
|
748
|
-
|
|
749
|
-
#### `get_memory(-Messages)`
|
|
750
|
-
|
|
751
|
-
Bind the current memory as a list of `message{role, content, media}` dicts, for a
|
|
752
|
-
predicate that needs to inspect or rebuild it.
|
|
753
|
-
|
|
754
|
-
---
|
|
755
|
-
|
|
756
|
-
### Media Predicates
|
|
757
|
-
|
|
758
|
-
Images are **workspace files**; DML carries only a reference. See
|
|
759
|
-
`docs/DML_MEDIA.md`.
|
|
760
|
-
|
|
761
|
-
#### `read_media(+Path, -Media)`
|
|
762
|
-
|
|
763
|
-
Bind `Media = media(Path, Mime)` for a workspace-relative image (PNG, JPEG, GIF,
|
|
764
|
-
WebP). The bytes are not read into Prolog.
|
|
765
|
-
|
|
766
|
-
#### `attach_media(+Media)`
|
|
767
|
-
|
|
768
|
-
Append the image to conversation memory (reference only), so the next `task/N`
|
|
769
|
-
call sends it to the model as an image block:
|
|
770
|
-
|
|
771
|
-
```prolog
|
|
772
|
-
agent_main :-
|
|
773
|
-
read_media("photos/fox.png", Img),
|
|
774
|
-
attach_media(Img),
|
|
775
|
-
task("Describe the image in one sentence.", Description),
|
|
776
|
-
answer(Description).
|
|
777
|
-
```
|
|
778
|
-
|
|
779
|
-
Memory stores `media{path, mime}` — never the image bytes. Judgments
|
|
780
|
-
(`choose`/`rate`/`verify`/`probability`) stay text-only.
|
|
781
|
-
|
|
782
|
-
#### `save_image(+Media, +OutPath)`
|
|
783
|
-
|
|
784
|
-
Write a media reference to a workspace file — a copied image
|
|
785
|
-
(`save_image(media("in.png", "image/png"), "out.png")`) or inline SVG
|
|
786
|
-
(`save_image(media{svg: Svg}, "out.svg")`). Parent directories must exist.
|
|
787
|
-
|
|
788
|
-
---
|
|
789
|
-
|
|
790
|
-
#### Running a command with data in it
|
|
791
|
-
|
|
792
|
-
`argv` takes the command and its arguments as a **list**, and the runtime quotes
|
|
793
|
-
each element. Pass values here and you never write a quote, so an argument
|
|
794
|
-
containing a space, a quote, `$`, a backtick or `;` is inert:
|
|
795
|
-
|
|
796
|
-
```prolog
|
|
797
|
-
exec(bash(argv: ["python3", Script, UserText]), R), get_dict(stdout, R, Text).
|
|
798
|
-
```
|
|
799
|
-
|
|
800
|
-
It is the same shell underneath (and the same sandbox), so pipelines and redirection
|
|
801
|
-
still work with `command`; `argv` is the way to pass *data*. Prefer it whenever an
|
|
802
|
-
argument comes from a file, a model, or the user. There is no `stdin` argument.
|
|
803
|
-
|
|
804
|
-
#### Do not parse in DML — shell out or ask the model
|
|
805
|
-
|
|
806
|
-
String handling is the fiddliest part of Prolog, and hand-rolled parsing is the
|
|
807
|
-
easiest way to write DML that looks fine and is quietly wrong. Do not build a
|
|
808
|
-
parser out of `sub_string/5`, `split_string/4`, `atom_concat/3`, `format/2` and an
|
|
809
|
-
accumulator. Two better answers, depending on what the work actually is:
|
|
810
|
-
|
|
811
|
-
- **Mechanical** (pull a field, change a format, count, filter, join): write a
|
|
812
|
-
**helper script** and run it. A script is a file the harness links with
|
|
813
|
-
`script_file/2`, it is testable on its own, and Python/jq/sed are built for this.
|
|
814
|
-
Have it emit **JSON** and read the result with `json_get/3` / `json_gets/3` /
|
|
815
|
-
`json_text/2`, rather than splitting its stdout by hand.
|
|
816
|
-
- **Meaning** (find the field named X, classify, summarise, decide): make it a
|
|
817
|
-
**model call** with a typed output — `task("…", list(string(Items)))`,
|
|
818
|
-
`schema/2`, or `choose`/`rate`/`verify` for a bounded judgment. The model is the
|
|
819
|
-
right tool for understanding text; Prolog is the right tool for *sequencing and
|
|
820
|
-
checking* it.
|
|
821
|
-
|
|
822
|
-
So `exec(bash(command: "cat", stdin: "…"), R), get_dict(stdout, R, O)` has no
|
|
823
|
-
place here on either count: there is no stdin, and the structured reading of the
|
|
824
|
-
result is a job for a script or a model, not for the DML around the call.
|
|
825
|
-
|
|
826
|
-
### File I/O and paths — prefer the shell
|
|
827
|
-
|
|
828
|
-
**`/workspace` is the project, and it is the working directory.** A DML path is
|
|
829
|
-
either absolute under `/workspace` or relative to it, and the two forms name the
|
|
830
|
-
same file:
|
|
831
|
-
|
|
832
|
-
out/report.txt and /workspace/out/report.txt
|
|
833
|
-
|
|
834
|
-
Prefer the `/workspace/...` form: the same name works from DML, from
|
|
835
|
-
`exec(bash(...))`, and from the shell tool, on every backend, so a path never has
|
|
836
|
-
to be translated between them. There is **no paths file and no search-path
|
|
837
|
-
registry** — nothing to declare, register, or discover. `script_file(Name, Path)`
|
|
838
|
-
links a file that belongs to the harness (it is bundled on `export`); it does not
|
|
839
|
-
resolve anything at run time.
|
|
840
|
-
|
|
841
|
-
**Everything outside `/workspace` is the ephemeral VM filesystem.** `/etc`,
|
|
842
|
-
`/tmp`, `/home` are not this machine. They are an in-memory filesystem that
|
|
843
|
-
belongs to the session and is discarded when it ends, so they are fine for scratch
|
|
844
|
-
and useless for results. **Only files under `/workspace` reach the host.** For
|
|
845
|
-
scratch, use `$TMPDIR`, which is a per-session directory in every backend (a bare
|
|
846
|
-
`/tmp` is the real one when nothing is sandboxed).
|
|
847
|
-
|
|
848
|
-
**Prefer `exec(bash(...))` for file operations.** Reading, writing, copying, or
|
|
849
|
-
converting files is usually clearer and more robust as a shell command; reach for
|
|
850
|
-
the DML predicates below only when the content must be bound and reasoned over
|
|
851
|
-
inside Prolog. Pulling a file into DML just to hand it back to the shell is a
|
|
852
|
-
smell (`DML_AUTHORING.md` §2).
|
|
853
|
-
|
|
854
|
-
The file predicates take a path — absolute under `/workspace`, or relative:
|
|
855
|
-
|
|
856
|
-
```prolog
|
|
857
|
-
read_file("/workspace/images/a.png", Bytes),
|
|
858
|
-
read_file("images/a.png", Bytes), % same file
|
|
859
|
-
write_file("/workspace/out/report.txt", Text),
|
|
860
|
-
make_directory_path("/workspace/out/nested"), % create a directory (and parents)
|
|
861
|
-
append_file("out/log.txt", Line),
|
|
862
|
-
delete_file("out/report.txt"),
|
|
863
|
-
directory_files("images", Names), % bare entry names: ["a.png", ...]
|
|
864
|
-
exists_file("images/a.png"),
|
|
865
|
-
size_file("images/a.png", Size),
|
|
866
|
-
time_file("images/a.png", Modified).
|
|
867
|
-
```
|
|
868
|
-
|
|
869
|
-
`write_file/2` does **not** create parent directories — call
|
|
870
|
-
`make_directory_path/1` first. `directory_files/2` returns bare entry names (no
|
|
871
|
-
directory), so build a path with `atom_concat('images/', Name, Path)` when you
|
|
872
|
-
need one.
|
|
873
|
-
|
|
874
|
-
These predicates are **real clauses in the session module**, not only
|
|
875
|
-
interpreter handlers, so DML code, a nested `task/N`, and a direct host query
|
|
876
|
-
(the SDK's `runDML`, or `deepclause repl`) all resolve the same definition and
|
|
877
|
-
the same path.
|
|
878
|
-
|
|
879
|
-
`open/3`, `close/1`, `read_string/3` and `write/2` are SWI builtins and cannot be
|
|
880
|
-
shadowed, but they resolve paths the same way — the working directory is
|
|
881
|
-
`/workspace`, so `open("f.txt", read, S)` reads the workspace file. They are not
|
|
882
|
-
a special case with their own path rule.
|
|
883
|
-
|
|
884
|
-
Paths are **isolated by the mount, not by string checks**: there is no rewriting
|
|
885
|
-
layer, so a path is passed through to the filesystem as written. `..` does not
|
|
886
|
-
climb out of the workspace, because above `/workspace` is the VM's own empty
|
|
887
|
-
filesystem. The one thing a mount cannot police is a **symlink inside the
|
|
888
|
-
workspace** pointing outside it; avoid committing those.
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
### Output Predicates
|
|
892
|
-
|
|
893
|
-
#### `output(html(+Path))`
|
|
894
|
-
|
|
895
|
-
Display a workspace HTML file as an interactive miniapp:
|
|
896
|
-
|
|
897
|
-
```prolog
|
|
898
|
-
agent_main :-
|
|
899
|
-
output(html("miniapp/index.html")).
|
|
900
|
-
```
|
|
901
|
-
|
|
902
|
-
The path is workspace-relative. The web host loads the file, inlines relative
|
|
903
|
-
images, CSS and scripts from the same directory tree, and renders it in a
|
|
904
|
-
sandboxed iframe. The miniapp runs without same-origin access to the app.
|
|
905
|
-
|
|
906
|
-
Inside the miniapp, `window.dc.call(Goal)` runs a DML goal in the session or run
|
|
907
|
-
that rendered it and returns a promise:
|
|
908
|
-
|
|
909
|
-
```html
|
|
910
|
-
<script>
|
|
911
|
-
window.dc.call('double(21, X).').then((result) => {
|
|
912
|
-
console.log(result.bindings[0].value); // 42
|
|
913
|
-
});
|
|
914
|
-
</script>
|
|
915
|
-
```
|
|
916
|
-
|
|
917
|
-
The result contains `{ ok, output, bindings, error? }`. Calls are scoped to the
|
|
918
|
-
rendering owner; the iframe cannot access the app DOM, OPFS, cookies or other
|
|
919
|
-
sessions. Keep miniapp calls bounded and deterministic.
|
|
920
|
-
|
|
921
|
-
The same rendering is available through an `html-file` fenced block in an
|
|
922
|
-
answer. `output(html(Path))` is the DML-level form.
|
|
923
|
-
|
|
924
|
-
#### `output(+Text)`
|
|
925
|
-
|
|
926
|
-
Emit an output event to the caller. Does NOT affect the LLM conversation. Useful for progress updates:
|
|
927
|
-
|
|
928
|
-
```prolog
|
|
929
|
-
agent_main :-
|
|
930
|
-
output("Starting analysis..."),
|
|
931
|
-
task("Analyze the data"),
|
|
932
|
-
output("Analysis complete!"),
|
|
933
|
-
answer("Done").
|
|
934
|
-
```
|
|
935
|
-
|
|
936
|
-
**Use it for debugging.** When a predicate does not do what you expect, add
|
|
937
|
-
`output/1` calls between the steps: you see how far execution gets, what the
|
|
938
|
-
intermediate values actually are, and which call returned nothing. It costs one
|
|
939
|
-
line, it is invisible to the model (unlike a `task/N` description), and it is the
|
|
940
|
-
fastest way to find where a chain goes wrong:
|
|
941
|
-
|
|
942
|
-
```prolog
|
|
943
|
-
summarise(Doc, Summary) :-
|
|
944
|
-
extract_sections(Doc, Sections),
|
|
945
|
-
format(string(S), "sections: ~w", [Sections]), output(S),
|
|
946
|
-
pick_main(Sections, Main),
|
|
947
|
-
format(string(M), "main: ~w", [Main]), output(M),
|
|
948
|
-
task("Summarise this in one sentence: ~w", [Main], Summary).
|
|
949
|
-
```
|
|
950
|
-
|
|
951
|
-
Remove them before the final version, or keep the ones that read as progress
|
|
952
|
-
reports — a predicate that says what it is doing is easier to debug the next
|
|
953
|
-
time too.
|
|
954
|
-
|
|
955
|
-
#### `yield(+Text)`
|
|
956
|
-
|
|
957
|
-
Alias for `output/1`.
|
|
958
|
-
|
|
959
|
-
#### `log(+Text)`
|
|
960
|
-
|
|
961
|
-
Emit a log event. Similar to output but typed as 'log' for filtering:
|
|
962
|
-
|
|
963
|
-
```prolog
|
|
964
|
-
agent_main :-
|
|
965
|
-
log("Debug: entering main"),
|
|
966
|
-
task("Process request"),
|
|
967
|
-
log("Debug: task completed"),
|
|
968
|
-
answer("Done").
|
|
969
|
-
```
|
|
970
|
-
|
|
971
|
-
---
|
|
972
|
-
|
|
973
|
-
### `answer(+Text)`
|
|
974
|
-
|
|
975
|
-
Emit the final answer and **commit** - no backtracking occurs after `answer/1`:
|
|
976
|
-
|
|
977
|
-
```prolog
|
|
978
|
-
agent_main :-
|
|
979
|
-
task("Generate a poem"),
|
|
980
|
-
answer("Poem complete!"). % Execution stops here
|
|
981
|
-
```
|
|
982
|
-
|
|
983
|
-
**Important:** `answer/1` commits the execution. After answering, the program completes and does not try alternative clauses.
|
|
984
|
-
|
|
985
|
-
---
|
|
986
|
-
|
|
987
|
-
### Human input
|
|
988
|
-
|
|
989
|
-
#### `input(+Prompt, -Input)`
|
|
990
|
-
|
|
991
|
-
Ask the human and bind their reply. In the REPL this opens the editor's input
|
|
992
|
-
prompt; in a non-interactive run (`-g`, piped stdin, CI) it **fails** rather than
|
|
993
|
-
hang, so guard it when a goal may run unattended:
|
|
994
|
-
|
|
995
|
-
```prolog
|
|
996
|
-
asker(Question, Answer) :-
|
|
997
|
-
( input(Question, Answer)
|
|
998
|
-
-> true
|
|
999
|
-
; Answer = "(no answer available)"
|
|
1000
|
-
).
|
|
1001
|
-
```
|
|
1002
|
-
|
|
1003
|
-
### Conversation: `chat/1` and `input/1`
|
|
1004
|
-
|
|
1005
|
-
A conversation is a harness that talks with the person over many turns and acts
|
|
1006
|
-
between them. Failures of `input/1` end the loop.
|
|
1007
|
-
|
|
1008
|
-
`write/1`, `writeln/1` and `format/2` are captured as output events in the REPL
|
|
1009
|
-
(and in `execute`); outside it they write to the process stdout as usual.
|
|
1010
|
-
|
|
1011
|
-
#### `input(-Message)`
|
|
1012
|
-
|
|
1013
|
-
Wait for the person's **next message**, with no prompt — the embedding UI is a
|
|
1014
|
-
chat interface and is already asking. Fails when there is nobody to talk to (a
|
|
1015
|
-
non-interactive run), which is how a conversation loop ends:
|
|
1016
|
-
|
|
1017
|
-
```prolog
|
|
1018
|
-
loop :-
|
|
1019
|
-
input(A),
|
|
1020
|
-
chat(A),
|
|
1021
|
-
loop.
|
|
1022
|
-
```
|
|
1023
|
-
|
|
1024
|
-
`input/2` (with a prompt) is for a question inside a task; `input/1` is the turn
|
|
1025
|
-
boundary of a conversation.
|
|
1026
|
-
|
|
1027
|
-
#### `next(-Item)`
|
|
1028
|
-
|
|
1029
|
-
The next thing from the conversation **inbox**: `user(Text)` when the person
|
|
1030
|
-
speaks, or `message(Term)` when a worker (a subagent or service) sent this
|
|
1031
|
-
session a message. Fails when there is nothing left. This is how a conversation
|
|
1032
|
-
also reacts to events, without polling:
|
|
1033
|
-
|
|
1034
|
-
```prolog
|
|
1035
|
-
loop(Me) :- next(Item), handle(Me, Item), loop(Me).
|
|
1036
|
-
|
|
1037
|
-
handle(_, user(Text)) :- chat(Text).
|
|
1038
|
-
handle(_, message(mail(M))) :- system("New email."), chat("Summarise: {M}").
|
|
1039
|
-
```
|
|
1040
|
-
|
|
1041
|
-
`input/1` is `next/1` restricted to the person — a worker's message that arrives
|
|
1042
|
-
first stays queued for `next/1`.
|
|
1043
|
-
|
|
1044
|
-
#### `chat(+Message)` / `chat(+Message, -Reply)`
|
|
1045
|
-
|
|
1046
|
-
One **conversational turn**: append `Message` as the user message, run the agent
|
|
1047
|
-
loop with every `tool/N` the harness declares, and stop when the model stops
|
|
1048
|
-
calling tools. A traditional agent loop — no `finish`, no `set_result`, no
|
|
1049
|
-
nudging. The reply is streamed to the UI and kept in memory, so the next `chat/1`
|
|
1050
|
-
sees the conversation; `chat/2` also binds the last assistant message.
|
|
1051
|
-
|
|
1052
|
-
```prolog
|
|
1053
|
-
agent_main :-
|
|
1054
|
-
system("You are a support assistant. Be brief."),
|
|
1055
|
-
loop.
|
|
1056
|
-
|
|
1057
|
-
loop :- input(A), chat(A), loop.
|
|
1058
|
-
```
|
|
1059
|
-
|
|
1060
|
-
Use it as the foreground goal (not inside `execute` or a subagent). A turn may
|
|
1061
|
-
open a form, so structured input fits inside a conversation. **A failed turn does
|
|
1062
|
-
not end the conversation**: `chat/1` reports the failure, leaves memory as it was,
|
|
1063
|
-
and the next message starts a fresh turn. See
|
|
1064
|
-
[`docs/DML_CONVERSATION.md`](../../../../docs/DML_CONVERSATION.md).
|
|
1065
|
-
|
|
1066
|
-
### Forms (structured human input)
|
|
1067
|
-
|
|
1068
|
-
A form asks the human for typed, validated input and hands the values back keyed
|
|
1069
|
-
by field name. Forms are always available — there is no directive and nothing to
|
|
1070
|
-
enable.
|
|
1071
|
-
|
|
1072
|
-
**Two shapes**, by where the fields come from: **dynamic** — the model designs
|
|
1073
|
-
the form from a description (give `task/N` the form tools); **fixed** — the spec
|
|
1074
|
-
is written in the code, with no model. Both use the same registry and the same
|
|
1075
|
-
validation.
|
|
1076
|
-
|
|
1077
|
-
**The spec.** `version` is not needed and a field's `type` defaults to `string`:
|
|
1078
|
-
|
|
1079
|
-
```prolog
|
|
1080
|
-
Spec = _{ title: "Refund request",
|
|
1081
|
-
fields: [ _{name: amount, type: number, required: true},
|
|
1082
|
-
_{name: reason, type: string, widget: select, required: true,
|
|
1083
|
-
enum: ["duplicate_charge", "not_received", "other"]},
|
|
1084
|
-
_{name: notes, widget: textarea, maxLength: 500} ],
|
|
1085
|
-
actions: [ _{name: submit, title: "Issue refund", kind: primary},
|
|
1086
|
-
_{name: cancel, title: "Cancel", kind: link} ] }.
|
|
1087
|
-
```
|
|
1088
|
-
|
|
1089
|
-
Field `type` is `string` (default), `number`, `integer`, `boolean`, or an
|
|
1090
|
-
`object` / `array` group; `enum` requires a `string` field. `widget` is a
|
|
1091
|
-
presentation hint only — `text | textarea | number | slider | select | radio |
|
|
1092
|
-
multiselect | checkbox | switch | date | time | datetime | hidden` — and never
|
|
1093
|
-
affects validation. `actions` defaults to submit/cancel.
|
|
1094
|
-
|
|
1095
|
-
**Dynamic: a model drives the loop.** Give `task/N` the form tools and it
|
|
1096
|
-
designs the form from the prompt, waits, and reports:
|
|
1097
|
-
|
|
1098
|
-
```prolog
|
|
1099
|
-
with_tools([render_form, wait_for_form_change, close_form, set_result, finish],
|
|
1100
|
-
task("Ask for the amount and a reason, then report what the user entered.",
|
|
1101
|
-
string(Summary)))
|
|
1102
|
-
```
|
|
1103
|
-
|
|
1104
|
-
The model's three calls: `render_form(Spec)` → a form id;
|
|
1105
|
-
`wait_for_form_change(FormId)` → `{action, values, changed, errors}` with
|
|
1106
|
-
`action` = `"submit"` | `"cancel"`; `close_form(FormId)`.
|
|
1107
|
-
|
|
1108
|
-
In a **conversation** (`chat/1`) the third leg is optional: a chat turn does not
|
|
1109
|
-
end while a form it opened is still unanswered, so it waits for the person and
|
|
1110
|
-
hands back the submission. `wait_for_form_change` is then only needed for another
|
|
1111
|
-
round on a form you kept open.
|
|
1112
|
-
|
|
1113
|
-
**Fixed: the harness drives it itself**, with no model, using the primitives
|
|
1114
|
-
`form/2`, `form_update/2`, `form_errors/2`, `await_form/2,3` and `close_form/1`:
|
|
1115
|
-
|
|
1116
|
-
```prolog
|
|
1117
|
-
agent_main :-
|
|
1118
|
-
form(Spec, F), % render; F is the form handle
|
|
1119
|
-
await_form(F, Change), % blocks until the user acts
|
|
1120
|
-
close_form(F),
|
|
1121
|
-
( Change.action == submit % an atom: submit, cancel, …
|
|
1122
|
-
-> Change.values = Values % dict keyed by field name
|
|
1123
|
-
; Values = _{}
|
|
1124
|
-
).
|
|
1125
|
-
```
|
|
1126
|
-
|
|
1127
|
-
`Change` is `{ formId, revision, action, values, changed, errors }`; `action` is
|
|
1128
|
-
an **atom**.
|
|
1129
|
-
|
|
1130
|
-
**Validation is the host's.** On a submit the host enforces the spec (`required`,
|
|
1131
|
-
`enum`, ranges, `pattern`, lengths) and the harness's `form_validate(+Values,
|
|
1132
|
-
-Errors)`. A refused submit is never returned: the host puts the errors on the
|
|
1133
|
-
form and `await_form/2` / `wait_for_form_change` keeps waiting. Soft rules go in
|
|
1134
|
-
`form_advisories(+Values, -Advisories)` (never blocking; the `advisories` tool).
|
|
1135
|
-
|
|
1136
|
-
`form/2` and friends are **host handlers, not clauses**, so
|
|
1137
|
-
`current_predicate(form/2)` reports `no` — exactly as it does for `exec/2`. That
|
|
1138
|
-
is expected; it does not mean forms are unavailable. The model-facing tools
|
|
1139
|
-
(`render_form`, `update_form`, `set_form_issues`, `wait_for_form_change`,
|
|
1140
|
-
`validate_form`, `advisories`, `close_form`) are built in.
|
|
1141
|
-
|
|
1142
|
-
Full reference: `reference("forms")`.
|
|
1143
|
-
|
|
1144
|
-
---
|
|
1145
|
-
|
|
1146
|
-
## Processes and concurrency
|
|
1147
|
-
|
|
1148
|
-
A **process** (a "subagent") is an isolated DML execution with its own private
|
|
1149
|
-
memory, a private snapshot of this module, and a mailbox. Processes outlive the
|
|
1150
|
-
turn that started them, so a harness can background long work, wait for
|
|
1151
|
-
messages, or run many things at once.
|
|
1152
|
-
|
|
1153
|
-
Process primitives work anywhere a goal runs, including inside a `tool/2` body:
|
|
1154
|
-
a tool executes in its own engine, but `self/1` is the process the tool runs in,
|
|
1155
|
-
so a tool can route work to other processes.
|
|
1156
|
-
|
|
1157
|
-
A process runs the harness **as of its spawn**: later edits to a predicate do not
|
|
1158
|
-
reach a process already running, while a process spawned afterwards sees them.
|
|
1159
|
-
Inspect the code a process runs with `ps(code: "<pid or name>")`, and the
|
|
1160
|
-
session's current harness version with `ps(code: "")`.
|
|
1161
|
-
|
|
1162
|
-
### `spawn(+Goal, -Pid)` / `spawn_opt(+Goal, -Pid, +Options)`
|
|
1163
|
-
|
|
1164
|
-
Start `Goal` in a new process and return its pid immediately. `Goal` is **copied**:
|
|
1165
|
-
variables in the child are fresh, so a child can never bind a variable in the
|
|
1166
|
-
parent. A result comes back by message (`send/2`) or as the child's `answer/1`.
|
|
1167
|
-
|
|
1168
|
-
```prolog
|
|
1169
|
-
worker(Topic, Parent) :-
|
|
1170
|
-
task("Summarise {Topic} in one sentence.", string(Summary)),
|
|
1171
|
-
send(Parent, done(Topic, Summary)),
|
|
1172
|
-
answer(Summary).
|
|
1173
|
-
|
|
1174
|
-
fan_out(Topics, Results) :-
|
|
1175
|
-
self(Me),
|
|
1176
|
-
maplist(spawn_worker(Me), Topics, _Pids),
|
|
1177
|
-
collect(Topics, Results).
|
|
1178
|
-
|
|
1179
|
-
spawn_worker(Me, Topic, Pid) :- spawn(worker(Topic, Me), Pid).
|
|
1180
|
-
|
|
1181
|
-
collect([], []).
|
|
1182
|
-
collect([Topic|Topics], [Topic-Summary|Rest]) :-
|
|
1183
|
-
receive(done(Topic, Summary), 300000),
|
|
1184
|
-
collect(Topics, Rest).
|
|
1185
|
-
```
|
|
1186
|
-
|
|
1187
|
-
`spawn_opt/3` takes the keys `name`, `priority`
|
|
1188
|
-
(`foreground`/`interactive`/`background`), `timeout` (ms) and `code` — as a dict
|
|
1189
|
-
(`_{name: worker}`), a list (`[name(worker), priority(background)]`) or a single
|
|
1190
|
-
option (`name(worker)`). An option it does not understand is an error; it used to
|
|
1191
|
-
be ignored, so the process silently kept its default label.
|
|
1192
|
-
|
|
1193
|
-
The goal's shape decides the lifecycle:
|
|
1194
|
-
|
|
1195
|
-
- **one-shot** — calls `output/1`/`answer/1` and returns.
|
|
1196
|
-
- **message-waiting** — loops on `receive/1,2`, handling terms from other
|
|
1197
|
-
processes or from the user.
|
|
1198
|
-
- **interactive** — calls `input/2` and blocks until the user answers.
|
|
1199
|
-
|
|
1200
|
-
### `send(+Target, +Message)` / `receive(?Message[, +Timeout])`
|
|
1201
|
-
|
|
1202
|
-
`send/2` copies a term into another process's mailbox; `Target` is a pid, a
|
|
1203
|
-
registered name, or a process label. `receive/2` pops the oldest message and
|
|
1204
|
-
fails on timeout. `receive_match/3` pops the oldest message that unifies with a
|
|
1205
|
-
template, requeues the rest, and fails on timeout.
|
|
1206
|
-
|
|
1207
|
-
```prolog
|
|
1208
|
-
receive(request(From, Ref, Query), 30000),
|
|
1209
|
-
handle(Query, Answer),
|
|
1210
|
-
send(From, reply(Ref, Answer)).
|
|
1211
|
-
```
|
|
1212
|
-
|
|
1213
|
-
### `self/1`, `register/2`, `whereis/2`
|
|
1214
|
-
|
|
1215
|
-
`self(Pid)` is this process's pid. `register(Name, Pid)` names a process in the
|
|
1216
|
-
session; `whereis(Name, Pid)` resolves it. A name is released when the process
|
|
1217
|
-
exits. A process's default label is its goal's functor, so `send(keeper, stop)`
|
|
1218
|
-
reaches an unregistered `keeper/…` process.
|
|
1219
|
-
|
|
1220
|
-
### `serve(+Name, +Goal[, -Pid])` / `service_call(+Target, +Request, -Reply[, +Timeout])` / `service_cast(+Target, +Message)`
|
|
1221
|
-
|
|
1222
|
-
`serve/2` is `spawn/2` + `register/2` and binds nothing; `serve/3` also binds the
|
|
1223
|
-
pid (what you need to `stop`, `wait` or link it — `spawn/2` already returns one, so
|
|
1224
|
-
there is no separate "options" argument). `service_call` sends
|
|
1225
|
-
`request(Self, Ref, Request)` and waits for `reply(Ref, Reply)`, ignoring other
|
|
1226
|
-
messages; `service_cast` sends without waiting. A service is an ordinary
|
|
1227
|
-
`receive` loop:
|
|
1228
|
-
|
|
1229
|
-
```prolog
|
|
1230
|
-
counter_service(Count) :-
|
|
1231
|
-
receive(Msg),
|
|
1232
|
-
( Msg = request(From, Ref, read) -> send(From, reply(Ref, Count)), counter_service(Count)
|
|
1233
|
-
; Msg = request(From, Ref, bump) -> Next is Count + 1, send(From, reply(Ref, Next)), counter_service(Next)
|
|
1234
|
-
; Msg = stop -> true
|
|
1235
|
-
; counter_service(Count)
|
|
1236
|
-
).
|
|
1237
|
-
```
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
The process is labelled with `Name` (not the goal functor), so `ps`, `whereis/2`
|
|
1241
|
-
and `service_call/3` all use the same handle. `process_info/2` reports both the
|
|
1242
|
-
label and the registered names, and its `usage` counts model tokens — a relay
|
|
1243
|
-
service shows zeros while running.
|
|
1244
|
-
### `swarm(+Worker, +Items, -Results[, +Concurrency])` / `pmap(+Worker, +Items, -Values)`
|
|
1245
|
-
|
|
1246
|
-
Run `call(Worker, Item, Value)` once per item, each in its own process, and
|
|
1247
|
-
collect the results **in input order**. At most `Concurrency` items run at once
|
|
1248
|
-
(default 4), so a large list does not fire every model call simultaneously.
|
|
1249
|
-
`swarm` returns `ok(Value)`/`failed` per item; `pmap` returns bare values and
|
|
1250
|
-
fails if any item failed.
|
|
1251
|
-
|
|
1252
|
-
```prolog
|
|
1253
|
-
swarm(summarise_file, Files, Results, 4),
|
|
1254
|
-
findall(S, member(ok(S), Results), Summaries).
|
|
1255
|
-
```
|
|
1256
|
-
|
|
1257
|
-
### `suspend(+Continuation)`
|
|
1258
|
-
|
|
1259
|
-
Stop the turn at a **safe point** and let the host persist where to continue.
|
|
1260
|
-
`Continuation` is the goal that resumes — the entry point of the loop whose state
|
|
1261
|
-
is its argument:
|
|
1262
|
-
|
|
1263
|
-
```prolog
|
|
1264
|
-
loop(N) :-
|
|
1265
|
-
( N >= 2
|
|
1266
|
-
-> suspend(loop(N)) % stop; a later --session resumes with loop(N)
|
|
1267
|
-
; M is N + 1, loop(M)
|
|
1268
|
-
).
|
|
1269
|
-
```
|
|
1270
|
-
|
|
1271
|
-
The turn ends cleanly (like `answer/1`), the host records the continuation and the
|
|
1272
|
-
memory, and `deepclause repl --session <id>` runs it. **A turn cannot suspend while
|
|
1273
|
-
holding something a snapshot cannot carry**: an open stream (`open/3,4` … `close/1`)
|
|
1274
|
-
or an open form (`form/2` … `close_form/1`) makes it fail with
|
|
1275
|
-
`cannot suspend while holding …`. A suspension is always *between* host calls —
|
|
1276
|
-
never inside a `task/N`, `exec/2` or form wait — and the program chooses the point.
|
|
1277
|
-
See [`docs/DML_REPL_SUSPEND_RESUME.md`](../../../../docs/DML_REPL_SUSPEND_RESUME.md).
|
|
1278
|
-
|
|
1279
|
-
### `wait(+Pid[, -Outcome])`
|
|
1280
|
-
|
|
1281
|
-
Block until a process terminates, then report what happened. `Outcome` is
|
|
1282
|
-
`ok(Result)`, `failed(Error)`, or `killed(Reason)`; `Result` is the process's
|
|
1283
|
-
terminal text as a Prolog string. `wait/1` is semidet — it succeeds only on a
|
|
1284
|
-
successful finish.
|
|
1285
|
-
|
|
1286
|
-
```prolog
|
|
1287
|
-
spawn(research("qec", Me), Pid),
|
|
1288
|
-
wait(Pid, ok(Text)), % Text is the subagent's terminal text
|
|
1289
|
-
```
|
|
1290
|
-
|
|
1291
|
-
For a structured result, prefer the message form: have the child
|
|
1292
|
-
`send(Parent, result(Term))` and `receive` it in the parent.
|
|
1293
|
-
|
|
1294
|
-
### `exit/1,2` and stopping
|
|
1295
|
-
|
|
1296
|
-
`exit(Reason)` terminates the current process. `exit(Pid, Reason)` terminates
|
|
1297
|
-
another (a registered name or a process label works too); there is no `stop/1`
|
|
1298
|
-
predicate, so `exit/2` is how DML cancels a peer. (The `/stop` command and the
|
|
1299
|
-
`stop` tool are the interactive equivalents.) `process_info(Pid, Info)` returns a
|
|
1300
|
-
dict (`pid`, `name`, `state`, `priority`, `mailbox`, `usage`, …). `sleep(Ms)`
|
|
1301
|
-
yields; `now_ms(T)` and `make_ref(Ref)` are available.
|
|
1302
|
-
|
|
1303
|
-
### Rules
|
|
1304
|
-
|
|
1305
|
-
- **Isolation.** A process runs against a private module snapshot: its
|
|
1306
|
-
`assert`/`retract` do not affect the harness, and it does not see commits made
|
|
1307
|
-
after it started.
|
|
1308
|
-
- **Value semantics.** `spawn` and `send` copy terms; never rely on a shared
|
|
1309
|
-
variable with a child.
|
|
1310
|
-
- **Determinism.** A process that calls `task/N`, `exec/2`, `read_media/2`, or
|
|
1311
|
-
writes a file should yield one solution (`once/1`, `->`, `!`).
|
|
1312
|
-
- **Bound the work.** Every `swarm` item is a process and usually a model call;
|
|
1313
|
-
the session has a **live-process limit** (default 16 concurrent — finished
|
|
1314
|
-
processes do not count, so a long session can fan out again) and the provider
|
|
1315
|
-
has rate limits. A `swarm` item whose process cannot be spawned is reported as
|
|
1316
|
-
`failed(...)`; `pmap` then fails.
|
|
1317
|
-
- **CPU-bound Prolog** blocks the in-process host (L1). Long compute belongs in
|
|
1318
|
-
the REPL's `--execution worker` (L2), not a `swarm` on the default host.
|
|
1319
|
-
|
|
1320
|
-
---
|
|
1321
|
-
|
|
1322
|
-
## Control Flow
|
|
1323
|
-
|
|
1324
|
-
DML supports standard Prolog control flow:
|
|
1325
|
-
|
|
1326
|
-
### Conjunction (and)
|
|
1327
|
-
```prolog
|
|
1328
|
-
goal1, goal2, goal3
|
|
1329
|
-
```
|
|
1330
|
-
|
|
1331
|
-
### Disjunction (or)
|
|
1332
|
-
```prolog
|
|
1333
|
-
(goal1 ; goal2)
|
|
1334
|
-
```
|
|
1335
|
-
|
|
1336
|
-
### If-Then-Else
|
|
1337
|
-
```prolog
|
|
1338
|
-
(Condition -> Then ; Else)
|
|
1339
|
-
```
|
|
1340
|
-
|
|
1341
|
-
### If-Then (soft cut)
|
|
1342
|
-
```prolog
|
|
1343
|
-
(Condition -> Then)
|
|
1344
|
-
```
|
|
1345
|
-
|
|
1346
|
-
### Negation as Failure
|
|
1347
|
-
```prolog
|
|
1348
|
-
\+ goal
|
|
1349
|
-
```
|
|
1350
|
-
|
|
1351
|
-
### Cut
|
|
1352
|
-
```prolog
|
|
1353
|
-
!
|
|
1354
|
-
```
|
|
1355
|
-
|
|
1356
|
-
### Catch/Throw
|
|
1357
|
-
```prolog
|
|
1358
|
-
catch(Goal, Error, Recovery)
|
|
1359
|
-
throw(Error)
|
|
1360
|
-
```
|
|
1361
|
-
|
|
1362
|
-
---
|
|
1363
|
-
|
|
1364
|
-
## String Interpolation
|
|
1365
|
-
|
|
1366
|
-
Text arguments support `{variable}` interpolation with bound variables:
|
|
1367
|
-
|
|
1368
|
-
```prolog
|
|
1369
|
-
agent_main(Topic) :-
|
|
1370
|
-
system("You are a research assistant."),
|
|
1371
|
-
task("Research the topic: {Topic}"), % Topic is interpolated
|
|
1372
|
-
answer("Research on {Topic} complete!").
|
|
1373
|
-
```
|
|
1374
|
-
|
|
1375
|
-
---
|
|
1376
|
-
|
|
1377
|
-
## Patterns: one template, build or parse
|
|
1378
|
-
|
|
1379
|
-
`pattern/3` is `format/3` and its inverse. Literal text matches exactly and `$name`
|
|
1380
|
-
marks a slot, so the same template renders a string or parses it — the direction
|
|
1381
|
-
follows from what is bound:
|
|
1382
|
-
|
|
1383
|
-
```prolog
|
|
1384
|
-
pattern("Name: $name, age: $age", Text, [name="Ada", age=36]).
|
|
1385
|
-
% Text = "Name: Ada, age: 36"
|
|
1386
|
-
|
|
1387
|
-
pattern("Name: $name, age: $age", "Name: Ada, age: 36", Bindings).
|
|
1388
|
-
% Bindings = [name="Ada", age="36"]
|
|
1389
|
-
|
|
1390
|
-
pattern("DOI: $doi", Text, [doi=D]). % build a DOI line
|
|
1391
|
-
pattern("n=$n:int", "n=42", B). % B = [n=42] (typed slot)
|
|
1392
|
-
```
|
|
1393
|
-
|
|
1394
|
-
- Bindings are a list of `Name=Value`, so `member(Name=Value, Bs)` reads them.
|
|
1395
|
-
- A slot consumes **up to the next literal**, so the literals decide the split and
|
|
1396
|
-
`"$left - $right"` against `"a - b - c"` gives `left="a"`, `right="b - c"`.
|
|
1397
|
-
- `$name:type` converts on parse and validates on build. Types: `string` (default),
|
|
1398
|
-
`int`, `integer`, `number`. A parse that does not match throws, rather than
|
|
1399
|
-
binding the text.
|
|
1400
|
-
- Slot names match case- and separator-insensitively, like `dict_field/3`.
|
|
1401
|
-
- `$` is the marker rather than `{…}`, so a template can carry JSON or any other
|
|
1402
|
-
brace-bearing text verbatim, and it never collides with the `{Var}`
|
|
1403
|
-
interpolation in `task/N` descriptions. `$$` is a literal dollar.
|
|
1404
|
-
- A template must be **anchored by literal text**: `"$a$b"` is rejected as
|
|
1405
|
-
ambiguous rather than resolved arbitrarily.
|
|
1406
|
-
|
|
1407
|
-
This is the deterministic alternative to asking the model to reformat text: parse
|
|
1408
|
-
the parts you can read exactly, and use a `task/N` only for what genuinely needs
|
|
1409
|
-
language understanding.
|
|
1410
|
-
|
|
1411
|
-
## Backtracking
|
|
1412
|
-
|
|
1413
|
-
DML supports full Prolog backtracking, **including across LLM calls**. This enables powerful retry logic:
|
|
1414
|
-
|
|
1415
|
-
### Multiple Clauses
|
|
1416
|
-
```prolog
|
|
1417
|
-
% Try first approach
|
|
1418
|
-
agent_main :-
|
|
1419
|
-
output("Trying approach 1..."),
|
|
1420
|
-
task("Solve using method A"),
|
|
1421
|
-
fail. % Force failure to try next clause
|
|
1422
|
-
|
|
1423
|
-
% Fallback approach
|
|
1424
|
-
agent_main :-
|
|
1425
|
-
output("Trying approach 2..."),
|
|
1426
|
-
task("Solve using method B"),
|
|
1427
|
-
answer("Solved!").
|
|
1428
|
-
```
|
|
1429
|
-
|
|
1430
|
-
### State Restoration
|
|
1431
|
-
|
|
1432
|
-
When backtracking occurs, the memory state is automatically restored:
|
|
1433
|
-
|
|
1434
|
-
```prolog
|
|
1435
|
-
agent_main :-
|
|
1436
|
-
system("Context A"), % This is in memory
|
|
1437
|
-
output("Trying path A"),
|
|
1438
|
-
fail. % Memory is rolled back!
|
|
1439
|
-
|
|
1440
|
-
agent_main :-
|
|
1441
|
-
system("Context B"), % Fresh memory
|
|
1442
|
-
output("Trying path B"),
|
|
1443
|
-
answer("Done").
|
|
1444
|
-
```
|
|
1445
|
-
|
|
1446
|
-
### Disjunction Backtracking
|
|
1447
|
-
|
|
1448
|
-
```prolog
|
|
1449
|
-
agent_main :-
|
|
1450
|
-
(
|
|
1451
|
-
task("Try difficult approach"),
|
|
1452
|
-
fail % Backtrack
|
|
1453
|
-
;
|
|
1454
|
-
task("Try easier approach")
|
|
1455
|
-
),
|
|
1456
|
-
answer("Completed").
|
|
1457
|
-
```
|
|
1458
|
-
|
|
1459
|
-
---
|
|
1460
|
-
|
|
1461
|
-
## Full Prolog Support
|
|
1462
|
-
|
|
1463
|
-
DML is built on SWI-Prolog, so you have access to the full Prolog language — and
|
|
1464
|
-
to the constraint libraries (`clpfd`, `clpq`, `clpr`). Many questions are best
|
|
1465
|
-
answered by a plain Prolog or CLP goal run with `execute`, with no model call at
|
|
1466
|
-
all: arithmetic, counting, ordering, membership, `findall/3`, `aggregate_all/3`,
|
|
1467
|
-
list/set operations, and constraint or optimisation problems. Reach for `task/N`
|
|
1468
|
-
only when the step genuinely needs language understanding.
|
|
1469
|
-
|
|
1470
|
-
### Lists and common operations
|
|
1471
|
-
|
|
1472
|
-
A list is `[1,2,3]` or `[Head|Tail]`; the recursion below is the shape everything
|
|
1473
|
-
else is built on. Prefer the library predicates to hand-rolled recursion.
|
|
1474
|
-
|
|
1475
|
-
```prolog
|
|
1476
|
-
process_items([]).
|
|
1477
|
-
process_items([H|T]) :-
|
|
1478
|
-
format(string(Msg), "Processing: ~w", [H]),
|
|
1479
|
-
output(Msg),
|
|
1480
|
-
process_items(T).
|
|
1481
|
-
```
|
|
1482
|
-
|
|
1483
|
-
`maplist/3`, `include/3`, `exclude/3`, `foldl/4` and `predsort/3` take a **goal with
|
|
1484
|
-
extra arguments**, written `[X,Y]>>Goal` (a *yall* lambda). The list before `>>` is
|
|
1485
|
-
the extra arguments — so `[X,Y]>>(Y is X*X)` is a two-argument goal. The lambda's
|
|
1486
|
-
arity must match the predicate you are using.
|
|
1487
|
-
|
|
1488
|
-
**Transform**
|
|
1489
|
-
|
|
1490
|
-
| Want | Write |
|
|
1491
|
-
|---|---|
|
|
1492
|
-
| Apply to each | `maplist([X,Y]>>(Y is X*X), [1,2,3], L)` → `[1,4,9]` |
|
|
1493
|
-
| Combine two lists | `maplist([A,B,C]>>(C is A+B), [1,2], [10,20], L)` → `[11,22]` |
|
|
1494
|
-
| Apply, skipping failures | `convlist([X,Y]>>(integer(X), Y is X*2), [1,a,3], L)` → `[2,6]` |
|
|
1495
|
-
| Keep / drop matching | `include(P, L, Keep)` / `exclude(P, L, Drop)` |
|
|
1496
|
-
| Reduce to one value | `foldl([X,A0,A]>>(A is A0+X), [1,2,3], 0, S)` → `6` |
|
|
1497
|
-
| Reverse | `reverse([1,2,3], L)` |
|
|
1498
|
-
| Take / split | `append(Chunk, Rest, List)`, or `length(Chunk, 2)` to bound it |
|
|
1499
|
-
| A list of N blanks | `length(L, 3)` |
|
|
1500
|
-
|
|
1501
|
-
**Select and aggregate**
|
|
1502
|
-
|
|
1503
|
-
| Want | Write |
|
|
1504
|
-
|---|---|
|
|
1505
|
-
| Element at position | `nth0(1, [a,b,c], E)` (0-based) / `nth1(1, …, E)` (1-based) |
|
|
1506
|
-
| Remove one occurrence | `select(b, [a,b,c], L)` → `[a,c]` |
|
|
1507
|
-
| Check membership (once) | `memberchk(b, L)` — semidet, no choice point |
|
|
1508
|
-
| Last element | `last([a,b,c], E)` |
|
|
1509
|
-
| Sum | `sum_list([1,2,3], S)` → `6` |
|
|
1510
|
-
| Largest / smallest | `max_member(M, L)` / `min_member(M, L)` |
|
|
1511
|
-
| Any aggregate | `aggregate_all(max(N), member(N,[1,9,3]), M)` → `9`; also `min`, `sum`, `count`, `bag` |
|
|
1512
|
-
|
|
1513
|
-
**Sort, group, dedupe**
|
|
1514
|
-
|
|
1515
|
-
| Want | Write |
|
|
1516
|
-
|---|---|
|
|
1517
|
-
| Sort and dedupe | `sort([3,1,2,1], L)` → `[1,2,3]` |
|
|
1518
|
-
| Sort keeping duplicates | `msort([3,1,2,1], L)` → `[1,1,2,3]` (stable) |
|
|
1519
|
-
| Sort pairs by key | `keysort([b-2,a-1], L)` → `[a-1,b-2]` (stable) |
|
|
1520
|
-
| Sort compounds by an argument | `sort(2, @>=, [a-1,b-3,c-2], L)` — the `2` is the argument position |
|
|
1521
|
-
| Sort with your own comparison | `predsort([O,A,B]>>compare(O,A,B), L, Sorted)` |
|
|
1522
|
-
| Dedupe, keeping first order | `list_to_set([a,b,a,c], L)` → `[a,b,c]` |
|
|
1523
|
-
| Group by key | `group_pairs_by_key([a-1,a-2,b-3], G)` → `[a-[1,2], b-[3]]` |
|
|
1524
|
-
| Set difference / intersect / union | `subtract/3`, `intersection/3`, `union/3` |
|
|
1525
|
-
| Zip / unzip | `pairs_keys_values(Pairs, Keys, Values)`, `pairs_keys/2`, `pairs_values/2` |
|
|
1526
|
-
|
|
1527
|
-
**Strings in a list.** `split_string/4` leaves empty strings behind, which is the
|
|
1528
|
-
usual reason a list "has blanks in it":
|
|
1529
|
-
|
|
1530
|
-
```prolog
|
|
1531
|
-
split_string("a,,b", ",", "", Parts), % Parts = ["a","","b"]
|
|
1532
|
-
exclude(==(""), Parts, Clean). % Clean = ["a","b"]
|
|
1533
|
-
include(dif(""), Parts, Clean). % the same, by unification
|
|
1534
|
-
exclude(=([]), Lists, NonEmpty). % drop empty lists
|
|
1535
|
-
```
|
|
1536
|
-
|
|
1537
|
-
**A field from a list of dicts** — the most common list task with model output:
|
|
1538
|
-
|
|
1539
|
-
```prolog
|
|
1540
|
-
json_gets(Doc, "rows.*.name", Names), % one call, collects
|
|
1541
|
-
findall(N, (member(D, Dicts), dict_field(D, name, N)), Names). % from a list
|
|
1542
|
-
```
|
|
1543
|
-
|
|
1544
|
-
To sort a list of dicts, use `predsort/3`: `sort/4` addresses arguments of a
|
|
1545
|
-
compound and a dict has none.
|
|
1546
|
-
|
|
1547
|
-
**Batch a list into chunks.** There is no builtin; this is the definition:
|
|
1548
|
-
|
|
1549
|
-
```prolog
|
|
1550
|
-
chunks([], _, []).
|
|
1551
|
-
chunks(List, N, [Chunk|Rest]) :-
|
|
1552
|
-
N > 0,
|
|
1553
|
-
length(Chunk, N),
|
|
1554
|
-
append(Chunk, Tail, List),
|
|
1555
|
-
chunks(Tail, N, Rest).
|
|
1556
|
-
chunks(List, N, [List]) :-
|
|
1557
|
-
N > 0,
|
|
1558
|
-
length(List, Len),
|
|
1559
|
-
Len < N.
|
|
1560
|
-
% chunks([1,2,3,4,5], 2, L) -> L = [[1,2],[3,4],[5]]
|
|
23
|
+
```text
|
|
24
|
+
:- export([summarise/2, classify/2]).
|
|
1561
25
|
```
|
|
1562
26
|
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
- **`setof/3` and `bagof/3` fail when there are no solutions**; `findall/3` succeeds
|
|
1566
|
-
with `[]`. Use `findall/3` unless you want that failure.
|
|
1567
|
-
- **`sort/2` silently removes duplicates.** Use `msort/2` to keep them.
|
|
1568
|
-
- **`max_list([])` fails**, and `sum_list([a,b])` raises a type error — guard a
|
|
1569
|
-
possibly-empty or possibly-non-numeric list before aggregating.
|
|
1570
|
-
- **A nondeterministic goal inside `maplist`, `include` or `foldl` multiplies
|
|
1571
|
-
solutions**, and re-runs any model call in it. Keep the goal semidet
|
|
1572
|
-
(`once/1`, `->`, a cut).
|
|
1573
|
-
- **Not available in this build:** `nth0/4` (replace an element), `numlist/4` (range
|
|
1574
|
-
with a step), `chunk/3`, `rename_keys/3`. Replace an element with
|
|
1575
|
-
`nth0(I, L, _, Tail), nth0(I, New, V, Tail)`, and use `chunks/3` above.
|
|
1576
|
-
|
|
1577
|
-
### Arithmetic
|
|
1578
|
-
```prolog
|
|
1579
|
-
agent_main :-
|
|
1580
|
-
X is 10 + 5 * 2,
|
|
1581
|
-
format(string(Msg), "Result: ~w", [X]),
|
|
1582
|
-
answer(Msg).
|
|
1583
|
-
```
|
|
27
|
+
Import only the exports you use:
|
|
1584
28
|
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
format(string(S), "Hello ~w, you are ~d years old", [alice, 30]),
|
|
1589
|
-
answer(S).
|
|
29
|
+
```text
|
|
30
|
+
:- use_harness(support, [summarise/2]).
|
|
31
|
+
:- use_harness(support, version(3), [detail/1]).
|
|
1590
32
|
```
|
|
1591
33
|
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
findall(C, color(C), Colors),
|
|
1600
|
-
format(string(Msg), "Colors: ~w", [Colors]),
|
|
1601
|
-
answer(Msg).
|
|
1602
|
-
```
|
|
34
|
+
Imported predicates are read-only. Their private helpers remain private, and
|
|
35
|
+
the importing harness must not redefine or delete an imported predicate. The
|
|
36
|
+
host resolves and preloads dependency modules; imports do not inherit the other
|
|
37
|
+
harness's `shell/1`, tools, workflows or `agent_main`. Exported declarations are
|
|
38
|
+
validated at load time, and a version pin must resolve to a matching published
|
|
39
|
+
harness version. Prefer explicit arguments and pure exports over shared mutable
|
|
40
|
+
state. A cycle or missing export fails the load with a provenance error.
|
|
1603
41
|
|
|
1604
|
-
|
|
42
|
+
## Model operations
|
|
1605
43
|
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
has no threads) to bound it by inference count:
|
|
44
|
+
`task(Description, Outputs...)`: bounded model agent with DML harness memory and
|
|
45
|
+
scoped nested tools. Typed wrappers are load-time sugar, preserving variable names.
|
|
46
|
+
The loader supports task/1..5 and prompt/1..4; do not author internal task_named
|
|
47
|
+
or prompt_named forms. The no-output form is for work whose output is not consumed.
|
|
1611
48
|
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
).
|
|
1619
|
-
```
|
|
49
|
+
`prompt(Description, Outputs...)`: fresh model step, no harness tools, no memory
|
|
50
|
+
read/write. `with_fresh_memory(Goal)` isolates a group of accumulating tasks.
|
|
51
|
+
`llm(Messages, Reply)` accepts explicit messages (or supported text input), returns
|
|
52
|
+
raw text and leaves harness memory unchanged. Prefer typed prompt/task normally.
|
|
53
|
+
`chat(Message[, Reply])` is for a custom ongoing DML conversation, not a default
|
|
54
|
+
Work shell. Full memory/tool/type contracts are in `tasks`.
|
|
1620
55
|
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
`
|
|
56
|
+
Output wrappers: string, integer, number/float, boolean, list(Type), object,
|
|
57
|
+
schema(Name, Var), list(schema(Name, Vars)). Bare variables default to string.
|
|
58
|
+
`media(Var)` asks an image backend to generate an image path; it is not ordinary
|
|
59
|
+
text/vision and fails if no image backend is configured.
|
|
1624
60
|
|
|
1625
|
-
|
|
1626
|
-
sudoku_solve(Puzzle, Solution) :-
|
|
1627
|
-
...
|
|
1628
|
-
call_with_inference_limit(label(Solution), 500000, Result),
|
|
1629
|
-
( Result == inference_limit_exceeded
|
|
1630
|
-
-> throw(error(inference_limit_exceeded, context(sudoku_solve/2, label)))
|
|
1631
|
-
; true
|
|
1632
|
-
).
|
|
1633
|
-
```
|
|
61
|
+
## Memory and scopes
|
|
1634
62
|
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
63
|
+
`system(Text)` and `user(Text)` add backtrackable DML memory messages.
|
|
64
|
+
`get_memory(Messages)` binds current DML memory; it is not the authoring transcript.
|
|
65
|
+
`clear_memory` empties it. `push_context`/`pop_context` save/restore;
|
|
66
|
+
`push_context(clear)` also starts empty. Use with_fresh_memory for normal scopes.
|
|
67
|
+
A nested task in a tool starts fresh; explicit arguments carry context. Processes
|
|
68
|
+
have independent memory. A fresh prompt does not see attached images.
|
|
1639
69
|
|
|
1640
|
-
|
|
70
|
+
`with_tools([Name,...], Goal)` limits nested task tools; `without_tools` excludes
|
|
71
|
+
names. `with_model(Spec, Goal)` uses a different available model for scoped calls;
|
|
72
|
+
string specs use provider:model and optional #reasoning, or a model dict.
|
|
73
|
+
`with_reasoning(Goal, Level)` (GOAL FIRST) scopes supported reasoning effort.
|
|
74
|
+
`with_recipe(Goal, Query)` adds transient recipe context when the embedding has
|
|
75
|
+
configured a recipe library; it is not persistent memory. These scopes do not
|
|
76
|
+
change judgment backend; see judgments section for with_judgment/require_judgment.
|
|
77
|
+
Never invent a model id or infer credentials. Use current models/catalog.
|
|
1641
78
|
|
|
1642
|
-
|
|
1643
|
-
```prolog
|
|
1644
|
-
agent_main :-
|
|
1645
|
-
assertz(fact(42)),
|
|
1646
|
-
fact(X),
|
|
1647
|
-
format(string(Msg), "Stored fact: ~w", [X]),
|
|
1648
|
-
answer(Msg).
|
|
1649
|
-
```
|
|
79
|
+
## Sampling
|
|
1650
80
|
|
|
1651
|
-
|
|
81
|
+
`sample_token(Prompt, Token)` requests a fresh single-token text result;
|
|
82
|
+
`sample_token(Prompt, AllowedStrings, Token)` constrains the allowed frontier.
|
|
83
|
+
An out-of-set result is normalized/falls back to the first allowed entry; do not
|
|
84
|
+
use that fallback as evidence that an external condition was verified.
|
|
85
|
+
This is for a grammar/label frontier, not a replacement for typed task outputs.
|
|
86
|
+
`with_model` applies to it. For a semantic bounded choice prefer choose/4.
|
|
1652
87
|
|
|
1653
|
-
|
|
1654
|
-
puzzles, exact search). It is the wrong tool for ordinary arithmetic and
|
|
1655
|
-
transformations — prefer a `task/N`/`prompt/N` step when the numbers or the
|
|
1656
|
-
operation are open-ended (`DML_AUTHORING.md` §0). CLP also regresses easily: an
|
|
1657
|
-
under-specified model, or one that is simply **unsatisfiable**, can search
|
|
1658
|
-
essentially forever, so a buggy skill hangs the turn instead of failing fast.
|
|
1659
|
-
If you use it:
|
|
88
|
+
## Host calls and scripts
|
|
1660
89
|
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
- `all_distinct/1` / `all_different/1` over the list constrains it pairwise.
|
|
1665
|
-
- Call `label/1` (or `labeling/2` with options such as `ff`) only when you need
|
|
1666
|
-
concrete values; wrap it in `once/1` when a single witness is enough.
|
|
1667
|
-
- To bound a search that can run away, wrap it in `call_with_inference_limit/3`
|
|
1668
|
-
(see *Bounding a goal* above):
|
|
1669
|
-
`call_with_inference_limit(label(Xs), 500000, R)` — `R == inference_limit_exceeded`
|
|
1670
|
-
when it gave up. This works for CLP(FD) predicates in this runtime.
|
|
1671
|
-
- Keep the model small; a big model is a sign the step belongs in a `task/N`.
|
|
90
|
+
`exec(Tool(key: Value,...), Result)` invokes a CURRENT registered host capability.
|
|
91
|
+
Do not copy an arbitrary tool name from another embedding. Read topic tools for
|
|
92
|
+
actual schemas; topic python is the browser Python contract.
|
|
1672
93
|
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
94
|
+
`run_script(Name, Args, Value)` resolves script_file(Name, Path), stringifies atomic
|
|
95
|
+
arguments, checks exitCode and parses JSON stdout (else returns stdout).
|
|
96
|
+
Nonzero exit throws script_failed. Define/script link names must not overlap:
|
|
1676
97
|
|
|
1677
98
|
```prolog
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
% Small, fully bounded search; one witness.
|
|
1681
|
-
solve_sum_product(Total, X, Y) :-
|
|
1682
|
-
[X, Y] ins 0..100, % bound the domains; never leave them open
|
|
1683
|
-
X + Y #= Total,
|
|
1684
|
-
X * Y #= 2400,
|
|
1685
|
-
once(label([X, Y])).
|
|
1686
|
-
|
|
1687
|
-
% A search bounded by inference count instead of by the domain.
|
|
1688
|
-
bounded_label(Xs, Result) :-
|
|
1689
|
-
call_with_inference_limit(label(Xs), 500000, Result).
|
|
99
|
+
script_file(count_py, "scripts/count.py").
|
|
100
|
+
count_words(File, Count) :- run_script(count_py, [File], Stats), get_dict(words, Stats, Count).
|
|
1690
101
|
```
|
|
1691
102
|
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
**CLP(R)** (reals) — there is no `clpfq`. `library(simplex)` loads but returns
|
|
1696
|
-
unreliable answers in this runtime (its minimum/maximum come back wrong); do not
|
|
1697
|
-
build on it.
|
|
1698
|
-
|
|
1699
|
-
**Continuous LP** — `clpr` (reals) / `clpq` (rationals), same interface. `{...}`
|
|
1700
|
-
posts the constraints; `maximize/1` / `minimize/1` find the optimum:
|
|
1701
|
-
|
|
1702
|
-
```prolog
|
|
1703
|
-
:- use_module(library(clpr)).
|
|
1704
|
-
|
|
1705
|
-
lp(X, Y) :-
|
|
1706
|
-
{X >= 0, Y >= 0, X =< 10, Y =< 10, X + 2*Y =< 14},
|
|
1707
|
-
maximize(X + Y). % X = 10.0, Y = 2.0
|
|
1708
|
-
```
|
|
103
|
+
`Args` is a list. A script should print one JSON result with newline; diagnostics
|
|
104
|
+
belong on stderr. Export bundles LINKED files. A successful host call returning an
|
|
105
|
+
error/nonzero dict is not necessarily success of the requested operation.
|
|
1709
106
|
|
|
1710
|
-
|
|
1711
|
-
> is a *unique vertex*. If the optimum is a face (a family of optima), they succeed
|
|
1712
|
-
> and bind nothing. Use `sup/2` / `inf/2` to get the optimum **value** reliably —
|
|
1713
|
-
> `{X >= 0, Y >= 0, X + Y =< 10, 2*X + Y =< 15}, sup(X + Y, S)` → `S = 10.0`.
|
|
1714
|
-
> (`inf/3` / `sup/3` do not exist in this build.)
|
|
107
|
+
## Nested tools
|
|
1715
108
|
|
|
1716
|
-
|
|
1717
|
-
comes back as the integer vertex:
|
|
109
|
+
Define a real predicate and a same-name/same-arity delegating annotation:
|
|
1718
110
|
|
|
1719
111
|
```prolog
|
|
1720
|
-
:-
|
|
1721
|
-
|
|
1722
|
-
mip(Inf, Vertex) :-
|
|
1723
|
-
{X >= 0, Y >= 0, X + Y =< 4, X + 3*Y =< 6},
|
|
1724
|
-
bb_inf([X, Y], -(3*X + 2*Y), Inf, Vertex, 0.001).
|
|
1725
|
-
% Inf = -12.0, Vertex = [4,0] (negate the objective to maximise)
|
|
112
|
+
double(N, R) :- R is N * 2.
|
|
113
|
+
tool(double(N, R), "Double a number.", [number]) :- double(N, R).
|
|
1726
114
|
```
|
|
1727
115
|
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
:- use_module(library(clpfd)).
|
|
1735
|
-
|
|
1736
|
-
exact_max(X, Y) :-
|
|
1737
|
-
[X, Y] ins 0..10,
|
|
1738
|
-
X + Y #=< 4,
|
|
1739
|
-
X + 3*Y #=< 6,
|
|
1740
|
-
call_with_inference_limit(labeling([max(3*X + 2*Y), down], [X, Y]), 500000, _).
|
|
1741
|
-
% X = 4, Y = 0
|
|
1742
|
-
```
|
|
116
|
+
Last argument is the ONLY output, earlier ones are inputs. The optional type list
|
|
117
|
+
labels inputs; missing types default to string. Multi-field results go in one dict.
|
|
118
|
+
Do not call tool/N as an ordinary DML goal; the loader registers the annotation.
|
|
119
|
+
Scope each tool-using task. Avoid an LLM-backed step advertising itself as the
|
|
120
|
+
same tool to its own nested task. Work shell tools are a separate explicit
|
|
121
|
+
interface with inputs/outputs; see shell topic.
|
|
1743
122
|
|
|
1744
|
-
|
|
123
|
+
## Output and entry results
|
|
1745
124
|
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
125
|
+
`output(Text)` emits progress without model-memory changes; `yield/1` aliases it.
|
|
126
|
+
`log(Text)` emits a diagnostic event. `answer(Text)` emits a final one-shot answer
|
|
127
|
+
and terminates execution via the answer commit; it does NOT commit code edits.
|
|
128
|
+
Workflow/helper/tool outputs must be bound arguments and normal return, not answer.
|
|
1750
129
|
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
130
|
+
`output(media(Path))`, `output(media{svg: Svg})` display images; `save_image/2`
|
|
131
|
+
saves a reference. Browser `output(html(Path))` renders a workspace miniapp.
|
|
132
|
+
Read media for distinctions between display, vision and generation.
|
|
1754
133
|
|
|
1755
|
-
|
|
1756
|
-
dict_field(Dict, "affiliation", Affiliation), % fails if absent
|
|
1757
|
-
dict_field(Dict, full_name, "unknown", Name), % with a default
|
|
1758
|
-
```
|
|
134
|
+
## Data and schemas
|
|
1759
135
|
|
|
1760
|
-
|
|
1761
|
-
|
|
136
|
+
`schema(Name, Fields)` declares fields with `field(Name, Type, required)` or
|
|
137
|
+
`default(Value)`; types include primitives, list(Type), schema(Name) and nested
|
|
138
|
+
schema(Name, _). `schema_fill(Name, Raw, Filled)` fills defaults and checks types.
|
|
139
|
+
Task schema outputs fail if required/wrong-typed fields are invalid. Extra fields
|
|
140
|
+
are retained, not silently dropped.
|
|
141
|
+
Dict keys are atoms. `get_dict(Key, Dict, Value)` is strict; use dict_field/3,4
|
|
142
|
+
for model-varying keys and optional defaults.
|
|
1762
143
|
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
atom_json_dict(Text,
|
|
1766
|
-
|
|
144
|
+
JSON helpers: `json_get(D, Path, V)`, `json_get(D, Path, Default, V)`,
|
|
145
|
+
`json_gets(D, "rows.*.name", Values)`, `json_put(D, KeyPath, V, Updated)`,
|
|
146
|
+
`json_text(D, Text)`, `atom_json_dict(Text, D, [])` in either direction.
|
|
147
|
+
Missing json_get path fails; explicit-default arity supplies a default.
|
|
1767
148
|
|
|
1768
|
-
|
|
149
|
+
## Strings and interpolation
|
|
1769
150
|
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
json_text(Doc, Text), % compact JSON
|
|
1778
|
-
```
|
|
151
|
+
The loader interpolates bound `{Variable}` in supported DML text positions such
|
|
152
|
+
as task/prompt descriptions and output/answer. For arbitrary strings use
|
|
153
|
+
`format(string(S), "~w ~d ~n", [Term, Number])`; ~q quotes a read-back-safe term,
|
|
154
|
+
~s writes text, ~w writes values. Strings escape newline/quotes/backslashes.
|
|
155
|
+
`pattern(Template, Text, Bindings)` builds/parses small anchored templates;
|
|
156
|
+
$name slots use `name=Value` pairs, $name:int converts numbers, $$ is a dollar.
|
|
157
|
+
Do not build a large custom parser where a script fits.
|
|
1779
158
|
|
|
1780
|
-
|
|
1781
|
-
visible. Key matching is the same tolerant match as `dict_field/3` (atom or string,
|
|
1782
|
-
any case, `_`/`-`/space ignored). `json_put/4` sets keys and creates intermediate
|
|
1783
|
-
dicts; it rejects an index path, so lists are read-only. For layout or streaming,
|
|
1784
|
-
`json_write_dict/3` from `library(http/json)` is available.
|
|
159
|
+
## Grammars and parameters
|
|
1785
160
|
|
|
1786
|
-
|
|
1787
|
-
|
|
161
|
+
DCGs (`-->`) are expanded by the DML loader. A grammar needs a list input;
|
|
162
|
+
`library(dcg/basics)` normally expects character CODES. Do not hand a Prolog
|
|
163
|
+
string to phrase/2 and assume it is a code list.
|
|
1788
164
|
|
|
1789
165
|
```prolog
|
|
1790
166
|
:- use_module(library(dcg/basics)).
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
`
|
|
1804
|
-
|
|
1805
|
-
`
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
##
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
Each element of `Specs` is `Question - Output`. The output variable is bound
|
|
1878
|
-
when the batch completes.
|
|
1879
|
-
|
|
1880
|
-
```prolog
|
|
1881
|
-
agent_main(Message) :-
|
|
1882
|
-
judge(Message, [
|
|
1883
|
-
choose("Which team should handle this?",
|
|
1884
|
-
[billing-"Charges and refunds", orders-"Delivery and returns",
|
|
1885
|
-
account-"Login and security"]) - Team,
|
|
1886
|
-
rate("How frustrated is the customer?", [calm, frustrated, angry]) - Frustration,
|
|
1887
|
-
verify("Does the message ask for a refund?") - Refund,
|
|
1888
|
-
probability("Is this urgent?") - Urgency
|
|
1889
|
-
]),
|
|
1890
|
-
( Refund == yes
|
|
1891
|
-
-> answer("Escalating to the refund queue.")
|
|
1892
|
-
; format(string(R), "Routing to ~w (frustration ~w, urgency ~w)", [Team, Frustration, Urgency]),
|
|
1893
|
-
answer(R)
|
|
1894
|
-
).
|
|
1895
|
-
```
|
|
1896
|
-
|
|
1897
|
-
Question forms:
|
|
1898
|
-
|
|
1899
|
-
- `choose(Instruction, Options)` - options are atoms or `Option-"description"`.
|
|
1900
|
-
- `rate(Instruction, Levels)` - an ordered list of level descriptions.
|
|
1901
|
-
- `verify(Instruction)` / `verify(Instruction, criteria(True, False))`.
|
|
1902
|
-
- `probability(Instruction)`.
|
|
1903
|
-
|
|
1904
|
-
### One-off predicates
|
|
1905
|
-
|
|
1906
|
-
Each is a single request for a single judgment:
|
|
1907
|
-
|
|
1908
|
-
```prolog
|
|
1909
|
-
choose(State, Question, Options, Choice)
|
|
1910
|
-
rate(State, Question, Levels, Level)
|
|
1911
|
-
verify(State, Question, Truth) % yes | no | unknown
|
|
1912
|
-
probability(State, Question, P) % number
|
|
1913
|
-
holds(State, Question) % semidet: succeeds when verify == yes
|
|
1914
|
-
holds(State, Question, Threshold) % semidet: probability >= Threshold
|
|
1915
|
-
```
|
|
1916
|
-
|
|
1917
|
-
### Backends and capabilities
|
|
1918
|
-
|
|
1919
|
-
Judgments are backend-agnostic. Backends are registered on the SDK
|
|
1920
|
-
(`createDeepClause({ judgeBackends, defaultJudge })`) and can be selected per
|
|
1921
|
-
run or per scope:
|
|
167
|
+
number_value(N) --> integer(N).
|
|
168
|
+
parse_number(Text, N) :- string_codes(Text, Codes), phrase(number_value(N), Codes).
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
For session inputs/configuration, `param(Name, Value)` reads declared parameter
|
|
172
|
+
facts; `:- param(Name, Value).` is a supported load directive. Positional run
|
|
173
|
+
inputs are normally predicate arguments. Never invent undeclared free variables
|
|
174
|
+
or use a parameter name as assignment syntax. Read current host configuration
|
|
175
|
+
before relying on optional limits, recipe libraries or resume behavior.
|
|
176
|
+
|
|
177
|
+
## Control and deterministic glue
|
|
178
|
+
|
|
179
|
+
Conjunction `A,B`, alternatives `(A;B)`, committed `(C->T;E)`, negation `\+ G`,
|
|
180
|
+
unification `=`, arithmetic `is`/`=:=`, identity `==`, disequality dif/2,
|
|
181
|
+
`once/1`, cut `!`, `catch/3` and `throw/1` are supported. Read basics for modes.
|
|
182
|
+
A cut commits its clause and the goals to its left, and is scoped by `\+`,
|
|
183
|
+
`call/1`, `findall/3` and if-then-else. This holds in pure predicates (run
|
|
184
|
+
natively) and in interpreted ones that call `task/N`, `exec/2`, `output/1`, forms
|
|
185
|
+
or processes (the cut is compiled to `once/1` plus a clause commit), so prefer a
|
|
186
|
+
cut over defensive re-checking. Goals after the cut still enumerate.
|
|
187
|
+
Backtracking restores logical bindings/memory; it does NOT undo host/file actions.
|
|
188
|
+
Select one intended effectful path. Pure relations may intentionally enumerate.
|
|
189
|
+
|
|
190
|
+
Lists/library glue: maplist, include, exclude, foldl, member/memberchk, findall,
|
|
191
|
+
aggregate_all, sum_list, sort/msort, keysort, nth0/3, append, reverse. Availability
|
|
192
|
+
of a particular library builtin should be checked with a pure bounded query;
|
|
193
|
+
handlers such as form/exec do not appear as ordinary current_predicate clauses.
|
|
194
|
+
See snippets for focused recipes. Do not use LLMs for exact arithmetic/counting.
|
|
195
|
+
|
|
196
|
+
## Files and persistence
|
|
197
|
+
|
|
198
|
+
The runtime environment states workspace paths and isolation. Browser DML/Python
|
|
199
|
+
share /workspace; private tmp filesystems differ. DML write_file/2 needs existing
|
|
200
|
+
parent directories; the authoring write_file TOOL creates parents. read_file/2,
|
|
201
|
+
write_file/2, append_file/2, directory_files/2, exists_file/1, exists_directory/1,
|
|
202
|
+
size_file/2 and time_file/2 are common helpers. directory_files returns bare names.
|
|
203
|
+
Use scripts for substantial byte/file operations. Do not assume native shell
|
|
204
|
+
binaries, symlink policy or host paths from another environment.
|
|
205
|
+
Authoring commits, runtime session facts, process snapshots and workspace records
|
|
206
|
+
have different lifetimes. Explicitly choose/test storage; a runtime assert is not
|
|
207
|
+
an authoring end_turn. Never bake secrets into facts/history/exported scripts.
|
|
208
|
+
|
|
209
|
+
## Forms and human input
|
|
210
|
+
|
|
211
|
+
No forms activation directive is required, but the execution host must support
|
|
212
|
+
interaction. Foreground Work/query/run paths can render forms; browser scratch
|
|
213
|
+
execute and worker-hosted processes cannot. input(Prompt, Answer) asks a question
|
|
214
|
+
where a host is attached. input(Message) waits for the next conversational turn;
|
|
215
|
+
next(Item) dispatches user(Text)/message(Term) for a custom event-driven loop.
|
|
216
|
+
|
|
217
|
+
Fixed form lifecycle: form(Spec, F), await_form(F, Change), close_form(F).
|
|
218
|
+
Change.action is an atom such as submit/cancel/unavailable; values is a dict.
|
|
219
|
+
Hard validation is host-enforced; rejected submits stay waiting. Never treat
|
|
220
|
+
cancel/unavailable as saved values. Read forms before implementing this path.
|
|
221
|
+
|
|
222
|
+
## Processes
|
|
223
|
+
|
|
224
|
+
spawn/2, spawn_opt/3, serve/2,3, send/2, receive/1,2, receive_match/3,
|
|
225
|
+
self/1, register/2, whereis/2, service_call/3,4, service_cast/2,
|
|
226
|
+
wait/1,2, exit/1,2, process_info/2, sleep/1 and make_ref/1 are process APIs.
|
|
227
|
+
Copies are by value: child output variables never bind parent variables.
|
|
228
|
+
Use bounded messages/wait outcomes and stop/reap test workers.
|
|
229
|
+
swarm/3,4 returns ordered ok(Value)/failed per independent item; pmap/3 returns
|
|
230
|
+
bare values, failing if any worker fails. Default concurrency is 4; bound it.
|
|
231
|
+
Use processes topic for exact message envelopes, snapshot and filesystem rules.
|
|
232
|
+
`suspend(Continuation)` needs a supported resume host and closed streams/forms;
|
|
233
|
+
suspend only at a safe point between calls, never inside a model/host wait.
|
|
234
|
+
|
|
235
|
+
## Judgments
|
|
236
|
+
|
|
237
|
+
`choose(State, Question, Options, Choice)`, `rate(State, Question, Levels, Level)`,
|
|
238
|
+
`verify(State, Question, Truth)`, `probability(State, Question, P)`, holds/2,3.
|
|
239
|
+
`judge(State, Specs)` batches specs such as choose(Question, Options)-Choice.
|
|
240
|
+
Choose returns a supplied atom; verify is yes/no/unknown. Supply real evidence;
|
|
241
|
+
judgments do not see task memory/images and are not a guarantee of external state.
|
|
242
|
+
`with_judgment(Backend, Goal)` selects a configured backend;
|
|
243
|
+
`require_judgment(Capability, Goal)` requires calibrated/probability/etc support.
|
|
244
|
+
`with_model` does not select the judgment backend. Inspect actual registration.
|
|
245
|
+
|
|
246
|
+
## Constraint search
|
|
247
|
+
|
|
248
|
+
Use CLP only for a genuine small bounded search. Library directives must be
|
|
249
|
+
TOP LEVEL so operators exist at parse time. Use clpfd for finite integers,
|
|
250
|
+
clpq for rationals, clpr for reals. There is no clpfq. Avoid relying on simplex
|
|
251
|
+
in this build. Bound domains BEFORE labeling, and bound inference separately.
|
|
1922
252
|
|
|
1923
253
|
```prolog
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
> **In the DML REPL**, an `llm` backend is always registered (it reuses the
|
|
1929
|
-
> active model), and `jev` is registered when `judgment.jev.enabled` is set in
|
|
1930
|
-
> `.deepclause/config.json` and its API key is available. `with_judgment(jev,
|
|
1931
|
-
> ...)` fails if `jev` is not registered.
|
|
1932
|
-
|
|
1933
|
-
`require_judgment/2` fails the wrapped goal before it runs when the active
|
|
1934
|
-
backend does not provide the capability, so a skill that depends on calibrated
|
|
1935
|
-
probabilities cannot silently run on an uncalibrated backend. Available
|
|
1936
|
-
capabilities include `calibrated`, `probability`, `confidence`, and
|
|
1937
|
-
`independentQuestions`.
|
|
1938
|
-
|
|
1939
|
-
Observations are memoized per run by backend, model, state, and questions, so
|
|
1940
|
-
backtracking reuses an answer instead of re-querying the model.
|
|
1941
|
-
|
|
1942
|
-
### Notes
|
|
1943
|
-
|
|
1944
|
-
- `verify` is three-valued: `yes`, `no`, or `unknown`. Never read `\+` as
|
|
1945
|
-
"the model said no"; use the returned truth value.
|
|
1946
|
-
- Values are constrained to the options/levels you supply. A `choose` answer is
|
|
1947
|
-
always one of your option atoms.
|
|
1948
|
-
- Prefer one `judge/2` batch over several one-off calls when you need more than
|
|
1949
|
-
one or two judgments.
|
|
1950
|
-
### Load-time directives
|
|
1951
|
-
|
|
1952
|
-
A `.dml` file may contain directives. These are handled:
|
|
1953
|
-
|
|
1954
|
-
```prolog
|
|
1955
|
-
:- use_module(library(clpfd)). % library import
|
|
1956
|
-
:- consult("other.dml"). % load another workspace file
|
|
1957
|
-
:- param(topic, "the subject"). % declared session parameter
|
|
1958
|
-
:- repl_delete(old_skill/2). % remove a predicate (same as the bare fact form)
|
|
1959
|
-
:- require_sandbox. % refuse to load unless the shell is sandboxed
|
|
254
|
+
:- use_module(library(clpfd)).
|
|
255
|
+
solve(Total, X, Y) :-
|
|
256
|
+
[X,Y] ins 0..20, X + Y #= Total, X #< Y,
|
|
257
|
+
once(label([X,Y])).
|
|
1960
258
|
```
|
|
1961
259
|
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
check. Only the **user** sets this (the `/set-require-sandbox` command); an agent
|
|
1968
|
-
cannot add or remove it.
|
|
1969
|
-
|
|
1970
|
-
`:- repl_delete(Name/Arity).` abolishes a predicate, which `retract/1` cannot do:
|
|
1971
|
-
retracting the last clause leaves an empty predicate whose calls fail silently.
|
|
1972
|
-
The bare fact form `repl_delete(Name/Arity).` works the same way.
|
|
1973
|
-
|
|
1974
|
-
These apply to a file **loaded** into a session (`deepclause repl -l file.dml`).
|
|
1975
|
-
They are not the way to edit a live harness. `consult/1`, a file-list directive and
|
|
1976
|
-
`use_module/1` on a workspace `.dml` assert straight into the module rather than
|
|
1977
|
-
through the REPL's edit tools, so the predicates they add are absent from the
|
|
1978
|
-
transaction's tracked set — the nondeterminism probe does not see them, and a
|
|
1979
|
-
directive that fails inside the file only warns. They do still appear in the next
|
|
1980
|
-
commit's diff, so the change is recorded without any account of where it came from —
|
|
1981
|
-
and outside a transaction there is no snapshot, so nothing validates the load at all.
|
|
1982
|
-
An agent changing a harness adds code with `assert`/`assert_many`/`define` inside a
|
|
1983
|
-
transaction instead.
|
|
1984
|
-
|
|
1985
|
-
Any other directive does nothing, and the loader now says so — it reports
|
|
1986
|
-
`unrecognised directive ignored: …` after the file loads, so a directive that
|
|
1987
|
-
never took effect is not mistaken for one that did. `dynamic/1`,
|
|
1988
|
-
`discontiguous/1` and `multifile/1` are accepted and ignored silently, since
|
|
1989
|
-
session predicates are asserted and already behave that way.
|
|
1990
|
-
|
|
1991
|
-
A **predicate with no clauses fails silently** when called — it does not error —
|
|
1992
|
-
so an emptied or never-written predicate looks like "no results" at the call site.
|
|
1993
|
-
`current_predicate(Name/Arity)` in a `/goal` answers whether it exists, and a
|
|
1994
|
-
`doc/2` for a predicate with no clauses is reported at `end_turn`.
|
|
1995
|
-
|
|
1996
|
-
## The DML REPL (`deepclause repl`)
|
|
1997
|
-
|
|
1998
|
-
DML skills can also be grown interactively in a persistent **living module**.
|
|
260
|
+
A single builtin may not yield to the interpreter's gas counter;
|
|
261
|
+
call_with_inference_limit(Goal, Bound, Result) can report inference_limit_exceeded.
|
|
262
|
+
A scratch execute worker has wall-time limits but foreground goals differ.
|
|
263
|
+
Do not replace exact search with invented model output if the constraint model
|
|
264
|
+
fails. Read the available SWI API before advanced optimization options.
|
|
1999
265
|
|
|
2000
|
-
|
|
2001
|
-
`goal: <dml>.` form still works).
|
|
2002
|
-
- Plain English builds the module: the **authoring agent** inspects and edits it
|
|
2003
|
-
through tools (`listing`, `begin_turn`, `define`/`assert`/`assert_many`,
|
|
2004
|
-
`retract`/`delete`, `execute`, `end_turn`/`rollback`). Edits are transactions:
|
|
2005
|
-
`begin_turn` is required before any edit, `end_turn` commits a version.
|
|
2006
|
-
Nothing is auto-run; the agent uses `execute` to test during a turn.
|
|
2007
|
-
- There is **no implicit `agent_main` requirement** in the REPL. Run any
|
|
2008
|
-
predicate with `/goal <name>(…)`. Define `agent_main` in the module when it
|
|
2009
|
-
should also run with `deepclause run` / `/dc-run`.
|
|
2010
|
-
- `freeze.` makes the module read-only; `export <file>.` serializes it.
|
|
2011
|
-
`export harness.zip` bundles the module with its linked script files;
|
|
2012
|
-
`export harness.dml` inlines them into one portable file.
|
|
2013
|
-
- `input/2` / `exec(ask_user(...))` (module) ask the human. They never block in
|
|
2014
|
-
non-interactive runs (`-g`, piped stdin, CI).
|
|
266
|
+
## Editing and directives
|
|
2015
267
|
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
untrusted data through files or stdin, never interpolated into the shell
|
|
2022
|
-
command.
|
|
268
|
+
Authoring tools: listing, begin_turn, define, delete, end_turn, rollback, execute,
|
|
269
|
+
reference and available file/media/process tools. Define/delete are the only
|
|
270
|
+
predicate edit operations; each requires a transaction. Keyed annotation delete
|
|
271
|
+
forms are doc:Name/Arity, schema:Name and script_file:Name; tool:Name removes the
|
|
272
|
+
nested annotation only. An arity change needs deleting the old predicate/doc key.
|
|
2023
273
|
|
|
2024
|
-
|
|
274
|
+
System library imports use `:- use_module(library(...)).` Unknown directives are
|
|
275
|
+
reported ignored. consult/load on user DML are user load actions, not authoring
|
|
276
|
+
edits; do not bypass tracked transactions. The user controls sandbox requirements.
|
|
277
|
+
No compiler translates Markdown to DML. Author valid DML and test it directly.
|