Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat: route JEV through OpenRouter and preserve sessions

Rahman8a854f90e9a4
diff --git a/app/api/v1/agent-sessions/route.ts b/app/api/v1/agent-sessions/route.ts
index f291ab37..beaeaabd 100644
--- a/app/api/v1/agent-sessions/route.ts
+++ b/app/api/v1/agent-sessions/route.ts
@@ -14,6 +14,8 @@ import { pruneAgentSessionArchives } from "@/lib/agent/session-archive";
import { sessionWorkflowDraftDefinition } from "@/lib/agent/session-workflow-draft";
import { resolveHistoricalSessionArtifactForOwner } from "@/lib/agent/session-artifact-resolver";
import { createWorkflowGraph } from "@/lib/workflow/graph-store";
+import { optimizeSessionWithJev } from "@/lib/workflow/jev-session-optimizer";
+import { jevPreservationStatus, optimizeSessionPreservationBatch } from "@/lib/agent/session-jev-preservation";
import {
ownerSessionSummaries,
resolveAgentSessionOwnerRef,
@@ -63,6 +65,10 @@ export async function GET(req: NextRequest) {
return NextResponse.json({ error: missing ? "session_not_found" : "artifact_revision_unavailable" }, { status: missing ? 404 : 503, headers: { "Cache-Control": "private, no-store" } });
}
}
+ if (view === "jev-preservation") {
+ try { return NextResponse.json(await jevPreservationStatus(), { headers: { "Cache-Control": "private, no-store" } }); }
+ catch (cause) { return error(cause); }
+ }
if (view === "monitor" || view === "graph") {
try {
const id = req.nextUrl.searchParams.get("id");
@@ -111,6 +117,9 @@ export async function POST(req: NextRequest) {
cwd?: string;
parentSessionId?: string;
step_ref?: string;
+ jev?: unknown;
+ cursor?: number;
+ limit?: number;
};
try {
body = await req.json();
@@ -178,6 +187,17 @@ export async function POST(req: NextRequest) {
session: await renameAgentSession(principal, body.id, body.title),
});
}
+ if (body.action === "optimize-with-jev") {
+ const ref = String(body.ref || body.id || "").trim();
+ if (!ref) return NextResponse.json({ error: "session_reference_required" }, { status: 400 });
+ const source = await resolveAgentSessionOwnerRef(ref);
+ const view = await ownerSessionGraph(source.id, 120);
+ if (!view) return NextResponse.json({ error: "session_not_found" }, { status: 404 });
+ return NextResponse.json({ optimization: await optimizeSessionWithJev(view, body.jev) }, { headers: { "Cache-Control": "private, no-store" } });
+ }
+ if (body.action === "optimize-all-with-jev") {
+ return NextResponse.json(await optimizeSessionPreservationBatch({ cursor: body.cursor, limit: body.limit }), { headers: { "Cache-Control": "private, no-store" } });
+ }
if (body.action === "save-workflow-draft") {
const ref = String(body.ref || body.id || "").trim();
if (!ref) return NextResponse.json({ error: "session_reference_required" }, { status: 400 });
diff --git a/app/api/v1/workflows/route.ts b/app/api/v1/workflows/route.ts
index cec23c46..536d7850 100644
--- a/app/api/v1/workflows/route.ts
+++ b/app/api/v1/workflows/route.ts
@@ -25,7 +25,7 @@ import { listAutomationScripts, readAutomationScript } from "@/lib/orchestration
import { listLearnedRecipes, recipeMaturity } from "@/lib/workflow";
import { createWorkflowDataTable, deleteWorkflowDataTable, deleteWorkflowDataTableRow, getWorkflowDataTable, listWorkflowDataTables, upsertWorkflowDataTableRow } from "@/lib/workflow/data-table-store";
import { optimizeWorkflowGraph } from "@/lib/workflow/graph-optimizer";
-import { createJevWorkflowOptimizerEvaluator } from "@/lib/workflow/jev-optimizer";
+import { createResolvedJevWorkflowOptimizerEvaluator } from "@/lib/workflow/jev-evaluator";
import { resolveJevIntegrationConfig } from "@/lib/workflow/jev-integration";
export const runtime="nodejs";export const dynamic="force-dynamic";const headers={"Cache-Control":"no-store, private"};
const fail=(error:unknown,status=400)=>NextResponse.json({error:error instanceof Error?error.message.slice(0,500):String(error).slice(0,500)||"workflow request failed"},{status,headers});
@@ -69,7 +69,7 @@ export async function POST(req:NextRequest){const session=await auth("operator")
const mode=body.mode==="jev"?"jev" as const:"deterministic" as const;let evaluator;
if(mode==="jev"){
if(!roleAtLeast(session.context.role,"owner"))return fail("owner_required",403);
- evaluator=createJevWorkflowOptimizerEvaluator(await resolveJevIntegrationConfig(body.jev));
+ evaluator=createResolvedJevWorkflowOptimizerEvaluator(await resolveJevIntegrationConfig(body.jev));
}
const optimized=await optimizeWorkflowGraph(graph,{mode,threshold:Number(body.threshold)||undefined,applyReview:body.apply_review===true,evaluator,resolveTool:name=>TOOLS_BY_NAME.get(name)});
if(action==="optimize_preview")return NextResponse.json({optimization:optimized.preview},{headers});
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 7781912e..03d95d64 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- route JEV through OpenRouter and preserve sessions
- `integrations` clarify DOKU credential fields
## 2026-09-25
diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md
index 210448d1..57b23b51 100644
--- a/docs/INTEGRATIONS.md
+++ b/docs/INTEGRATIONS.md
@@ -36,7 +36,7 @@ their duration; concurrent work cannot mix two profiles partway through one oper
### Integration Variables
Integration Variables are global, metadata-only aliases to an existing named connection,
-for example JEV → credential-user / mcp / jev. A variable stores only provider, user and
+for example JEV → credential-user / mcp / jev. This JEV alias is now a legacy/diagnostic MCP override; native Jev optimization uses the OpenRouter key from the shared AI Provider store. A variable stores only provider, user and
connection references; it never copies endpoint, API key, bearer token, OAuth bundle or
connection field values. Names use uppercase A-Z, 0-9 and underscore. integration_manage
owns variable.set / variable.delete, while integration_query with view=variables returns
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index cfb29c30..761c4a60 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,7 @@
+## 2026-09-26 — JEV session preservation + OpenRouter SSOT
+
+JEV now uses `~typesafe/jev-latest` through OpenRouter’s Decisions API by default. Its credential is read from the same `hostCredentialStore()` used by Settings → AI and Integrations → AI Providers, so MSO no longer needs a separate TypeSafe/JEV token for the normal path. Existing named MCP JEV connections and the `JEV` Integration Variable remain explicit diagnostic compatibility overrides. Workflow Sessions expose **Use JEV**, can copy a bounded `mso.jev-session-optimization.v1` packet for another LLM, and expose **Optimize all before cleanup**. Batch preservation covers both live durable sessions and archived compacted session snapshots. Old archive deletion is hard-gated by an exact SHA-256-bound JEV preservation receipt; unpreserved archives and their action indexes are retained instead of silently aging out.
+
## 2026-09-26 — Make DOKU credential fields self-explanatory
The native DOKU setup form now puts the official source beside each credential
diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.md
index 3da3c159..8d6a6ac4 100644
--- a/docs/WORKFLOW-GRAPH.md
+++ b/docs/WORKFLOW-GRAPH.md
@@ -231,12 +231,12 @@ Two candidate classes exist in v1:
Decision modes:
- `deterministic` is always available and uses local policy scores.
-- `jev` sends only the compact workflow summary plus host-generated candidate descriptions to a named generic MCP Integration. The graph arguments themselves, credentials and capability authority stay in MSO. Jev can score the candidates; it cannot invent a new tool call, alter arguments, authorize an action, or execute anything. The preview also computes a deterministic shadow baseline and reports agreement/disagreement so rollout can be measured before relying more heavily on Jev.
+- `jev` sends only the compact workflow summary plus host-generated candidate descriptions to TypeSafe Jev through OpenRouter’s Decisions API by default. The OpenRouter key comes from the exact Settings → AI / Integrations → AI Providers credential store. Graph arguments, credentials and capability authority stay in MSO. Jev can score host-generated candidates; it cannot invent a new tool call, alter arguments, authorize an action, or execute anything. The preview also computes a deterministic shadow baseline and reports agreement/disagreement.
- If the Jev call fails or returns no usable probability, the preview records `provider: fallback` and uses the deterministic scores.
-For Jev, create a normal **Integrations → Project MCP** named connection to the reviewed Jev MCP endpoint, keep the bearer key in the private Integrations form, and optionally pin allowedTools to the exact decision tool (for example jev_decide). Point the metadata-only **Integration Variable JEV** at that named connection. Jev optimization resolves JEV by default; an explicit user/connection override remains available for diagnostics or alternate evaluators. Neither path stores the endpoint/token in the Workflow Graph.
+For Jev, connect **OpenRouter** once in **Settings → AI** or **Integrations → AI Providers**. Both surfaces use the same server-side credential store. MSO calls `~typesafe/jev-latest` through OpenRouter’s Decisions API and never creates a second Jev/TypeSafe key store. Existing `JEV` Integration Variables and named MCP Jev connections remain supported only as explicit diagnostic/legacy overrides; they are no longer the default path. Neither path stores credentials in a Workflow Graph.
-The native Workflows UI exposes **Optimize** and a Flow Optimizer detail panel. Dirty graph edits are saved before opening the optimizer so preview/clone always operate on the revision the user can see. Jev mode now shows JEV as the normal path, with explicit connection fields moved under an optional override.
+The native Workflows UI exposes **Optimize** and a Flow Optimizer detail panel. Dirty graph edits are saved before opening the optimizer so preview/clone always operate on the revision the user can see. Jev mode shows OpenRouter Jev as the normal path, with explicit named-MCP fields retained only under a legacy/diagnostic override.
## Automatic learning
diff --git a/frontend/slices/os-settings/components/ai-section.tsx b/frontend/slices/os-settings/components/ai-section.tsx
index e556b1d1..2db02252 100644
--- a/frontend/slices/os-settings/components/ai-section.tsx
+++ b/frontend/slices/os-settings/components/ai-section.tsx
@@ -158,6 +158,7 @@ export function AiSection() {
<>
Provider/model availability is discovered dynamically while runtime endpoints remain pinned by MSO. Keys are stored server-side and never shown again.
Free means the live model catalog explicitly reports $0 input and $0 output token cost; an account/API key and provider rate limits may still apply.
+ MSO’s JEV decision kernel reuses the OpenRouter key from this exact store with ~typesafe/jev-latest; it never creates a separate JEV credential.
</>
}
>
diff --git a/frontend/slices/workflows/components/workflow-optimizer-panel.tsx b/frontend/slices/workflows/components/workflow-optimizer-panel.tsx
index d8e62f90..034dcc01 100644
--- a/frontend/slices/workflows/components/workflow-optimizer-panel.tsx
+++ b/frontend/slices/workflows/components/workflow-optimizer-panel.tsx
@@ -28,7 +28,7 @@ export function WorkflowOptimizerPanel({ graph, onCloned }: {
...(mode === "jev" ? {
jev: user.trim() && connection.trim()
? { user: user.trim(), connection: connection.trim() }
- : { variable: "JEV" },
+ : undefined,
} : {}),
});
@@ -69,14 +69,14 @@ export function WorkflowOptimizerPanel({ graph, onCloned }: {
</label>
{mode === "jev" ? <div className="grid gap-2">
<div className="rounded-md border border-dashed p-2 text-[11px] leading-relaxed text-muted-foreground">
- Uses Integrations variable <b className="text-foreground">JEV</b> by default. The variable only points to a named MCP connection; endpoint and token remain private in Integrations.
+ Uses <b className="text-foreground">OpenRouter → ~typesafe/jev-latest</b> by default. The OpenRouter key is the same server-side credential managed by Settings → AI and Integrations → AI Providers.
</div>
<details className="rounded-md border p-2">
- <summary className="cursor-pointer text-xs font-medium">Override JEV connection</summary>
+ <summary className="cursor-pointer text-xs font-medium">Legacy / diagnostic MCP override</summary>
<div className="mt-2 grid gap-2">
<Input className={inputClass} value={user} onChange={(event) => setUser(event.target.value)} placeholder="Credential user ID"/>
<Input className={inputClass} value={connection} onChange={(event) => setConnection(event.target.value)} placeholder="MCP connection ID"/>
- {hasUser !== hasConnection ? <p className="text-[11px] text-destructive">Fill both override fields, or leave both empty to use JEV.</p> : null}
+ {hasUser !== hasConnection ? <p className="text-[11px] text-destructive">Fill both override fields, or leave both empty to use OpenRouter JEV.</p> : null}
</div>
</details>
</div> : null}
diff --git a/frontend/slices/workflows/components/workflow-session-details.tsx b/frontend/slices/workflows/components/workflow-session-details.tsx
index 93d8bd11..d63c6558 100644
--- a/frontend/slices/workflows/components/workflow-session-details.tsx
+++ b/frontend/slices/workflows/components/workflow-session-details.tsx
@@ -7,7 +7,7 @@ import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import type { SessionFlowAction, SessionFlowStep, SessionGraphView } from "@/lib/contracts/session-monitor";
import type { WorkflowGraphNode } from "@/lib/contracts/workflow-graph";
-import { getSessionArtifactHistory, type SessionArtifactHistoryResponse, type WorkflowLearningRecipeSummary } from "../lib/api";
+import { getSessionArtifactHistory, optimizeSessionWithJev, type JevSessionOptimization, type SessionArtifactHistoryResponse, type WorkflowLearningRecipeSummary } from "../lib/api";
function value(config: Record<string, unknown>, key: string): string | undefined {
const raw = config[key]; return typeof raw === "string" && raw ? raw : undefined;
@@ -98,11 +98,18 @@ export function WorkflowSessionDetails({ view, node, onOpenTerminal, onOpenCode,
const ref = node ? value(node.config, "ref") : undefined;
const step: SessionFlowStep | undefined = ref ? view.steps.find((item) => item.ref === ref) : undefined;
const linked = learning.filter((recipe) => recipe.sourceSessions.some((source) => source.label === view.session.label));
+ const [jev, setJev] = useState<JevSessionOptimization | null>(null);
+ const [jevBusy, setJevBusy] = useState(false);
+ const [jevError, setJevError] = useState("");
+ const useJev = async () => { setJevBusy(true); setJevError(""); try { setJev(await optimizeSessionWithJev(view.session.id)); } catch (cause) { setJevError(cause instanceof Error ? cause.message : "JEV unavailable"); } finally { setJevBusy(false); } };
return <div className="flex h-full min-h-0 flex-col bg-card/20">
<div className="border-b p-3">
<div className="break-words text-sm font-semibold">{view.session.label}</div>
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-[10px] uppercase text-muted-foreground"><span>{view.session.source}</span><span>·</span><span>{view.session.status}</span><Badge variant="outline" className="h-5 px-1.5 text-[9px] normal-case">{view.steps.length} semantic steps</Badge></div>
<p className="mt-2 text-xs text-muted-foreground">Canvas shows intent-level steps. Click a step to inspect its grouped actions, commands, code, artifacts, and raw execution receipt.</p>
+ <div className="mt-2 flex flex-wrap items-center gap-2"><Button data-slot="use-jev-session" type="button" size="sm" variant="outline" className="h-7 text-[10px]" disabled={jevBusy} onClick={() => void useJev()}><BrainCircuit className="size-3.5"/>{jevBusy ? "Calculating…" : "Use JEV"}</Button><span className="text-[10px] text-muted-foreground">Review-first optimization packet for this session; no tools are executed.</span></div>
+ {jevError ? <p className="mt-2 text-[10px] text-destructive">{jevError}</p> : null}
+ {jev ? <div data-slot="jev-session-output" className="mt-2 rounded-lg border bg-muted/15 p-2.5 text-[10px]"><div className="flex items-center gap-2"><Badge variant="outline" className="h-5 text-[9px]">{jev.provider === "jev" ? "JEV" : "fallback"}</Badge><span>{jev.recommendations.length} optimization signals</span><Button type="button" size="sm" variant="ghost" className="ml-auto h-6 text-[9px]" onClick={() => void navigator.clipboard?.writeText(JSON.stringify(jev.llmContext,null,2))}><Copy className="size-3"/>Copy for LLM</Button></div>{jev.fallbackReason ? <p className="mt-1 text-muted-foreground">{jev.fallbackReason}</p> : null}<div className="mt-2 space-y-1">{jev.recommendations.slice(0,6).map(item=><div key={item.id} className="rounded border bg-background/40 p-2"><div className="font-medium">{Math.round(item.probability*100)}% · {item.title}</div><p className="mt-0.5 text-muted-foreground">{item.description}</p><div className="mt-1 font-mono text-[9px] text-muted-foreground">{item.actionRefs.slice(0,8).join(" · ")}</div></div>)}</div></div> : null}
{view.omittedEvents ? <p className="mt-2 text-[10px] text-muted-foreground">Projection uses the latest {view.shownEvents} of {view.totalEvents} events to stay fast. Raw session history remains the source of truth.</p> : null}
</div>
<ScrollArea className="min-h-0 flex-1"><div className="space-y-3 p-3">
diff --git a/frontend/slices/workflows/components/workflow-session-library.tsx b/frontend/slices/workflows/components/workflow-session-library.tsx
index 51814e50..3529fd8d 100644
--- a/frontend/slices/workflows/components/workflow-session-library.tsx
+++ b/frontend/slices/workflows/components/workflow-session-library.tsx
@@ -1,21 +1,24 @@
"use client";
import { useEffect, useState } from "react";
-import { Activity, ChevronLeft, ChevronRight, RefreshCw, Search } from "lucide-react";
+import { Activity, BrainCircuit, ChevronLeft, ChevronRight, RefreshCw, Search } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import type { SessionPage } from "@/lib/contracts/session-monitor";
-import { listWorkflowSessions } from "../lib/api";
+import { getJevPreservationStatus, listWorkflowSessions, optimizeAllSessionsWithJev, type JevPreservationStatus } from "../lib/api";
export function WorkflowSessionLibrary({ activeId, onSelect }: { activeId?: string; onSelect: (id: string) => void }) {
const [search, setSearch] = useState(""), [query, setQuery] = useState(""), [page, setPage] = useState(1);
const [data, setData] = useState<SessionPage | null>(null), [error, setError] = useState(""), [nonce, setNonce] = useState(0);
+ const [preservation, setPreservation] = useState<JevPreservationStatus | null>(null), [preserving, setPreserving] = useState(false);
useEffect(() => {
let alive = true;
void listWorkflowSessions(page, query).then((value) => { if (alive) { setError(""); setData(value); } }).catch((cause) => { if (alive) setError(cause instanceof Error ? cause.message : "Sessions unavailable"); });
return () => { alive = false; };
}, [page, query, nonce]);
+ useEffect(() => { let alive=true; void getJevPreservationStatus().then((value)=>{if(alive)setPreservation(value);}).catch(()=>undefined); return()=>{alive=false;}; }, [nonce]);
+ const optimizeAll = async () => { setPreserving(true); setError(""); try { const result=await optimizeAllSessionsWithJev(); setPreservation(await getJevPreservationStatus()); setNonce((value)=>value+1); if(result.failed) setError(`${result.failed} session(s) still require an OpenRouter JEV decision. Connect OpenRouter in Settings → AI or Integrations → AI Providers, then run this again.`); } catch(cause) { setError(cause instanceof Error?cause.message:"JEV preservation failed"); } finally { setPreserving(false); } };
return <div className="flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-card/20">
<div className="shrink-0 space-y-2 border-b p-3">
<form className="flex min-w-0 gap-1" onSubmit={(event) => { event.preventDefault(); setPage(1); setQuery(search.trim()); }}>
@@ -24,6 +27,8 @@ export function WorkflowSessionLibrary({ activeId, onSelect }: { activeId?: stri
<Button type="button" variant="ghost" size="icon" className="size-8 shrink-0" aria-label="Refresh sessions" onClick={() => setNonce((value) => value + 1)}><RefreshCw className="size-3.5"/></Button>
</form>
<p className="text-[10px] leading-4 text-muted-foreground">Readable execution flows. Session labels use agent-context; internal IDs stay hidden.</p>
+ <Button type="button" variant="outline" size="sm" className="h-8 w-full justify-start text-[10px]" disabled={preserving || preservation?.pending === 0} onClick={() => void optimizeAll()}><BrainCircuit className="size-3.5"/>{preserving ? "Optimizing sessions with JEV…" : "Optimize all before cleanup"}</Button>
+ {preservation ? <p className="text-[10px] leading-4 text-muted-foreground">JEV {preservation.preservedLive + preservation.preservedArchives}/{preservation.liveSessions + preservation.archives} preserved · {preservation.model}{preservation.openrouterConnected ? " · OpenRouter ready" : " · connect OpenRouter in Settings → AI or Integrations → AI Providers"}</p> : null}
</div>
<ScrollArea className="min-h-0 min-w-0 flex-1"><div className="space-y-1.5 p-2.5">
{error ? <p className="p-2 text-xs text-destructive">{error}</p> : null}
diff --git a/frontend/slices/workflows/lib/api.ts b/frontend/slices/workflows/lib/api.ts
index bf65f074..696a822c 100644
--- a/frontend/slices/workflows/lib/api.ts
+++ b/frontend/slices/workflows/lib/api.ts
@@ -70,6 +70,13 @@ export type WorkflowLearningRecipeSummary = {
sourceSessions:Array<{label:string;actionRef:string;eventRef:string;artifactRefs:string[]}>; forge:{eligible:boolean;promotion:"explicit"};
};
export async function listWorkflowLearning(force=false){const load=async()=> (await json<{recipes:WorkflowLearningRecipeSummary[]}>("/api/v1/workflows?learning=1")).recipes;return force?load():cachedWorkflowResource("learning",10000,load);}
+export type JevSessionOptimization={provider:"jev"|"fallback";source:{sessionLabel:string;observedAt:string;shownEvents:number;omittedEvents:number};recommendations:Array<{id:string;title:string;description:string;probability:number;actionRefs:string[]}>;llmContext:{kind:"mso.jev-session-optimization.v1";instruction:string;facts:string[];recommendations:Array<{id:string;probability:number;actionRefs:string[];guidance:string}>};fallbackReason?:string};
+export async function optimizeSessionWithJev(id:string){return(await json<{optimization:JevSessionOptimization}>("/api/v1/agent-sessions",{method:"POST",body:JSON.stringify({action:"optimize-with-jev",id})})).optimization;}
+export type JevPreservationStatus={model:string;credentialSource:"settings-ai/openrouter";openrouterConnected:boolean;liveSessions:number;archives:number;preservedLive:number;preservedArchives:number;pending:number};
+export type JevPreservationBatch={total:number;cursor:number;nextCursor?:number;processed:number;preserved:number;skipped:number;failed:number;errors:string[]};
+export async function getJevPreservationStatus(){return json<JevPreservationStatus>("/api/v1/agent-sessions?view=jev-preservation");}
+export async function optimizeAllSessionsWithJev(){let cursor:number|undefined=0,total=0,preserved=0,skipped=0,failed=0;const errors:string[]=[];do{const batch:JevPreservationBatch=await json<JevPreservationBatch>("/api/v1/agent-sessions",{method:"POST",body:JSON.stringify({action:"optimize-all-with-jev",cursor,limit:100})});total=batch.total;preserved+=batch.preserved;skipped+=batch.skipped;failed+=batch.failed;errors.push(...batch.errors.slice(0,4));cursor=batch.nextCursor;}while(cursor!==undefined);return{total,preserved,skipped,failed,errors};}
+
export async function saveSessionWorkflowDraft(id:string,stepRef?:string){
const next=(await json<{graph:WorkflowGraph}>("/api/v1/agent-sessions",{method:"POST",body:JSON.stringify({action:"save-workflow-draft",id,...(stepRef?{step_ref:stepRef}:{})})})).graph;
invalidateWorkflowResources("graphs"); seedWorkflowResource(`graph:${next.id}`,next,8000); return next;
diff --git a/lib/agent/session-archive.ts b/lib/agent/session-archive.ts
index 33a0197c..f2553a89 100644
--- a/lib/agent/session-archive.ts
+++ b/lib/agent/session-archive.ts
@@ -1,13 +1,14 @@
-import { randomUUID } from "node:crypto";
+import { createHash, randomUUID } from "node:crypto";
import { constants as fsConstants, promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
-import { gzip } from "node:zlib";
+import { gunzip, gzip } from "node:zlib";
import type { AgentSession } from "./session-types";
import { redactUnknown } from "@/lib/security/redact-text";
const gzipAsync = promisify(gzip);
+const gunzipAsync = promisify(gunzip);
const ARCHIVE_FILE = /^\d{8}_\d{6}_[a-f0-9]{8}__\d{8}T\d{6}Z__[a-z0-9-]+\.json\.gz$/;
function expandHome(value: string): string {
@@ -18,6 +19,10 @@ export function agentSessionArchiveRoot(): string {
return path.resolve(expandHome(process.env.OS_AGENT_SESSION_ARCHIVE_DIR || path.join(os.homedir(), ".mso", "agent-session-archive")));
}
+export function agentSessionPreservationRoot(): string {
+ return path.resolve(expandHome(process.env.OS_AGENT_SESSION_PRESERVATION_DIR || path.join(os.homedir(), ".mso", "agent-session-preservation")));
+}
+
export function archiveRetentionDays(): number {
const raw = Number(process.env.OS_AGENT_SESSION_ARCHIVE_DAYS);
return Number.isFinite(raw) ? Math.max(1, Math.min(365, Math.trunc(raw))) : 30;
@@ -38,6 +43,74 @@ async function secureRoot(): Promise<string> {
return root;
}
+async function securePreservationRoot(): Promise<string> {
+ const root = agentSessionPreservationRoot();
+ await fs.mkdir(root, { recursive: true, mode: 0o700 });
+ await fs.chmod(root, 0o700).catch(() => undefined);
+ return root;
+}
+
+function receiptName(archiveName: string): string {
+ if (!ARCHIVE_FILE.test(archiveName)) throw new Error("invalid agent session archive name");
+ return `${archiveName}.jev.json`;
+}
+
+async function archiveSha256(file: string): Promise<string> {
+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null;
+ try {
+ handle = await fs.open(file, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size <= 0 || stat.size > 32 * 1024 * 1024) throw new Error("agent session archive has an invalid file shape");
+ if ((stat.mode & 0o077) !== 0) throw new Error("agent session archive permissions are too broad; expected 0600");
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("agent session archive is not owned by the MSO user");
+ return createHash("sha256").update(await handle.readFile()).digest("hex");
+ } finally { await handle?.close().catch(() => undefined); }
+}
+
+export async function listAgentSessionArchives(): Promise<Array<{ name: string; bytes: number; mtimeMs: number }>> {
+ const root = await secureRoot();
+ const names = (await fs.readdir(root).catch(() => [] as string[])).filter((name) => ARCHIVE_FILE.test(name)).sort();
+ const out: Array<{ name: string; bytes: number; mtimeMs: number }> = [];
+ for (const name of names) {
+ try {
+ const stat = await fs.stat(path.join(root, name));
+ if (stat.isFile()) out.push({ name, bytes: stat.size, mtimeMs: stat.mtimeMs });
+ } catch { /* file raced with another maintenance pass */ }
+ }
+ return out;
+}
+
+export async function readAgentSessionArchive(name: string): Promise<{ schemaVersion: 1; archivedAt: string; reason: string; session: AgentSession; sha256: string }> {
+ if (!ARCHIVE_FILE.test(name)) throw new Error("invalid agent session archive name");
+ const file = path.join(await secureRoot(), name);
+ const sha256 = await archiveSha256(file);
+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null;
+ try {
+ handle = await fs.open(file, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
+ const raw = JSON.parse((await gunzipAsync(await handle.readFile())).toString("utf8")) as { schemaVersion?: unknown; archivedAt?: unknown; reason?: unknown; session?: AgentSession };
+ if (raw.schemaVersion !== 1 || typeof raw.archivedAt !== "string" || typeof raw.reason !== "string" || !raw.session?.id) throw new Error("agent session archive has an invalid payload");
+ return { schemaVersion: 1, archivedAt: raw.archivedAt, reason: raw.reason, session: raw.session, sha256 };
+ } finally { await handle?.close().catch(() => undefined); }
+}
+
+export async function writeAgentSessionArchiveJevReceipt(archiveName: string, archiveSha: string, receipt: Record<string, unknown>): Promise<void> {
+ if (!/^[a-f0-9]{64}$/.test(archiveSha)) throw new Error("invalid agent session archive digest");
+ const root = await securePreservationRoot(), file = path.join(root, receiptName(archiveName));
+ const body = JSON.stringify(redactUnknown({ ...receipt, schemaVersion: 1, kind: "mso.jev-archive-preservation.v1", archiveName, archiveSha256: archiveSha, preservedAt: new Date().toISOString(), provider: "jev" }), null, 2);
+ const tmp = `${file}.${randomUUID()}.tmp`;
+ await fs.writeFile(tmp, body, { encoding: "utf8", mode: 0o600, flag: "wx" });
+ await fs.chmod(tmp, 0o600); await fs.rename(tmp, file); await fs.chmod(file, 0o600);
+}
+
+export async function hasAgentSessionArchiveJevReceipt(archiveName: string, archiveFile?: string): Promise<boolean> {
+ try {
+ const file = archiveFile ?? path.join(await secureRoot(), archiveName), sha = await archiveSha256(file);
+ const receiptFile = path.join(await securePreservationRoot(), receiptName(archiveName));
+ const raw = JSON.parse(await fs.readFile(receiptFile, "utf8")) as Record<string, unknown>;
+ return raw.schemaVersion === 1 && raw.kind === "mso.jev-archive-preservation.v1" && raw.provider === "jev" && raw.archiveName === archiveName && raw.archiveSha256 === sha;
+ } catch { return false; }
+}
+
export async function archiveAgentSession(record: AgentSession, reason: string, now = new Date()): Promise<string> {
const root = await secureRoot();
const name = `${record.id}__${stamp(now)}__${safeReason(reason)}.json.gz`;
@@ -53,11 +126,11 @@ export async function archiveAgentSession(record: AgentSession, reason: string,
return target;
}
-export async function pruneAgentSessionArchives(now = Date.now()): Promise<{ removed: number; kept: number }> {
+export async function pruneAgentSessionArchives(now = Date.now()): Promise<{ removed: number; kept: number; blocked: number }> {
const root = await secureRoot();
const cutoff = now - archiveRetentionDays() * 86_400_000;
const names = await fs.readdir(root).catch(() => [] as string[]);
- let removed = 0, kept = 0;
+ let removed = 0, kept = 0, blocked = 0;
for (const name of names) {
if (!ARCHIVE_FILE.test(name)) continue;
const file = path.join(root, name);
@@ -69,11 +142,14 @@ export async function pruneAgentSessionArchives(now = Date.now()): Promise<{ rem
if (stat.mtimeMs >= cutoff) { kept++; continue; }
} catch { continue; }
finally { await handle?.close().catch(() => undefined); }
+ if (!(await hasAgentSessionArchiveJevReceipt(name, file))) { blocked++; kept++; continue; }
await fs.unlink(file).then(() => { removed++; }).catch(() => undefined);
}
- try {
- const { pruneSessionActionIndexes } = await import("./session-action-history");
- removed += await pruneSessionActionIndexes(now);
- } catch { /* action-index pruning is best-effort */ }
- return { removed, kept };
+ if (blocked === 0) {
+ try {
+ const { pruneSessionActionIndexes } = await import("./session-action-history");
+ removed += await pruneSessionActionIndexes(now);
+ } catch { /* action-index pruning is best-effort */ }
+ }
+ return { removed, kept, blocked };
}
diff --git a/lib/agent/session-files.ts b/lib/agent/session-files.ts
index 39b552eb..b205862a 100644
--- a/lib/agent/session-files.ts
+++ b/lib/agent/session-files.ts
@@ -161,14 +161,18 @@ export async function writeSessionFile(record: AgentSession): Promise<void> {
await fs.chmod(tmp, 0o600); await fs.rename(tmp, file); await fs.chmod(file, 0o600);
}
-export async function listSessionRecords(): Promise<AgentSession[]> {
+export async function listSessionIds(): Promise<string[]> {
let names: string[];
try { names = await fs.readdir(ROOT); } catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
throw error;
}
+ return names.filter(name => name.endsWith(".json") && SESSION_ID.test(name.slice(0, -5))).map(name => name.slice(0, -5)).sort();
+}
+
+export async function listSessionRecords(): Promise<AgentSession[]> {
const out: AgentSession[] = [];
- const ids = names.filter(name => name.endsWith(".json") && SESSION_ID.test(name.slice(0, -5))).map(name => name.slice(0, -5));
+ const ids = await listSessionIds();
// Bounded concurrency, complete enumeration: never silently drop later sessions.
for (let start = 0; start < ids.length; start += 32) {
const rows = await Promise.all(ids.slice(start, start + 32).map(id => readSessionFile(id).catch(() => null)));
diff --git a/lib/agent/session-jev-preservation.test.ts b/lib/agent/session-jev-preservation.test.ts
new file mode 100644
index 00000000..ae132372
--- /dev/null
+++ b/lib/agent/session-jev-preservation.test.ts
@@ -0,0 +1,24 @@
+import { afterAll, describe, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+const root=await fs.mkdtemp(path.join(os.tmpdir(),"mso-jev-preserve-"));
+process.env.OS_AGENT_SESSIONS_DIR=path.join(root,"sessions");
+process.env.OS_AGENT_MEMORY_DIR=path.join(root,"memory");
+process.env.OS_AGENT_SESSION_ARCHIVE_DIR=path.join(root,"archives");
+process.env.OS_AGENT_SESSION_PRESERVATION_DIR=path.join(root,"preservation");
+vi.mock("@/lib/config/store",()=>({hostCredentialStore:()=>({getKey:vi.fn(async()=>"openrouter-key")})}));
+vi.mock("@/lib/workflow/jev-session-optimizer",()=>({optimizeSessionWithJev:vi.fn(async(view:{session:{label:string}})=>({provider:"jev",source:{sessionLabel:view.session.label,observedAt:new Date().toISOString(),shownEvents:1,omittedEvents:0},recommendations:[],llmContext:{kind:"mso.jev-session-optimization.v1",instruction:"review",facts:["safe"],recommendations:[]}}))}));
+vi.resetModules();
+const store=await import("./session-store");
+const preservation=await import("./session-jev-preservation");
+afterAll(async()=>{for(const key of ["OS_AGENT_SESSIONS_DIR","OS_AGENT_MEMORY_DIR","OS_AGENT_SESSION_ARCHIVE_DIR","OS_AGENT_SESSION_PRESERVATION_DIR"])delete process.env[key];await fs.rm(root,{recursive:true,force:true});});
+describe("JEV session preservation",()=>{
+ it("preserves every live session once and reports zero pending",async()=>{
+ await store.createAgentSession("principal:jev","cli",{title:"Preserve me"});
+ const before=await preservation.jevPreservationStatus();expect(before).toMatchObject({openrouterConnected:true,liveSessions:1,preservedLive:0,pending:1});
+ const batch=await preservation.optimizeSessionPreservationBatch({limit:6});expect(batch).toMatchObject({total:1,processed:1,preserved:1,failed:0});
+ const after=await preservation.jevPreservationStatus();expect(after).toMatchObject({preservedLive:1,pending:0});
+ const replay=await preservation.optimizeSessionPreservationBatch({limit:6});expect(replay).toMatchObject({processed:1,preserved:0,skipped:1,failed:0});
+ });
+});
diff --git a/lib/agent/session-jev-preservation.ts b/lib/agent/session-jev-preservation.ts
new file mode 100644
index 00000000..b0bb64dd
--- /dev/null
+++ b/lib/agent/session-jev-preservation.ts
@@ -0,0 +1,53 @@
+import { createHash, randomUUID } from "node:crypto";
+import { promises as fs } from "node:fs";
+import path from "node:path";
+import { hostCredentialStore } from "@/lib/config/store";
+import type { SessionCard } from "@/lib/contracts/session-monitor";
+import { redactUnknown } from "@/lib/security/redact-text";
+import { DEFAULT_JEV_OPENROUTER_MODEL } from "@/lib/workflow/jev-openrouter";
+import { optimizeSessionWithJev } from "@/lib/workflow/jev-session-optimizer";
+import { agentSessionLabel } from "./session-name";
+import { sessionGraph } from "./session-graph";
+import { listSessionIds, listSessionRecords, normalizeSession, readSessionFile } from "./session-files";
+import type { AgentSession } from "./session-types";
+import { agentSessionPreservationRoot, hasAgentSessionArchiveJevReceipt, listAgentSessionArchives, readAgentSessionArchive, writeAgentSessionArchiveJevReceipt } from "./session-archive";
+
+export type JevPreservationStatus = { model: string; credentialSource: "settings-ai/openrouter"; openrouterConnected: boolean; liveSessions: number; archives: number; preservedLive: number; preservedArchives: number; pending: number };
+export type JevPreservationBatch = { total: number; cursor: number; nextCursor?: number; processed: number; preserved: number; skipped: number; failed: number; errors: string[] };
+
+type Source = { kind: "live"; key: string; sessionId: string } | { kind: "archive"; key: string; archiveName: string };
+
+function hash(value: string): string { return createHash("sha256").update(value).digest("hex"); }
+function liveReceiptName(record: AgentSession): string { return `live-${record.id}-${hash(record.updatedAt).slice(0, 16)}.jev.json`; }
+async function root(): Promise<string> { const dir=agentSessionPreservationRoot(); await fs.mkdir(dir,{recursive:true,mode:0o700}); await fs.chmod(dir,0o700).catch(()=>undefined); return dir; }
+async function hasLiveReceipt(record: AgentSession): Promise<boolean> { try { const raw=JSON.parse(await fs.readFile(path.join(await root(),liveReceiptName(record)),"utf8")) as Record<string,unknown>; return raw.schemaVersion===1&&raw.kind==="mso.jev-session-preservation.v1"&&raw.provider==="jev"&&raw.sessionId===record.id&&raw.updatedAt===record.updatedAt; } catch { return false; } }
+async function writeLiveReceipt(record: AgentSession, optimization: Awaited<ReturnType<typeof optimizeSessionWithJev>>): Promise<void> { const dir=await root(),file=path.join(dir,liveReceiptName(record)),tmp=`${file}.${randomUUID()}.tmp`; const body=JSON.stringify(redactUnknown({schemaVersion:1,kind:"mso.jev-session-preservation.v1",provider:"jev",model:DEFAULT_JEV_OPENROUTER_MODEL,sessionId:record.id,sessionLabel:agentSessionLabel(record.name,record.title,record.cwd),updatedAt:record.updatedAt,preservedAt:new Date().toISOString(),optimization:optimization.llmContext}),null,2); await fs.writeFile(tmp,body,{encoding:"utf8",mode:0o600,flag:"wx"}); await fs.chmod(tmp,0o600); await fs.rename(tmp,file); await fs.chmod(file,0o600); }
+
+function card(record: AgentSession): SessionCard { return { id:record.id,name:record.name,label:agentSessionLabel(record.name,record.title,record.cwd),title:record.title,source:record.source,status:"offline",receiverConnected:false,lastSeenAt:record.updatedAt,createdAt:record.createdAt,...(record.cwd?{cwd:record.cwd}:{}),eventCount:record.events.length,archiveCount:record.archiveCount,...(record.resumedFrom?{resumedFrom:record.resumedFrom}:{}),...(record.parentSessionId?{parentSessionId:record.parentSessionId}:{}) }; }
+async function sources(): Promise<Source[]> { const live=await listSessionIds(),archives=await listAgentSessionArchives(); return [...live.map(sessionId=>({kind:"live" as const,key:`live:${sessionId}`,sessionId})),...archives.map(row=>({kind:"archive" as const,key:`archive:${row.name}`,archiveName:row.name}))].sort((a,b)=>a.key.localeCompare(b.key)); }
+
+export async function jevPreservationStatus(): Promise<JevPreservationStatus> { const [key,live,archives]=await Promise.all([hostCredentialStore().getKey(undefined,"openrouter"),listSessionRecords(),listAgentSessionArchives()]); let preservedLive=0,preservedArchives=0; for(const row of live)if(await hasLiveReceipt(row))preservedLive++; for(const row of archives)if(await hasAgentSessionArchiveJevReceipt(row.name))preservedArchives++; return {model:DEFAULT_JEV_OPENROUTER_MODEL,credentialSource:"settings-ai/openrouter",openrouterConnected:Boolean(key),liveSessions:live.length,archives:archives.length,preservedLive,preservedArchives,pending:(live.length-preservedLive)+(archives.length-preservedArchives)}; }
+
+export async function optimizeSessionPreservationBatch(input: { cursor?: number; limit?: number } = {}): Promise<JevPreservationBatch> {
+ const all=await sources(),cursor=Math.max(0,Math.trunc(Number(input.cursor)||0)),limit=Math.max(1,Math.min(100,Math.trunc(Number(input.limit)||50))),slice=all.slice(cursor,cursor+limit); let processed=0,preserved=0,skipped=0,failed=0; const errors:string[]=[];
+ for(const source of slice){
+ processed++;
+ try{
+ let record: AgentSession;
+ if(source.kind==="live"){
+ const live=await readSessionFile(source.sessionId);
+ if(!live){skipped++;continue;}
+ record=live;
+ if(await hasLiveReceipt(record)){skipped++;continue;}
+ }else{
+ if(await hasAgentSessionArchiveJevReceipt(source.archiveName)){skipped++;continue;}
+ record=normalizeSession((await readAgentSessionArchive(source.archiveName)).session);
+ }
+ const view=sessionGraph(record,card(record),120),optimization=await optimizeSessionWithJev(view);
+ if(optimization.provider!=="jev")throw new Error(optimization.fallbackReason||"JEV decision unavailable");
+ if(source.kind==="live")await writeLiveReceipt(record,optimization);else{const archive=await readAgentSessionArchive(source.archiveName);await writeAgentSessionArchiveJevReceipt(source.archiveName,archive.sha256,{model:DEFAULT_JEV_OPENROUTER_MODEL,sessionId:record.id,sessionLabel:view.session.label,optimization:optimization.llmContext});}
+ preserved++;
+ }catch(cause){failed++;errors.push(`${source.key}: ${cause instanceof Error?cause.message:"JEV preservation failed"}`.slice(0,320));}
+ }
+ const next=cursor+slice.length;return{total:all.length,cursor,processed,preserved,skipped,failed,errors,...(next<all.length?{nextCursor:next}:{})};
+}
diff --git a/lib/agent/session-store.test.ts b/lib/agent/session-store.test.ts
index e7d28c74..162a760f 100644
--- a/lib/agent/session-store.test.ts
+++ b/lib/agent/session-store.test.ts
@@ -10,15 +10,17 @@ const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-agent-session-p0-"));
const sessions = path.join(root, "sessions");
const memory = path.join(root, "memory");
const archives = path.join(root, "archives");
+const preservation = path.join(root, "preservation");
process.env.OS_AGENT_SESSIONS_DIR = sessions;
process.env.OS_AGENT_MEMORY_DIR = memory;
process.env.OS_AGENT_SESSION_ARCHIVE_DIR = archives;
+process.env.OS_AGENT_SESSION_PRESERVATION_DIR = preservation;
process.env.OS_AGENT_SESSION_COMPACT_TOKENS = "10000";
process.env.OS_AGENT_SESSION_RECENT_TOKENS = "5000";
process.env.OS_AGENT_SESSION_ARCHIVE_DAYS = "30";
afterAll(async () => {
- for (const key of ["OS_AGENT_SESSIONS_DIR", "OS_AGENT_MEMORY_DIR", "OS_AGENT_SESSION_ARCHIVE_DIR", "OS_AGENT_SESSION_COMPACT_TOKENS", "OS_AGENT_SESSION_RECENT_TOKENS", "OS_AGENT_SESSION_ARCHIVE_DAYS"]) delete process.env[key];
+ for (const key of ["OS_AGENT_SESSIONS_DIR", "OS_AGENT_MEMORY_DIR", "OS_AGENT_SESSION_ARCHIVE_DIR", "OS_AGENT_SESSION_PRESERVATION_DIR", "OS_AGENT_SESSION_COMPACT_TOKENS", "OS_AGENT_SESSION_RECENT_TOKENS", "OS_AGENT_SESSION_ARCHIVE_DAYS"]) delete process.env[key];
await fs.rm(root, { recursive: true, force: true });
});
@@ -50,13 +52,18 @@ describe("durable agent session context policy", () => {
expect(archived).toContain("[redacted]");
});
- it("prunes archives older than the default 30-day retention window", async () => {
+ it("blocks old archive cleanup until an exact JEV preservation receipt exists", async () => {
const [name] = (await fs.readdir(archives)).filter((row) => row.endsWith(".json.gz"));
const file = path.join(archives, name);
const old = new Date(Date.now() - 31 * 86_400_000);
await fs.utimes(file, old, old);
+ const blocked = await archive.pruneAgentSessionArchives();
+ expect(blocked).toMatchObject({ removed: 0, blocked: 1 });
+ await expect(fs.stat(file)).resolves.toBeTruthy();
+ const archived = await archive.readAgentSessionArchive(name);
+ await archive.writeAgentSessionArchiveJevReceipt(name, archived.sha256, { optimization: { kind: "fixture" } });
const result = await archive.pruneAgentSessionArchives();
- expect(result.removed).toBe(1);
+ expect(result).toMatchObject({ removed: 1, blocked: 0 });
await expect(fs.stat(file)).rejects.toMatchObject({ code: "ENOENT" });
});
diff --git a/lib/infra/connection-ui-layout.test.ts b/lib/infra/connection-ui-layout.test.ts
index 45041ea2..668ef4c8 100644
--- a/lib/infra/connection-ui-layout.test.ts
+++ b/lib/infra/connection-ui-layout.test.ts
@@ -27,6 +27,8 @@ it("keeps AI Providers on the existing AI config/runtime SSOT and browser-only c
expect(() => new Function(CONNECTION_MANAGER_SCRIPT)).not.toThrow();
expect(CONNECTION_MANAGER_SCRIPT).toContain("same AI runtime/config store as Settings");
expect(CONNECTION_MANAGER_SCRIPT).toContain("Integration Variables");
+ expect(CONNECTION_MANAGER_SCRIPT).toContain("~typesafe/jev-latest");
+ expect(CONNECTION_MANAGER_SCRIPT).toContain("same OpenRouter key managed here and in Settings");
expect(INTEGRATION_BROWSER_SCRIPT).toContain('bridge.aiConfig=()=>json("/api/config")');
expect(INTEGRATION_BROWSER_SCRIPT).toContain('bridge.aiCatalog=()=>json("/api/models/providers")');
expect(INTEGRATION_BROWSER_SCRIPT).toContain('bridge.aiTest=()=>json("/api/models/test"');
diff --git a/lib/infra/connection-ui.ts b/lib/infra/connection-ui.ts
index 599b8767..e409e066 100644
--- a/lib/infra/connection-ui.ts
+++ b/lib/infra/connection-ui.ts
@@ -91,7 +91,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
const variables=snapshot.variables&&typeof snapshot.variables==="object"?snapshot.variables:{};
const entries=Object.entries(variables).sort(([a],[b])=>a.localeCompare(b));
if(!entries.length)detail.append(n("p","No Integration Variables yet.","identity-muted"));
- for(const[key,ref]of entries){const card=n("article",undefined,"connection-card"),top=n("header",undefined,"connection-heading"),copy=n("div");copy.append(n("h3",key),n("small",ref.user+" / "+ref.provider+" / "+ref.connection));top.append(copy);card.append(top);if(key==="JEV")card.append(n("p","Default decision-kernel alias used by Workflow Optimizer.","identity-muted"));const remove=b("Remove",()=>change({action:"variable.delete",key}),"danger");remove.disabled=!bridge.manage;card.append(n("div",undefined,"identity-actions"));card.lastChild.append(remove);detail.append(card)}
+ for(const[key,ref]of entries){const card=n("article",undefined,"connection-card"),top=n("header",undefined,"connection-heading"),copy=n("div");copy.append(n("h3",key),n("small",ref.user+" / "+ref.provider+" / "+ref.connection));top.append(copy);card.append(top);if(key==="JEV")card.append(n("p","Legacy MCP override for JEV diagnostics. Native Workflow and Session optimization uses the shared OpenRouter AI credential by default.","identity-muted"));const remove=b("Remove",()=>change({action:"variable.delete",key}),"danger");remove.disabled=!bridge.manage;card.append(n("div",undefined,"identity-actions"));card.lastChild.append(remove);detail.append(card)}
const editor=n("div",undefined,"connection-card");editor.append(n("h3","Add or update variable"),n("p","Select a credential owner in the sidebar, then point the variable to one of that owner’s named connections.","identity-muted"));
if(!user){editor.append(n("p","Select a credential owner first.","identity-muted"));detail.append(editor);return}
const key=input("Variable name",variables.JEV?"":"JEV"),providerSelect=n("select"),providerLabel=n("label","Provider"),connectionSelect=n("select"),connectionLabel=n("label","Named connection");
@@ -115,6 +115,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
const dynamic=Array.isArray(catalogResult?.providers)?catalogResult.providers:[],connected=Array.isArray(cfg?.providers)?cfg.providers:[],meta=new Map();
for(const row of dynamic)meta.set(row.id,{id:row.id,name:row.name||row.id,...row});for(const row of connected)meta.set(row.id,{id:row.id,name:meta.get(row.id)?.name||row.id,...meta.get(row.id),...row});if(cfg.provider&&!meta.has(cfg.provider))meta.set(cfg.provider,{id:cfg.provider,name:cfg.provider});
detail.replaceChildren(n("h2","AI Providers"),n("p","Alfa provider/model selection and credentials share the exact Settings SSOT. Saved keys stay server-side and are only shown masked."));
+ const openrouter=connected.find(row=>row.id==="openrouter"),jev=n("div",undefined,"connection-card"),jevTop=n("header",undefined,"connection-heading"),jevCopy=n("div");jevCopy.append(n("h3","JEV decision kernel"),n("small","~typesafe/jev-latest · OpenRouter Decisions API"));jevTop.append(jevCopy,n("span",openrouter?.hasKey?"Ready":"OpenRouter required","connection-state"));jev.append(jevTop,n("p","JEV reuses the same OpenRouter key managed here and in Settings → AI. No TypeSafe/JEV credential is stored separately.","identity-muted"));detail.append(jev);
const providerSelect=n("select"),providerLabel=n("label","Active provider"),modelSelect=n("select"),modelLabel=n("label","Model"),key=input("API key","","password"),fields=n("div",undefined,"identity-fields");
for(const row of [...meta.values()].sort((a,b)=>String(a.name).localeCompare(String(b.name)))){const o=n("option",row.name+(row.freeAgentModelCount? " · "+row.freeAgentModelCount+" free agent model"+(row.freeAgentModelCount===1?"":"s"):""));o.value=row.id;providerSelect.append(o)}
providerSelect.value=cfg.provider||providerSelect.options[0]?.value||"";providerLabel.append(providerSelect);modelLabel.append(modelSelect);fields.append(providerLabel,modelLabel,key.label);detail.append(fields);
diff --git a/lib/mcp/tools-flows.ts b/lib/mcp/tools-flows.ts
index 1592a272..1d409e6f 100644
--- a/lib/mcp/tools-flows.ts
+++ b/lib/mcp/tools-flows.ts
@@ -15,7 +15,7 @@ import { resolveProjectHint } from "@/lib/host/projects-api";
import { listAutomationScripts } from "@/lib/orchestration/repo-memory-artifacts";
import { createWorkflowDataTable, deleteWorkflowDataTable, deleteWorkflowDataTableRow, getWorkflowDataTable, listWorkflowDataTables, upsertWorkflowDataTableRow } from "@/lib/workflow/data-table-store";
import { optimizeWorkflowGraph } from "@/lib/workflow/graph-optimizer";
-import { createJevWorkflowOptimizerEvaluator } from "@/lib/workflow/jev-optimizer";
+import { createResolvedJevWorkflowOptimizerEvaluator } from "@/lib/workflow/jev-evaluator";
import { resolveJevIntegrationConfig } from "@/lib/workflow/jev-integration";
const project = { type: "string", maxLength: 4096 };
const flow = { type: "string", maxLength: 64 };
@@ -99,7 +99,7 @@ export const FLOW_TOOLS: McpTool[] = [
const mode = data.mode === "jev" ? "jev" as const : "deterministic" as const;
let evaluator;
if (mode === "jev") {
- evaluator = createJevWorkflowOptimizerEvaluator(await resolveJevIntegrationConfig(data.jev));
+ evaluator = createResolvedJevWorkflowOptimizerEvaluator(await resolveJevIntegrationConfig(data.jev));
}
const { TOOLS_BY_NAME } = await import("./tools");
const optimized = await optimizeWorkflowGraph(graph, { mode, threshold: Number(data.threshold) || undefined, applyReview: data.apply_review === true, evaluator, resolveTool: name => TOOLS_BY_NAME.get(name) });
diff --git a/lib/workflow/jev-evaluator.ts b/lib/workflow/jev-evaluator.ts
new file mode 100644
index 00000000..baf6a6d7
--- /dev/null
+++ b/lib/workflow/jev-evaluator.ts
@@ -0,0 +1,9 @@
+import { createJevWorkflowOptimizerEvaluator } from "./jev-optimizer";
+import { createOpenRouterJevWorkflowOptimizerEvaluator } from "./jev-openrouter";
+import type { JevIntegrationConfig } from "./jev-integration";
+
+export function createResolvedJevWorkflowOptimizerEvaluator(config: JevIntegrationConfig) {
+ return config.transport === "openrouter"
+ ? createOpenRouterJevWorkflowOptimizerEvaluator({ model: config.model })
+ : createJevWorkflowOptimizerEvaluator(config);
+}
diff --git a/lib/workflow/jev-integration.test.ts b/lib/workflow/jev-integration.test.ts
index 05ea3612..a2c0330f 100644
--- a/lib/workflow/jev-integration.test.ts
+++ b/lib/workflow/jev-integration.test.ts
@@ -7,25 +7,26 @@ let root:string;
beforeEach(async()=>{root=await fs.mkdtemp(path.join(os.tmpdir(),"mso-jev-ref-"));process.env.OS_INFRA_STORE=path.join(root,"infra.json");vi.resetModules();});
afterEach(async()=>{delete process.env.OS_INFRA_STORE;await fs.rm(root,{recursive:true,force:true});vi.resetModules();});
-describe("Jev Integration Variable resolution",()=>{
- it("uses JEV by default and preserves an explicit connection override",async()=>{
+describe("Jev routing resolution",()=>{
+ it("uses the shared OpenRouter AI credential path by default and preserves explicit MCP overrides",async()=>{
const {integrationManage}=await import("@/lib/infra/connection-manage");
await integrationManage({action:"user.create",confirm:true,user:"alice"});
await integrationManage({action:"connection.create",confirm:true,user:"alice",provider:"mcp",connection:"jev",source:"direct",authMethod:"direct"});
await integrationManage({action:"connection.create",confirm:true,user:"alice",provider:"mcp",connection:"alternate",source:"direct",authMethod:"direct"});
await integrationManage({action:"variable.set",confirm:true,key:"JEV",user:"alice",provider:"mcp",connection:"jev"});
const {resolveJevIntegrationConfig}=await import("./jev-integration");
- await expect(resolveJevIntegrationConfig()).resolves.toEqual({user:"alice",connection:"jev"});
- await expect(resolveJevIntegrationConfig({variable:"JEV",model:"decision-model"})).resolves.toEqual({user:"alice",connection:"jev",model:"decision-model"});
- await expect(resolveJevIntegrationConfig({user:"alice",connection:"alternate"})).resolves.toEqual({user:"alice",connection:"alternate"});
+ await expect(resolveJevIntegrationConfig()).resolves.toEqual({transport:"openrouter",provider:"openrouter",model:"~typesafe/jev-latest"});
+ await expect(resolveJevIntegrationConfig({model:"typesafe/jev-1.13"})).resolves.toEqual({transport:"openrouter",provider:"openrouter",model:"typesafe/jev-1.13"});
+ await expect(resolveJevIntegrationConfig({variable:"JEV",model:"decision-model"})).resolves.toEqual({transport:"mcp",user:"alice",connection:"jev",model:"decision-model"});
+ await expect(resolveJevIntegrationConfig({user:"alice",connection:"alternate"})).resolves.toEqual({transport:"mcp",user:"alice",connection:"alternate"});
await expect(resolveJevIntegrationConfig({user:"alice"})).rejects.toThrow("both integration user and connection");
});
- it("rejects a variable that points to a non-MCP provider",async()=>{
+ it("rejects an explicit legacy variable that points to a non-MCP provider",async()=>{
const {integrationManage}=await import("@/lib/infra/connection-manage");
await integrationManage({action:"user.create",confirm:true,user:"alice"});
await integrationManage({action:"connection.create",confirm:true,user:"alice",provider:"github",connection:"work",source:"direct",authMethod:"direct"});
await integrationManage({action:"variable.set",confirm:true,key:"JEV",user:"alice",provider:"github",connection:"work"});
const {resolveJevIntegrationConfig}=await import("./jev-integration");
- await expect(resolveJevIntegrationConfig()).rejects.toThrow("must reference provider mcp");
+ await expect(resolveJevIntegrationConfig({variable:"JEV"})).rejects.toThrow("must reference provider mcp");
});
});
diff --git a/lib/workflow/jev-integration.ts b/lib/workflow/jev-integration.ts
index 77b69444..2903f439 100644
--- a/lib/workflow/jev-integration.ts
+++ b/lib/workflow/jev-integration.ts
@@ -1,4 +1,5 @@
import { resolveIntegrationVariable } from "@/lib/infra/connection-service";
+import { DEFAULT_JEV_OPENROUTER_MODEL } from "./jev-openrouter";
export type JevIntegrationInput = {
variable?: string;
@@ -8,12 +9,9 @@ export type JevIntegrationInput = {
model?: string;
};
-export type JevIntegrationConfig = {
- user: string;
- connection: string;
- tool?: string;
- model?: string;
-};
+export type JevIntegrationConfig =
+ | { transport: "openrouter"; provider: "openrouter"; model: string }
+ | { transport: "mcp"; user: string; connection: string; tool?: string; model?: string };
function optionalText(value: unknown, max: number): string | undefined {
if (value === undefined) return undefined;
@@ -27,12 +25,17 @@ export async function resolveJevIntegrationConfig(raw?: unknown): Promise<JevInt
const connection = optionalText(input.connection, 64);
const tool = optionalText(input.tool, 180);
const model = optionalText(input.model, 180);
+ const variable = optionalText(input.variable, 64);
+
if (user || connection) {
if (!user || !connection) throw new Error("Jev override requires both integration user and connection");
- return { user, connection, ...(tool ? { tool } : {}), ...(model ? { model } : {}) };
+ return { transport: "mcp", user, connection, ...(tool ? { tool } : {}), ...(model ? { model } : {}) };
+ }
+ if (variable) {
+ const ref = await resolveIntegrationVariable(variable);
+ if (ref.provider !== "mcp") throw new Error(variable + " Integration Variable must reference provider mcp");
+ return { transport: "mcp", user: ref.user, connection: ref.connection, ...(tool ? { tool } : {}), ...(model ? { model } : {}) };
}
- const variable = optionalText(input.variable, 64) ?? "JEV";
- const ref = await resolveIntegrationVariable(variable);
- if (ref.provider !== "mcp") throw new Error(variable + " Integration Variable must reference provider mcp");
- return { user: ref.user, connection: ref.connection, ...(tool ? { tool } : {}), ...(model ? { model } : {}) };
+ if (tool) throw new Error("Jev tool override requires an MCP connection override");
+ return { transport: "openrouter", provider: "openrouter", model: model ?? DEFAULT_JEV_OPENROUTER_MODEL };
}
diff --git a/lib/workflow/jev-openrouter.test.ts b/lib/workflow/jev-openrouter.test.ts
new file mode 100644
index 00000000..f57f9a48
--- /dev/null
+++ b/lib/workflow/jev-openrouter.test.ts
@@ -0,0 +1,22 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { WorkflowOptimizerCandidate } from "./graph-optimizer";
+const getKey=vi.fn(),safeProviderFetch=vi.fn();
+vi.mock("@/lib/config/store",()=>({hostCredentialStore:()=>({getKey})}));
+vi.mock("@/lib/host/ssrf",()=>({safeProviderFetch}));
+const {createOpenRouterJevWorkflowOptimizerEvaluator}=await import("./jev-openrouter");
+const candidate=(id:string):WorkflowOptimizerCandidate=>({id,kind:"presentation-group",title:`Candidate ${id}`,description:"Improve a bounded route.",nodeIds:["a","b"],risk:"safe",estimatedNodeDelta:1,hostEligible:true});
+beforeEach(()=>{getKey.mockReset();safeProviderFetch.mockReset();});
+describe("OpenRouter Jev evaluator",()=>{
+ it("reuses the Settings AI OpenRouter key and Decisions API without exposing it in state",async()=>{
+ getKey.mockResolvedValue("private-key");
+ safeProviderFetch.mockResolvedValue(new Response(JSON.stringify({model:"typesafe/jev-1.13",answers:{q1:{type:"noul",noul:.93}},usage:{input_tokens:123}}),{status:200,headers:{"content-type":"application/json"}}));
+ const result=await createOpenRouterJevWorkflowOptimizerEvaluator()({workflow:{nodeCount:2}},[candidate("c1")]);
+ expect(result).toEqual({provider:"jev",probabilities:{c1:.93}});
+ expect(getKey).toHaveBeenCalledWith(undefined,"openrouter");
+ const [url,init]=safeProviderFetch.mock.calls[0];expect(url).toBe("https://openrouter.ai/api/alpha/decisions");
+ const body=JSON.parse(String(init.body));expect(body.model).toBe("~typesafe/jev-latest");expect(body.state).toEqual({workflow:{nodeCount:2}});expect(JSON.stringify(body)).not.toContain("private-key");
+ expect(init.headers.authorization).toBe("Bearer private-key");
+ });
+ it("uses no token and does not require an OpenRouter key when there is no decision candidate",async()=>{getKey.mockResolvedValue(null);await expect(createOpenRouterJevWorkflowOptimizerEvaluator()({},[])).resolves.toEqual({provider:"jev",probabilities:{}});expect(getKey).not.toHaveBeenCalled();expect(safeProviderFetch).not.toHaveBeenCalled();});
+ it("fails closed when OpenRouter is not connected",async()=>{getKey.mockResolvedValue(null);await expect(createOpenRouterJevWorkflowOptimizerEvaluator()({},[candidate("c1")])).rejects.toThrow("OpenRouter is not connected");expect(safeProviderFetch).not.toHaveBeenCalled();});
+});
diff --git a/lib/workflow/jev-openrouter.ts b/lib/workflow/jev-openrouter.ts
new file mode 100644
index 00000000..43eb0a33
--- /dev/null
+++ b/lib/workflow/jev-openrouter.ts
@@ -0,0 +1,59 @@
+import { hostCredentialStore } from "@/lib/config/store";
+import { safeProviderFetch } from "@/lib/host/ssrf";
+import type { WorkflowOptimizerCandidate, WorkflowOptimizerEvaluation } from "./graph-optimizer";
+
+export const DEFAULT_JEV_OPENROUTER_MODEL = "~typesafe/jev-latest";
+const OPENROUTER_JEV_ENDPOINT = "https://openrouter.ai/api/alpha/decisions";
+
+function object(value: unknown): value is Record<string, unknown> {
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
+}
+
+function probability(answer: unknown): number | null {
+ if (!object(answer)) return null;
+ const value = Number(answer.noul);
+ return Number.isFinite(value) && value >= 0 && value <= 1 ? value : null;
+}
+
+export function createOpenRouterJevWorkflowOptimizerEvaluator(config: { model?: string } = {}) {
+ const model = typeof config.model === "string" && config.model.trim() ? config.model.trim() : DEFAULT_JEV_OPENROUTER_MODEL;
+ if (model.length > 180) throw new Error("invalid Jev OpenRouter model");
+
+ return async (state: Record<string, unknown>, candidates: WorkflowOptimizerCandidate[]): Promise<WorkflowOptimizerEvaluation> => {
+ if (!candidates.length) return { provider: "jev", probabilities: {} };
+ const apiKey = await hostCredentialStore().getKey(undefined, "openrouter");
+ if (!apiKey) throw new Error("OpenRouter is not connected. Add an OpenRouter key in Settings → AI or Integrations → AI Providers.");
+
+ const mapping = new Map<string, string>();
+ const questions = Object.fromEntries(candidates.slice(0, 16).map((candidate, index) => {
+ const key = `q${index + 1}`;
+ mapping.set(key, candidate.id);
+ return [key, {
+ type: "noul",
+ instructions: `Should MSO apply candidate "${candidate.title}"? Answer yes only when it meaningfully improves or compacts this workflow while preserving semantics, permissions, bounded execution, auditability and debuggability. Candidate risk: ${candidate.risk}.`,
+ }];
+ }));
+
+ const response = await safeProviderFetch(OPENROUTER_JEV_ENDPOINT, {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${apiKey}`,
+ "content-type": "application/json",
+ "x-title": "MSO JEV Decision Kernel",
+ },
+ body: JSON.stringify({ model, state, questions }),
+ signal: AbortSignal.timeout(20_000),
+ });
+ if (!response.ok) throw new Error(`OpenRouter Jev request failed (${response.status})`);
+ const payload = await response.json() as unknown;
+ if (!object(payload) || !object(payload.answers)) throw new Error("OpenRouter Jev returned no typed answers");
+
+ const probabilities: Record<string, number> = {};
+ for (const [question, candidateId] of mapping) {
+ const p = probability(payload.answers[question]);
+ if (p !== null) probabilities[candidateId] = p;
+ }
+ if (!Object.keys(probabilities).length) throw new Error("OpenRouter Jev returned no usable probabilities");
+ return { provider: "jev", probabilities };
+ };
+}
diff --git a/lib/workflow/jev-session-optimizer.test.ts b/lib/workflow/jev-session-optimizer.test.ts
new file mode 100644
index 00000000..2732776f
--- /dev/null
+++ b/lib/workflow/jev-session-optimizer.test.ts
@@ -0,0 +1,10 @@
+import { expect, it, vi } from "vitest";
+vi.mock("./jev-integration",()=>({resolveJevIntegrationConfig:vi.fn(async()=>({transport:"openrouter",provider:"openrouter",model:"~typesafe/jev-latest"}))}));
+vi.mock("./jev-evaluator",()=>({createResolvedJevWorkflowOptimizerEvaluator:vi.fn(()=>async(_state:unknown,candidates:Array<{id:string}>)=>({provider:"jev",probabilities:Object.fromEntries(candidates.map(c=>[c.id,.9]))}))}));
+import { optimizeSessionWithJev } from "./jev-session-optimizer";
+const action=(ref:string,tool:string)=>({id:ref,ref,eventRef:`E${ref}`,title:ref,category:"implement" as const,at:new Date().toISOString(),kind:"tool",tool,state:"completed"});
+it("returns a bounded LLM-consumable JEV packet without executable arguments",async()=>{
+ const view:any={session:{id:"s",name:"a",label:"agent-project",title:"Ship feature",source:"mcp",status:"offline",receiverConnected:false,lastSeenAt:"",createdAt:"",eventCount:3,archiveCount:0,cwd:"/project"},graph:{},steps:[{id:"1",ref:"S1",title:"Implement",category:"implement",summary:"work",startedAt:"",finishedAt:"",groups:[],actions:[action("S1.A1","fs_read"),action("S1.A2","fs_read"),action("S1.A3","exec_run")]}],totalEvents:3,shownEvents:3,omittedEvents:0,observedAt:new Date().toISOString()};
+ const result=await optimizeSessionWithJev(view);
+ expect(result.provider).toBe("jev"); expect(result.recommendations.length).toBeGreaterThan(0); expect(result.llmContext.kind).toBe("mso.jev-session-optimization.v1"); expect(result.llmContext.recommendations.every(row => !Object.hasOwn(row,"arguments"))).toBe(true);
+});
diff --git a/lib/workflow/jev-session-optimizer.ts b/lib/workflow/jev-session-optimizer.ts
new file mode 100644
index 00000000..81776c6c
--- /dev/null
+++ b/lib/workflow/jev-session-optimizer.ts
@@ -0,0 +1,34 @@
+import type { SessionGraphView } from "@/lib/contracts/session-monitor";
+import { createResolvedJevWorkflowOptimizerEvaluator } from "./jev-evaluator";
+import { resolveJevIntegrationConfig, type JevIntegrationInput } from "./jev-integration";
+import type { WorkflowOptimizerCandidate } from "./graph-optimizer";
+
+export type JevSessionOptimization = {
+ provider: "jev" | "fallback";
+ source: { sessionLabel: string; observedAt: string; shownEvents: number; omittedEvents: number };
+ recommendations: Array<{ id: string; title: string; description: string; probability: number; actionRefs: string[] }>;
+ llmContext: { kind: "mso.jev-session-optimization.v1"; instruction: string; facts: string[]; recommendations: Array<{ id: string; probability: number; actionRefs: string[]; guidance: string }> };
+ fallbackReason?: string;
+};
+
+function candidates(view: SessionGraphView): WorkflowOptimizerCandidate[] {
+ const out: WorkflowOptimizerCandidate[] = [];
+ for (const step of view.steps) {
+ if (step.actions.length >= 3) out.push({ id:`compact-${step.ref}`, kind:"loop-compaction", hostEligible:true, title:`Compact ${step.ref}: ${step.title}`, description:`Replace repeated planning/inspection overhead in ${step.ref} with the smallest reusable bounded workflow while preserving verification and authorization boundaries.`, nodeIds:step.actions.map(a=>a.ref), estimatedNodeDelta:Math.max(1,step.actions.length-2), risk:"review" });
+ const tools = step.actions.map(a=>a.tool).filter((v):v is string=>Boolean(v));
+ if (tools.length >= 2 && new Set(tools).size < tools.length) out.push({ id:`reuse-${step.ref}`, kind:"loop-compaction", hostEligible:true, title:`Reuse proven route from ${step.ref}`, description:`Prefer the repeated tool route already evidenced in ${step.ref} over rediscovering the same route with another LLM.`, nodeIds:step.actions.filter(a=>a.tool).map(a=>a.ref), estimatedNodeDelta:Math.max(1,tools.length-new Set(tools).size), risk:"safe" });
+ }
+ if (view.steps.length >= 4) out.push({ id:"handoff-packet", kind:"presentation-group", hostEligible:true, title:"Create compact continuation packet", description:"Use the semantic session flow, durable action refs, artifacts and learned recipes as the continuation context instead of replaying the raw transcript.", nodeIds:view.steps.map(s=>s.ref), estimatedNodeDelta:Math.max(1,view.steps.length-2), risk:"safe" });
+ return out.slice(0, 16);
+}
+
+export async function optimizeSessionWithJev(view: SessionGraphView, raw?: unknown): Promise<JevSessionOptimization> {
+ const options = raw && typeof raw === "object" ? raw as JevIntegrationInput : undefined;
+ const rows = candidates(view);
+ const state = { session:{ label:view.session.label, title:view.session.title, source:view.session.source, status:view.session.status, project:view.session.cwd }, coverage:{ shownEvents:view.shownEvents, omittedEvents:view.omittedEvents }, steps:view.steps.map(s=>({ ref:s.ref, category:s.category, title:s.title, summary:s.summary, actions:s.actions.map(a=>({ref:a.ref,tool:a.tool,state:a.state,kind:a.kind,artifactRefs:a.artifact?[a.artifact.ref]:[]})) })) };
+ let provider: "jev" | "fallback" = "jev", probabilities: Record<string,number> = {}, fallbackReason: string | undefined;
+ try { probabilities=(await createResolvedJevWorkflowOptimizerEvaluator(await resolveJevIntegrationConfig(options))(state,rows)).probabilities; }
+ catch (cause) { provider="fallback"; fallbackReason=cause instanceof Error?cause.message.slice(0,240):"Jev evaluation failed"; }
+ const recommendations=rows.map(row=>({...row, probability:provider==="jev"?(probabilities[row.id]??0):0, actionRefs:row.nodeIds})).filter(row=>row.probability>=0.5).sort((a,b)=>b.probability-a.probability).map(({id,title,description,probability,actionRefs})=>({id,title,description,probability,actionRefs}));
+ return { provider, source:{sessionLabel:view.session.label,observedAt:view.observedAt,shownEvents:view.shownEvents,omittedEvents:view.omittedEvents}, recommendations, llmContext:{kind:"mso.jev-session-optimization.v1",instruction:"Treat these as review-first decision signals. Re-check live state before mutation. Never infer credentials, arguments, permissions, or success from this packet.",facts:[`Session ${view.session.label} has ${view.steps.length} semantic steps.`,`Projection covers ${view.shownEvents}/${view.totalEvents} events.`,...(view.omittedEvents?[`${view.omittedEvents} older events are omitted from this bounded projection.`]:[])],recommendations:recommendations.map(r=>({id:r.id,probability:r.probability,actionRefs:r.actionRefs,guidance:r.description}))},...(fallbackReason?{fallbackReason}:{}) };
+}