deepclause-sdk 0.6.0 → 0.7.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 +57 -0
- package/dist/agent.d.ts +2 -0
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +5 -0
- package/dist/agent.js.map +1 -1
- package/dist/cli/agent-inbox.d.ts +25 -0
- package/dist/cli/agent-inbox.d.ts.map +1 -0
- package/dist/cli/agent-inbox.js +46 -0
- package/dist/cli/agent-inbox.js.map +1 -0
- package/dist/cli/config.d.ts +28 -28
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.js +7 -2
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/repl.d.ts +7 -0
- package/dist/cli/repl.d.ts.map +1 -1
- package/dist/cli/repl.js +181 -13
- package/dist/cli/repl.js.map +1 -1
- package/dist/cli/run.d.ts +1 -0
- package/dist/cli/run.d.ts.map +1 -1
- package/dist/cli/run.js +3 -1
- package/dist/cli/run.js.map +1 -1
- package/dist/cli/serve.d.ts +3 -0
- package/dist/cli/serve.d.ts.map +1 -0
- package/dist/cli/serve.js +131 -0
- package/dist/cli/serve.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/judge/llm.d.ts.map +1 -1
- package/dist/judge/llm.js +9 -4
- package/dist/judge/llm.js.map +1 -1
- package/dist/judge/types.d.ts +10 -0
- package/dist/judge/types.d.ts.map +1 -1
- package/dist/judge/types.js.map +1 -1
- package/dist/prolog-src/deepclause_mi.pl +370 -54
- package/dist/repl/agent-inbox.d.ts +73 -0
- package/dist/repl/agent-inbox.d.ts.map +1 -0
- package/dist/repl/agent-inbox.js +168 -0
- package/dist/repl/agent-inbox.js.map +1 -0
- package/dist/repl/agent.d.ts +14 -1
- package/dist/repl/agent.d.ts.map +1 -1
- package/dist/repl/agent.js +25 -6
- package/dist/repl/agent.js.map +1 -1
- package/dist/repl/backend.d.ts +6 -0
- package/dist/repl/backend.d.ts.map +1 -1
- package/dist/repl/backend.js +17 -2
- package/dist/repl/backend.js.map +1 -1
- package/dist/repl/event-history.d.ts.map +1 -1
- package/dist/repl/event-history.js +3 -0
- package/dist/repl/event-history.js.map +1 -1
- package/dist/repl/harness-tools.d.ts +9 -2
- package/dist/repl/harness-tools.d.ts.map +1 -1
- package/dist/repl/harness-tools.js +38 -14
- package/dist/repl/harness-tools.js.map +1 -1
- package/dist/repl/history.d.ts +14 -3
- package/dist/repl/history.d.ts.map +1 -1
- package/dist/repl/history.js +62 -5
- package/dist/repl/history.js.map +1 -1
- package/dist/repl/index.d.ts +11 -0
- package/dist/repl/index.d.ts.map +1 -1
- package/dist/repl/index.js +6 -2
- package/dist/repl/index.js.map +1 -1
- package/dist/repl/process-backend.d.ts +1 -0
- package/dist/repl/process-backend.d.ts.map +1 -1
- package/dist/repl/process-executor.d.ts +4 -0
- package/dist/repl/process-executor.d.ts.map +1 -1
- package/dist/repl/process-executor.js +36 -1
- package/dist/repl/process-executor.js.map +1 -1
- package/dist/repl/process-worker.d.ts.map +1 -1
- package/dist/repl/process-worker.js +33 -8
- package/dist/repl/process-worker.js.map +1 -1
- package/dist/repl/processes.d.ts +14 -1
- package/dist/repl/processes.d.ts.map +1 -1
- package/dist/repl/processes.js +8 -2
- package/dist/repl/processes.js.map +1 -1
- package/dist/repl/reference.d.ts.map +1 -1
- package/dist/repl/reference.js +4 -3
- package/dist/repl/reference.js.map +1 -1
- package/dist/repl/render.d.ts.map +1 -1
- package/dist/repl/render.js +13 -0
- package/dist/repl/render.js.map +1 -1
- package/dist/repl/session.d.ts +72 -5
- package/dist/repl/session.d.ts.map +1 -1
- package/dist/repl/session.js +595 -42
- package/dist/repl/session.js.map +1 -1
- package/dist/repl/toolset.d.ts +8 -0
- package/dist/repl/toolset.d.ts.map +1 -1
- package/dist/repl/toolset.js +53 -4
- package/dist/repl/toolset.js.map +1 -1
- package/dist/repl/tui/renderer.d.ts.map +1 -1
- package/dist/repl/tui/renderer.js +3 -1
- package/dist/repl/tui/renderer.js.map +1 -1
- package/dist/repl/work-hooks.d.ts +29 -0
- package/dist/repl/work-hooks.d.ts.map +1 -0
- package/dist/repl/work-hooks.js +117 -0
- package/dist/repl/work-hooks.js.map +1 -0
- package/dist/repl/worker-host.d.ts +2 -0
- package/dist/repl/worker-host.d.ts.map +1 -1
- package/dist/repl/worker-host.js +48 -4
- package/dist/repl/worker-host.js.map +1 -1
- package/dist/repl/worker-protocol.d.ts +23 -2
- package/dist/repl/worker-protocol.d.ts.map +1 -1
- package/dist/repl/worker-protocol.js +1 -1
- package/dist/runner.d.ts +2 -2
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +19 -3
- package/dist/runner.js.map +1 -1
- package/dist/runtime-identity.json +6 -6
- package/dist/serve/agent-broadcast.d.ts +29 -0
- package/dist/serve/agent-broadcast.d.ts.map +1 -0
- package/dist/serve/agent-broadcast.js +28 -0
- package/dist/serve/agent-broadcast.js.map +1 -0
- package/dist/serve/agent-preferences.d.ts +16 -0
- package/dist/serve/agent-preferences.d.ts.map +1 -0
- package/dist/serve/agent-preferences.js +42 -0
- package/dist/serve/agent-preferences.js.map +1 -0
- package/dist/serve/api-docs.d.ts +61 -0
- package/dist/serve/api-docs.d.ts.map +1 -0
- package/dist/serve/api-docs.js +122 -0
- package/dist/serve/api-docs.js.map +1 -0
- package/dist/serve/backend.d.ts +12 -0
- package/dist/serve/backend.d.ts.map +1 -0
- package/dist/serve/backend.js +52 -0
- package/dist/serve/backend.js.map +1 -0
- package/dist/serve/capabilities.d.ts +6 -0
- package/dist/serve/capabilities.d.ts.map +1 -0
- package/dist/serve/capabilities.js +21 -0
- package/dist/serve/capabilities.js.map +1 -0
- package/dist/serve/example-agent.d.ts +5 -0
- package/dist/serve/example-agent.d.ts.map +1 -0
- package/dist/serve/example-agent.js +5 -0
- package/dist/serve/example-agent.js.map +1 -0
- package/dist/serve/files.d.ts +55 -0
- package/dist/serve/files.d.ts.map +1 -0
- package/dist/serve/files.js +249 -0
- package/dist/serve/files.js.map +1 -0
- package/dist/serve/harness.d.ts +3 -0
- package/dist/serve/harness.d.ts.map +1 -0
- package/dist/serve/harness.js +53 -0
- package/dist/serve/harness.js.map +1 -0
- package/dist/serve/previews.d.ts +40 -0
- package/dist/serve/previews.d.ts.map +1 -0
- package/dist/serve/previews.js +240 -0
- package/dist/serve/previews.js.map +1 -0
- package/dist/serve/protocol.d.ts +228 -0
- package/dist/serve/protocol.d.ts.map +1 -0
- package/dist/serve/protocol.js +2 -0
- package/dist/serve/protocol.js.map +1 -0
- package/dist/serve/schedules.d.ts +85 -0
- package/dist/serve/schedules.d.ts.map +1 -0
- package/dist/serve/schedules.js +249 -0
- package/dist/serve/schedules.js.map +1 -0
- package/dist/serve/server.d.ts +50 -0
- package/dist/serve/server.d.ts.map +1 -0
- package/dist/serve/server.js +1696 -0
- package/dist/serve/server.js.map +1 -0
- package/dist/serve/session-worker.d.ts +2 -0
- package/dist/serve/session-worker.d.ts.map +1 -0
- package/dist/serve/session-worker.js +291 -0
- package/dist/serve/session-worker.js.map +1 -0
- package/dist/serve/sessions.d.ts +178 -0
- package/dist/serve/sessions.d.ts.map +1 -0
- package/dist/serve/sessions.js +905 -0
- package/dist/serve/sessions.js.map +1 -0
- package/dist/serve/storage.d.ts +41 -0
- package/dist/serve/storage.d.ts.map +1 -0
- package/dist/serve/storage.js +211 -0
- package/dist/serve/storage.js.map +1 -0
- package/dist/serve/ui/api-docs.html +17 -0
- package/dist/serve/ui/api-docs.js +36 -0
- package/dist/serve/ui/app.js +958 -0
- package/dist/serve/ui/authoring.js +92 -0
- package/dist/serve/ui/deepclause-logo.png +0 -0
- package/dist/serve/ui/deepclause-mark.svg +1 -0
- package/dist/serve/ui/diff.js +16 -0
- package/dist/serve/ui/dompurify-LICENSE.txt +202 -0
- package/dist/serve/ui/features.css +15 -0
- package/dist/serve/ui/files.js +13 -0
- package/dist/serve/ui/ibm-plex-mono-latin.woff2 +0 -0
- package/dist/serve/ui/ibmplexmono-OFL.txt +93 -0
- package/dist/serve/ui/icons.js +30 -0
- package/dist/serve/ui/index.html +68 -0
- package/dist/serve/ui/manrope-OFL.txt +93 -0
- package/dist/serve/ui/manrope-latin.woff2 +0 -0
- package/dist/serve/ui/markdown.js +38 -0
- package/dist/serve/ui/marked-LICENSE.txt +44 -0
- package/dist/serve/ui/marked.js +88 -0
- package/dist/serve/ui/purify.js +2454 -0
- package/dist/serve/ui/style.css +249 -0
- package/dist/serve/ui/web-work.css +247 -0
- package/dist/serve/ui/web.css +1848 -0
- package/dist/serve/workflow-bundles.d.ts +8 -0
- package/dist/serve/workflow-bundles.d.ts.map +1 -0
- package/dist/serve/workflow-bundles.js +78 -0
- package/dist/serve/workflow-bundles.js.map +1 -0
- package/dist/serve/workflow-calls.d.ts +6 -0
- package/dist/serve/workflow-calls.d.ts.map +1 -0
- package/dist/serve/workflow-calls.js +13 -0
- package/dist/serve/workflow-calls.js.map +1 -0
- package/dist/serve/workflows.d.ts +93 -0
- package/dist/serve/workflows.d.ts.map +1 -0
- package/dist/serve/workflows.js +219 -0
- package/dist/serve/workflows.js.map +1 -0
- package/dist/system/assets/docs/AGENT_PROMPT.md +6 -6
- package/dist/system/assets/docs/DML_AUTHORING.md +80 -2
- package/dist/system/assets/docs/DML_PROCESSES.md +24 -0
- package/dist/system/assets/docs/DML_REFERENCE.md +98 -10
- package/dist/system/assets/docs/DML_SHELL.md +149 -7
- package/dist/system/assets/docs/DML_TASKS.md +10 -3
- package/dist/system/assets/docs/LOCAL_AGENT_PROMPT.md +6 -6
- package/dist/system/environment.d.ts +5 -1
- package/dist/system/environment.d.ts.map +1 -1
- package/dist/system/environment.js +14 -8
- package/dist/system/environment.js.map +1 -1
- package/dist/system/runtime/agentvm-manager.d.ts +12 -1
- package/dist/system/runtime/agentvm-manager.d.ts.map +1 -1
- package/dist/system/runtime/agentvm-manager.js +136 -20
- package/dist/system/runtime/agentvm-manager.js.map +1 -1
- package/dist/system/runtime/shell-manager.d.ts +3 -0
- package/dist/system/runtime/shell-manager.d.ts.map +1 -1
- package/dist/system/runtime/shell-manager.js +1 -1
- package/dist/system/runtime/shell-manager.js.map +1 -1
- package/dist/system/timezone.d.ts +20 -0
- package/dist/system/timezone.d.ts.map +1 -0
- package/dist/system/timezone.js +37 -0
- package/dist/system/timezone.js.map +1 -0
- package/dist/types.d.ts +37 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/work/index.d.ts +13 -3
- package/dist/work/index.d.ts.map +1 -1
- package/dist/work/index.js +80 -15
- package/dist/work/index.js.map +1 -1
- package/docs/DEEP_RESEARCH_EXAMPLE.md +127 -0
- package/docs/SERVE.md +664 -0
- package/docs/WORK_AGENT_HOOKS_PLAN.md +416 -0
- package/docs/WORK_AGENT_INBOX.md +140 -0
- package/docs/WORK_AGENT_INBOX_PLAN.md +91 -0
- package/docs/WORK_MODE.md +269 -0
- package/package.json +24 -2
- package/sdk-examples/deep-research.dml +144 -0
- package/sdk-examples/deep-research.py +502 -0
- package/sdk-examples/hooked-agent.dml +49 -0
- package/sdk-examples/subagent-inbox.dml +66 -0
- package/src/prolog-src/deepclause_mi.pl +370 -54
package/dist/repl/session.js
CHANGED
|
@@ -19,8 +19,10 @@ import { DmlProcessExecutor } from './process-executor.js';
|
|
|
19
19
|
import { pidKey } from './processes.js';
|
|
20
20
|
import { compactMemory, boundCompactionSettings, estimateMemoryTokens, shouldCompact, toCompactionEvent, } from './compaction.js';
|
|
21
21
|
import { HarnessAgent } from './agent.js';
|
|
22
|
+
import { AgentInbox, agentMessageSource } from './agent-inbox.js';
|
|
23
|
+
import { HookMemoryBridge, parseHookResult, validateHookSnapshot, HOOK_STATE_MAX_BYTES } from './work-hooks.js';
|
|
22
24
|
import { BRIEF_VALUE_CHARS, createHarnessTools, createWorkAgentTools } from './harness-tools.js';
|
|
23
|
-
import { buildParamsTerm, plainValue, quoteAtom, quotePrologString } from './frames.js';
|
|
25
|
+
import { buildParamsTerm, plainValue, quoteAtom, quotePrologString, toPrologTerm } from './frames.js';
|
|
24
26
|
import { buildHarnessHeader, } from './export.js';
|
|
25
27
|
import { HistoryStore, assertHarnessName, assertSessionId, harnessHash, moduleVersion, } from './history.js';
|
|
26
28
|
import { buildDiagramPrompt, extractMermaid, parseMermaidFlowchart, rasterizeSvg, renderFlowchartSvg, renderMermaidAscii, resolveMedia, validateMermaid, } from '../visualize/index.js';
|
|
@@ -28,7 +30,7 @@ import { generateLlmReply } from '../prolog/bridge.js';
|
|
|
28
30
|
import { FormRegistry } from '../forms/registry.js';
|
|
29
31
|
import { formatModelCatalogEntry } from './model-resolver.js';
|
|
30
32
|
import { historyEventFromRecord } from './event-history.js';
|
|
31
|
-
import { buildWorkSystemPrompt, executeWorkEntry, formatWorkResult, renderWorkShell, validateWorkShell, workShellDiagnostics } from '../work/index.js';
|
|
33
|
+
import { buildWorkSystemPrompt, executeWorkEntry, formatWorkResult, renderWorkShell, renderWorkflowDeclaration, validateWorkShell, workShellDiagnostics } from '../work/index.js';
|
|
32
34
|
/**
|
|
33
35
|
* Context note added when a saved session is reloaded. The opening words are
|
|
34
36
|
* also the de-duplication marker in `repl_note_resumed/2` — keep them in sync.
|
|
@@ -151,11 +153,21 @@ export class DMLSession {
|
|
|
151
153
|
/** Persisted authoring-agent conversation (agent mode). */
|
|
152
154
|
agentMessages = [];
|
|
153
155
|
harnessAgent;
|
|
156
|
+
agentInbox;
|
|
157
|
+
inboxOpening;
|
|
158
|
+
agentReference = `agent_ref(${JSON.stringify(crypto.randomUUID())})`;
|
|
159
|
+
inboxPumping = false;
|
|
160
|
+
inboxDispatchBlocked = false;
|
|
161
|
+
inboxController;
|
|
162
|
+
workHooks;
|
|
163
|
+
activeWorkHook;
|
|
164
|
+
workHookMemoryBefore;
|
|
154
165
|
/** Active host-tool trace scopes; nested tool calls push/pop here. */
|
|
155
166
|
traceToolIds = [];
|
|
156
167
|
traceToolSeq = 0;
|
|
157
168
|
/** Open edit transaction (agent mode): predicate list at snapshot. */
|
|
158
169
|
transactionBefore = null;
|
|
170
|
+
transactionScriptsBefore = null;
|
|
159
171
|
transactionDirty = false;
|
|
160
172
|
/** Whether the last agent turn committed an edit (for the history record). */
|
|
161
173
|
lastTurnCommitted = false;
|
|
@@ -282,6 +294,7 @@ export class DMLSession {
|
|
|
282
294
|
this.runner.bindSession(this.sessionId);
|
|
283
295
|
}
|
|
284
296
|
static async open(options) {
|
|
297
|
+
options = { ...options, workflowOnly: options.workflowOnly ?? options.harnessSnapshot?.workflowOnly, harnessModules: options.harnessModules ?? options.harnessSnapshot?.modules };
|
|
285
298
|
if (options.resume && options.sessionId && options.history) {
|
|
286
299
|
const store = new HistoryStore(options.workspacePath ?? process.cwd(), options.sessionId, options.history);
|
|
287
300
|
const meta = await store.readSessionMetadata();
|
|
@@ -322,6 +335,11 @@ export class DMLSession {
|
|
|
322
335
|
}
|
|
323
336
|
const store = new HistoryStore(options.workspacePath ?? process.cwd(), session.sessionId, options.history, session.harnessName);
|
|
324
337
|
snapshot = await store.readSessionHarness();
|
|
338
|
+
const savedMetadata = await store.readSessionMetadata();
|
|
339
|
+
if (savedMetadata?.workHooksVersion !== undefined && (savedMetadata.workHooksVersion !== 1 || !snapshot?.workHooks)) {
|
|
340
|
+
await session.dispose(false);
|
|
341
|
+
throw new Error('Saved agent hook state is missing or unsupported; start a new conversation. Initialization will not be replayed.');
|
|
342
|
+
}
|
|
325
343
|
session.recordedServices = await store.readServiceRecords();
|
|
326
344
|
session.pendingSuspensionValue = (await store.readSuspendRecord()) ?? undefined;
|
|
327
345
|
// A session can have a transcript but no harness snapshot (older builds,
|
|
@@ -358,6 +376,16 @@ export class DMLSession {
|
|
|
358
376
|
session.agentMessages = snapshot.memory.agent;
|
|
359
377
|
}
|
|
360
378
|
await session.restoreHarnessFromHistory(snapshot);
|
|
379
|
+
if (snapshot.workHooks) {
|
|
380
|
+
try {
|
|
381
|
+
session.workHooks = validateHookSnapshot(snapshot.workHooks);
|
|
382
|
+
session.workHooks.state = session.validateHookState(session.workHooks.state);
|
|
383
|
+
}
|
|
384
|
+
catch (error) {
|
|
385
|
+
await session.dispose(false);
|
|
386
|
+
throw error;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
361
389
|
session.noteSessionResumed();
|
|
362
390
|
}
|
|
363
391
|
else if (options.harnessSnapshot) {
|
|
@@ -413,19 +441,25 @@ export class DMLSession {
|
|
|
413
441
|
session.pinnedWorkScripts = snapshot?.workIdentity?.scripts ?? snapshot?.scripts;
|
|
414
442
|
if (!session.isEmpty()) {
|
|
415
443
|
const scripts = await session.scriptHashes();
|
|
416
|
-
const stateHash =
|
|
417
|
-
const programHash =
|
|
444
|
+
const stateHash = session.identityHash(session.moduleSource(), scripts);
|
|
445
|
+
const programHash = session.identityHash(session.canonicalSource(), scripts);
|
|
418
446
|
const expected = snapshot?.hash ?? options.harnessSnapshot?.hash;
|
|
419
447
|
const offeredSource = snapshot?.module ?? options.harnessSnapshot?.source;
|
|
420
448
|
// Validate the exact source carried over the host boundary. Re-rendering
|
|
421
449
|
// can reorder annotations without changing a valid, untouched snapshot.
|
|
422
|
-
const offeredHash = offeredSource === undefined ? undefined :
|
|
450
|
+
const offeredHash = offeredSource === undefined ? undefined : session.identityHash(offeredSource, scripts);
|
|
423
451
|
if (expected && expected !== offeredHash && expected !== (snapshot ? stateHash : programHash) && expected !== stateHash) {
|
|
424
452
|
await session.dispose();
|
|
425
453
|
throw new Error('Saved Work snapshot or linked scripts changed. Refresh before starting a new run.');
|
|
426
454
|
}
|
|
427
455
|
session.pinnedWorkHash = snapshot?.workIdentity?.hash ?? programHash;
|
|
428
|
-
|
|
456
|
+
try {
|
|
457
|
+
await session.workSpec();
|
|
458
|
+
}
|
|
459
|
+
catch (error) {
|
|
460
|
+
await session.dispose(false);
|
|
461
|
+
throw error;
|
|
462
|
+
}
|
|
429
463
|
}
|
|
430
464
|
}
|
|
431
465
|
if (!session.isEmpty())
|
|
@@ -440,7 +474,26 @@ export class DMLSession {
|
|
|
440
474
|
return { ...(await this.history?.readSessionMetadata() ?? {}), id: this.sessionId, harness: this.harnessName,
|
|
441
475
|
mode: this.purpose, kind: this.openOptions.sessionKind ?? 'conversation', model: this.model, backend: this.provider };
|
|
442
476
|
}
|
|
477
|
+
workflowSourceError(source, complete = true) {
|
|
478
|
+
if (!this.openOptions.workflowOnly)
|
|
479
|
+
return;
|
|
480
|
+
try {
|
|
481
|
+
const result = this.prologQuery(`deepclause_mi:repl_validate_workflow_source('${this.sessionId}',${quoteString(source)},${complete ? 'true' : 'false'},Result)`);
|
|
482
|
+
const value = plainValue(result?.Result);
|
|
483
|
+
return value === 'ok' ? undefined : String(value ?? 'Workflow source must declare exactly one literal workflow/1 interface and only workflow-owned code');
|
|
484
|
+
}
|
|
485
|
+
catch (error) {
|
|
486
|
+
return String(error);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
identityHash(source, scripts) {
|
|
490
|
+
const modules = this.harnessModuleSources().slice().sort((a, b) => a.id.localeCompare(b.id));
|
|
491
|
+
return harnessHash(modules.length ? source + '\n% Captured immutable modules\n' + JSON.stringify(modules) : source, scripts);
|
|
492
|
+
}
|
|
443
493
|
workShellErrors() {
|
|
494
|
+
const owned = this.workflowSourceError(this.moduleSource());
|
|
495
|
+
if (owned)
|
|
496
|
+
return [owned];
|
|
444
497
|
const shell = this.shell();
|
|
445
498
|
if (shell)
|
|
446
499
|
return validateWorkShell(shell, this.harnessView().predicates);
|
|
@@ -453,7 +506,7 @@ export class DMLSession {
|
|
|
453
506
|
const diagnostics = !shell && errors.length ? [] : workShellDiagnostics(shell);
|
|
454
507
|
diagnostics.push(...errors);
|
|
455
508
|
const scripts = await this.scriptHashes();
|
|
456
|
-
const stateHash =
|
|
509
|
+
const stateHash = this.identityHash(this.canonicalSource(), scripts);
|
|
457
510
|
const scriptsChanged = this.purpose === 'work' && this.pinnedWorkScripts && JSON.stringify(this.pinnedWorkScripts) !== JSON.stringify(scripts);
|
|
458
511
|
if (scriptsChanged)
|
|
459
512
|
diagnostics.push('Linked scripts changed. Refresh into a new Work snapshot.');
|
|
@@ -463,6 +516,15 @@ export class DMLSession {
|
|
|
463
516
|
this.pinnedWorkSource ??= this.moduleSource();
|
|
464
517
|
this.pinnedWorkScripts ??= scripts;
|
|
465
518
|
this.pinnedWorkVersion ??= this.history?.currentVersion;
|
|
519
|
+
if ((Object.keys(shell.hooks ?? {}).length || shell.inbox || this.openOptions.agentInboxPolicy?.workflowMessages) && !this.workHooks) {
|
|
520
|
+
const hostOnly = !Object.keys(shell.hooks ?? {}).length && !shell.inbox;
|
|
521
|
+
if (!hostOnly && this.resume && (this.agentMessages.some(message => message.role === 'user') || (await this.history?.lastTurn(this.sessionId) ?? 0) > 0))
|
|
522
|
+
throw new Error('Saved agent has no hook lifecycle state; start a new conversation.');
|
|
523
|
+
this.workHooks = { version: 1, initialization: hostOnly ? 'ready' : 'new', state: 'state{}', messages: [
|
|
524
|
+
{ role: 'system', content: shell.system.trim() || 'You are the assistant for this harness.', contextOrigin: 'hook' },
|
|
525
|
+
...(hostOnly ? structuredClone(this.agentMessages).map(({ media, ...message }) => ({ ...message, ...(media ? { mediaRefs: media } : {}) })) : []),
|
|
526
|
+
] };
|
|
527
|
+
}
|
|
466
528
|
}
|
|
467
529
|
const snapshotSource = this.purpose === 'work' ? this.pinnedWorkSource ?? this.moduleSource() : this.moduleSource();
|
|
468
530
|
const snapshotScripts = this.purpose === 'work' ? this.pinnedWorkScripts ?? scripts : scripts;
|
|
@@ -470,7 +532,8 @@ export class DMLSession {
|
|
|
470
532
|
status: errors.length || scriptsChanged ? 'invalid' : shell ? 'ready' : 'missing',
|
|
471
533
|
version: this.purpose === 'work' ? this.pinnedWorkVersion : this.history?.currentVersion,
|
|
472
534
|
hash: this.purpose === 'work' ? this.pinnedWorkHash ?? stateHash : stateHash,
|
|
473
|
-
snapshot: { source: snapshotSource, hash:
|
|
535
|
+
snapshot: { source: snapshotSource, scripts: structuredClone(snapshotScripts), hash: this.identityHash(snapshotSource, snapshotScripts),
|
|
536
|
+
...(this.harnessModuleSources().length ? { modules: structuredClone(this.harnessModuleSources()) } : {}), ...(this.openOptions.workflowOnly ? { workflowOnly: true } : {}),
|
|
474
537
|
version: this.purpose === 'work' ? this.pinnedWorkVersion : this.history?.currentVersion } };
|
|
475
538
|
}
|
|
476
539
|
requestSignal(signal) {
|
|
@@ -489,6 +552,7 @@ export class DMLSession {
|
|
|
489
552
|
finally {
|
|
490
553
|
this.activeOperation = undefined;
|
|
491
554
|
this.activeRequestSignal = undefined;
|
|
555
|
+
this.wakeAgentInbox();
|
|
492
556
|
}
|
|
493
557
|
}
|
|
494
558
|
/**
|
|
@@ -571,7 +635,7 @@ export class DMLSession {
|
|
|
571
635
|
this.processBackend = host;
|
|
572
636
|
return host;
|
|
573
637
|
}
|
|
574
|
-
const executor = new DmlProcessExecutor(this, { onEvent });
|
|
638
|
+
const executor = new DmlProcessExecutor(this, { onEvent, beforeRun: this.openOptions.onProcessLaunch });
|
|
575
639
|
this.processBackend = executor;
|
|
576
640
|
return executor;
|
|
577
641
|
})();
|
|
@@ -703,6 +767,21 @@ export class DMLSession {
|
|
|
703
767
|
processes() {
|
|
704
768
|
return this.processBackend?.processes() ?? [];
|
|
705
769
|
}
|
|
770
|
+
processRuntimeSettings() {
|
|
771
|
+
return { workflowOnly: this.openOptions.workflowOnly, trace: this.openOptions.trace, gasLimit: this.gasLimit, maxModelCalls: this.maxModelCalls,
|
|
772
|
+
registerLaunches: Boolean(this.openOptions.onProcessLaunch), modelCatalog: this.modelResolver?.catalog() };
|
|
773
|
+
}
|
|
774
|
+
async resolveProcessModel(spec) {
|
|
775
|
+
if (!this.modelResolver)
|
|
776
|
+
throw new Error('Model switching is not configured');
|
|
777
|
+
return this.modelResolver.resolve(spec);
|
|
778
|
+
}
|
|
779
|
+
async registerProcessLaunch(launch) {
|
|
780
|
+
await this.openOptions.onProcessLaunch?.(launch);
|
|
781
|
+
}
|
|
782
|
+
async processTrace(pid) {
|
|
783
|
+
return await this.processBackend?.trace?.(pid) ?? [];
|
|
784
|
+
}
|
|
706
785
|
processInfo(pid) {
|
|
707
786
|
return this.processBackend?.info(pid);
|
|
708
787
|
}
|
|
@@ -769,6 +848,8 @@ export class DMLSession {
|
|
|
769
848
|
return candidate.handleRequest(pid, request, signal);
|
|
770
849
|
}
|
|
771
850
|
async handleForeground(request, signal) {
|
|
851
|
+
if (request.op === 'agent_self' || request.op === 'agent_post')
|
|
852
|
+
return this.handleAgentInboxRequest(request);
|
|
772
853
|
return (await this.ensureProcessBackend()).foregroundHandle(request, signal);
|
|
773
854
|
}
|
|
774
855
|
/** Host tool descriptors, for a worker's proxy tools. */
|
|
@@ -793,8 +874,8 @@ export class DMLSession {
|
|
|
793
874
|
return tool.execute(args, { signal });
|
|
794
875
|
}
|
|
795
876
|
/** Prompt the human on behalf of a worker's `input/2`. */
|
|
796
|
-
requestHumanInput(prompt) {
|
|
797
|
-
return this.requireInput(prompt);
|
|
877
|
+
requestHumanInput(prompt, choices, signal) {
|
|
878
|
+
return this.requireInput(prompt, choices, signal ? this.requestSignal(signal) : this.requestSignal());
|
|
798
879
|
}
|
|
799
880
|
// Accessors for building a worker's init data (see worker-host.ts).
|
|
800
881
|
workspacePathValue() {
|
|
@@ -835,14 +916,14 @@ export class DMLSession {
|
|
|
835
916
|
if (this.processSnapshot)
|
|
836
917
|
return this.processSnapshot;
|
|
837
918
|
const text = this.harnessTextSync();
|
|
838
|
-
return { text, version: moduleVersion(text) };
|
|
919
|
+
return { text, version: this.harnessModuleSources().length ? this.identityHash(text, []).slice(0, 12) : moduleVersion(text) };
|
|
839
920
|
}
|
|
840
921
|
/**
|
|
841
922
|
* Adopt a process snapshot pushed by the main session (worker hosts only).
|
|
842
923
|
* Keeps a worker's children on the code the user actually committed.
|
|
843
924
|
*/
|
|
844
925
|
setProcessSnapshot(text, version) {
|
|
845
|
-
this.processSnapshot = { text, version: version ?? moduleVersion(text) };
|
|
926
|
+
this.processSnapshot = { text, version: version ?? (this.harnessModuleSources().length ? this.identityHash(text, []).slice(0, 12) : moduleVersion(text)) };
|
|
846
927
|
}
|
|
847
928
|
/**
|
|
848
929
|
* A private child session carrying a snapshot of this harness (invariant C).
|
|
@@ -895,6 +976,9 @@ export class DMLSession {
|
|
|
895
976
|
if (this.disposed) {
|
|
896
977
|
return { error: 'Session has been disposed' };
|
|
897
978
|
}
|
|
979
|
+
const owned = this.workflowSourceError(code);
|
|
980
|
+
if (owned)
|
|
981
|
+
return { error: owned };
|
|
898
982
|
const result = this.prologQuery(`deepclause_mi:load_code('${this.sessionId}', ${quoteString(code)}, Error)`);
|
|
899
983
|
const error = plainValue(result?.Error);
|
|
900
984
|
if (error === undefined || error === null) {
|
|
@@ -1013,6 +1097,11 @@ export class DMLSession {
|
|
|
1013
1097
|
...this.agentMessages.filter((message) => !message.content.startsWith(RESUME_NOTE_PREFIX)),
|
|
1014
1098
|
{ role: 'system', content: RESUME_NOTE },
|
|
1015
1099
|
];
|
|
1100
|
+
if (this.workHooks)
|
|
1101
|
+
this.workHooks.messages = [
|
|
1102
|
+
...this.workHooks.messages.filter(message => !message.content.startsWith(RESUME_NOTE_PREFIX)),
|
|
1103
|
+
{ role: 'system', content: RESUME_NOTE },
|
|
1104
|
+
];
|
|
1016
1105
|
}
|
|
1017
1106
|
/**
|
|
1018
1107
|
* Restore a resumed session's harness from its durable snapshot and continue
|
|
@@ -1031,7 +1120,7 @@ export class DMLSession {
|
|
|
1031
1120
|
}
|
|
1032
1121
|
// Consistency check: the saved hash covers the module *and* its scripts;
|
|
1033
1122
|
// scripts live in the workspace and may have been edited since.
|
|
1034
|
-
const hash =
|
|
1123
|
+
const hash = this.identityHash(snapshot.module, await this.scriptHashes());
|
|
1035
1124
|
if (snapshot.hash && hash !== snapshot.hash) {
|
|
1036
1125
|
this.warnHistory(new Error('harness or its scripts differ from the saved session state'));
|
|
1037
1126
|
}
|
|
@@ -1041,24 +1130,28 @@ export class DMLSession {
|
|
|
1041
1130
|
* restore it even after the process exits. Captures the *current* module
|
|
1042
1131
|
* (including goal-mode drift) plus the serialized conversation memory.
|
|
1043
1132
|
*/
|
|
1044
|
-
async persistSessionHarness(version, clean) {
|
|
1133
|
+
async persistSessionHarness(version, clean, strict = this.workHooks !== undefined) {
|
|
1045
1134
|
if (!this.history)
|
|
1046
1135
|
return;
|
|
1047
1136
|
try {
|
|
1048
1137
|
const module = this.moduleSource();
|
|
1049
1138
|
const scripts = await this.scriptHashes();
|
|
1050
|
-
const hash =
|
|
1051
|
-
if (this.purpose === 'work' && this.pinnedWorkScripts && JSON.stringify(this.pinnedWorkScripts) !== JSON.stringify(scripts))
|
|
1139
|
+
const hash = this.identityHash(module, scripts);
|
|
1140
|
+
if (this.purpose === 'work' && this.pinnedWorkScripts && JSON.stringify(this.pinnedWorkScripts) !== JSON.stringify(scripts)) {
|
|
1141
|
+
if (strict)
|
|
1142
|
+
throw new Error('Linked scripts changed; cannot checkpoint hook state');
|
|
1052
1143
|
return;
|
|
1144
|
+
}
|
|
1053
1145
|
const isClean = clean ?? (this.purpose === 'work' && this.pinnedWorkHash
|
|
1054
|
-
? (
|
|
1146
|
+
? (this.identityHash(this.canonicalSource(), scripts) === this.pinnedWorkHash || hash === this.pinnedWorkHash)
|
|
1055
1147
|
: this.history.currentHash ? hash === this.history.currentHash : version === 0);
|
|
1056
1148
|
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,
|
|
1149
|
+
shellKind: this.shell()?.kind, ...(this.workHooks ? { workHooksVersion: 1 } : {}), harnessHash: this.purpose === 'work' ? this.pinnedWorkHash ?? hash : hash, sessionStateHash: hash,
|
|
1058
1150
|
harnessVersion: this.purpose === 'work' ? this.pinnedWorkVersion : version });
|
|
1059
1151
|
await this.history.writeSessionHarness({
|
|
1060
1152
|
...(this.purpose === 'work' && this.pinnedWorkHash && this.pinnedWorkShell && this.pinnedWorkScripts
|
|
1061
1153
|
? { workIdentity: { hash: this.pinnedWorkHash, source: this.pinnedWorkSource, shell: this.pinnedWorkShell, scripts: this.pinnedWorkScripts } } : {}),
|
|
1154
|
+
...(this.workHooks ? { workHooks: validateHookSnapshot({ ...this.workHooks, messages: this.harnessAgent?.contextMessages() ?? this.workHooks.messages }) } : {}),
|
|
1062
1155
|
baseSourceHash: this.baseSourceHash,
|
|
1063
1156
|
sessionId: this.sessionId,
|
|
1064
1157
|
version: this.purpose === 'work' ? this.pinnedWorkVersion ?? version : version,
|
|
@@ -1068,7 +1161,7 @@ export class DMLSession {
|
|
|
1068
1161
|
scripts,
|
|
1069
1162
|
...(this.openOptions.harnessModules?.length ? { harnessModules: this.openOptions.harnessModules } : {}),
|
|
1070
1163
|
memory: {
|
|
1071
|
-
harness: this.dumpMemoryTerm('harness'),
|
|
1164
|
+
harness: this.workHookMemoryBefore ?? this.dumpMemoryTerm('harness'),
|
|
1072
1165
|
meta: this.dumpMemoryTerm('meta'),
|
|
1073
1166
|
...(this.agentMessages.length > 0 ? { agent: this.agentMessages } : {}),
|
|
1074
1167
|
},
|
|
@@ -1076,6 +1169,8 @@ export class DMLSession {
|
|
|
1076
1169
|
});
|
|
1077
1170
|
}
|
|
1078
1171
|
catch (error) {
|
|
1172
|
+
if (strict)
|
|
1173
|
+
throw error;
|
|
1079
1174
|
this.warnHistory(error);
|
|
1080
1175
|
}
|
|
1081
1176
|
}
|
|
@@ -1630,7 +1725,7 @@ export class DMLSession {
|
|
|
1630
1725
|
* The child frame uses the living scratch module and may itself call task()
|
|
1631
1726
|
* (RLM-style recursion); its harness-memory writes are discarded afterward.
|
|
1632
1727
|
*/
|
|
1633
|
-
async executeGoal(goal, limit = 5, onEvent, signal, bindingMode = 'full', process, preserveMemory = false) {
|
|
1728
|
+
async executeGoal(goal, limit = 5, onEvent, signal, bindingMode = 'full', process, preserveMemory = false, hookFrame = false) {
|
|
1634
1729
|
signal = this.requestSignal(signal);
|
|
1635
1730
|
const startedAt = Date.now();
|
|
1636
1731
|
const elapsed = () => Date.now() - startedAt;
|
|
@@ -1644,7 +1739,7 @@ export class DMLSession {
|
|
|
1644
1739
|
elapsedMs: elapsed(),
|
|
1645
1740
|
};
|
|
1646
1741
|
}
|
|
1647
|
-
const start = this.prologQuery(`deepclause_mi:repl_execute_frame('${this.sessionId}', ${quoteString(goal)}, FrameId, Error)`);
|
|
1742
|
+
const start = this.prologQuery(`deepclause_mi:${hookFrame ? 'repl_hook_frame' : 'repl_execute_frame'}('${this.sessionId}', ${quoteString(goal)}, FrameId, Error)`);
|
|
1648
1743
|
const error = plainValue(start?.Error);
|
|
1649
1744
|
if (error === undefined || error === null) {
|
|
1650
1745
|
return { bindings: [], solutions: [], output: '', error: 'Failed to start execute frame', elapsedMs: elapsed() };
|
|
@@ -1717,7 +1812,7 @@ export class DMLSession {
|
|
|
1717
1812
|
async *agentPrompt(request, options = {}) {
|
|
1718
1813
|
yield* this.exclusive('prompt', () => this.agentPromptInner(request, { ...options, signal: this.requestSignal(options.signal) }), options.signal);
|
|
1719
1814
|
}
|
|
1720
|
-
async *agentPromptInner(request, options = {}) {
|
|
1815
|
+
async *agentPromptInner(request, options = {}, incoming) {
|
|
1721
1816
|
if (this.purpose === 'work') {
|
|
1722
1817
|
await this.materializeMissingEmbeddedScripts();
|
|
1723
1818
|
const spec = await this.workSpec();
|
|
@@ -1734,14 +1829,29 @@ export class DMLSession {
|
|
|
1734
1829
|
yield { type: 'error', content: 'Session has been disposed' };
|
|
1735
1830
|
return;
|
|
1736
1831
|
}
|
|
1737
|
-
if (!this.llmBackend) {
|
|
1832
|
+
if (!this.llmBackend && !this.workHooks) {
|
|
1738
1833
|
yield { type: 'error', content: 'authoring agent requires an injected LLM backend' };
|
|
1739
1834
|
return;
|
|
1740
1835
|
}
|
|
1836
|
+
if (this.purpose === 'work' && !incoming && (this.shell()?.inbox || this.openOptions.agentInboxPolicy?.workflowMessages) && this.openOptions.agentInboxPolicy?.enabled !== false) {
|
|
1837
|
+
await (await this.ensureAgentInbox()).resume(true);
|
|
1838
|
+
this.inboxDispatchBlocked = false;
|
|
1839
|
+
this.publishInboxStatus();
|
|
1840
|
+
}
|
|
1741
1841
|
this.turnCounter += 1;
|
|
1742
1842
|
const turn = this.turnCounter;
|
|
1743
1843
|
const historyStart = Date.now();
|
|
1744
|
-
|
|
1844
|
+
if (this.workHooks) {
|
|
1845
|
+
this.modelCallsThisTurn = 0;
|
|
1846
|
+
this.modelCallBudget = incoming ? Math.min(this.maxModelCalls || 10, 10) : this.maxModelCalls;
|
|
1847
|
+
}
|
|
1848
|
+
await this.recordHistoryTurnStart({ turn, mode: 'prompt', request: incoming ? '' : request,
|
|
1849
|
+
source: incoming ? agentMessageSource(incoming) : 'user', messageId: incoming?.id });
|
|
1850
|
+
if (incoming) {
|
|
1851
|
+
const event = { type: 'agent_message', agentMessage: incoming };
|
|
1852
|
+
this.recordHistoryEvent(turn, event);
|
|
1853
|
+
yield event;
|
|
1854
|
+
}
|
|
1745
1855
|
this.lastTurnCommitted = false;
|
|
1746
1856
|
this.lastCommitVersion = undefined;
|
|
1747
1857
|
// No automatic transaction: `define`/`assert`/… are refused until the agent
|
|
@@ -1753,7 +1863,8 @@ export class DMLSession {
|
|
|
1753
1863
|
let requestText = request;
|
|
1754
1864
|
try {
|
|
1755
1865
|
for (;;) {
|
|
1756
|
-
|
|
1866
|
+
const events = this.workHooks ? this.runHookedAgentTurn(requestText, agent, this.requestSignal(options.signal), incoming) : agent.run(requestText, { signal: options.signal });
|
|
1867
|
+
for await (const event of events) {
|
|
1757
1868
|
// A nested (`execute` child) error is a tool result the agent can
|
|
1758
1869
|
// react to; only the agent's own errors fail the turn.
|
|
1759
1870
|
if (event.type === 'error' && event.frameKind !== 'nested')
|
|
@@ -1784,6 +1895,8 @@ export class DMLSession {
|
|
|
1784
1895
|
}
|
|
1785
1896
|
finally {
|
|
1786
1897
|
this.agentMessages = agent.getMessages();
|
|
1898
|
+
if (this.workHooks)
|
|
1899
|
+
this.workHooks.messages = agent.contextMessages();
|
|
1787
1900
|
}
|
|
1788
1901
|
if (options.signal?.aborted || failed) {
|
|
1789
1902
|
await this.rollbackTurn();
|
|
@@ -1805,7 +1918,15 @@ export class DMLSession {
|
|
|
1805
1918
|
this.recordHistoryEvent(turn, marker);
|
|
1806
1919
|
yield marker;
|
|
1807
1920
|
}
|
|
1808
|
-
|
|
1921
|
+
try {
|
|
1922
|
+
await this.persistSessionHarness(this.history?.currentVersion ?? 0);
|
|
1923
|
+
}
|
|
1924
|
+
catch (error) {
|
|
1925
|
+
failed = true;
|
|
1926
|
+
const event = { type: 'error', content: `Could not checkpoint agent state: ${error instanceof Error ? error.message : String(error)}` };
|
|
1927
|
+
this.recordHistoryEvent(turn, event);
|
|
1928
|
+
yield event;
|
|
1929
|
+
}
|
|
1809
1930
|
const outcome = options.signal?.aborted
|
|
1810
1931
|
? 'aborted'
|
|
1811
1932
|
: failed
|
|
@@ -1816,7 +1937,8 @@ export class DMLSession {
|
|
|
1816
1937
|
await this.finishHistoryTurn({
|
|
1817
1938
|
turn,
|
|
1818
1939
|
mode: 'prompt',
|
|
1819
|
-
request,
|
|
1940
|
+
request: incoming ? '' : request,
|
|
1941
|
+
source: incoming ? agentMessageSource(incoming) : 'user', messageId: incoming?.id,
|
|
1820
1942
|
outcome,
|
|
1821
1943
|
commitVersion: this.lastCommitVersion,
|
|
1822
1944
|
durationMs: Date.now() - historyStart,
|
|
@@ -1824,18 +1946,359 @@ export class DMLSession {
|
|
|
1824
1946
|
error: failed ? 'authoring turn failed' : undefined,
|
|
1825
1947
|
});
|
|
1826
1948
|
}
|
|
1949
|
+
async ensureAgentInbox() {
|
|
1950
|
+
if (this.disposed || this.purpose !== 'work' || this.openOptions.sessionKind === 'workflow-run' || this.openOptions.agentInboxPolicy?.enabled === false)
|
|
1951
|
+
throw new Error('agent_inbox_unavailable');
|
|
1952
|
+
const spec = await this.workSpec();
|
|
1953
|
+
if (spec.status !== 'ready' || !spec.shell || (!spec.shell.inbox && !this.openOptions.agentInboxPolicy?.workflowMessages) || spec.shell.kind !== 'agent')
|
|
1954
|
+
throw new Error('agent_inbox_not_enabled');
|
|
1955
|
+
if (!this.inboxOpening) {
|
|
1956
|
+
const store = this.openOptions.agentInboxStore ?? (this.history ? {
|
|
1957
|
+
read: () => this.history.readAgentInbox(), write: (snapshot) => this.history.writeAgentInbox(snapshot),
|
|
1958
|
+
} : undefined);
|
|
1959
|
+
if (!store)
|
|
1960
|
+
throw new Error('agent_inbox_requires_persistent_history');
|
|
1961
|
+
const policy = {
|
|
1962
|
+
...this.openOptions.agentInboxPolicy,
|
|
1963
|
+
maxPending: Math.min(spec.shell.inbox?.max_pending ?? 32, this.openOptions.agentInboxPolicy?.maxPending ?? 32),
|
|
1964
|
+
maxAutoTurns: Math.min(spec.shell.inbox?.max_auto_turns ?? 10, this.openOptions.agentInboxPolicy?.maxAutoTurns ?? 10),
|
|
1965
|
+
};
|
|
1966
|
+
this.inboxOpening = (async () => {
|
|
1967
|
+
const metadata = await this.history?.readSessionMetadata();
|
|
1968
|
+
if (metadata?.agentInboxVersion !== undefined && metadata.agentInboxVersion !== 1)
|
|
1969
|
+
throw new Error('Unsupported required agent inbox version');
|
|
1970
|
+
const inbox = await AgentInbox.open(store, spec.hash, policy, this.resume && metadata?.agentInboxVersion === 1);
|
|
1971
|
+
await this.history?.updateSessionMetadata({ agentInboxVersion: 1 });
|
|
1972
|
+
return this.agentInbox = inbox;
|
|
1973
|
+
})();
|
|
1974
|
+
}
|
|
1975
|
+
return this.inboxOpening;
|
|
1976
|
+
}
|
|
1977
|
+
agentInboxStatus() {
|
|
1978
|
+
const status = this.agentInbox?.status() ?? { pending: 0, autoTurns: 0 };
|
|
1979
|
+
return this.inboxDispatchBlocked ? { ...status, paused: 'Inbox checkpoint failed; explicit resume required' } : status;
|
|
1980
|
+
}
|
|
1981
|
+
publishInboxStatus() {
|
|
1982
|
+
const event = { type: 'agent_inbox', agentInbox: this.agentInboxStatus() };
|
|
1983
|
+
this.recordHistoryEvent(this.turnCounter, event);
|
|
1984
|
+
try {
|
|
1985
|
+
this.openOptions.onAgentInboxEvent?.(event);
|
|
1986
|
+
}
|
|
1987
|
+
catch { /* Presentation cannot invalidate a committed post. */ }
|
|
1988
|
+
}
|
|
1989
|
+
async pauseAgentInbox() { await (await this.ensureAgentInbox()).pause(); this.publishInboxStatus(); }
|
|
1990
|
+
async resumeAgentInbox() {
|
|
1991
|
+
await (await this.ensureAgentInbox()).resume(!this.inboxController);
|
|
1992
|
+
this.inboxDispatchBlocked = false;
|
|
1993
|
+
this.publishInboxStatus();
|
|
1994
|
+
this.wakeAgentInbox();
|
|
1995
|
+
}
|
|
1996
|
+
cancelAgentInboxTurn() { this.inboxController?.abort(); }
|
|
1997
|
+
/** Called only by the owning foreground or its authenticated process broker. */
|
|
1998
|
+
async handleAgentInboxRequest(request, sender) {
|
|
1999
|
+
if (sender && this.openOptions.agentInboxRequest)
|
|
2000
|
+
return this.openOptions.agentInboxRequest(request, sender);
|
|
2001
|
+
if (request.op === 'agent_self') {
|
|
2002
|
+
if (!this.shell()?.inbox)
|
|
2003
|
+
throw new Error('agent_inbox_not_enabled');
|
|
2004
|
+
if (sender)
|
|
2005
|
+
throw new Error('agent_self_requires_owning_foreground');
|
|
2006
|
+
await this.ensureAgentInbox();
|
|
2007
|
+
return { key: 'agent_self', term: `ok(${this.agentReference})` };
|
|
2008
|
+
}
|
|
2009
|
+
if (!this.shell()?.inbox)
|
|
2010
|
+
throw new Error('agent_inbox_not_enabled');
|
|
2011
|
+
if (request.op !== 'agent_post' || !sender)
|
|
2012
|
+
throw new Error('agent_post_requires_delegated_process');
|
|
2013
|
+
if (request.to !== this.agentReference)
|
|
2014
|
+
throw new Error('invalid_or_stale_agent_reference');
|
|
2015
|
+
const inbox = await this.ensureAgentInbox();
|
|
2016
|
+
if (!request.message || request.message.length > 16384)
|
|
2017
|
+
throw new Error('agent_message_too_large');
|
|
2018
|
+
const item = await inbox.post(JSON.parse(request.message), { pid: sender.pid, name: sender.name.slice(0, 120) });
|
|
2019
|
+
this.publishInboxStatus();
|
|
2020
|
+
this.wakeAgentInbox();
|
|
2021
|
+
return { key: 'agent_post', term: `ok(${quotePrologString(item.id)})` };
|
|
2022
|
+
}
|
|
2023
|
+
/** Trusted host entry point; message data cannot choose or spoof its source. */
|
|
2024
|
+
async acceptWorkflowMessage(message, sender) {
|
|
2025
|
+
if (!sender.workflow || sender.pid)
|
|
2026
|
+
throw new Error('workflow_provenance_required');
|
|
2027
|
+
return this.acceptHostMessage(message, sender);
|
|
2028
|
+
}
|
|
2029
|
+
async acceptHostMessage(message, sender) {
|
|
2030
|
+
if ((!sender.workflow && !sender.agent) || sender.pid)
|
|
2031
|
+
throw new Error('host_message_provenance_required');
|
|
2032
|
+
const item = await (await this.ensureAgentInbox()).post(message, sender);
|
|
2033
|
+
this.publishInboxStatus();
|
|
2034
|
+
this.wakeAgentInbox();
|
|
2035
|
+
return item.id;
|
|
2036
|
+
}
|
|
2037
|
+
/** Drain one accepted delivery under the same exclusive session lock as human turns. */
|
|
2038
|
+
async *processAgentInbox(options = {}) {
|
|
2039
|
+
yield* this.exclusive('agent-inbox', () => this.processAgentInboxInner(options), options.signal);
|
|
2040
|
+
}
|
|
2041
|
+
async *processAgentInboxInner(options) {
|
|
2042
|
+
let item;
|
|
2043
|
+
let failed = false;
|
|
2044
|
+
let finished = false;
|
|
2045
|
+
this.inboxController = new AbortController();
|
|
2046
|
+
const signal = this.requestSignal(AbortSignal.any([this.inboxController.signal, ...(options.signal ? [options.signal] : [])]));
|
|
2047
|
+
try {
|
|
2048
|
+
if (signal.aborted || this.inboxDispatchBlocked)
|
|
2049
|
+
return;
|
|
2050
|
+
item = await (await this.ensureAgentInbox()).claim();
|
|
2051
|
+
this.publishInboxStatus();
|
|
2052
|
+
if (!item)
|
|
2053
|
+
return;
|
|
2054
|
+
for await (const event of this.agentPromptInner(item.text, { ...options, signal }, item)) {
|
|
2055
|
+
if (event.type === 'error' && event.frameKind !== 'nested')
|
|
2056
|
+
failed = true;
|
|
2057
|
+
yield event;
|
|
2058
|
+
}
|
|
2059
|
+
finished = true;
|
|
2060
|
+
}
|
|
2061
|
+
catch (error) {
|
|
2062
|
+
failed = true;
|
|
2063
|
+
if (!item)
|
|
2064
|
+
this.inboxDispatchBlocked = true;
|
|
2065
|
+
yield { type: 'error', content: `Background delivery failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
2066
|
+
}
|
|
2067
|
+
finally {
|
|
2068
|
+
try {
|
|
2069
|
+
if (item)
|
|
2070
|
+
await this.agentInbox.finish(item.id, signal.aborted || !finished ? 'interrupted' : failed ? 'failed' : 'completed');
|
|
2071
|
+
}
|
|
2072
|
+
catch (error) {
|
|
2073
|
+
this.inboxDispatchBlocked = true;
|
|
2074
|
+
const event = { type: 'error', content: `Could not checkpoint background delivery: ${error instanceof Error ? error.message : String(error)}` };
|
|
2075
|
+
this.recordHistoryEvent(this.turnCounter, event);
|
|
2076
|
+
yield event;
|
|
2077
|
+
}
|
|
2078
|
+
this.inboxController = undefined;
|
|
2079
|
+
this.publishInboxStatus();
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
wakeAgentInbox() {
|
|
2083
|
+
const status = this.agentInboxStatus();
|
|
2084
|
+
if (this.disposed || this.activeOperation || this.inboxPumping || !status.pending || status.paused)
|
|
2085
|
+
return;
|
|
2086
|
+
if (this.openOptions.onAgentInboxReady) {
|
|
2087
|
+
try {
|
|
2088
|
+
this.openOptions.onAgentInboxReady(status);
|
|
2089
|
+
}
|
|
2090
|
+
catch { /* Host may explicitly resume later. */ }
|
|
2091
|
+
return;
|
|
2092
|
+
}
|
|
2093
|
+
this.inboxPumping = true;
|
|
2094
|
+
setTimeout(() => {
|
|
2095
|
+
void (async () => {
|
|
2096
|
+
try {
|
|
2097
|
+
if (this.activeOperation || this.disposed)
|
|
2098
|
+
return;
|
|
2099
|
+
for await (const event of this.processAgentInbox()) {
|
|
2100
|
+
try {
|
|
2101
|
+
this.openOptions.onAgentInboxEvent?.(event);
|
|
2102
|
+
}
|
|
2103
|
+
catch { /* presentation only */ }
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
catch {
|
|
2107
|
+
this.inboxDispatchBlocked = true;
|
|
2108
|
+
}
|
|
2109
|
+
finally {
|
|
2110
|
+
this.inboxPumping = false;
|
|
2111
|
+
this.wakeAgentInbox();
|
|
2112
|
+
}
|
|
2113
|
+
})();
|
|
2114
|
+
}, 0);
|
|
2115
|
+
}
|
|
2116
|
+
validateHookState(text) {
|
|
2117
|
+
if (typeof text !== 'string' || new TextEncoder().encode(text).byteLength > HOOK_STATE_MAX_BYTES)
|
|
2118
|
+
throw new Error('Hook state exceeds size limit');
|
|
2119
|
+
const result = this.prologQuery(`deepclause_mi:repl_hook_state(${quotePrologString(text)}, Canonical)`);
|
|
2120
|
+
const canonical = plainValue(result?.Canonical);
|
|
2121
|
+
if (typeof canonical !== 'string')
|
|
2122
|
+
throw new Error('Invalid hook state: expected bounded ground data');
|
|
2123
|
+
return canonical;
|
|
2124
|
+
}
|
|
2125
|
+
async commitHookTransition(agent, candidate) {
|
|
2126
|
+
const previous = { ...this.workHooks, messages: agent.contextMessages() };
|
|
2127
|
+
candidate = validateHookSnapshot(candidate);
|
|
2128
|
+
this.workHooks = candidate;
|
|
2129
|
+
agent.replaceContext(candidate.messages);
|
|
2130
|
+
try {
|
|
2131
|
+
await this.persistSessionHarness(this.history?.currentVersion ?? 0, undefined, true);
|
|
2132
|
+
}
|
|
2133
|
+
catch (error) {
|
|
2134
|
+
this.workHooks = previous;
|
|
2135
|
+
agent.replaceContext(previous.messages);
|
|
2136
|
+
throw error;
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
async *invokeWorkHook(name, goal, context, signal, messages) {
|
|
2140
|
+
if (signal.aborted)
|
|
2141
|
+
throw signal.reason ?? new Error('Hook cancelled');
|
|
2142
|
+
const bridge = new HookMemoryBridge(messages);
|
|
2143
|
+
const memoryBefore = this.dumpMemoryTerm('harness');
|
|
2144
|
+
const local = new AbortController();
|
|
2145
|
+
const effective = AbortSignal.any([signal, local.signal]);
|
|
2146
|
+
const timer = setTimeout(() => local.abort(new Error(`Hook ${name} timed out after 30000ms`)), 30000);
|
|
2147
|
+
timer.unref?.();
|
|
2148
|
+
const queue = [];
|
|
2149
|
+
let wake;
|
|
2150
|
+
let done = false;
|
|
2151
|
+
let value;
|
|
2152
|
+
let failure;
|
|
2153
|
+
let operation;
|
|
2154
|
+
const taskId = `hook_${this.turnCounter}_${name}`;
|
|
2155
|
+
try {
|
|
2156
|
+
const state = this.validateHookState(this.workHooks.state);
|
|
2157
|
+
this.workHookMemoryBefore = memoryBefore;
|
|
2158
|
+
this.prologQuery(`deepclause_mi:repl_set_memory('${this.sessionId}', harness, ${bridge.seedTerm()})`);
|
|
2159
|
+
this.activeWorkHook = name;
|
|
2160
|
+
yield { type: 'task_activity', taskState: 'started', taskId, taskDescription: `Agent ${name}` };
|
|
2161
|
+
// Protocol discriminants are atoms; user text/payload values stay strings/data.
|
|
2162
|
+
const contextTerm = `dict{${Object.entries(context).map(([key, value]) => `${key}:${key === 'source' && (value === 'user' || value === 'process' || value === 'workflow' || value === 'agent') ? value : toPrologTerm(value)}`).join(',')}}`;
|
|
2163
|
+
const invocation = `${goal}(${contextTerm},${state},HookState,HookDecision)`;
|
|
2164
|
+
operation = this.executeForeground(invocation, 1, effective, event => {
|
|
2165
|
+
if (event.type === 'solution' || event.type === 'finished')
|
|
2166
|
+
return;
|
|
2167
|
+
// Intermediate task JSON/text is activity, not the public assistant reply.
|
|
2168
|
+
queue.push(['stream', 'reasoning', 'output', 'answer', 'error'].includes(event.type)
|
|
2169
|
+
? { type: 'log', content: `[${name} ${event.type}] ${event.content ?? ''}` } : event);
|
|
2170
|
+
wake?.();
|
|
2171
|
+
wake = undefined;
|
|
2172
|
+
}, 'full').then(result => { value = result; }, error => { failure = error; }).finally(() => { done = true; wake?.(); wake = undefined; });
|
|
2173
|
+
while (!done || queue.length) {
|
|
2174
|
+
while (queue.length)
|
|
2175
|
+
yield queue.shift();
|
|
2176
|
+
if (!done)
|
|
2177
|
+
await new Promise(resolve => { wake = resolve; });
|
|
2178
|
+
}
|
|
2179
|
+
await operation;
|
|
2180
|
+
if (effective.aborted)
|
|
2181
|
+
throw effective.reason ?? new Error('Hook cancelled');
|
|
2182
|
+
if (failure)
|
|
2183
|
+
throw failure;
|
|
2184
|
+
const binding = value?.solutions[0]?.find(binding => binding.name === 'HookJson');
|
|
2185
|
+
if (value?.error || value?.outcome !== 'succeeded' || !binding)
|
|
2186
|
+
throw new Error(`Hook ${name} failed: ${value?.error ?? 'must return one solution with bound state and decision'}`);
|
|
2187
|
+
const result = parseHookResult(binding.value);
|
|
2188
|
+
if (name === 'on_start' && result.action !== 'continue')
|
|
2189
|
+
throw new Error('on_start must return continue');
|
|
2190
|
+
const exported = this.prologQuery(`deepclause_mi:repl_hook_memory('${this.sessionId}', Json)`);
|
|
2191
|
+
const memoryJson = plainValue(exported?.Json);
|
|
2192
|
+
if (typeof memoryJson !== 'string')
|
|
2193
|
+
throw new Error('Could not export hook memory');
|
|
2194
|
+
const next = bridge.commit(JSON.parse(memoryJson));
|
|
2195
|
+
yield { type: 'task_activity', taskState: 'completed', taskId };
|
|
2196
|
+
return { result, messages: next };
|
|
2197
|
+
}
|
|
2198
|
+
catch (error) {
|
|
2199
|
+
yield { type: 'task_activity', taskState: 'failed', taskId };
|
|
2200
|
+
throw error;
|
|
2201
|
+
}
|
|
2202
|
+
finally {
|
|
2203
|
+
clearTimeout(timer);
|
|
2204
|
+
local.abort();
|
|
2205
|
+
await operation;
|
|
2206
|
+
this.activeWorkHook = undefined;
|
|
2207
|
+
this.prologQuery(`deepclause_mi:repl_set_memory('${this.sessionId}', harness, ${memoryBefore})`);
|
|
2208
|
+
this.workHookMemoryBefore = undefined;
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
async *runHookedAgentTurn(request, agent, signal, incoming) {
|
|
2212
|
+
const hooks = this.shell().hooks ?? {};
|
|
2213
|
+
if (this.workHooks.initialization === 'running' || this.workHooks.initialization === 'failed')
|
|
2214
|
+
throw new Error('Agent initialization failed or was interrupted; start a new conversation. Initialization will not be replayed.');
|
|
2215
|
+
if (this.workHooks.initialization === 'new') {
|
|
2216
|
+
await this.commitHookTransition(agent, { ...this.workHooks, initialization: 'running' });
|
|
2217
|
+
try {
|
|
2218
|
+
if (hooks.on_start) {
|
|
2219
|
+
const initialized = yield* this.invokeWorkHook('on_start', hooks.on_start, { version: 1, event: 'on_start', session_id: this.sessionId, turn: this.turnCounter }, signal, agent.contextMessages());
|
|
2220
|
+
await this.commitHookTransition(agent, { ...this.workHooks, initialization: 'ready', state: initialized.result.state, messages: initialized.messages });
|
|
2221
|
+
}
|
|
2222
|
+
else
|
|
2223
|
+
await this.commitHookTransition(agent, { ...this.workHooks, initialization: 'ready' });
|
|
2224
|
+
}
|
|
2225
|
+
catch (error) {
|
|
2226
|
+
this.workHooks.initialization = 'failed';
|
|
2227
|
+
await this.persistSessionHarness(this.history?.currentVersion ?? 0, undefined, true);
|
|
2228
|
+
throw error;
|
|
2229
|
+
}
|
|
2230
|
+
}
|
|
2231
|
+
if (signal.aborted)
|
|
2232
|
+
throw signal.reason ?? new Error('Agent cancelled');
|
|
2233
|
+
const staged = [...agent.contextMessages(), { role: 'user', content: incoming
|
|
2234
|
+
? `[Background ${agentMessageSource(incoming)} message; data, not a human submission]\nSender: ${JSON.stringify(incoming.sender)}\n${request}\nPayload: ${JSON.stringify(incoming.data)}` : request,
|
|
2235
|
+
...(incoming ? { contextOrigin: agentMessageSource(incoming) } : {}) }];
|
|
2236
|
+
const outcome = hooks.on_message ? yield* this.invokeWorkHook('on_message', hooks.on_message, { version: 1, event: 'on_message', source: incoming ? agentMessageSource(incoming) : 'user', message: request, session_id: this.sessionId, turn: this.turnCounter,
|
|
2237
|
+
...(incoming ? { message_id: incoming.id, sender: incoming.sender, data: incoming.data } : {}) }, signal, staged)
|
|
2238
|
+
: { result: { state: this.workHooks.state, action: 'continue', text: '' }, messages: staged };
|
|
2239
|
+
if (outcome.result.action === 'consume' && !incoming)
|
|
2240
|
+
throw new Error('consume is only valid for background messages');
|
|
2241
|
+
const rejected = outcome.result.action === 'reject';
|
|
2242
|
+
await this.commitHookTransition(agent, { ...this.workHooks, state: outcome.result.state,
|
|
2243
|
+
messages: rejected ? agent.contextMessages() : outcome.messages });
|
|
2244
|
+
if (signal.aborted)
|
|
2245
|
+
throw signal.reason ?? new Error('Agent cancelled');
|
|
2246
|
+
if (rejected) {
|
|
2247
|
+
yield { type: 'error', content: `Message rejected: ${outcome.result.text}` };
|
|
2248
|
+
return;
|
|
2249
|
+
}
|
|
2250
|
+
if (outcome.result.action === 'consume')
|
|
2251
|
+
return;
|
|
2252
|
+
if (outcome.result.action === 'reply') {
|
|
2253
|
+
const previous = agent.contextMessages();
|
|
2254
|
+
agent.addReply(outcome.result.text);
|
|
2255
|
+
try {
|
|
2256
|
+
await this.persistSessionHarness(this.history?.currentVersion ?? 0, undefined, true);
|
|
2257
|
+
}
|
|
2258
|
+
catch (error) {
|
|
2259
|
+
agent.replaceContext(previous);
|
|
2260
|
+
throw error;
|
|
2261
|
+
}
|
|
2262
|
+
yield { type: 'answer', content: outcome.result.text };
|
|
2263
|
+
}
|
|
2264
|
+
else {
|
|
2265
|
+
if (!this.llmBackend)
|
|
2266
|
+
throw new Error('Continuing the agent requires an injected LLM backend');
|
|
2267
|
+
yield* agent.run(request, { signal, preparedRequest: true });
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
1827
2270
|
/**
|
|
1828
2271
|
* Deliver a steering message into the running authoring turn (agent mode).
|
|
1829
2272
|
* Ignored when no agent turn is active.
|
|
1830
2273
|
*/
|
|
1831
2274
|
steer(text) {
|
|
2275
|
+
if (this.workHooks)
|
|
2276
|
+
throw new Error('Steering is not supported for hook-enabled agents; send a new message when idle.');
|
|
1832
2277
|
this.harnessAgent?.steer(text);
|
|
1833
2278
|
}
|
|
2279
|
+
hostWorkflowCatalog;
|
|
2280
|
+
/** Embedding host refreshes only between turns; existing invocation closures stay pinned. */
|
|
2281
|
+
setAdditionalSystemPrompt(text) {
|
|
2282
|
+
if (this.activeOperation)
|
|
2283
|
+
throw new Error('Wait for the Agent to finish its current operation before changing instructions');
|
|
2284
|
+
this.openOptions.additionalSystemPrompt = text;
|
|
2285
|
+
}
|
|
2286
|
+
setHostWorkflowCatalog(catalog) {
|
|
2287
|
+
if (this.activeOperation)
|
|
2288
|
+
throw new Error('Cannot refresh workflow catalog during an active turn');
|
|
2289
|
+
this.hostWorkflowCatalog = { entries: structuredClone(catalog.entries), disabledLocal: structuredClone(catalog.disabledLocal ?? []), run: catalog.run };
|
|
2290
|
+
if (this.harnessAgent && this.purpose === 'work') {
|
|
2291
|
+
const workflow = createWorkAgentTools(this, this.tools, this.toolPolicy, this.hostWorkflowCatalog).get('run_workflow');
|
|
2292
|
+
this.harnessAgent.tools.delete('run_workflow');
|
|
2293
|
+
if (workflow)
|
|
2294
|
+
this.harnessAgent.tools.set('run_workflow', workflow);
|
|
2295
|
+
}
|
|
2296
|
+
}
|
|
1834
2297
|
async getHarnessAgent() {
|
|
1835
2298
|
if (this.harnessAgent)
|
|
1836
2299
|
return this.harnessAgent;
|
|
1837
2300
|
const authoringTools = this.purpose === 'work'
|
|
1838
|
-
? createWorkAgentTools(this)
|
|
2301
|
+
? createWorkAgentTools(this, this.tools, this.toolPolicy, this.hostWorkflowCatalog)
|
|
1839
2302
|
: createHarnessTools(this);
|
|
1840
2303
|
const allowed = this.purpose !== 'work' && this.openOptions.authoringToolNames
|
|
1841
2304
|
? new Set(this.openOptions.authoringToolNames)
|
|
@@ -1861,7 +2324,8 @@ export class DMLSession {
|
|
|
1861
2324
|
temperature: this.temperature,
|
|
1862
2325
|
maxTokens: this.maxTokens,
|
|
1863
2326
|
streaming: true,
|
|
1864
|
-
maxModelCalls: this.maxModelCalls,
|
|
2327
|
+
maxModelCalls: this.workHooks ? 0 : this.maxModelCalls,
|
|
2328
|
+
reserveModelCall: this.workHooks ? () => this.reserveModelCall() : undefined,
|
|
1865
2329
|
askInput: (prompt, options) => this.requireInput(prompt, options),
|
|
1866
2330
|
contextWindow: this.contextWindow,
|
|
1867
2331
|
compaction: this.compactionSettings
|
|
@@ -1870,12 +2334,15 @@ export class DMLSession {
|
|
|
1870
2334
|
workspacePath: this.workspacePath,
|
|
1871
2335
|
environment: this.executionEnvironment,
|
|
1872
2336
|
capabilityTool: this.openOptions.capabilityTool,
|
|
2337
|
+
capabilityTools: [...this.tools.keys()],
|
|
1873
2338
|
currentModel: `${this.provider}:${this.model}`,
|
|
1874
2339
|
modelCatalog: this.modelResolver?.catalog(),
|
|
1875
2340
|
knownMessages: this.agentMessages,
|
|
2341
|
+
contextMessages: this.workHooks?.messages,
|
|
1876
2342
|
traceToolStart: (name, args) => this.traceToolStart(name, args),
|
|
1877
2343
|
traceToolEnd: (name, args, result) => this.traceToolEnd(name, args, result),
|
|
1878
|
-
agentSystemPrompt: this.purpose === 'work' ? buildWorkSystemPrompt(this.shell()) : this.openOptions.agentSystemPrompt,
|
|
2344
|
+
agentSystemPrompt: this.purpose === 'work' ? buildWorkSystemPrompt(this.shell(), !this.workHooks) : this.openOptions.agentSystemPrompt,
|
|
2345
|
+
additionalSystemPrompt: () => this.openOptions.additionalSystemPrompt ?? '',
|
|
1879
2346
|
});
|
|
1880
2347
|
return this.harnessAgent;
|
|
1881
2348
|
}
|
|
@@ -2015,6 +2482,8 @@ export class DMLSession {
|
|
|
2015
2482
|
return { ok: false, error: 'no open transaction; call begin_turn before adding an import' };
|
|
2016
2483
|
if (this.purpose === 'work')
|
|
2017
2484
|
return { ok: false, error: 'Work cannot author the harness' };
|
|
2485
|
+
if (this.openOptions.workflowOnly)
|
|
2486
|
+
return { ok: false, error: 'Workflow dependencies are pinned by the host' };
|
|
2018
2487
|
if (!/^[a-z][a-z0-9_]*$/.test(name))
|
|
2019
2488
|
return { ok: false, error: 'harness module names must be lowercase identifiers' };
|
|
2020
2489
|
if (this.harnessName === name)
|
|
@@ -2095,6 +2564,7 @@ export class DMLSession {
|
|
|
2095
2564
|
}
|
|
2096
2565
|
this.prologQuery(`deepclause_mi:repl_snapshot_save('${this.sessionId}')`);
|
|
2097
2566
|
this.prologQuery(`deepclause_mi:repl_edit_touched_clear('${this.sessionId}')`);
|
|
2567
|
+
this.transactionScriptsBefore = await this.scriptHashes();
|
|
2098
2568
|
this.transactionBefore = this.predicateList();
|
|
2099
2569
|
this.transactionDirty = false;
|
|
2100
2570
|
return { ok: true };
|
|
@@ -2106,7 +2576,11 @@ export class DMLSession {
|
|
|
2106
2576
|
if (this.transactionBefore === null) {
|
|
2107
2577
|
return { committed: false, changed: [], error: 'no open transaction' };
|
|
2108
2578
|
}
|
|
2109
|
-
|
|
2579
|
+
const owned = this.workflowSourceError(this.moduleSource());
|
|
2580
|
+
if (owned)
|
|
2581
|
+
return { committed: false, error: owned };
|
|
2582
|
+
const scriptsChanged = JSON.stringify(this.transactionScriptsBefore) !== JSON.stringify(await this.scriptHashes());
|
|
2583
|
+
if (this.transactionDirty || scriptsChanged) {
|
|
2110
2584
|
const errors = this.workShellErrors();
|
|
2111
2585
|
if (errors.length)
|
|
2112
2586
|
return { committed: false, error: `Invalid Work shell; fix it before committing:\n${errors.join('\n')}` };
|
|
@@ -2116,7 +2590,8 @@ export class DMLSession {
|
|
|
2116
2590
|
const touched = this.editTouched();
|
|
2117
2591
|
const changed = this.simplePredicateDiff(before, after, touched);
|
|
2118
2592
|
this.transactionBefore = null;
|
|
2119
|
-
const committed = this.transactionDirty;
|
|
2593
|
+
const committed = this.transactionDirty || scriptsChanged;
|
|
2594
|
+
this.transactionScriptsBefore = null;
|
|
2120
2595
|
let version;
|
|
2121
2596
|
if (committed && this.history) {
|
|
2122
2597
|
version = await this.recordHistoryChange('commit', this.turnCounter, before, { touched });
|
|
@@ -2126,6 +2601,14 @@ export class DMLSession {
|
|
|
2126
2601
|
this.transactionDirty = false;
|
|
2127
2602
|
this.prologQuery(`deepclause_mi:repl_edit_touched_clear('${this.sessionId}')`);
|
|
2128
2603
|
await this.persistSessionHarness(this.history?.currentVersion ?? 0);
|
|
2604
|
+
if (committed && this.openOptions.onHarnessCommit) {
|
|
2605
|
+
try {
|
|
2606
|
+
await this.openOptions.onHarnessCommit(version);
|
|
2607
|
+
}
|
|
2608
|
+
catch (error) {
|
|
2609
|
+
return { committed, changed, error: `Version saved locally, but activation failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
2610
|
+
}
|
|
2611
|
+
}
|
|
2129
2612
|
// Advisory: probe changed pure predicates for accidental nondeterminism.
|
|
2130
2613
|
let warnings = [];
|
|
2131
2614
|
if (committed) {
|
|
@@ -2151,6 +2634,15 @@ export class DMLSession {
|
|
|
2151
2634
|
* `header: none` keeps it free of the export banner, so it round-trips through
|
|
2152
2635
|
* `replaceHarness` without accumulating comments.
|
|
2153
2636
|
*/
|
|
2637
|
+
/** Read-only copy of a pinned workflow: keep its helpers, omit Agent shell/hooks/tools. */
|
|
2638
|
+
async workflowCopySource(name, copyName) {
|
|
2639
|
+
const spec = await this.workSpec(), entry = spec.shell?.workflows.find(item => item.name === name);
|
|
2640
|
+
if (!this.openOptions.workflowOnly || spec.shell?.kind !== 'workflow' || !entry)
|
|
2641
|
+
throw new Error('Workflow extraction requires an isolated workflow bundle; migrate the flattened harness first');
|
|
2642
|
+
const sid = quoteAtom(this.sessionId);
|
|
2643
|
+
const result = this.prologQuery(`with_output_to(string(Text),(deepclause_mi:export_directives(${sid}),deepclause_mi:export_tools(${sid}),deepclause_mi:repl_display_clauses(${sid},[workflow/1])))`);
|
|
2644
|
+
return renderWorkflowDeclaration({ ...entry, name: copyName }) + '\n' + String(plainValue(result?.Text) ?? '');
|
|
2645
|
+
}
|
|
2154
2646
|
async harnessSource() {
|
|
2155
2647
|
const result = this.prologQuery(`deepclause_mi:repl_display_harness('${this.sessionId}', Text)`);
|
|
2156
2648
|
return String(plainValue(result?.Text) ?? '');
|
|
@@ -2182,6 +2674,21 @@ export class DMLSession {
|
|
|
2182
2674
|
const conflict = await this.persistentConflict();
|
|
2183
2675
|
if (conflict)
|
|
2184
2676
|
return { committed: false, error: conflict };
|
|
2677
|
+
if (this.openOptions.workflowOnly) {
|
|
2678
|
+
if (expectedHash && (await this.workSpec()).hash !== expectedHash)
|
|
2679
|
+
return { committed: false, error: 'Workflow changed; refresh before saving' };
|
|
2680
|
+
if (shell.kind !== 'workflow' || shell.workflows.length !== 1)
|
|
2681
|
+
return { committed: false, error: 'A bundle declares exactly one workflow' };
|
|
2682
|
+
const started = await this.beginTurn();
|
|
2683
|
+
if (!started.ok)
|
|
2684
|
+
return { committed: false, error: started.error };
|
|
2685
|
+
const defined = await this.define('workflow(_)', renderWorkflowDeclaration(shell.workflows[0]));
|
|
2686
|
+
if (!defined.ok) {
|
|
2687
|
+
await this.rollbackTurn();
|
|
2688
|
+
return { committed: false, error: defined.error };
|
|
2689
|
+
}
|
|
2690
|
+
return this.endTurn();
|
|
2691
|
+
}
|
|
2185
2692
|
const errors = validateWorkShell(shell, this.harnessView().predicates);
|
|
2186
2693
|
if (errors.length)
|
|
2187
2694
|
return { committed: false, error: errors.join('; ') };
|
|
@@ -2224,6 +2731,9 @@ export class DMLSession {
|
|
|
2224
2731
|
// `repl_rollback` abolishes the predicates *before* loading, so a syntax error
|
|
2225
2732
|
// would otherwise leave the session empty. Keep the previous text and put it
|
|
2226
2733
|
// back if the new source does not load.
|
|
2734
|
+
const owned = this.workflowSourceError(source);
|
|
2735
|
+
if (owned)
|
|
2736
|
+
return { committed: false, error: owned };
|
|
2227
2737
|
const previous = await this.harnessSource();
|
|
2228
2738
|
const before = this.predicateList();
|
|
2229
2739
|
const result = this.prologQuery(`deepclause_mi:repl_rollback('${this.sessionId}', ${quoteString(source)}, Result)`);
|
|
@@ -2246,6 +2756,14 @@ export class DMLSession {
|
|
|
2246
2756
|
this.lastTurnCommitted = true;
|
|
2247
2757
|
this.lastCommitVersion = version;
|
|
2248
2758
|
await this.persistSessionHarness(this.history?.currentVersion ?? 0);
|
|
2759
|
+
if (this.openOptions.onHarnessCommit) {
|
|
2760
|
+
try {
|
|
2761
|
+
await this.openOptions.onHarnessCommit(version);
|
|
2762
|
+
}
|
|
2763
|
+
catch (error) {
|
|
2764
|
+
return { committed: true, changed, error: `Version saved locally, but activation failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
2765
|
+
}
|
|
2766
|
+
}
|
|
2249
2767
|
const warnings = [
|
|
2250
2768
|
...(await this.probeNondeterminism(after)),
|
|
2251
2769
|
...this.probeToolContracts(),
|
|
@@ -2311,8 +2829,9 @@ export class DMLSession {
|
|
|
2311
2829
|
/**
|
|
2312
2830
|
* Probe changed predicates for accidental nondeterminism: a pure predicate
|
|
2313
2831
|
* that yields more than `threshold` solutions on fresh variables is very likely
|
|
2314
|
-
* missing an `once/1`/`!` and would flood an `execute`.
|
|
2315
|
-
*
|
|
2832
|
+
* missing an `once/1`/`!` and would flood an `execute`. The Prolog gate follows
|
|
2833
|
+
* local delegates and admits only a conservative pure subset; fact tables,
|
|
2834
|
+
* exception handlers, process/runtime calls and unknown capabilities are skipped.
|
|
2316
2835
|
*/
|
|
2317
2836
|
async probeNondeterminism(indicators) {
|
|
2318
2837
|
const reserved = new Set(['doc', 'module_doc', 'tool', 'schema', 'script_file']);
|
|
@@ -2334,7 +2853,7 @@ export class DMLSession {
|
|
|
2334
2853
|
}
|
|
2335
2854
|
else if (verdict === 'timeout') {
|
|
2336
2855
|
warnings.push(`${name}/${arity} did not settle within the inference limit when probed `
|
|
2337
|
-
+ '(possible unbounded search
|
|
2856
|
+
+ '(possible unbounded pure search).');
|
|
2338
2857
|
}
|
|
2339
2858
|
}
|
|
2340
2859
|
catch {
|
|
@@ -2356,6 +2875,7 @@ export class DMLSession {
|
|
|
2356
2875
|
return;
|
|
2357
2876
|
this.prologQuery(`deepclause_mi:repl_snapshot_restore('${this.sessionId}')`);
|
|
2358
2877
|
this.transactionBefore = null;
|
|
2878
|
+
this.transactionScriptsBefore = null;
|
|
2359
2879
|
this.lastTurnCommitted = false;
|
|
2360
2880
|
this.lastCommitVersion = undefined;
|
|
2361
2881
|
this.transactionDirty = false;
|
|
@@ -2408,6 +2928,9 @@ export class DMLSession {
|
|
|
2408
2928
|
return { ok: false, error: String(result) };
|
|
2409
2929
|
}
|
|
2410
2930
|
async define(head, clauses) {
|
|
2931
|
+
const owned = this.workflowSourceError(clauses, false);
|
|
2932
|
+
if (owned)
|
|
2933
|
+
return { ok: false, error: owned };
|
|
2411
2934
|
const closed = this.requireTransaction();
|
|
2412
2935
|
if (closed)
|
|
2413
2936
|
return closed;
|
|
@@ -2415,6 +2938,9 @@ export class DMLSession {
|
|
|
2415
2938
|
return this.editResult(plainValue(result?.Result));
|
|
2416
2939
|
}
|
|
2417
2940
|
async assertClause(clause) {
|
|
2941
|
+
const owned = this.workflowSourceError(clause, false);
|
|
2942
|
+
if (owned)
|
|
2943
|
+
return { ok: false, error: owned };
|
|
2418
2944
|
const closed = this.requireTransaction();
|
|
2419
2945
|
if (closed)
|
|
2420
2946
|
return closed;
|
|
@@ -2422,6 +2948,9 @@ export class DMLSession {
|
|
|
2422
2948
|
return this.editResult(plainValue(result?.Result));
|
|
2423
2949
|
}
|
|
2424
2950
|
async assertMany(clauses) {
|
|
2951
|
+
const owned = this.workflowSourceError(clauses, false);
|
|
2952
|
+
if (owned)
|
|
2953
|
+
return { ok: false, error: owned };
|
|
2425
2954
|
const closed = this.requireTransaction();
|
|
2426
2955
|
if (closed)
|
|
2427
2956
|
return closed;
|
|
@@ -2566,6 +3095,11 @@ export class DMLSession {
|
|
|
2566
3095
|
const key = referenceTopic(topic);
|
|
2567
3096
|
if (key === 'index')
|
|
2568
3097
|
return referenceIndex();
|
|
3098
|
+
if (key === 'workflows') {
|
|
3099
|
+
const entries = this.hostWorkflowCatalog?.entries ?? [];
|
|
3100
|
+
return renderReference(key, '# Reusable workflows\nRead-only catalog for this turn. DML run_workflow(Name, Inputs, Result) requires a host grant; when granted, draft tests call real workflows with real effects.\n\n'
|
|
3101
|
+
+ (entries.map(entry => `## ${entry.name}\n${entry.description ?? ''}\n\n\`\`\`json\n${JSON.stringify(entry, null, 2)}\n\`\`\``).join('\n\n') || 'No host workflows supplied.'), options);
|
|
3102
|
+
}
|
|
2569
3103
|
if (key === 'tools') {
|
|
2570
3104
|
const catalog = this.hostToolsCatalog ?? '(no host capability tools registered)';
|
|
2571
3105
|
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\`\`\``);
|
|
@@ -2594,9 +3128,11 @@ export class DMLSession {
|
|
|
2594
3128
|
async executeForeground(goal, limit, signal, onEvent, bindingMode = 'full', _timeoutMs) {
|
|
2595
3129
|
if (this.purpose === 'work' && this.pendingSuspensionValue)
|
|
2596
3130
|
return { bindings: [], solutions: [], output: '', elapsedMs: 0, outcome: 'failed', error: 'Resume the pending continuation or open a new Work conversation before starting another operation.' };
|
|
3131
|
+
if (this.purpose === 'work' && this.openOptions.workflowOnly && this.harnessModuleSources().some(module => module.name === 'workflow_support'))
|
|
3132
|
+
goal = `(bp_workflow_policy,(${goal}))`;
|
|
2597
3133
|
const existing = new Set(this.forms.list().map(form => form.formId));
|
|
2598
3134
|
try {
|
|
2599
|
-
return await this.executeGoal(goal, limit ?? 5, onEvent, signal, bindingMode, undefined, true);
|
|
3135
|
+
return await this.executeGoal(goal, limit ?? 5, onEvent, signal, bindingMode, undefined, true, this.activeWorkHook !== undefined);
|
|
2600
3136
|
}
|
|
2601
3137
|
finally {
|
|
2602
3138
|
for (const form of this.forms.list())
|
|
@@ -2608,6 +3144,9 @@ export class DMLSession {
|
|
|
2608
3144
|
}
|
|
2609
3145
|
}
|
|
2610
3146
|
}
|
|
3147
|
+
async validateWorkInputs(entry, inputs) {
|
|
3148
|
+
await this.openOptions.validateWorkInputs?.(entry, inputs);
|
|
3149
|
+
}
|
|
2611
3150
|
/** Deterministic named invocation. This never asks a model which goal to run. */
|
|
2612
3151
|
async *runWorkflow(name, inputs = {}, options = {}) {
|
|
2613
3152
|
yield* this.exclusive('workflow', () => this.runWorkflowInner(name, inputs, options), options.signal);
|
|
@@ -2647,7 +3186,7 @@ export class DMLSession {
|
|
|
2647
3186
|
const queue = [];
|
|
2648
3187
|
let wake;
|
|
2649
3188
|
let result;
|
|
2650
|
-
const operation = executeWorkEntry(entry, inputs, goal => this.executeForeground(goal, 1, signal, event => { queue.push(event); wake?.(); wake = undefined; }, 'full'), signal)
|
|
3189
|
+
const operation = executeWorkEntry(entry, inputs, goal => this.executeForeground(goal, 1, signal, event => { queue.push(event); wake?.(); wake = undefined; }, 'full'), signal, values => this.validateWorkInputs(entry, values))
|
|
2651
3190
|
.then(value => { result = value; wake?.(); wake = undefined; });
|
|
2652
3191
|
try {
|
|
2653
3192
|
while (!result || queue.length) {
|
|
@@ -2672,8 +3211,10 @@ export class DMLSession {
|
|
|
2672
3211
|
this.harnessAgent.addContext(context);
|
|
2673
3212
|
this.agentMessages = this.harnessAgent.getMessages();
|
|
2674
3213
|
}
|
|
2675
|
-
else
|
|
3214
|
+
else {
|
|
2676
3215
|
this.agentMessages.push({ role: 'user', content: context });
|
|
3216
|
+
this.workHooks?.messages.push({ role: 'user', content: context, contextOrigin: 'hook' });
|
|
3217
|
+
}
|
|
2677
3218
|
await this.finishHistoryTurn({ turn, mode: 'goal', request,
|
|
2678
3219
|
workflow: { name, inputs, status: final.status, outputs: final.outputs },
|
|
2679
3220
|
outcome: final.status === 'succeeded' ? 'query' : final.status === 'cancelled' ? 'aborted' : final.status,
|
|
@@ -2715,7 +3256,7 @@ export class DMLSession {
|
|
|
2715
3256
|
async *prompt(request, options = {}) {
|
|
2716
3257
|
yield* this.agentPrompt(request, options);
|
|
2717
3258
|
}
|
|
2718
|
-
async dispose() {
|
|
3259
|
+
async dispose(persist = true) {
|
|
2719
3260
|
if (this.disposed)
|
|
2720
3261
|
return;
|
|
2721
3262
|
this.disposed = true;
|
|
@@ -2731,7 +3272,7 @@ export class DMLSession {
|
|
|
2731
3272
|
// teardown is best-effort
|
|
2732
3273
|
}
|
|
2733
3274
|
}
|
|
2734
|
-
if (this.history) {
|
|
3275
|
+
if (this.history && persist) {
|
|
2735
3276
|
try {
|
|
2736
3277
|
await this.persistSessionHarness(this.history.currentVersion);
|
|
2737
3278
|
this.assertHistoryFacts(await this.history.endSession('dispose'));
|
|
@@ -2740,6 +3281,7 @@ export class DMLSession {
|
|
|
2740
3281
|
this.warnHistory(error);
|
|
2741
3282
|
}
|
|
2742
3283
|
}
|
|
3284
|
+
await this.agentInbox?.close();
|
|
2743
3285
|
this.prologQuery(`deepclause_mi:destroy_session('${this.sessionId}')`);
|
|
2744
3286
|
this.runner.clearFrames();
|
|
2745
3287
|
await this.runner.dispose();
|
|
@@ -2757,7 +3299,11 @@ export class DMLSession {
|
|
|
2757
3299
|
onForm: this.formHandler,
|
|
2758
3300
|
// A turn that called suspend/1 stops here; the record is what --session
|
|
2759
3301
|
// resumes from (docs/DML_REPL_SUSPEND_RESUME.md).
|
|
2760
|
-
onSuspend: (payload) =>
|
|
3302
|
+
onSuspend: (payload) => {
|
|
3303
|
+
if (this.activeWorkHook)
|
|
3304
|
+
throw new Error('Agent hooks cannot suspend');
|
|
3305
|
+
return this.handleSuspend(payload);
|
|
3306
|
+
},
|
|
2761
3307
|
signal: options.signal,
|
|
2762
3308
|
onModelCall: () => this.reserveModelCall(),
|
|
2763
3309
|
// A run that is not itself a process resolves primitives through the
|
|
@@ -2946,6 +3492,13 @@ export class DMLSession {
|
|
|
2946
3492
|
* (interactive runs); autonomous runs abort. `0` means unlimited.
|
|
2947
3493
|
*/
|
|
2948
3494
|
async reserveModelCall() {
|
|
3495
|
+
// Autonomous turns have a hard sub-budget, even when human turns are unlimited.
|
|
3496
|
+
if (this.inboxController) {
|
|
3497
|
+
if (this.modelCallsThisTurn >= this.modelCallBudget)
|
|
3498
|
+
return false;
|
|
3499
|
+
this.modelCallsThisTurn += 1;
|
|
3500
|
+
return true;
|
|
3501
|
+
}
|
|
2949
3502
|
if (this.maxModelCalls <= 0) {
|
|
2950
3503
|
this.modelCallsThisTurn += 1;
|
|
2951
3504
|
return true;
|