deepclause-sdk 0.3.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 +148 -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 +467 -53
- package/dist/cli/repl.js.map +1 -1
- package/dist/cli/run.d.ts.map +1 -1
- package/dist/cli/run.js +4 -0
- package/dist/cli/run.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 +2596 -268
- package/dist/prolog-src/deepclause_strings.pl +36 -3
- package/dist/repl/agent.d.ts +12 -0
- package/dist/repl/agent.d.ts.map +1 -1
- package/dist/repl/agent.js +40 -16
- 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 +26 -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 +75 -3
- package/dist/repl/history.d.ts.map +1 -1
- package/dist/repl/history.js +155 -4
- package/dist/repl/history.js.map +1 -1
- package/dist/repl/index.d.ts +33 -5
- package/dist/repl/index.d.ts.map +1 -1
- package/dist/repl/index.js +30 -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 +17 -0
- package/dist/repl/render.js.map +1 -1
- package/dist/repl/session.d.ts +166 -23
- package/dist/repl/session.d.ts.map +1 -1
- package/dist/repl/session.js +980 -188
- 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 +7 -1
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +81 -23
- package/dist/runner.js.map +1 -1
- package/dist/runtime-identity.json +10 -0
- package/dist/system/assets/docs/AGENT_PROMPT.md +265 -2943
- package/dist/system/assets/docs/DML_AUTHORING.md +81 -295
- 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 -1912
- 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 +62 -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 +2596 -268
- package/src/prolog-src/deepclause_strings.pl +36 -3
package/dist/repl/session.js
CHANGED
|
@@ -12,19 +12,23 @@ import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate';
|
|
|
12
12
|
import { loadProlog, mountWorkspace, takePrologMessages, } from '../prolog/loader.js';
|
|
13
13
|
import { describeShellExecutionBackend, } from '../system/runtime/shell-manager.js';
|
|
14
14
|
import { getWorkspaceDocAssetPath } from '../system/assets/index.js';
|
|
15
|
+
import { REFERENCE_TOPICS, referenceTopic, referenceIndex, renderReference } from './reference.js';
|
|
15
16
|
import { DMLRunner, toJsValue } from '../runner.js';
|
|
17
|
+
import { resolveReplJudgeSelection } from './judge.js';
|
|
16
18
|
import { DmlProcessExecutor } from './process-executor.js';
|
|
17
19
|
import { pidKey } from './processes.js';
|
|
18
|
-
import { compactMemory, estimateMemoryTokens, shouldCompact, toCompactionEvent, } from './compaction.js';
|
|
20
|
+
import { compactMemory, boundCompactionSettings, estimateMemoryTokens, shouldCompact, toCompactionEvent, } from './compaction.js';
|
|
19
21
|
import { HarnessAgent } from './agent.js';
|
|
20
|
-
import { BRIEF_VALUE_CHARS, createHarnessTools } from './harness-tools.js';
|
|
21
|
-
import { buildParamsTerm, plainValue, quotePrologString } from './frames.js';
|
|
22
|
+
import { BRIEF_VALUE_CHARS, createHarnessTools, createWorkAgentTools } from './harness-tools.js';
|
|
23
|
+
import { buildParamsTerm, plainValue, quoteAtom, quotePrologString } from './frames.js';
|
|
22
24
|
import { buildHarnessHeader, } from './export.js';
|
|
23
|
-
import { HistoryStore, harnessHash, moduleVersion, } from './history.js';
|
|
25
|
+
import { HistoryStore, assertHarnessName, assertSessionId, harnessHash, moduleVersion, } from './history.js';
|
|
24
26
|
import { buildDiagramPrompt, extractMermaid, parseMermaidFlowchart, rasterizeSvg, renderFlowchartSvg, renderMermaidAscii, resolveMedia, validateMermaid, } from '../visualize/index.js';
|
|
25
27
|
import { generateLlmReply } from '../prolog/bridge.js';
|
|
26
28
|
import { FormRegistry } from '../forms/registry.js';
|
|
27
29
|
import { formatModelCatalogEntry } from './model-resolver.js';
|
|
30
|
+
import { historyEventFromRecord } from './event-history.js';
|
|
31
|
+
import { buildWorkSystemPrompt, executeWorkEntry, formatWorkResult, renderWorkShell, validateWorkShell, workShellDiagnostics } from '../work/index.js';
|
|
28
32
|
/**
|
|
29
33
|
* Context note added when a saved session is reloaded. The opening words are
|
|
30
34
|
* also the de-duplication marker in `repl_note_resumed/2` — keep them in sync.
|
|
@@ -32,6 +36,54 @@ import { formatModelCatalogEntry } from './model-resolver.js';
|
|
|
32
36
|
const RESUME_NOTE = 'This session was reloaded from a saved snapshot and its transient state was reset: '
|
|
33
37
|
+ 'the harness and conversation memory were restored, but any subagents/services running '
|
|
34
38
|
+ 'before are gone. Re-create anything you still need.';
|
|
39
|
+
/** Predicate indicators declared by `:- export(...)` directives. */
|
|
40
|
+
function exportedIndicators(source) {
|
|
41
|
+
const found = [];
|
|
42
|
+
for (const match of source.matchAll(/^\s*:-\s*export\s*\(([\s\S]*?)\)\s*\./gm)) {
|
|
43
|
+
for (const indicator of match[1].matchAll(/([a-z][A-Za-z0-9_]*)\s*\/\s*(\d+)/g)) {
|
|
44
|
+
const value = `${indicator[1]}/${indicator[2]}`;
|
|
45
|
+
if (!found.includes(value))
|
|
46
|
+
found.push(value);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return found;
|
|
50
|
+
}
|
|
51
|
+
const FOREIGN_CLAUSE_HEAD = /^([a-z][A-Za-z0-9_]*)\s*(?:\(|\.|:-)/;
|
|
52
|
+
function extractForeignPredicate(source, selection) {
|
|
53
|
+
const name = selection.split('/')[0];
|
|
54
|
+
const lines = source.split('\n');
|
|
55
|
+
let start = -1;
|
|
56
|
+
for (let index = 0; index < lines.length; index++) {
|
|
57
|
+
const match = FOREIGN_CLAUSE_HEAD.exec(lines[index]);
|
|
58
|
+
if (match?.[1] === name) {
|
|
59
|
+
start = index;
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (start < 0)
|
|
64
|
+
return '';
|
|
65
|
+
let end = start + 1;
|
|
66
|
+
for (; end < lines.length; end++) {
|
|
67
|
+
const match = FOREIGN_CLAUSE_HEAD.exec(lines[end]);
|
|
68
|
+
if (match && match[1] !== name)
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
return lines.slice(start, end).join('\n').trimEnd();
|
|
72
|
+
}
|
|
73
|
+
function foreignFilter(filter) {
|
|
74
|
+
const match = /^harness:([a-z][a-z0-9_]*)(?::(.*))?$/.exec(filter.trim());
|
|
75
|
+
return match ? { name: match[1], selection: (match[2] ?? 'all').trim() || 'all' } : null;
|
|
76
|
+
}
|
|
77
|
+
/** JSON text for a trace payload; never throw because a value is cyclic. */
|
|
78
|
+
function traceJson(value) {
|
|
79
|
+
try {
|
|
80
|
+
const text = JSON.stringify(value);
|
|
81
|
+
return text === undefined ? 'null' : text;
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return String(value);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
35
87
|
const RESUME_NOTE_PREFIX = 'This session was reloaded';
|
|
36
88
|
let sessionCounter = 0;
|
|
37
89
|
/**
|
|
@@ -39,55 +91,6 @@ let sessionCounter = 0;
|
|
|
39
91
|
* subagent are served strictly in order (see `requireInput`).
|
|
40
92
|
*/
|
|
41
93
|
let sharedInputQueue = Promise.resolve();
|
|
42
|
-
/** Rebuild a `DMLEvent` from a persisted history record, or undefined. */
|
|
43
|
-
function historyEventFromRecord(record) {
|
|
44
|
-
const type = typeof record.type === 'string' ? record.type : undefined;
|
|
45
|
-
if (!type)
|
|
46
|
-
return undefined;
|
|
47
|
-
const frameKind = typeof record.frame === 'string' ? record.frame : undefined;
|
|
48
|
-
const content = typeof record.content === 'string' ? record.content : undefined;
|
|
49
|
-
switch (type) {
|
|
50
|
-
case 'stream':
|
|
51
|
-
return content ? { type, frameKind, content } : undefined;
|
|
52
|
-
case 'output':
|
|
53
|
-
case 'answer':
|
|
54
|
-
case 'error':
|
|
55
|
-
return { type, frameKind, content };
|
|
56
|
-
case 'log':
|
|
57
|
-
return { type, frameKind, content, level: record.level };
|
|
58
|
-
case 'tool_call':
|
|
59
|
-
return {
|
|
60
|
-
type,
|
|
61
|
-
frameKind,
|
|
62
|
-
toolName: typeof record.toolName === 'string' ? record.toolName : undefined,
|
|
63
|
-
toolState: record.toolState,
|
|
64
|
-
toolSummary: typeof record.toolSummary === 'string' ? record.toolSummary : undefined,
|
|
65
|
-
toolArgs: record.toolArgs,
|
|
66
|
-
toolResult: record.toolResult,
|
|
67
|
-
toolError: typeof record.toolError === 'string' ? record.toolError : undefined,
|
|
68
|
-
toolDurationMs: typeof record.toolDurationMs === 'number' ? record.toolDurationMs : undefined,
|
|
69
|
-
toolExitCode: typeof record.toolExitCode === 'number' ? record.toolExitCode : undefined,
|
|
70
|
-
};
|
|
71
|
-
case 'solution':
|
|
72
|
-
return {
|
|
73
|
-
type,
|
|
74
|
-
frameKind,
|
|
75
|
-
solution: {
|
|
76
|
-
bindings: (Array.isArray(record.bindings) ? record.bindings : []),
|
|
77
|
-
deterministic: false,
|
|
78
|
-
},
|
|
79
|
-
};
|
|
80
|
-
case 'task_activity':
|
|
81
|
-
return {
|
|
82
|
-
type,
|
|
83
|
-
frameKind,
|
|
84
|
-
taskState: record.taskState,
|
|
85
|
-
taskDescription: typeof record.taskDescription === 'string' ? record.taskDescription : undefined,
|
|
86
|
-
};
|
|
87
|
-
default:
|
|
88
|
-
return undefined;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
94
|
/** The log-view line for an event, or undefined for per-tick noise. */
|
|
92
95
|
function processLogText(event) {
|
|
93
96
|
switch (event.type) {
|
|
@@ -128,6 +131,7 @@ export class DMLSession {
|
|
|
128
131
|
model;
|
|
129
132
|
provider;
|
|
130
133
|
tools;
|
|
134
|
+
authoringTools;
|
|
131
135
|
toolPolicy;
|
|
132
136
|
inputHandler;
|
|
133
137
|
/** Host-side interaction for an opened form (docs/DML_FORMS.md). */
|
|
@@ -147,6 +151,9 @@ export class DMLSession {
|
|
|
147
151
|
/** Persisted authoring-agent conversation (agent mode). */
|
|
148
152
|
agentMessages = [];
|
|
149
153
|
harnessAgent;
|
|
154
|
+
/** Active host-tool trace scopes; nested tool calls push/pop here. */
|
|
155
|
+
traceToolIds = [];
|
|
156
|
+
traceToolSeq = 0;
|
|
150
157
|
/** Open edit transaction (agent mode): predicate list at snapshot. */
|
|
151
158
|
transactionBefore = null;
|
|
152
159
|
transactionDirty = false;
|
|
@@ -160,13 +167,18 @@ export class DMLSession {
|
|
|
160
167
|
modelCallsThisTurn = 0;
|
|
161
168
|
/** Current budget; grows by maxModelCalls when the user extends it. */
|
|
162
169
|
modelCallBudget;
|
|
163
|
-
|
|
164
|
-
dmlAuthoring;
|
|
165
|
-
dmlForms;
|
|
166
|
-
harnessExamples;
|
|
167
|
-
harnessPatterns;
|
|
168
|
-
prologSnippets;
|
|
170
|
+
referenceDocs = new Map();
|
|
169
171
|
disposed = false;
|
|
172
|
+
lifetime = new AbortController();
|
|
173
|
+
activeRequestSignal;
|
|
174
|
+
purpose;
|
|
175
|
+
activeOperation;
|
|
176
|
+
pinnedWorkHash;
|
|
177
|
+
pinnedWorkVersion;
|
|
178
|
+
pinnedWorkShell;
|
|
179
|
+
pinnedWorkSource;
|
|
180
|
+
baseSourceHash;
|
|
181
|
+
pinnedWorkScripts;
|
|
170
182
|
/** History recorder; present only when the caller enables it. */
|
|
171
183
|
history;
|
|
172
184
|
historyOptions;
|
|
@@ -197,6 +209,7 @@ export class DMLSession {
|
|
|
197
209
|
static PROCESS_LOG_LIMIT = 500;
|
|
198
210
|
/** Service declarations replayed from the session record (resume only). */
|
|
199
211
|
recordedServices = [];
|
|
212
|
+
pendingSuspensionValue;
|
|
200
213
|
/** Monotonic per-session turn counter used by history records. */
|
|
201
214
|
turnCounter = 0;
|
|
202
215
|
historyWarned = false;
|
|
@@ -204,10 +217,11 @@ export class DMLSession {
|
|
|
204
217
|
this.swipl = swipl;
|
|
205
218
|
this.sessionId = options.sessionId ?? nextSessionId();
|
|
206
219
|
this.workspacePath = options.workspacePath;
|
|
207
|
-
this.gasLimit = options.gasLimit;
|
|
220
|
+
this.gasLimit = options.gasLimit ?? ((options.mode ?? (options.workMode ? 'work' : 'develop')) === 'work' ? 1_000_000 : undefined);
|
|
208
221
|
this.model = options.runnerOptions.model;
|
|
209
222
|
this.provider = String(options.runnerOptions.provider);
|
|
210
223
|
this.tools = options.tools ?? new Map();
|
|
224
|
+
this.authoringTools = options.authoringTools ?? new Map();
|
|
211
225
|
this.toolPolicy = options.toolPolicy ?? null;
|
|
212
226
|
this.inputHandler = options.onInput
|
|
213
227
|
?? (options.askUser ? (prompt, choices) => options.askUser(prompt, choices).then((r) => ('cancelled' in r ? undefined : r.answer)) : undefined)
|
|
@@ -222,10 +236,18 @@ export class DMLSession {
|
|
|
222
236
|
this.resume = options.resume ?? false;
|
|
223
237
|
this.harnessName = options.harnessName ?? 'main';
|
|
224
238
|
this.executionBackend = options.executionBackend ?? 'clean-room';
|
|
225
|
-
this.executionEnvironment =
|
|
239
|
+
this.executionEnvironment = this.executionBackend === 'wasm'
|
|
240
|
+
? {
|
|
241
|
+
kind: 'wasm',
|
|
242
|
+
backendLabel: 'wasm',
|
|
243
|
+
description: 'WebAssembly sandbox in the browser',
|
|
244
|
+
sandboxed: true,
|
|
245
|
+
}
|
|
246
|
+
: describeShellExecutionBackend(this.executionBackend === 'agentvm', this.executionBackend === 'agentvm' ? {} : { wrapper: this.executionBackend });
|
|
226
247
|
this.autoLoadHarness = options.autoLoadHarness ?? true;
|
|
227
248
|
this.openOptions = options;
|
|
228
|
-
this.
|
|
249
|
+
this.purpose = options.mode ?? (options.workMode ? 'work' : 'develop');
|
|
250
|
+
this.compactionSettings = options.compaction ? boundCompactionSettings(options.compaction.settings, options.contextWindow) : undefined;
|
|
229
251
|
this.compactionAuto = options.compaction?.auto ?? false;
|
|
230
252
|
this.contextWindow = options.contextWindow;
|
|
231
253
|
this.llmBackend = options.runnerOptions.llmBackend;
|
|
@@ -233,8 +255,24 @@ export class DMLSession {
|
|
|
233
255
|
this.modelResolver = options.runnerOptions.modelResolver;
|
|
234
256
|
this.temperature = options.runnerOptions.temperature;
|
|
235
257
|
this.maxTokens = options.runnerOptions.maxTokens;
|
|
258
|
+
// Direct DMLSession users (notably the browser child workers) do not go
|
|
259
|
+
// through createHarnessRepl's judge wiring. Without a default selection,
|
|
260
|
+
// judge/2 fails with "Unknown judgment backend: llm".
|
|
261
|
+
const judgeSelection = options.runnerOptions.judgeSelection
|
|
262
|
+
?? resolveReplJudgeSelection({
|
|
263
|
+
llmBackend: options.runnerOptions.llmBackend,
|
|
264
|
+
model: options.runnerOptions.model,
|
|
265
|
+
provider: String(options.runnerOptions.provider),
|
|
266
|
+
temperature: options.runnerOptions.temperature,
|
|
267
|
+
maxTokens: options.runnerOptions.maxTokens,
|
|
268
|
+
baseUrl: options.runnerOptions.baseUrl,
|
|
269
|
+
providerOptions: options.runnerOptions.providerOptions,
|
|
270
|
+
defaultJudge: options.defaultJudge,
|
|
271
|
+
jev: options.jev,
|
|
272
|
+
}).selection;
|
|
236
273
|
this.runner = new DMLRunner(swipl, {
|
|
237
274
|
...options.runnerOptions,
|
|
275
|
+
judgeSelection,
|
|
238
276
|
environment: this.executionEnvironment,
|
|
239
277
|
capabilityTool: options.capabilityTool,
|
|
240
278
|
compactMessages: options.compaction
|
|
@@ -244,6 +282,29 @@ export class DMLSession {
|
|
|
244
282
|
this.runner.bindSession(this.sessionId);
|
|
245
283
|
}
|
|
246
284
|
static async open(options) {
|
|
285
|
+
if (options.resume && options.sessionId && options.history) {
|
|
286
|
+
const store = new HistoryStore(options.workspacePath ?? process.cwd(), options.sessionId, options.history);
|
|
287
|
+
const meta = await store.readSessionMetadata();
|
|
288
|
+
const explicit = options.mode ?? (options.workMode === undefined ? undefined : options.workMode ? 'work' : 'develop');
|
|
289
|
+
if (!meta?.mode && !explicit)
|
|
290
|
+
throw new Error('Legacy session has no recorded mode. Resume with explicit mode develop or work and the original harness name.');
|
|
291
|
+
if (!meta?.harness && !options.harnessName)
|
|
292
|
+
throw new Error('Legacy session has no recorded harness. Specify the original harness explicitly.');
|
|
293
|
+
if (meta?.mode && explicit && meta.mode !== explicit)
|
|
294
|
+
throw new Error(`Session is ${meta.mode}; open a separate ${explicit} conversation instead of changing its purpose.`);
|
|
295
|
+
if (meta?.harness && options.harnessName && meta.harness !== options.harnessName)
|
|
296
|
+
throw new Error(`Session belongs to harness '${meta.harness}', not '${options.harnessName}'.`);
|
|
297
|
+
options = { ...options, mode: meta?.mode ?? explicit, harnessName: meta?.harness ?? options.harnessName,
|
|
298
|
+
sessionKind: meta?.kind ?? options.sessionKind, origin: options.origin ?? meta?.origin };
|
|
299
|
+
}
|
|
300
|
+
if (options.mode !== undefined && options.mode !== 'develop' && options.mode !== 'work')
|
|
301
|
+
throw new Error('Invalid session purpose');
|
|
302
|
+
if (options.gasLimit !== undefined && (!Number.isSafeInteger(options.gasLimit) || options.gasLimit < -1))
|
|
303
|
+
throw new Error('gasLimit must be an integer >= -1');
|
|
304
|
+
if (options.sessionId)
|
|
305
|
+
assertSessionId(options.sessionId);
|
|
306
|
+
if (options.harnessName)
|
|
307
|
+
assertHarnessName(options.harnessName);
|
|
247
308
|
const swipl = await loadProlog();
|
|
248
309
|
const session = new DMLSession(swipl, options);
|
|
249
310
|
// Mount the workspace so DML file I/O and `[file].` consult resolve under
|
|
@@ -262,6 +323,7 @@ export class DMLSession {
|
|
|
262
323
|
const store = new HistoryStore(options.workspacePath ?? process.cwd(), session.sessionId, options.history, session.harnessName);
|
|
263
324
|
snapshot = await store.readSessionHarness();
|
|
264
325
|
session.recordedServices = await store.readServiceRecords();
|
|
326
|
+
session.pendingSuspensionValue = (await store.readSuspendRecord()) ?? undefined;
|
|
265
327
|
// A session can have a transcript but no harness snapshot (older builds,
|
|
266
328
|
// or a turn interrupted before its first commit). Resume it from the
|
|
267
329
|
// current harness instead of refusing to open it; the transcript reader
|
|
@@ -276,8 +338,8 @@ export class DMLSession {
|
|
|
276
338
|
sandbox: session.executionBackend.replace(/-/g, '_'),
|
|
277
339
|
...options.params,
|
|
278
340
|
};
|
|
279
|
-
if (
|
|
280
|
-
sessionParams.gas_limit =
|
|
341
|
+
if (session.gasLimit !== undefined) {
|
|
342
|
+
sessionParams.gas_limit = session.gasLimit;
|
|
281
343
|
}
|
|
282
344
|
const harnessMemory = snapshot?.memory?.harness?.trim()
|
|
283
345
|
? snapshot.memory.harness
|
|
@@ -287,6 +349,9 @@ export class DMLSession {
|
|
|
287
349
|
if (!result) {
|
|
288
350
|
throw new Error('Failed to create REPL session');
|
|
289
351
|
}
|
|
352
|
+
if (snapshot?.harnessModules?.length)
|
|
353
|
+
session.openOptions.harnessModules = snapshot.harnessModules;
|
|
354
|
+
await session.loadHarnessModules();
|
|
290
355
|
await session.initHistory();
|
|
291
356
|
if (snapshot) {
|
|
292
357
|
if (snapshot.memory?.agent) {
|
|
@@ -295,6 +360,13 @@ export class DMLSession {
|
|
|
295
360
|
await session.restoreHarnessFromHistory(snapshot);
|
|
296
361
|
session.noteSessionResumed();
|
|
297
362
|
}
|
|
363
|
+
else if (options.harnessSnapshot) {
|
|
364
|
+
const loaded = await session.loadCode(options.harnessSnapshot.source);
|
|
365
|
+
if (loaded.error) {
|
|
366
|
+
await session.dispose();
|
|
367
|
+
throw new Error(loaded.error);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
298
370
|
else if (session.autoLoadHarness) {
|
|
299
371
|
// One harness per name: a fresh session starts from the harness's current
|
|
300
372
|
// content file (`harness.dml`), not an empty module.
|
|
@@ -327,11 +399,98 @@ export class DMLSession {
|
|
|
327
399
|
/* non-fatal: absolute paths still resolve */
|
|
328
400
|
}
|
|
329
401
|
}
|
|
402
|
+
if (session.purpose === 'work') {
|
|
403
|
+
try {
|
|
404
|
+
await session.materializeMissingEmbeddedScripts();
|
|
405
|
+
}
|
|
406
|
+
catch (error) {
|
|
407
|
+
await session.dispose();
|
|
408
|
+
throw error;
|
|
409
|
+
}
|
|
410
|
+
session.pinnedWorkVersion = snapshot?.version ?? options.harnessSnapshot?.version ?? session.history?.currentVersion;
|
|
411
|
+
session.pinnedWorkShell = snapshot?.workIdentity?.shell;
|
|
412
|
+
session.pinnedWorkSource = snapshot?.workIdentity?.source;
|
|
413
|
+
session.pinnedWorkScripts = snapshot?.workIdentity?.scripts ?? snapshot?.scripts;
|
|
414
|
+
if (!session.isEmpty()) {
|
|
415
|
+
const scripts = await session.scriptHashes();
|
|
416
|
+
const stateHash = harnessHash(session.moduleSource(), scripts);
|
|
417
|
+
const programHash = harnessHash(session.canonicalSource(), scripts);
|
|
418
|
+
const expected = snapshot?.hash ?? options.harnessSnapshot?.hash;
|
|
419
|
+
const offeredSource = snapshot?.module ?? options.harnessSnapshot?.source;
|
|
420
|
+
// Validate the exact source carried over the host boundary. Re-rendering
|
|
421
|
+
// can reorder annotations without changing a valid, untouched snapshot.
|
|
422
|
+
const offeredHash = offeredSource === undefined ? undefined : harnessHash(offeredSource, scripts);
|
|
423
|
+
if (expected && expected !== offeredHash && expected !== (snapshot ? stateHash : programHash) && expected !== stateHash) {
|
|
424
|
+
await session.dispose();
|
|
425
|
+
throw new Error('Saved Work snapshot or linked scripts changed. Refresh before starting a new run.');
|
|
426
|
+
}
|
|
427
|
+
session.pinnedWorkHash = snapshot?.workIdentity?.hash ?? programHash;
|
|
428
|
+
await session.workSpec();
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
if (!session.isEmpty())
|
|
432
|
+
await session.persistSessionHarness(snapshot?.version ?? session.history?.currentVersion ?? 0);
|
|
330
433
|
return session;
|
|
331
434
|
}
|
|
332
435
|
getSessionId() {
|
|
333
436
|
return this.sessionId;
|
|
334
437
|
}
|
|
438
|
+
async setTitle(title) { await this.history?.updateSessionMetadata({ title: title.trim().slice(0, 120) }); }
|
|
439
|
+
async sessionInfo() {
|
|
440
|
+
return { ...(await this.history?.readSessionMetadata() ?? {}), id: this.sessionId, harness: this.harnessName,
|
|
441
|
+
mode: this.purpose, kind: this.openOptions.sessionKind ?? 'conversation', model: this.model, backend: this.provider };
|
|
442
|
+
}
|
|
443
|
+
workShellErrors() {
|
|
444
|
+
const shell = this.shell();
|
|
445
|
+
if (shell)
|
|
446
|
+
return validateWorkShell(shell, this.harnessView().predicates);
|
|
447
|
+
return this.predicateArities('shell').some(arity => arity === 1 || arity === 3)
|
|
448
|
+
? ['The shell declaration cannot be read. Declare shell/1 as a supported fact and quote metadata names, e.g. name: "Query".'] : [];
|
|
449
|
+
}
|
|
450
|
+
async workSpec() {
|
|
451
|
+
const shell = this.shell();
|
|
452
|
+
const errors = this.workShellErrors();
|
|
453
|
+
const diagnostics = !shell && errors.length ? [] : workShellDiagnostics(shell);
|
|
454
|
+
diagnostics.push(...errors);
|
|
455
|
+
const scripts = await this.scriptHashes();
|
|
456
|
+
const stateHash = harnessHash(this.canonicalSource(), scripts);
|
|
457
|
+
const scriptsChanged = this.purpose === 'work' && this.pinnedWorkScripts && JSON.stringify(this.pinnedWorkScripts) !== JSON.stringify(scripts);
|
|
458
|
+
if (scriptsChanged)
|
|
459
|
+
diagnostics.push('Linked scripts changed. Refresh into a new Work snapshot.');
|
|
460
|
+
if (this.purpose === 'work' && shell && !errors.length) {
|
|
461
|
+
this.pinnedWorkHash ??= stateHash;
|
|
462
|
+
this.pinnedWorkShell ??= structuredClone(shell);
|
|
463
|
+
this.pinnedWorkSource ??= this.moduleSource();
|
|
464
|
+
this.pinnedWorkScripts ??= scripts;
|
|
465
|
+
this.pinnedWorkVersion ??= this.history?.currentVersion;
|
|
466
|
+
}
|
|
467
|
+
const snapshotSource = this.purpose === 'work' ? this.pinnedWorkSource ?? this.moduleSource() : this.moduleSource();
|
|
468
|
+
const snapshotScripts = this.purpose === 'work' ? this.pinnedWorkScripts ?? scripts : scripts;
|
|
469
|
+
return { harness: this.harnessName, shell: errors.length || scriptsChanged ? null : shell, diagnostics,
|
|
470
|
+
status: errors.length || scriptsChanged ? 'invalid' : shell ? 'ready' : 'missing',
|
|
471
|
+
version: this.purpose === 'work' ? this.pinnedWorkVersion : this.history?.currentVersion,
|
|
472
|
+
hash: this.purpose === 'work' ? this.pinnedWorkHash ?? stateHash : stateHash,
|
|
473
|
+
snapshot: { source: snapshotSource, hash: harnessHash(snapshotSource, snapshotScripts),
|
|
474
|
+
version: this.purpose === 'work' ? this.pinnedWorkVersion : this.history?.currentVersion } };
|
|
475
|
+
}
|
|
476
|
+
requestSignal(signal) {
|
|
477
|
+
return signal ? AbortSignal.any([signal, this.lifetime.signal]) : this.lifetime.signal;
|
|
478
|
+
}
|
|
479
|
+
async *exclusive(label, operation, signal) {
|
|
480
|
+
if (this.activeOperation) {
|
|
481
|
+
yield { type: 'error', content: `Session is busy (${this.activeOperation}); finish or cancel it first.` };
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
this.activeOperation = label;
|
|
485
|
+
this.activeRequestSignal = this.requestSignal(signal);
|
|
486
|
+
try {
|
|
487
|
+
yield* operation();
|
|
488
|
+
}
|
|
489
|
+
finally {
|
|
490
|
+
this.activeOperation = undefined;
|
|
491
|
+
this.activeRequestSignal = undefined;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
335
494
|
/**
|
|
336
495
|
* The live harness, for the side view: what predicates exist right now, how big
|
|
337
496
|
* each is, and what the open transaction has touched.
|
|
@@ -339,6 +498,20 @@ export class DMLSession {
|
|
|
339
498
|
* Read from the session module rather than from the last commit, so a side view
|
|
340
499
|
* shows the harness *being built* — including uncommitted edits.
|
|
341
500
|
*/
|
|
501
|
+
/** The harness's Work-mode presentation (`shell/1`), or null. */
|
|
502
|
+
shell() {
|
|
503
|
+
if (this.purpose === 'work' && this.pinnedWorkShell)
|
|
504
|
+
return structuredClone(this.pinnedWorkShell);
|
|
505
|
+
const result = this.prologQuery(`deepclause_mi:repl_shell_json('${this.sessionId}', Json)`);
|
|
506
|
+
const text = String(plainValue(result?.Json) ?? 'null');
|
|
507
|
+
try {
|
|
508
|
+
const parsed = JSON.parse(text);
|
|
509
|
+
return parsed && typeof parsed === 'object' ? parsed : null;
|
|
510
|
+
}
|
|
511
|
+
catch {
|
|
512
|
+
return null;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
342
515
|
harnessView() {
|
|
343
516
|
const result = this.prologQuery(`deepclause_mi:repl_harness_view('${this.sessionId}', Rows)`);
|
|
344
517
|
const raw = toJsValue(result?.Rows);
|
|
@@ -437,6 +610,47 @@ export class DMLSession {
|
|
|
437
610
|
recordedProcesses() {
|
|
438
611
|
return this.recordedServices;
|
|
439
612
|
}
|
|
613
|
+
/**
|
|
614
|
+
* A turn stopped by `suspend/1`: where it stopped and the goal that continues
|
|
615
|
+
* it. Set on resume, so a host can run the continuation once the harness and
|
|
616
|
+
* memory are back.
|
|
617
|
+
*/
|
|
618
|
+
pendingSuspension() {
|
|
619
|
+
return this.pendingSuspensionValue;
|
|
620
|
+
}
|
|
621
|
+
/** Forget the pending suspension (after resuming it, or deliberately dropping it). */
|
|
622
|
+
async clearSuspension() {
|
|
623
|
+
this.pendingSuspensionValue = undefined;
|
|
624
|
+
await this.history?.clearSuspendRecord();
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* Persist a suspension: the continuation, the memory it stopped with, and the
|
|
628
|
+
* module version it was running. The harness snapshot is written too, so the
|
|
629
|
+
* resumed session starts from exactly this module + memory.
|
|
630
|
+
*/
|
|
631
|
+
async handleSuspend(payload) {
|
|
632
|
+
if (!this.history)
|
|
633
|
+
return;
|
|
634
|
+
try {
|
|
635
|
+
if (payload.memory) {
|
|
636
|
+
// The turn's threaded memory is the authoritative one at the stop; make it
|
|
637
|
+
// the session's, so `harness.json` and the resumed state agree.
|
|
638
|
+
this.prologQuery(`deepclause_mi:repl_set_memory('${this.sessionId}', harness, ${payload.memory})`);
|
|
639
|
+
}
|
|
640
|
+
await this.history.writeSuspendRecord({
|
|
641
|
+
continuation: payload.continuation,
|
|
642
|
+
memory: payload.memory,
|
|
643
|
+
turn: this.turnCounter,
|
|
644
|
+
moduleVersion: this.history.currentVersion ? String(this.history.currentVersion) : undefined,
|
|
645
|
+
moduleHash: this.history.currentHash,
|
|
646
|
+
});
|
|
647
|
+
await this.persistSessionHarness(this.history.currentVersion);
|
|
648
|
+
this.pendingSuspensionValue = { continuation: payload.continuation, memory: payload.memory };
|
|
649
|
+
}
|
|
650
|
+
catch (error) {
|
|
651
|
+
this.warnHistory(error);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
440
654
|
/**
|
|
441
655
|
* Recent subagent output for the log view, oldest first. Answers and exits are
|
|
442
656
|
* included; per-tick state/activity updates are not (the summary shows those).
|
|
@@ -676,6 +890,8 @@ export class DMLSession {
|
|
|
676
890
|
}
|
|
677
891
|
/** Parse and load DML source into the living module. */
|
|
678
892
|
async loadCode(code) {
|
|
893
|
+
if (this.purpose === 'work' && this.pinnedWorkHash)
|
|
894
|
+
return { error: 'Work is pinned to its snapshot; open Develop or a fresh Work session to change it.' };
|
|
679
895
|
if (this.disposed) {
|
|
680
896
|
return { error: 'Session has been disposed' };
|
|
681
897
|
}
|
|
@@ -712,9 +928,12 @@ export class DMLSession {
|
|
|
712
928
|
* `embedded_file/2` facts back into the workspace.
|
|
713
929
|
*/
|
|
714
930
|
async load(file) {
|
|
931
|
+
const conflict = await this.persistentConflict();
|
|
932
|
+
if (conflict)
|
|
933
|
+
return { error: conflict };
|
|
715
934
|
const before = this.predicateList();
|
|
716
935
|
// On a fresh harness the loaded file *is* the baseline, not a version.
|
|
717
|
-
const recordLoad = this.history?.hasCommits ?? false;
|
|
936
|
+
const recordLoad = this.purpose !== 'work' && (this.history?.hasCommits ?? false);
|
|
718
937
|
const target = path.isAbsolute(file)
|
|
719
938
|
? file
|
|
720
939
|
: path.resolve(this.workspacePath ?? process.cwd(), file);
|
|
@@ -746,7 +965,12 @@ export class DMLSession {
|
|
|
746
965
|
async finalizeHarnessBaseline() {
|
|
747
966
|
if (!this.history)
|
|
748
967
|
return;
|
|
968
|
+
// Explicit CLI -l may import a NEW slot, but Work never overwrites an
|
|
969
|
+
// existing harness. Normal Work opens/runs do not call this bootstrap hook.
|
|
970
|
+
if (this.purpose === 'work' && (await this.history.readHeadModule())?.module.trim())
|
|
971
|
+
return;
|
|
749
972
|
await this.history.setInitialBaseline(this.moduleSource());
|
|
973
|
+
this.baseSourceHash = moduleVersion((await this.history.readHeadModule())?.module ?? '');
|
|
750
974
|
}
|
|
751
975
|
/** Workspace-relative files linked by `script_file/2` facts. */
|
|
752
976
|
scriptFiles() {
|
|
@@ -763,12 +987,15 @@ export class DMLSession {
|
|
|
763
987
|
try {
|
|
764
988
|
const store = new HistoryStore(this.workspacePath ?? process.cwd(), this.sessionId, this.historyOptions, this.harnessName);
|
|
765
989
|
await store.init();
|
|
990
|
+
this.baseSourceHash = moduleVersion((await store.readHeadModule())?.module ?? '');
|
|
766
991
|
const existing = await store.readFacts();
|
|
767
992
|
if (existing.trim()) {
|
|
768
993
|
this.prologQuery(`deepclause_mi:repl_history_load('${this.sessionId}', ${quoteString(existing)})`);
|
|
769
994
|
}
|
|
770
995
|
this.history = store;
|
|
771
|
-
this.assertHistoryFacts(await store.startSession({ model: this.model, backend: this.provider
|
|
996
|
+
this.assertHistoryFacts(await store.startSession({ model: this.model, backend: this.provider, harness: this.harnessName,
|
|
997
|
+
mode: this.purpose, kind: this.openOptions.sessionKind ?? 'conversation', origin: this.openOptions.origin,
|
|
998
|
+
parentSessionId: this.openOptions.parentSessionId }, { resume: this.resume }));
|
|
772
999
|
}
|
|
773
1000
|
catch (error) {
|
|
774
1001
|
this.warnHistory(error);
|
|
@@ -793,6 +1020,7 @@ export class DMLSession {
|
|
|
793
1020
|
* is not recorded as a new change.
|
|
794
1021
|
*/
|
|
795
1022
|
async restoreHarnessFromHistory(snapshot) {
|
|
1023
|
+
this.baseSourceHash = snapshot.baseSourceHash ?? this.baseSourceHash;
|
|
796
1024
|
this.turnCounter = (await this.history?.lastTurn(this.sessionId)) ?? 0;
|
|
797
1025
|
const module = snapshot.module.trim();
|
|
798
1026
|
if (module) {
|
|
@@ -820,15 +1048,25 @@ export class DMLSession {
|
|
|
820
1048
|
const module = this.moduleSource();
|
|
821
1049
|
const scripts = await this.scriptHashes();
|
|
822
1050
|
const hash = harnessHash(module, scripts);
|
|
823
|
-
|
|
824
|
-
|
|
1051
|
+
if (this.purpose === 'work' && this.pinnedWorkScripts && JSON.stringify(this.pinnedWorkScripts) !== JSON.stringify(scripts))
|
|
1052
|
+
return;
|
|
1053
|
+
const isClean = clean ?? (this.purpose === 'work' && this.pinnedWorkHash
|
|
1054
|
+
? (harnessHash(this.canonicalSource(), scripts) === this.pinnedWorkHash || hash === this.pinnedWorkHash)
|
|
1055
|
+
: this.history.currentHash ? hash === this.history.currentHash : version === 0);
|
|
1056
|
+
await this.history.updateSessionMetadata({ mode: this.purpose, harness: this.harnessName,
|
|
1057
|
+
shellKind: this.shell()?.kind, harnessHash: this.purpose === 'work' ? this.pinnedWorkHash ?? hash : hash, sessionStateHash: hash,
|
|
1058
|
+
harnessVersion: this.purpose === 'work' ? this.pinnedWorkVersion : version });
|
|
825
1059
|
await this.history.writeSessionHarness({
|
|
1060
|
+
...(this.purpose === 'work' && this.pinnedWorkHash && this.pinnedWorkShell && this.pinnedWorkScripts
|
|
1061
|
+
? { workIdentity: { hash: this.pinnedWorkHash, source: this.pinnedWorkSource, shell: this.pinnedWorkShell, scripts: this.pinnedWorkScripts } } : {}),
|
|
1062
|
+
baseSourceHash: this.baseSourceHash,
|
|
826
1063
|
sessionId: this.sessionId,
|
|
827
|
-
version,
|
|
1064
|
+
version: this.purpose === 'work' ? this.pinnedWorkVersion ?? version : version,
|
|
828
1065
|
hash,
|
|
829
1066
|
clean: isClean,
|
|
830
1067
|
savedAt: new Date().toISOString(),
|
|
831
1068
|
scripts,
|
|
1069
|
+
...(this.openOptions.harnessModules?.length ? { harnessModules: this.openOptions.harnessModules } : {}),
|
|
832
1070
|
memory: {
|
|
833
1071
|
harness: this.dumpMemoryTerm('harness'),
|
|
834
1072
|
meta: this.dumpMemoryTerm('meta'),
|
|
@@ -872,19 +1110,74 @@ export class DMLSession {
|
|
|
872
1110
|
.filter(Boolean);
|
|
873
1111
|
}
|
|
874
1112
|
moduleSource() {
|
|
1113
|
+
// Persisted `harness.dml` and the editor use the human view, so variable
|
|
1114
|
+
// names and schema wrappers survive. `export()` keeps the canonical A/B
|
|
1115
|
+
// export for byte-stable round-trips.
|
|
1116
|
+
const result = this.prologQuery(`deepclause_mi:repl_display_harness('${this.sessionId}', Text)`);
|
|
1117
|
+
return String(plainValue(result?.Text) ?? '');
|
|
1118
|
+
}
|
|
1119
|
+
embeddedScripts() {
|
|
1120
|
+
const result = this.prologQuery(`(current_predicate(${this.sessionId}:embedded_file/2) -> findall(_{path:P,content:C}, ${this.sessionId}:embedded_file(P,C), Files) ; Files=[]), deepclause_mi:atom_json_dict(Json, Files, [])`);
|
|
1121
|
+
try {
|
|
1122
|
+
return JSON.parse(String(plainValue(result?.Json) ?? '[]'));
|
|
1123
|
+
}
|
|
1124
|
+
catch {
|
|
1125
|
+
return [];
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
async materializeMissingEmbeddedScripts() {
|
|
1129
|
+
for (const script of this.embeddedScripts()) {
|
|
1130
|
+
if (typeof script.path !== 'string' || typeof script.content !== 'string')
|
|
1131
|
+
throw new Error('Invalid embedded script');
|
|
1132
|
+
const target = this.resolveWorkspacePath(script.path);
|
|
1133
|
+
const root = await fs.realpath(path.resolve(this.workspacePath ?? process.cwd()));
|
|
1134
|
+
let probe = target;
|
|
1135
|
+
for (;;) {
|
|
1136
|
+
try {
|
|
1137
|
+
const actual = await fs.realpath(probe);
|
|
1138
|
+
if (actual !== root && !actual.startsWith(root + path.sep))
|
|
1139
|
+
throw new Error('Embedded script path escapes the workspace through a symlink');
|
|
1140
|
+
break;
|
|
1141
|
+
}
|
|
1142
|
+
catch (error) {
|
|
1143
|
+
if (error.code !== 'ENOENT')
|
|
1144
|
+
throw error;
|
|
1145
|
+
const parent = path.dirname(probe);
|
|
1146
|
+
if (parent === probe)
|
|
1147
|
+
throw error;
|
|
1148
|
+
probe = parent;
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
try {
|
|
1152
|
+
await fs.access(target);
|
|
1153
|
+
continue;
|
|
1154
|
+
}
|
|
1155
|
+
catch { /* missing: bootstrap only */ }
|
|
1156
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
1157
|
+
try {
|
|
1158
|
+
await fs.writeFile(target, script.content, { encoding: 'utf8', flag: 'wx' });
|
|
1159
|
+
}
|
|
1160
|
+
catch (error) {
|
|
1161
|
+
if (error.code !== 'EEXIST')
|
|
1162
|
+
throw error;
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
canonicalSource() {
|
|
875
1167
|
const result = this.prologQuery(`deepclause_mi:export_harness('${this.sessionId}', none, Text)`);
|
|
876
1168
|
return String(plainValue(result?.Text) ?? '');
|
|
877
1169
|
}
|
|
878
1170
|
async scriptHashes() {
|
|
879
1171
|
const { createHash } = await import('crypto');
|
|
880
1172
|
const out = [];
|
|
881
|
-
for (const rel of this.scriptFiles()) {
|
|
1173
|
+
for (const rel of this.scriptFiles().sort()) {
|
|
882
1174
|
try {
|
|
883
1175
|
const content = await fs.readFile(this.resolveWorkspacePath(rel));
|
|
884
1176
|
out.push({ path: rel, sha256: createHash('sha256').update(content).digest('hex') });
|
|
885
1177
|
}
|
|
886
1178
|
catch {
|
|
887
|
-
|
|
1179
|
+
const embedded = this.embeddedScripts().find(script => script.path === rel)?.content;
|
|
1180
|
+
out.push({ path: rel, sha256: typeof embedded === 'string' ? createHash('sha256').update(embedded).digest('hex') : 'missing' });
|
|
888
1181
|
}
|
|
889
1182
|
}
|
|
890
1183
|
return out;
|
|
@@ -925,6 +1218,7 @@ export class DMLSession {
|
|
|
925
1218
|
manifest: this.manifestText(),
|
|
926
1219
|
});
|
|
927
1220
|
this.assertHistoryFacts(facts);
|
|
1221
|
+
this.baseSourceHash = moduleVersion(this.moduleSource());
|
|
928
1222
|
await this.persistSessionHarness(version, true);
|
|
929
1223
|
return version;
|
|
930
1224
|
}
|
|
@@ -990,6 +1284,20 @@ export class DMLSession {
|
|
|
990
1284
|
this.resolveWorkspacePath(rel);
|
|
991
1285
|
files.push({ rel, bytes });
|
|
992
1286
|
}
|
|
1287
|
+
// Bundles carry their dependency sources. Preload them into the session's
|
|
1288
|
+
// module registry before the importing harness is parsed.
|
|
1289
|
+
const manifestBytes = entries['manifest.json'];
|
|
1290
|
+
if (manifestBytes) {
|
|
1291
|
+
try {
|
|
1292
|
+
const manifest = JSON.parse(strFromU8(manifestBytes));
|
|
1293
|
+
if (Array.isArray(manifest.modules) && manifest.modules.length > 0) {
|
|
1294
|
+
await this.preloadHarnessModules(manifest.modules);
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
catch {
|
|
1298
|
+
/* A malformed manifest is ignored; the main source still gets a chance. */
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
993
1301
|
for (const file of files) {
|
|
994
1302
|
const abs = this.resolveWorkspacePath(file.rel);
|
|
995
1303
|
await fs.mkdir(path.dirname(abs), { recursive: true });
|
|
@@ -997,15 +1305,65 @@ export class DMLSession {
|
|
|
997
1305
|
}
|
|
998
1306
|
return this.loadCode(strFromU8(entries[harnessName]));
|
|
999
1307
|
}
|
|
1000
|
-
/**
|
|
1308
|
+
/** Workspace-relative script files linked by this harness. */
|
|
1309
|
+
async linkedScripts() {
|
|
1310
|
+
return this.scriptFiles();
|
|
1311
|
+
}
|
|
1312
|
+
/** Read-only listing of the living or a foreign harness module. */
|
|
1001
1313
|
async listing(filter = 'all') {
|
|
1002
|
-
const
|
|
1003
|
-
|
|
1004
|
-
|
|
1314
|
+
const normalized = filter.trim() || 'all';
|
|
1315
|
+
if (normalized === 'harnesses')
|
|
1316
|
+
return this.listForeignHarnesses();
|
|
1317
|
+
const foreign = foreignFilter(normalized);
|
|
1318
|
+
if (foreign)
|
|
1319
|
+
return this.inspectForeignHarness(foreign.name, foreign.selection);
|
|
1320
|
+
const filterTerm = normalized === 'all' || normalized === 'tools'
|
|
1321
|
+
? normalized
|
|
1322
|
+
: toListingFilter(normalized);
|
|
1005
1323
|
const result = this.prologQuery(`deepclause_mi:repl_listing('${this.sessionId}', ${filterTerm}, Text)`);
|
|
1006
1324
|
const text = plainValue(result?.Text);
|
|
1007
1325
|
return typeof text === 'string' ? text : '';
|
|
1008
1326
|
}
|
|
1327
|
+
async foreignHistory(name) {
|
|
1328
|
+
const store = new HistoryStore(this.workspacePath ?? process.cwd(), this.sessionId, this.openOptions.history ?? {}, name);
|
|
1329
|
+
await store.init();
|
|
1330
|
+
return store;
|
|
1331
|
+
}
|
|
1332
|
+
async listForeignHarnesses() {
|
|
1333
|
+
const history = this.history ?? new HistoryStore(this.workspacePath ?? process.cwd(), this.sessionId, this.openOptions.history ?? {}, this.harnessName);
|
|
1334
|
+
await history.init();
|
|
1335
|
+
const names = await history.listHarnessNames();
|
|
1336
|
+
if (names.length === 0)
|
|
1337
|
+
return 'no foreign harnesses';
|
|
1338
|
+
const lines = ['foreign harnesses (latest committed version; read-only):'];
|
|
1339
|
+
for (const name of names) {
|
|
1340
|
+
const store = await this.foreignHistory(name).catch(() => null);
|
|
1341
|
+
const head = store ? await store.readHeadModule() : null;
|
|
1342
|
+
if (!head?.module.trim())
|
|
1343
|
+
continue;
|
|
1344
|
+
const exports = exportedIndicators(head.module);
|
|
1345
|
+
lines.push(`- ${name} v${head.version} — ${exports.length ? `exports: ${exports.join(', ')}` : 'exports: (none)'}`);
|
|
1346
|
+
}
|
|
1347
|
+
return lines.join('\n');
|
|
1348
|
+
}
|
|
1349
|
+
async inspectForeignHarness(name, selection) {
|
|
1350
|
+
const store = await this.foreignHistory(name);
|
|
1351
|
+
const head = await store.readHeadModule();
|
|
1352
|
+
if (!head?.module.trim())
|
|
1353
|
+
return `foreign harness ${name}: no committed content`;
|
|
1354
|
+
const exports = exportedIndicators(head.module);
|
|
1355
|
+
const header = [
|
|
1356
|
+
`foreign harness ${name} v${head.version} (read-only)`,
|
|
1357
|
+
`exports: ${exports.length ? exports.join(', ') : '(none)'}`,
|
|
1358
|
+
`reuse with: :- use_harness(${name}, [${exports.join(', ') || '...'}]).`,
|
|
1359
|
+
].join('\n');
|
|
1360
|
+
if (selection !== 'all' && selection !== '') {
|
|
1361
|
+
const block = extractForeignPredicate(head.module, selection);
|
|
1362
|
+
if (block)
|
|
1363
|
+
return `${header}\n\n${block}`;
|
|
1364
|
+
}
|
|
1365
|
+
return `${header}\n\n${head.module}`;
|
|
1366
|
+
}
|
|
1009
1367
|
/**
|
|
1010
1368
|
* Run a goal and enumerate its solutions.
|
|
1011
1369
|
*
|
|
@@ -1013,6 +1371,13 @@ export class DMLSession {
|
|
|
1013
1371
|
* `answer` events from the goal, and finally `finished` or `error`.
|
|
1014
1372
|
*/
|
|
1015
1373
|
async *query(goal, options = {}) {
|
|
1374
|
+
if (this.purpose === 'work') {
|
|
1375
|
+
yield { type: 'error', content: 'Raw goals are a Develop operation. In Work, start a declared workflow.' };
|
|
1376
|
+
return;
|
|
1377
|
+
}
|
|
1378
|
+
yield* this.exclusive('query', () => this.queryInner(goal, { ...options, signal: this.requestSignal(options.signal) }), options.signal);
|
|
1379
|
+
}
|
|
1380
|
+
async *queryInner(goal, options = {}) {
|
|
1016
1381
|
if (this.disposed) {
|
|
1017
1382
|
yield { type: 'error', content: 'Session has been disposed' };
|
|
1018
1383
|
return;
|
|
@@ -1046,6 +1411,8 @@ export class DMLSession {
|
|
|
1046
1411
|
this.recordHistoryEvent(historyTurn, event);
|
|
1047
1412
|
if (event.type === 'error')
|
|
1048
1413
|
historyOutcome = 'failed';
|
|
1414
|
+
if (event.type === 'suspend')
|
|
1415
|
+
historyOutcome = 'suspended';
|
|
1049
1416
|
yield event;
|
|
1050
1417
|
}
|
|
1051
1418
|
}
|
|
@@ -1071,67 +1438,6 @@ export class DMLSession {
|
|
|
1071
1438
|
});
|
|
1072
1439
|
await this.persistSessionHarness(this.history?.currentVersion ?? 0);
|
|
1073
1440
|
}
|
|
1074
|
-
/** Load the bundled DML reference once, for inclusion in the meta prompt. */
|
|
1075
|
-
async loadDmlReference() {
|
|
1076
|
-
if (this.dmlReference !== undefined) {
|
|
1077
|
-
return this.dmlReference;
|
|
1078
|
-
}
|
|
1079
|
-
try {
|
|
1080
|
-
this.dmlReference = await fs.readFile(getWorkspaceDocAssetPath('dml-reference'), 'utf8');
|
|
1081
|
-
}
|
|
1082
|
-
catch {
|
|
1083
|
-
this.dmlReference = '';
|
|
1084
|
-
}
|
|
1085
|
-
return this.dmlReference;
|
|
1086
|
-
}
|
|
1087
|
-
/** Load the curated authoring patterns once, for the meta prompt. */
|
|
1088
|
-
async loadDmlAuthoring() {
|
|
1089
|
-
if (this.dmlAuthoring !== undefined) {
|
|
1090
|
-
return this.dmlAuthoring;
|
|
1091
|
-
}
|
|
1092
|
-
try {
|
|
1093
|
-
this.dmlAuthoring = await fs.readFile(getWorkspaceDocAssetPath('dml-authoring'), 'utf8');
|
|
1094
|
-
}
|
|
1095
|
-
catch {
|
|
1096
|
-
this.dmlAuthoring = '';
|
|
1097
|
-
}
|
|
1098
|
-
return this.dmlAuthoring;
|
|
1099
|
-
}
|
|
1100
|
-
/** Load a bundled doc asset once (cached by field). */
|
|
1101
|
-
async loadDocAsset(name) {
|
|
1102
|
-
if (name === 'dml-forms') {
|
|
1103
|
-
if (this.dmlForms !== undefined)
|
|
1104
|
-
return this.dmlForms;
|
|
1105
|
-
try {
|
|
1106
|
-
this.dmlForms = await fs.readFile(getWorkspaceDocAssetPath('dml-forms'), 'utf8');
|
|
1107
|
-
}
|
|
1108
|
-
catch {
|
|
1109
|
-
this.dmlForms = '';
|
|
1110
|
-
}
|
|
1111
|
-
return this.dmlForms;
|
|
1112
|
-
}
|
|
1113
|
-
const cached = name === 'harness-examples'
|
|
1114
|
-
? this.harnessExamples
|
|
1115
|
-
: name === 'harness-patterns'
|
|
1116
|
-
? this.harnessPatterns
|
|
1117
|
-
: this.prologSnippets;
|
|
1118
|
-
if (cached !== undefined)
|
|
1119
|
-
return cached;
|
|
1120
|
-
let text = '';
|
|
1121
|
-
try {
|
|
1122
|
-
text = await fs.readFile(getWorkspaceDocAssetPath(name), 'utf8');
|
|
1123
|
-
}
|
|
1124
|
-
catch {
|
|
1125
|
-
text = '';
|
|
1126
|
-
}
|
|
1127
|
-
if (name === 'harness-examples')
|
|
1128
|
-
this.harnessExamples = text;
|
|
1129
|
-
else if (name === 'harness-patterns')
|
|
1130
|
-
this.harnessPatterns = text;
|
|
1131
|
-
else
|
|
1132
|
-
this.prologSnippets = text;
|
|
1133
|
-
return text;
|
|
1134
|
-
}
|
|
1135
1441
|
/** Predicates replaced by the most recent successful commit ("name/arity, …"). */
|
|
1136
1442
|
lastCommitPredicates() {
|
|
1137
1443
|
const result = this.prologQuery(`deepclause_mi:repl_last_commit_summary('${this.sessionId}', Text)`);
|
|
@@ -1176,6 +1482,11 @@ export class DMLSession {
|
|
|
1176
1482
|
}
|
|
1177
1483
|
/** Clear the living module and memories (the `reset.` command). */
|
|
1178
1484
|
async reset() {
|
|
1485
|
+
if (this.purpose === 'work')
|
|
1486
|
+
throw new Error('Reset is a Develop operation.');
|
|
1487
|
+
const conflict = await this.persistentConflict();
|
|
1488
|
+
if (conflict)
|
|
1489
|
+
throw new Error(conflict);
|
|
1179
1490
|
if (this.isFrozen()) {
|
|
1180
1491
|
throw new Error('harness is frozen; reset is disabled');
|
|
1181
1492
|
}
|
|
@@ -1190,6 +1501,11 @@ export class DMLSession {
|
|
|
1190
1501
|
* rollback itself is recorded as a change (harness_rollback/5).
|
|
1191
1502
|
*/
|
|
1192
1503
|
async rollback() {
|
|
1504
|
+
if (this.purpose === 'work')
|
|
1505
|
+
return { ok: false, error: 'Rollback is a Develop operation.' };
|
|
1506
|
+
const conflict = await this.persistentConflict();
|
|
1507
|
+
if (conflict)
|
|
1508
|
+
return { ok: false, error: conflict };
|
|
1193
1509
|
if (this.disposed)
|
|
1194
1510
|
return { ok: false, error: 'Session has been disposed' };
|
|
1195
1511
|
if (!this.history)
|
|
@@ -1205,6 +1521,7 @@ export class DMLSession {
|
|
|
1205
1521
|
return { ok: false, error: String(outcome ?? 'rollback failed') };
|
|
1206
1522
|
}
|
|
1207
1523
|
this.assertHistoryFacts(await this.history.recordRollback(plan.from, plan.to, this.turnCounter, this.sessionId, plan.module));
|
|
1524
|
+
this.baseSourceHash = moduleVersion(plan.module);
|
|
1208
1525
|
return { ok: true, from: plan.from, to: plan.to };
|
|
1209
1526
|
}
|
|
1210
1527
|
// ---- Freeze lock (M2) ----
|
|
@@ -1285,6 +1602,17 @@ export class DMLSession {
|
|
|
1285
1602
|
entries[rel] = bytes;
|
|
1286
1603
|
manifestFiles.push({ path: rel, bytes: bytes.length });
|
|
1287
1604
|
}
|
|
1605
|
+
const modules = (this.openOptions.harnessModules ?? []).map((module) => ({
|
|
1606
|
+
id: module.id,
|
|
1607
|
+
name: module.name,
|
|
1608
|
+
version: module.version ?? 'head',
|
|
1609
|
+
hash: module.hash ?? moduleVersion(module.source),
|
|
1610
|
+
source: module.source,
|
|
1611
|
+
}));
|
|
1612
|
+
for (const module of modules) {
|
|
1613
|
+
const file = `modules/${module.id}.dml`;
|
|
1614
|
+
entries[file] = strToU8(module.source);
|
|
1615
|
+
}
|
|
1288
1616
|
entries['manifest.json'] = strToU8(`${JSON.stringify({
|
|
1289
1617
|
version: 1,
|
|
1290
1618
|
header,
|
|
@@ -1292,6 +1620,7 @@ export class DMLSession {
|
|
|
1292
1620
|
provider: this.provider,
|
|
1293
1621
|
timestamp: new Date().toISOString(),
|
|
1294
1622
|
files: manifestFiles,
|
|
1623
|
+
modules,
|
|
1295
1624
|
}, null, 2)}\n`);
|
|
1296
1625
|
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
1297
1626
|
await fs.writeFile(target, Buffer.from(zipSync(entries, { level: 6 })));
|
|
@@ -1301,7 +1630,8 @@ export class DMLSession {
|
|
|
1301
1630
|
* The child frame uses the living scratch module and may itself call task()
|
|
1302
1631
|
* (RLM-style recursion); its harness-memory writes are discarded afterward.
|
|
1303
1632
|
*/
|
|
1304
|
-
async executeGoal(goal, limit = 5, onEvent, signal, bindingMode = 'full', process) {
|
|
1633
|
+
async executeGoal(goal, limit = 5, onEvent, signal, bindingMode = 'full', process, preserveMemory = false) {
|
|
1634
|
+
signal = this.requestSignal(signal);
|
|
1305
1635
|
const startedAt = Date.now();
|
|
1306
1636
|
const elapsed = () => Date.now() - startedAt;
|
|
1307
1637
|
const childDepth = this.frameDepth + 1;
|
|
@@ -1330,6 +1660,7 @@ export class DMLSession {
|
|
|
1330
1660
|
const solutions = [];
|
|
1331
1661
|
let output = '';
|
|
1332
1662
|
let runError;
|
|
1663
|
+
let suspended = false;
|
|
1333
1664
|
this.frameDepth = childDepth;
|
|
1334
1665
|
try {
|
|
1335
1666
|
for await (const event of this.runner.runFrame(frame.id, this.buildRunOptions({ signal, process }))) {
|
|
@@ -1351,18 +1682,22 @@ export class DMLSession {
|
|
|
1351
1682
|
else if (event.type === 'error') {
|
|
1352
1683
|
runError = event.content;
|
|
1353
1684
|
}
|
|
1685
|
+
else if (event.type === 'suspend')
|
|
1686
|
+
suspended = true;
|
|
1354
1687
|
}
|
|
1355
1688
|
}
|
|
1356
1689
|
finally {
|
|
1357
1690
|
this.runner.endFrame(frame.id);
|
|
1358
1691
|
this.frameDepth = childDepth - 1;
|
|
1359
|
-
|
|
1692
|
+
if (!preserveMemory)
|
|
1693
|
+
this.setMemory('harness', memoryBefore);
|
|
1360
1694
|
}
|
|
1361
1695
|
const bindingCount = solutions[0]?.length ?? 0;
|
|
1362
1696
|
return {
|
|
1363
1697
|
...shapeBindings(solutions, bindingMode),
|
|
1364
1698
|
output: output.slice(0, 4000),
|
|
1365
1699
|
error: runError,
|
|
1700
|
+
outcome: signal?.aborted ? 'cancelled' : suspended ? 'suspended' : runError || !solutions.length ? 'failed' : 'succeeded',
|
|
1366
1701
|
elapsedMs: elapsed(),
|
|
1367
1702
|
...(bindingMode === 'full'
|
|
1368
1703
|
? {}
|
|
@@ -1380,6 +1715,21 @@ export class DMLSession {
|
|
|
1380
1715
|
* `finish`. It runs one or more committed turns per request.
|
|
1381
1716
|
*/
|
|
1382
1717
|
async *agentPrompt(request, options = {}) {
|
|
1718
|
+
yield* this.exclusive('prompt', () => this.agentPromptInner(request, { ...options, signal: this.requestSignal(options.signal) }), options.signal);
|
|
1719
|
+
}
|
|
1720
|
+
async *agentPromptInner(request, options = {}) {
|
|
1721
|
+
if (this.purpose === 'work') {
|
|
1722
|
+
await this.materializeMissingEmbeddedScripts();
|
|
1723
|
+
const spec = await this.workSpec();
|
|
1724
|
+
if (!spec.shell || spec.shell.kind !== 'agent') {
|
|
1725
|
+
yield { type: 'error', content: spec.diagnostics.join('\n') || 'This is a workflow-only shell; choose a workflow.' };
|
|
1726
|
+
return;
|
|
1727
|
+
}
|
|
1728
|
+
if (spec.hash !== this.pinnedWorkHash) {
|
|
1729
|
+
yield { type: 'error', content: 'Work snapshot or linked scripts changed. Refresh into a new Work session.' };
|
|
1730
|
+
return;
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1383
1733
|
if (this.disposed) {
|
|
1384
1734
|
yield { type: 'error', content: 'Session has been disposed' };
|
|
1385
1735
|
return;
|
|
@@ -1440,13 +1790,17 @@ export class DMLSession {
|
|
|
1440
1790
|
}
|
|
1441
1791
|
else if (this.transactionBefore !== null) {
|
|
1442
1792
|
// Last resort after the nudges: commit so nothing is lost, and show it.
|
|
1443
|
-
await this.endTurn();
|
|
1793
|
+
const result = await this.endTurn();
|
|
1794
|
+
if (result.error) {
|
|
1795
|
+
failed = true;
|
|
1796
|
+
const error = { type: 'error', content: result.error };
|
|
1797
|
+
this.recordHistoryEvent(turn, error);
|
|
1798
|
+
yield error;
|
|
1799
|
+
}
|
|
1444
1800
|
const marker = {
|
|
1445
|
-
type: 'tool_call',
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
toolState: 'completed',
|
|
1449
|
-
toolSummary: 'commit transaction (host; agent did not end_turn)',
|
|
1801
|
+
type: 'tool_call', toolName: 'end_turn', toolArgs: {},
|
|
1802
|
+
toolState: result.error ? 'failed' : 'completed', toolError: result.error,
|
|
1803
|
+
toolSummary: result.error ?? (result.committed ? 'commit transaction (host; agent did not end_turn)' : 'no edit committed'),
|
|
1450
1804
|
};
|
|
1451
1805
|
this.recordHistoryEvent(turn, marker);
|
|
1452
1806
|
yield marker;
|
|
@@ -1480,8 +1834,28 @@ export class DMLSession {
|
|
|
1480
1834
|
async getHarnessAgent() {
|
|
1481
1835
|
if (this.harnessAgent)
|
|
1482
1836
|
return this.harnessAgent;
|
|
1837
|
+
const authoringTools = this.purpose === 'work'
|
|
1838
|
+
? createWorkAgentTools(this)
|
|
1839
|
+
: createHarnessTools(this);
|
|
1840
|
+
const allowed = this.purpose !== 'work' && this.openOptions.authoringToolNames
|
|
1841
|
+
? new Set(this.openOptions.authoringToolNames)
|
|
1842
|
+
: null;
|
|
1843
|
+
if (allowed) {
|
|
1844
|
+
for (const name of [...authoringTools.keys()]) {
|
|
1845
|
+
if (!allowed.has(name))
|
|
1846
|
+
authoringTools.delete(name);
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
for (const [name, tool] of this.authoringTools) {
|
|
1850
|
+
if (this.purpose === 'work')
|
|
1851
|
+
continue;
|
|
1852
|
+
if (allowed && !allowed.has(name))
|
|
1853
|
+
continue;
|
|
1854
|
+
if (!authoringTools.has(name))
|
|
1855
|
+
authoringTools.set(name, tool);
|
|
1856
|
+
}
|
|
1483
1857
|
this.harnessAgent = new HarnessAgent({
|
|
1484
|
-
tools:
|
|
1858
|
+
tools: authoringTools,
|
|
1485
1859
|
llmBackend: this.llmBackend,
|
|
1486
1860
|
model: this.model,
|
|
1487
1861
|
temperature: this.temperature,
|
|
@@ -1499,6 +1873,9 @@ export class DMLSession {
|
|
|
1499
1873
|
currentModel: `${this.provider}:${this.model}`,
|
|
1500
1874
|
modelCatalog: this.modelResolver?.catalog(),
|
|
1501
1875
|
knownMessages: this.agentMessages,
|
|
1876
|
+
traceToolStart: (name, args) => this.traceToolStart(name, args),
|
|
1877
|
+
traceToolEnd: (name, args, result) => this.traceToolEnd(name, args, result),
|
|
1878
|
+
agentSystemPrompt: this.purpose === 'work' ? buildWorkSystemPrompt(this.shell()) : this.openOptions.agentSystemPrompt,
|
|
1502
1879
|
});
|
|
1503
1880
|
return this.harnessAgent;
|
|
1504
1881
|
}
|
|
@@ -1626,14 +2003,94 @@ export class DMLSession {
|
|
|
1626
2003
|
}
|
|
1627
2004
|
return undefined;
|
|
1628
2005
|
}
|
|
2006
|
+
async persistentConflict() {
|
|
2007
|
+
if (this.purpose !== 'develop' || !this.history || !this.baseSourceHash)
|
|
2008
|
+
return undefined;
|
|
2009
|
+
const current = moduleVersion((await this.history.readHeadModule())?.module ?? '');
|
|
2010
|
+
return current !== this.baseSourceHash ? 'Harness changed in another session. Export any private edits and reopen a fresh Develop conversation before committing.' : undefined;
|
|
2011
|
+
}
|
|
2012
|
+
/** Add a use_harness directive to the current edit transaction. */
|
|
2013
|
+
async useHarness(name, predicates, version) {
|
|
2014
|
+
if (this.transactionBefore === null)
|
|
2015
|
+
return { ok: false, error: 'no open transaction; call begin_turn before adding an import' };
|
|
2016
|
+
if (this.purpose === 'work')
|
|
2017
|
+
return { ok: false, error: 'Work cannot author the harness' };
|
|
2018
|
+
if (!/^[a-z][a-z0-9_]*$/.test(name))
|
|
2019
|
+
return { ok: false, error: 'harness module names must be lowercase identifiers' };
|
|
2020
|
+
if (this.harnessName === name)
|
|
2021
|
+
return { ok: false, error: 'a harness cannot import itself' };
|
|
2022
|
+
const valid = predicates.filter((predicate) => /^[a-z][A-Za-z0-9_]*\/\d+$/.test(predicate));
|
|
2023
|
+
if (valid.length !== predicates.length || valid.length === 0)
|
|
2024
|
+
return { ok: false, error: 'predicates must be Name/Arity indicators' };
|
|
2025
|
+
try {
|
|
2026
|
+
const store = await this.foreignHistory(name);
|
|
2027
|
+
const source = version !== undefined
|
|
2028
|
+
? await store.readHarnessVersion(Number(version))
|
|
2029
|
+
: (await store.readHeadModule())?.module ?? null;
|
|
2030
|
+
if (!source?.trim())
|
|
2031
|
+
return { ok: false, error: `foreign harness ${name} has no committed content` };
|
|
2032
|
+
const available = exportedIndicators(source);
|
|
2033
|
+
const missing = valid.filter((predicate) => !available.includes(predicate));
|
|
2034
|
+
if (missing.length)
|
|
2035
|
+
return { ok: false, error: `${name} does not export: ${missing.join(', ')}` };
|
|
2036
|
+
const hash = moduleVersion(source);
|
|
2037
|
+
const moduleId = `dcmod_${name}_${String(version ?? 'head')}_${hash}`.replace(/[^A-Za-z0-9_]/g, '_');
|
|
2038
|
+
await this.preloadHarnessModules([{ id: moduleId, name, version: version ?? 'head', hash, source }]);
|
|
2039
|
+
const versionTerm = version === undefined ? 'none' : `version(${quotePrologString(String(version))})`;
|
|
2040
|
+
const indicators = valid.map((predicate) => {
|
|
2041
|
+
const [predicateName, arity] = predicate.split('/');
|
|
2042
|
+
return `${quoteAtom(predicateName)}/${Number(arity)}`;
|
|
2043
|
+
}).join(', ');
|
|
2044
|
+
const result = this.prologQuery(`deepclause_mi:repl_add_harness_import('${this.sessionId}', ${quoteAtom(name)}, ${versionTerm}, [${indicators}], Result)`);
|
|
2045
|
+
const outcome = plainValue(result?.Result);
|
|
2046
|
+
if (outcome !== 'ok')
|
|
2047
|
+
return { ok: false, error: String(outcome ?? 'could not add import') };
|
|
2048
|
+
this.transactionDirty = true;
|
|
2049
|
+
return { ok: true };
|
|
2050
|
+
}
|
|
2051
|
+
catch (error) {
|
|
2052
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
/** Replace the harness export list inside the current transaction. */
|
|
2056
|
+
async setHarnessExports(predicates) {
|
|
2057
|
+
if (this.transactionBefore === null)
|
|
2058
|
+
return { ok: false, error: 'no open transaction; call begin_turn before changing exports' };
|
|
2059
|
+
if (this.purpose === 'work')
|
|
2060
|
+
return { ok: false, error: 'Work cannot author the harness' };
|
|
2061
|
+
const valid = predicates.filter((predicate) => /^[a-z][A-Za-z0-9_]*\/\d+$/.test(predicate));
|
|
2062
|
+
if (valid.length !== predicates.length)
|
|
2063
|
+
return { ok: false, error: 'exports must be Name/Arity indicators' };
|
|
2064
|
+
const indicators = valid.map((predicate) => {
|
|
2065
|
+
const [name, arity] = predicate.split('/');
|
|
2066
|
+
return `${quoteAtom(name)}/${Number(arity)}`;
|
|
2067
|
+
}).join(', ');
|
|
2068
|
+
try {
|
|
2069
|
+
const result = this.prologQuery(`deepclause_mi:repl_set_harness_exports('${this.sessionId}', [${indicators}], Result)`);
|
|
2070
|
+
const outcome = plainValue(result?.Result);
|
|
2071
|
+
if (outcome !== 'ok')
|
|
2072
|
+
return { ok: false, error: String(outcome ?? 'could not update exports') };
|
|
2073
|
+
this.transactionDirty = true;
|
|
2074
|
+
return { ok: true };
|
|
2075
|
+
}
|
|
2076
|
+
catch (error) {
|
|
2077
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
1629
2080
|
async beginTurn() {
|
|
1630
|
-
|
|
2081
|
+
if (this.purpose === 'work')
|
|
2082
|
+
return { ok: false, error: 'Work cannot author the harness. Open a separate Develop conversation.' };
|
|
2083
|
+
const conflict = await this.persistentConflict();
|
|
2084
|
+
if (conflict)
|
|
2085
|
+
return { ok: false, error: conflict };
|
|
2086
|
+
// A second begin_turn must not re-snapshot the *mid-transaction* state:
|
|
1631
2087
|
// `rollback` would stop meaning "the last committed harness" and the
|
|
1632
|
-
// recorded diff would lose
|
|
2088
|
+
// recorded diff would lose edits made before it. Treat it as an idempotent
|
|
2089
|
+
// reminder instead of an error so agents do not get stuck retrying it.
|
|
1633
2090
|
if (this.transactionBefore !== null) {
|
|
1634
2091
|
return {
|
|
1635
|
-
ok:
|
|
1636
|
-
|
|
2092
|
+
ok: true,
|
|
2093
|
+
message: 'transaction is already open; continue editing, then call end_turn to commit or rollback to discard',
|
|
1637
2094
|
};
|
|
1638
2095
|
}
|
|
1639
2096
|
this.prologQuery(`deepclause_mi:repl_snapshot_save('${this.sessionId}')`);
|
|
@@ -1643,9 +2100,17 @@ export class DMLSession {
|
|
|
1643
2100
|
return { ok: true };
|
|
1644
2101
|
}
|
|
1645
2102
|
async endTurn() {
|
|
2103
|
+
const conflict = await this.persistentConflict();
|
|
2104
|
+
if (conflict)
|
|
2105
|
+
return { committed: false, error: conflict };
|
|
1646
2106
|
if (this.transactionBefore === null) {
|
|
1647
2107
|
return { committed: false, changed: [], error: 'no open transaction' };
|
|
1648
2108
|
}
|
|
2109
|
+
if (this.transactionDirty) {
|
|
2110
|
+
const errors = this.workShellErrors();
|
|
2111
|
+
if (errors.length)
|
|
2112
|
+
return { committed: false, error: `Invalid Work shell; fix it before committing:\n${errors.join('\n')}` };
|
|
2113
|
+
}
|
|
1649
2114
|
const before = this.transactionBefore;
|
|
1650
2115
|
const after = this.predicateList();
|
|
1651
2116
|
const touched = this.editTouched();
|
|
@@ -1673,6 +2138,7 @@ export class DMLSession {
|
|
|
1673
2138
|
warnings = await this.probeNondeterminism([...candidates]);
|
|
1674
2139
|
warnings.push(...this.probeToolContracts());
|
|
1675
2140
|
warnings.push(...this.probeDocContracts());
|
|
2141
|
+
warnings.push(...this.probeComplexity());
|
|
1676
2142
|
}
|
|
1677
2143
|
// `committed` means a version was recorded. It used to be hard-coded `true`,
|
|
1678
2144
|
// so a turn whose every edit was refused reported `{committed: true,
|
|
@@ -1686,7 +2152,7 @@ export class DMLSession {
|
|
|
1686
2152
|
* `replaceHarness` without accumulating comments.
|
|
1687
2153
|
*/
|
|
1688
2154
|
async harnessSource() {
|
|
1689
|
-
const result = this.prologQuery(`deepclause_mi:
|
|
2155
|
+
const result = this.prologQuery(`deepclause_mi:repl_display_harness('${this.sessionId}', Text)`);
|
|
1690
2156
|
return String(plainValue(result?.Text) ?? '');
|
|
1691
2157
|
}
|
|
1692
2158
|
/**
|
|
@@ -1699,7 +2165,58 @@ export class DMLSession {
|
|
|
1699
2165
|
* the editor's text is the source of truth. The result is an ordinary commit:
|
|
1700
2166
|
* a history version, the persisted harness, and the same contract warnings.
|
|
1701
2167
|
*/
|
|
1702
|
-
async
|
|
2168
|
+
async updateWorkShell(shell, expectedHash) {
|
|
2169
|
+
if (this.activeOperation || this.transactionBefore !== null)
|
|
2170
|
+
return { committed: false, error: 'Finish the active operation/edit transaction before saving the shell.' };
|
|
2171
|
+
this.activeOperation = 'shell-edit';
|
|
2172
|
+
try {
|
|
2173
|
+
return await this.updateWorkShellInner(shell, expectedHash);
|
|
2174
|
+
}
|
|
2175
|
+
finally {
|
|
2176
|
+
this.activeOperation = undefined;
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
async updateWorkShellInner(shell, expectedHash) {
|
|
2180
|
+
if (this.purpose === 'work')
|
|
2181
|
+
return { committed: false, error: 'Save the shell through an idle Develop session.' };
|
|
2182
|
+
const conflict = await this.persistentConflict();
|
|
2183
|
+
if (conflict)
|
|
2184
|
+
return { committed: false, error: conflict };
|
|
2185
|
+
const errors = validateWorkShell(shell, this.harnessView().predicates);
|
|
2186
|
+
if (errors.length)
|
|
2187
|
+
return { committed: false, error: errors.join('; ') };
|
|
2188
|
+
if (expectedHash && (await this.workSpec()).hash !== expectedHash)
|
|
2189
|
+
return { committed: false, error: 'Harness changed since the editor opened. Refresh before saving.' };
|
|
2190
|
+
const started = await this.beginTurn();
|
|
2191
|
+
if (!started.ok)
|
|
2192
|
+
return { committed: false, error: started.error };
|
|
2193
|
+
try {
|
|
2194
|
+
for (const arity of [1, 3])
|
|
2195
|
+
if (this.predicateArities('shell').includes(arity)) {
|
|
2196
|
+
const removed = await this.deletePredicate(`shell/${arity}`);
|
|
2197
|
+
if (!removed.ok)
|
|
2198
|
+
throw new Error(removed.error);
|
|
2199
|
+
}
|
|
2200
|
+
const defined = await this.define('shell(_)', renderWorkShell(shell));
|
|
2201
|
+
if (!defined.ok)
|
|
2202
|
+
throw new Error(defined.error);
|
|
2203
|
+
return await this.endTurn();
|
|
2204
|
+
}
|
|
2205
|
+
catch (error) {
|
|
2206
|
+
await this.rollbackTurn();
|
|
2207
|
+
return { committed: false, error: error.message };
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
2210
|
+
async replaceHarness(source, expectedHash) {
|
|
2211
|
+
if (this.purpose === 'work')
|
|
2212
|
+
return { committed: false, error: 'Edit the shell in a separate Develop session.' };
|
|
2213
|
+
if (this.activeOperation)
|
|
2214
|
+
return { committed: false, error: 'Session is busy; finish or cancel before editing.' };
|
|
2215
|
+
const conflict = await this.persistentConflict();
|
|
2216
|
+
if (conflict)
|
|
2217
|
+
return { committed: false, error: conflict };
|
|
2218
|
+
if (expectedHash && (await this.workSpec()).hash !== expectedHash)
|
|
2219
|
+
return { committed: false, error: 'Harness changed since the editor opened; refresh before saving.' };
|
|
1703
2220
|
if (this.disposed)
|
|
1704
2221
|
return { committed: false, error: 'Session has been disposed' };
|
|
1705
2222
|
if (this.isFrozen())
|
|
@@ -1715,6 +2232,11 @@ export class DMLSession {
|
|
|
1715
2232
|
this.prologQuery(`deepclause_mi:repl_rollback('${this.sessionId}', ${quoteString(previous)}, _)`);
|
|
1716
2233
|
return { committed: false, error: String(outcome ?? 'replace failed') };
|
|
1717
2234
|
}
|
|
2235
|
+
const errors = this.workShellErrors();
|
|
2236
|
+
if (errors.length) {
|
|
2237
|
+
this.prologQuery(`deepclause_mi:repl_rollback('${this.sessionId}', ${quoteString(previous)}, _)`);
|
|
2238
|
+
return { committed: false, error: `Invalid Work shell; source was not committed:\n${errors.join('\n')}` };
|
|
2239
|
+
}
|
|
1718
2240
|
const after = this.predicateList();
|
|
1719
2241
|
const changed = this.simplePredicateDiff(before, after);
|
|
1720
2242
|
let version;
|
|
@@ -1768,6 +2290,24 @@ export class DMLSession {
|
|
|
1768
2290
|
return [];
|
|
1769
2291
|
}
|
|
1770
2292
|
}
|
|
2293
|
+
/**
|
|
2294
|
+
* Advisory checks for the shapes that turn a small skill into a page of
|
|
2295
|
+
* Prolog: a long clause, inline Python, and an `agent_main` that returns a
|
|
2296
|
+
* value instead of calling `answer/1`.
|
|
2297
|
+
*/
|
|
2298
|
+
probeComplexity() {
|
|
2299
|
+
try {
|
|
2300
|
+
const result = this.prologQuery(`deepclause_mi:repl_validate_complexity('${this.sessionId}', Warnings)`);
|
|
2301
|
+
const raw = plainValue(result?.Warnings);
|
|
2302
|
+
if (!Array.isArray(raw))
|
|
2303
|
+
return [];
|
|
2304
|
+
return raw.map((entry) => String(entry)).filter(Boolean);
|
|
2305
|
+
}
|
|
2306
|
+
catch {
|
|
2307
|
+
// A validation failure must never fail the commit.
|
|
2308
|
+
return [];
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
1771
2311
|
/**
|
|
1772
2312
|
* Probe changed predicates for accidental nondeterminism: a pure predicate
|
|
1773
2313
|
* that yields more than `threshold` solutions on fresh variables is very likely
|
|
@@ -1775,7 +2315,7 @@ export class DMLSession {
|
|
|
1775
2315
|
* side-effecting predicates are skipped by the Prolog probe.
|
|
1776
2316
|
*/
|
|
1777
2317
|
async probeNondeterminism(indicators) {
|
|
1778
|
-
const reserved = new Set(['doc', 'module_doc', 'tool']);
|
|
2318
|
+
const reserved = new Set(['doc', 'module_doc', 'tool', 'schema', 'script_file']);
|
|
1779
2319
|
const warnings = [];
|
|
1780
2320
|
const threshold = 100;
|
|
1781
2321
|
const bound = 200000;
|
|
@@ -1899,41 +2439,269 @@ export class DMLSession {
|
|
|
1899
2439
|
const closed = this.requireTransaction();
|
|
1900
2440
|
if (closed)
|
|
1901
2441
|
return closed;
|
|
2442
|
+
const quoteAtom = (name) => /^[a-z][A-Za-z0-9_]*$/.test(name) ? name : `'${name.replace(/'/g, "''")}'`;
|
|
2443
|
+
// `tool:name` (optionally `tool:name/arity`) removes one tool annotation and
|
|
2444
|
+
// its implementation, and leaves the delegate predicate in place.
|
|
2445
|
+
const toolMatch = /^\s*tool\s*:\s*([a-z][A-Za-z0-9_]*)\s*(?:\/\s*\d+\s*)?$/.exec(nameArity);
|
|
2446
|
+
if (toolMatch) {
|
|
2447
|
+
const result = this.prologQuery(`deepclause_mi:repl_delete_tool('${this.sessionId}', ${toolMatch[1]}, Result)`);
|
|
2448
|
+
return this.editResult(plainValue(result?.Result));
|
|
2449
|
+
}
|
|
2450
|
+
// Keyed annotations: delete exactly one entry, leaving all other keys.
|
|
2451
|
+
const docMatch = /^\s*doc\s*:\s*([^\s/]+)\s*\/\s*(\d+)\s*$/.exec(nameArity);
|
|
2452
|
+
if (docMatch) {
|
|
2453
|
+
const result = this.prologQuery(`deepclause_mi:repl_delete_doc('${this.sessionId}', ${quoteAtom(docMatch[1])}, ${Number(docMatch[2])}, Result)`);
|
|
2454
|
+
return this.editResult(plainValue(result?.Result));
|
|
2455
|
+
}
|
|
2456
|
+
const schemaMatch = /^\s*schema\s*:\s*([^\s]+)\s*$/.exec(nameArity);
|
|
2457
|
+
if (schemaMatch) {
|
|
2458
|
+
const result = this.prologQuery(`deepclause_mi:repl_delete_schema('${this.sessionId}', ${quoteAtom(schemaMatch[1])}, Result)`);
|
|
2459
|
+
return this.editResult(plainValue(result?.Result));
|
|
2460
|
+
}
|
|
2461
|
+
const scriptMatch = /^\s*script_file\s*:\s*([^\s]+)\s*$/.exec(nameArity);
|
|
2462
|
+
if (scriptMatch) {
|
|
2463
|
+
const result = this.prologQuery(`deepclause_mi:repl_delete_script('${this.sessionId}', ${quoteAtom(scriptMatch[1])}, Result)`);
|
|
2464
|
+
return this.editResult(plainValue(result?.Result));
|
|
2465
|
+
}
|
|
1902
2466
|
const match = /^\s*([^\s/]+)\s*\/\s*(\d+)\s*$/.exec(nameArity);
|
|
1903
2467
|
if (!match) {
|
|
1904
|
-
return { ok: false, error: `expected Name/Arity, got '${nameArity}'` };
|
|
2468
|
+
return { ok: false, error: `expected Name/Arity, tool:Name, doc:Name/Arity, schema:Name or script_file:Name; got '${nameArity}'` };
|
|
1905
2469
|
}
|
|
1906
2470
|
const [, name, arityText] = match;
|
|
1907
|
-
const
|
|
1908
|
-
const result = this.prologQuery(`deepclause_mi:repl_delete_predicate('${this.sessionId}', ${atom}, ${Number(arityText)}, Result)`);
|
|
2471
|
+
const result = this.prologQuery(`deepclause_mi:repl_delete_predicate('${this.sessionId}', ${quoteAtom(name)}, ${Number(arityText)}, Result)`);
|
|
1909
2472
|
return this.editResult(plainValue(result?.Result));
|
|
1910
2473
|
}
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
2474
|
+
/** Current dependency modules, including imports added during this session. */
|
|
2475
|
+
harnessModuleSources() {
|
|
2476
|
+
return [...(this.openOptions.harnessModules ?? [])];
|
|
2477
|
+
}
|
|
2478
|
+
/** Preload additional dependencies before an edit/load changes import directives. */
|
|
2479
|
+
async preloadHarnessModules(modules) {
|
|
2480
|
+
if (!modules.length)
|
|
2481
|
+
return;
|
|
2482
|
+
const existing = this.openOptions.harnessModules ?? [];
|
|
2483
|
+
const byId = new Map(existing.map((module) => [module.id, module]));
|
|
2484
|
+
for (const module of modules)
|
|
2485
|
+
byId.set(module.id, module);
|
|
2486
|
+
this.openOptions.harnessModules = [...byId.values()];
|
|
2487
|
+
await this.loadHarnessModules();
|
|
2488
|
+
}
|
|
2489
|
+
/** Load dependency modules before the main harness source is parsed. */
|
|
2490
|
+
async loadHarnessModules() {
|
|
2491
|
+
const modules = this.openOptions.harnessModules;
|
|
2492
|
+
if (!modules?.length)
|
|
2493
|
+
return;
|
|
2494
|
+
for (const module of modules) {
|
|
2495
|
+
const version = quotePrologString(String(module.version ?? 'head'));
|
|
2496
|
+
const hash = quotePrologString(module.hash ?? '');
|
|
2497
|
+
const source = quotePrologString(module.source);
|
|
2498
|
+
const query = `deepclause_mi:repl_load_harness_module('${this.sessionId}', '${module.id}', `
|
|
2499
|
+
+ `${quoteAtom(module.name)}, ${version}, ${hash}, ${source})`;
|
|
2500
|
+
const result = this.prologQuery(query);
|
|
2501
|
+
if (!result || result.success === false || result.error) {
|
|
2502
|
+
throw new Error(`could not load harness module '${module.name}': ${String(result.message ?? 'load failed')}`);
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
/** Open a tool scope so MI calls made by the tool nest under it. */
|
|
2507
|
+
traceToolStart(name, args) {
|
|
2508
|
+
if (!this.openOptions.trace)
|
|
2509
|
+
return;
|
|
2510
|
+
const id = `tool_${Date.now().toString(36)}_${++this.traceToolSeq}`;
|
|
2511
|
+
this.traceToolIds.push(id);
|
|
2512
|
+
try {
|
|
2513
|
+
this.prologQuery(`deepclause_mi:repl_trace_tool_start('${this.sessionId}', '${id}', `
|
|
2514
|
+
+ `${quotePrologString(name)}, ${quotePrologString(traceJson(args))})`);
|
|
2515
|
+
}
|
|
2516
|
+
catch {
|
|
2517
|
+
/* tracing must never break a tool */
|
|
2518
|
+
}
|
|
2519
|
+
}
|
|
2520
|
+
/** Close the current tool scope and attach its result. */
|
|
2521
|
+
traceToolEnd(_name, _args, result) {
|
|
2522
|
+
if (!this.openOptions.trace)
|
|
2523
|
+
return;
|
|
2524
|
+
const id = this.traceToolIds.pop();
|
|
2525
|
+
if (!id)
|
|
2526
|
+
return;
|
|
2527
|
+
try {
|
|
2528
|
+
this.prologQuery(`deepclause_mi:repl_trace_tool_end('${this.sessionId}', '${id}', ${quotePrologString(traceJson(result))})`);
|
|
2529
|
+
}
|
|
2530
|
+
catch {
|
|
2531
|
+
/* tracing must never break a tool */
|
|
2532
|
+
}
|
|
2533
|
+
}
|
|
2534
|
+
/** Read the full MI execution trace captured for this session. */
|
|
2535
|
+
/** Delete the captured MI trace for this session. */
|
|
2536
|
+
async clearTrace() {
|
|
2537
|
+
this.prologQuery(`deepclause_mi:repl_trace_clear('${this.sessionId}')`);
|
|
2538
|
+
}
|
|
2539
|
+
async trace() {
|
|
2540
|
+
try {
|
|
2541
|
+
const result = this.prologQuery(`deepclause_mi:repl_trace_json('${this.sessionId}', Json)`);
|
|
2542
|
+
const text = String(plainValue(result?.Json) ?? '[]');
|
|
2543
|
+
const parsed = JSON.parse(text);
|
|
2544
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
2545
|
+
}
|
|
2546
|
+
catch {
|
|
2547
|
+
return [];
|
|
1932
2548
|
}
|
|
1933
2549
|
}
|
|
2550
|
+
/** Read-only module provenance for the current harness. */
|
|
2551
|
+
harnessModuleInfo() {
|
|
2552
|
+
try {
|
|
2553
|
+
const result = this.prologQuery(`deepclause_mi:repl_harness_module_info_json('${this.sessionId}', Json)`);
|
|
2554
|
+
const raw = toJsValue(result?.Json);
|
|
2555
|
+
const parsed = (typeof raw === 'string' ? JSON.parse(raw) : raw);
|
|
2556
|
+
return {
|
|
2557
|
+
exports: Array.isArray(parsed?.exports) ? parsed.exports : [],
|
|
2558
|
+
modules: Array.isArray(parsed?.modules) ? parsed.modules : [],
|
|
2559
|
+
};
|
|
2560
|
+
}
|
|
2561
|
+
catch {
|
|
2562
|
+
return { exports: [], modules: [] };
|
|
2563
|
+
}
|
|
2564
|
+
}
|
|
2565
|
+
async reference(topic, options = {}) {
|
|
2566
|
+
const key = referenceTopic(topic);
|
|
2567
|
+
if (key === 'index')
|
|
2568
|
+
return referenceIndex();
|
|
2569
|
+
if (key === 'tools') {
|
|
2570
|
+
const catalog = this.hostToolsCatalog ?? '(no host capability tools registered)';
|
|
2571
|
+
const schemas = [...this.tools].map(([name, tool]) => `## ${name}\n${tool.description}\n\nParameters (source of truth):\n\n\`\`\`json\n${JSON.stringify(tool.parameters, null, 2)}\n\`\`\``);
|
|
2572
|
+
return renderReference(key, `# Current host tools\n${catalog}\n\n${schemas.join('\n\n')}`, options);
|
|
2573
|
+
}
|
|
2574
|
+
const entry = REFERENCE_TOPICS.find((item) => item.topic === key);
|
|
2575
|
+
if (!entry)
|
|
2576
|
+
throw new Error(`Unknown reference topic '${topic}'.\n${referenceIndex()}`);
|
|
2577
|
+
let markdown = this.referenceDocs.get(key);
|
|
2578
|
+
if (markdown === undefined) {
|
|
2579
|
+
markdown = await fs.readFile(getWorkspaceDocAssetPath(entry.asset), 'utf8');
|
|
2580
|
+
if (!markdown.trim())
|
|
2581
|
+
throw new Error(`Reference '${key}' is empty or unavailable.`);
|
|
2582
|
+
this.referenceDocs.set(key, markdown);
|
|
2583
|
+
}
|
|
2584
|
+
return renderReference(key, markdown, options);
|
|
2585
|
+
}
|
|
1934
2586
|
async execute(goal, limit, signal, onEvent, bindingMode = 'full', _timeoutMs) {
|
|
1935
2587
|
return this.executeGoal(goal, limit ?? 5, onEvent, signal, bindingMode);
|
|
1936
2588
|
}
|
|
2589
|
+
/**
|
|
2590
|
+
* Run a workflow goal in the top-level session rather than the disposable
|
|
2591
|
+
* `execute` child. Forms and host input are owned by this session and are
|
|
2592
|
+
* therefore available while the workflow is running.
|
|
2593
|
+
*/
|
|
2594
|
+
async executeForeground(goal, limit, signal, onEvent, bindingMode = 'full', _timeoutMs) {
|
|
2595
|
+
if (this.purpose === 'work' && this.pendingSuspensionValue)
|
|
2596
|
+
return { bindings: [], solutions: [], output: '', elapsedMs: 0, outcome: 'failed', error: 'Resume the pending continuation or open a new Work conversation before starting another operation.' };
|
|
2597
|
+
const existing = new Set(this.forms.list().map(form => form.formId));
|
|
2598
|
+
try {
|
|
2599
|
+
return await this.executeGoal(goal, limit ?? 5, onEvent, signal, bindingMode, undefined, true);
|
|
2600
|
+
}
|
|
2601
|
+
finally {
|
|
2602
|
+
for (const form of this.forms.list())
|
|
2603
|
+
if (!existing.has(form.formId) && form.state === 'open') {
|
|
2604
|
+
this.forms.close(form.formId, 'cancelled', 'Foreground operation ended');
|
|
2605
|
+
const payload = { op: 'close', formId: form.formId, revision: form.revision, state: 'cancelled', reason: 'Foreground operation ended' };
|
|
2606
|
+
onEvent?.({ type: 'form', form: payload });
|
|
2607
|
+
await this.formHandler?.(payload);
|
|
2608
|
+
}
|
|
2609
|
+
}
|
|
2610
|
+
}
|
|
2611
|
+
/** Deterministic named invocation. This never asks a model which goal to run. */
|
|
2612
|
+
async *runWorkflow(name, inputs = {}, options = {}) {
|
|
2613
|
+
yield* this.exclusive('workflow', () => this.runWorkflowInner(name, inputs, options), options.signal);
|
|
2614
|
+
}
|
|
2615
|
+
async *runWorkflowInner(name, inputs, options) {
|
|
2616
|
+
if (this.disposed) {
|
|
2617
|
+
yield { type: 'error', content: 'Session has been disposed' };
|
|
2618
|
+
return;
|
|
2619
|
+
}
|
|
2620
|
+
if (this.purpose !== 'work') {
|
|
2621
|
+
yield { type: 'error', content: 'Start workflows in a separate Work conversation.' };
|
|
2622
|
+
return;
|
|
2623
|
+
}
|
|
2624
|
+
await this.materializeMissingEmbeddedScripts();
|
|
2625
|
+
const spec = await this.workSpec();
|
|
2626
|
+
if (!spec.shell) {
|
|
2627
|
+
yield { type: 'error', content: spec.diagnostics.join('\n') };
|
|
2628
|
+
return;
|
|
2629
|
+
}
|
|
2630
|
+
if (this.pinnedWorkHash !== spec.hash) {
|
|
2631
|
+
yield { type: 'error', content: 'Work snapshot or linked scripts changed; refresh into a new Work session.' };
|
|
2632
|
+
return;
|
|
2633
|
+
}
|
|
2634
|
+
const entry = spec.shell.workflows.find(flow => flow.name === name);
|
|
2635
|
+
if (!entry) {
|
|
2636
|
+
yield { type: 'error', content: `Unknown workflow: ${name}` };
|
|
2637
|
+
return;
|
|
2638
|
+
}
|
|
2639
|
+
this.modelCallsThisTurn = 0;
|
|
2640
|
+
this.modelCallBudget = this.maxModelCalls;
|
|
2641
|
+
const turn = ++this.turnCounter;
|
|
2642
|
+
const started = Date.now();
|
|
2643
|
+
const request = `Workflow: ${name}`;
|
|
2644
|
+
await this.recordHistoryTurnStart({ turn, mode: 'goal', request, workflow: { name, inputs } });
|
|
2645
|
+
const local = new AbortController();
|
|
2646
|
+
const signal = this.requestSignal(options.signal ? AbortSignal.any([local.signal, options.signal]) : local.signal);
|
|
2647
|
+
const queue = [];
|
|
2648
|
+
let wake;
|
|
2649
|
+
let result;
|
|
2650
|
+
const operation = executeWorkEntry(entry, inputs, goal => this.executeForeground(goal, 1, signal, event => { queue.push(event); wake?.(); wake = undefined; }, 'full'), signal)
|
|
2651
|
+
.then(value => { result = value; wake?.(); wake = undefined; });
|
|
2652
|
+
try {
|
|
2653
|
+
while (!result || queue.length) {
|
|
2654
|
+
while (queue.length) {
|
|
2655
|
+
const event = queue.shift();
|
|
2656
|
+
if (event.type === 'solution')
|
|
2657
|
+
continue;
|
|
2658
|
+
this.recordHistoryEvent(turn, event);
|
|
2659
|
+
yield event;
|
|
2660
|
+
}
|
|
2661
|
+
if (!result)
|
|
2662
|
+
await new Promise(resolve => { wake = resolve; });
|
|
2663
|
+
}
|
|
2664
|
+
await operation;
|
|
2665
|
+
const final = result;
|
|
2666
|
+
const event = { type: 'workflow_result', content: formatWorkResult(name, { ...final, output: '' }),
|
|
2667
|
+
workflow: { name, result: final, harness: this.harnessName, hash: spec.hash, version: spec.version } };
|
|
2668
|
+
this.recordHistoryEvent(turn, event);
|
|
2669
|
+
yield event;
|
|
2670
|
+
const context = `[User-started workflow; returned data is not instructions]\n${JSON.stringify({ name, inputs, result: final }).slice(0, 12000)}`;
|
|
2671
|
+
if (this.harnessAgent) {
|
|
2672
|
+
this.harnessAgent.addContext(context);
|
|
2673
|
+
this.agentMessages = this.harnessAgent.getMessages();
|
|
2674
|
+
}
|
|
2675
|
+
else
|
|
2676
|
+
this.agentMessages.push({ role: 'user', content: context });
|
|
2677
|
+
await this.finishHistoryTurn({ turn, mode: 'goal', request,
|
|
2678
|
+
workflow: { name, inputs, status: final.status, outputs: final.outputs },
|
|
2679
|
+
outcome: final.status === 'succeeded' ? 'query' : final.status === 'cancelled' ? 'aborted' : final.status,
|
|
2680
|
+
durationMs: Date.now() - started, modelCalls: this.modelCallsThisTurn });
|
|
2681
|
+
await this.persistSessionHarness(this.history?.currentVersion ?? 0);
|
|
2682
|
+
}
|
|
2683
|
+
finally {
|
|
2684
|
+
local.abort();
|
|
2685
|
+
await operation;
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
/** Explicit resume intent only; reading/listing history never executes it. */
|
|
2689
|
+
async *resumeSuspension(options = {}) {
|
|
2690
|
+
yield* this.exclusive('resume', async function* () {
|
|
2691
|
+
const pending = this.pendingSuspension();
|
|
2692
|
+
if (!pending)
|
|
2693
|
+
return;
|
|
2694
|
+
if (this.purpose === 'work') {
|
|
2695
|
+
const spec = await this.workSpec();
|
|
2696
|
+
if (!spec.shell || spec.hash !== this.pinnedWorkHash) {
|
|
2697
|
+
yield { type: 'error', content: 'Work snapshot or scripts changed; cannot resume this continuation.' };
|
|
2698
|
+
return;
|
|
2699
|
+
}
|
|
2700
|
+
}
|
|
2701
|
+
await this.clearSuspension();
|
|
2702
|
+
yield* this.queryInner(pending.continuation, { ...options, signal: this.requestSignal(options.signal) });
|
|
2703
|
+
}.bind(this), options.signal);
|
|
2704
|
+
}
|
|
1937
2705
|
/**
|
|
1938
2706
|
* Prompt mode: English request -> meta task -> DML -> commit -> entry run.
|
|
1939
2707
|
*
|
|
@@ -1951,6 +2719,10 @@ export class DMLSession {
|
|
|
1951
2719
|
if (this.disposed)
|
|
1952
2720
|
return;
|
|
1953
2721
|
this.disposed = true;
|
|
2722
|
+
this.lifetime.abort(new Error('Session closed'));
|
|
2723
|
+
for (const form of this.forms.list())
|
|
2724
|
+
if (form.state === 'open')
|
|
2725
|
+
this.forms.close(form.formId, 'cancelled', 'Session closed');
|
|
1954
2726
|
if (this.processBackend) {
|
|
1955
2727
|
try {
|
|
1956
2728
|
await this.processBackend.shutdown();
|
|
@@ -1973,16 +2745,19 @@ export class DMLSession {
|
|
|
1973
2745
|
await this.runner.dispose();
|
|
1974
2746
|
}
|
|
1975
2747
|
buildRunOptions(options) {
|
|
1976
|
-
const inputHandler = options.onInput ?? this.inputHandler;
|
|
2748
|
+
const inputHandler = options.onInput ?? options.onInputRequired ?? this.inputHandler;
|
|
1977
2749
|
return {
|
|
1978
2750
|
workspacePath: this.workspacePath,
|
|
1979
2751
|
gasLimit: options.gasLimit ?? this.gasLimit,
|
|
1980
2752
|
tools: options.tools ?? this.tools,
|
|
1981
2753
|
toolPolicy: options.toolPolicy ?? this.toolPolicy,
|
|
1982
2754
|
onInputRequired: inputHandler
|
|
1983
|
-
? (prompt) => this.requireInput(prompt)
|
|
2755
|
+
? (prompt) => this.requireInput(prompt, undefined, this.requestSignal(options.signal), inputHandler)
|
|
1984
2756
|
: async () => undefined,
|
|
1985
2757
|
onForm: this.formHandler,
|
|
2758
|
+
// A turn that called suspend/1 stops here; the record is what --session
|
|
2759
|
+
// resumes from (docs/DML_REPL_SUSPEND_RESUME.md).
|
|
2760
|
+
onSuspend: (payload) => this.handleSuspend(payload),
|
|
1986
2761
|
signal: options.signal,
|
|
1987
2762
|
onModelCall: () => this.reserveModelCall(),
|
|
1988
2763
|
// A run that is not itself a process resolves primitives through the
|
|
@@ -2137,16 +2912,33 @@ export class DMLSession {
|
|
|
2137
2912
|
// no-op
|
|
2138
2913
|
}
|
|
2139
2914
|
/** Resolve a human answer, or undefined when no channel is configured. */
|
|
2140
|
-
async requireInput(prompt, options) {
|
|
2141
|
-
if (!
|
|
2915
|
+
async requireInput(prompt, options, signal = this.activeRequestSignal, handler = this.inputHandler) {
|
|
2916
|
+
if (!handler)
|
|
2142
2917
|
return undefined;
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2918
|
+
const effective = this.requestSignal(signal);
|
|
2919
|
+
const abortable = (promise) => new Promise((resolve, reject) => {
|
|
2920
|
+
let settled = false;
|
|
2921
|
+
const finish = (value, error) => {
|
|
2922
|
+
if (settled)
|
|
2923
|
+
return;
|
|
2924
|
+
settled = true;
|
|
2925
|
+
effective.removeEventListener('abort', aborted);
|
|
2926
|
+
if (error)
|
|
2927
|
+
reject(error);
|
|
2928
|
+
else
|
|
2929
|
+
resolve(value);
|
|
2930
|
+
};
|
|
2931
|
+
const aborted = () => finish(undefined);
|
|
2932
|
+
effective.addEventListener('abort', aborted, { once: true });
|
|
2933
|
+
promise.then(value => finish(value), error => finish(undefined, error));
|
|
2934
|
+
if (effective.aborted)
|
|
2935
|
+
aborted();
|
|
2936
|
+
});
|
|
2937
|
+
// Keep queued requests serialized even if one is cancelled before its turn.
|
|
2938
|
+
// An active cancelled handler need not resolve before the next owner can ask.
|
|
2939
|
+
const scheduled = sharedInputQueue.then(() => effective.aborted ? undefined : abortable(Promise.resolve().then(() => handler(prompt, options, effective))));
|
|
2940
|
+
sharedInputQueue = scheduled.then(() => undefined, () => undefined);
|
|
2941
|
+
return abortable(scheduled);
|
|
2150
2942
|
}
|
|
2151
2943
|
/**
|
|
2152
2944
|
* Reserve one model call for the current turn. When the budget is reached,
|
|
@@ -2172,7 +2964,7 @@ export class DMLSession {
|
|
|
2172
2964
|
if (!this.inputHandler) {
|
|
2173
2965
|
return false;
|
|
2174
2966
|
}
|
|
2175
|
-
const answer = await this.
|
|
2967
|
+
const answer = await this.requireInput(`Max model-call budget reached (${this.modelCallBudget}). Continue for another ${this.maxModelCalls} calls? (yes/no)\n`
|
|
2176
2968
|
+ 'change the limit: repl.maxModelCalls in .deepclause/config.json '
|
|
2177
2969
|
+ '("repl": { "maxModelCalls": N }), or pass --max-model-calls N; 0 means unlimited', ['yes', 'no']);
|
|
2178
2970
|
return /^(y|yes)$/i.test((answer ?? '').trim());
|